【问题标题】:discord.py - Cannot get average colour of a user's avatardiscord.py - 无法获得用户头像的平均颜色
【发布时间】:2020-05-30 10:47:05
【问题描述】:

所以我有这个函数来返回用户头像的平均颜色:

import discord
from discord.ext import commands
import asyncio
from PIL import Image
import requests
from io import BytesIO

class Bot(commands.Bot):

    ...

    @staticmethod
    async def get_average_colour(image_url, default=0x696969):
        try:
            resp = requests.get(image_url)
            assert resp.ok
            img = Image.open(BytesIO(resp.content))
            img2 = img.resize((1, 1), Image.ANTIALIAS)
            colour = img2.getpixel((0, 0))
            res = "{:02x}{:02x}{:02x}".format(*colour)
            return int(res, 16)
        except:
            return default

    ...

这可行,但问题在于它使用了requests,这是阻塞的。所以我尝试改用aiohttp

import discord
from discord.ext import commands
import asyncio
from PIL import Image
import aiohttp
from io import BytesIO

class Bot(commands.Bot):

    ...

    @staticmethod
    async def get_average_colour(image_url, default=0x696969):
        try:
            async with aiohttp.ClientSession() as session:
                async with session.get(image_url) as resp:
                    if resp.status != 200:
                        raise Exception
                    img = Image.open(BytesIO(await resp.read()))
            colour = img.resize((1, 1), Image.ANTIALIAS).getpixel((0, 0))
            return int("{:02x}{:02x}{:02x}".format(*colour), 16)
        except:
            return default

    ...

当我尝试查找random cat image link 的平均颜色时,该函数工作正常,但是当我尝试使用用户的avatar_url 调用此函数时,该函数始终返回默认值。有谁知道这个功能有什么问题?

【问题讨论】:

    标签: python python-3.x discord.py aiohttp discord.py-rewrite


    【解决方案1】:

    一个好方法是将image_url 转换为字符串。这样,它将始终是一个字符串,而不是 discord.Asset 对象。

    【讨论】:

      【解决方案2】:

      似乎调用async with session.get(str(image_url)) as resp: 而不是async with session.get(image_url) as resp: 可行。

      【讨论】:

        猜你喜欢
        • 2012-09-06
        • 1970-01-01
        • 2011-07-06
        • 2012-07-28
        • 2015-06-05
        • 2011-02-02
        • 2019-08-01
        • 1970-01-01
        相关资源
        最近更新 更多