因此,我具有此功能可返回用户的头像的平均颜色:
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
,它正在阻塞。因此,我尝试使用requests
代替:
aiohttp
[当我尝试查找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
对象。
似乎是调用avatar_url
而不是image_url
是可行的。