discord.py - 无法获取用户头像的平均颜色
discord.py - Cannot get average colour of a user's avatar
所以我有这个功能return用户头像的平均颜色:
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
, which is blocking. So I tried using 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, the function works fine, but when I try to call this function with a user's avatar_url
的平均颜色时,函数总是 return 默认值。有谁知道那个函数有什么问题吗?
似乎调用 async with session.get(str(image_url)) as resp:
而不是 async with session.get(image_url) as resp:
是可行的。
一个好方法是将 image_url
转换为字符串。这样它将始终是一个字符串,而不是 discord.Asset
对象。
所以我有这个功能return用户头像的平均颜色:
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
, which is blocking. So I tried using 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, the function works fine, but when I try to call this function with a user's avatar_url
的平均颜色时,函数总是 return 默认值。有谁知道那个函数有什么问题吗?
似乎调用 async with session.get(str(image_url)) as resp:
而不是 async with session.get(image_url) as resp:
是可行的。
一个好方法是将 image_url
转换为字符串。这样它将始终是一个字符串,而不是 discord.Asset
对象。