Discord机器人pixel命令报错:Member对象无avatar_as属性
修正后的代码及问题说明
问题原因
- 装饰器缩进错误:
@commands.cooldown装饰器前的多余缩进会导致语法错误,它需要与@commands.command()保持同一缩进层级。 - 头像方法调用错误:discord.py 版本差异导致方法名不同:
- v1.x 版本中,获取用户头像 URL 的方法是
avatar_url_as() - v2.x 版本中,
user.avatar是 Asset 对象,需通过display_avatar(优先用户自定义头像,无则用默认头像)结合with_format()和with_size()获取 URL
- v1.x 版本中,获取用户头像 URL 的方法是
- 缺失必要模块导入:代码中使用了
re、discord、asyncdagpi但未导入。
修正后的代码
import re import discord from discord.ext import commands import asyncdagpi @commands.command() @commands.cooldown(rate=1, per=10.0, type=commands.BucketType.user) async def pixel(self, ctx, user=None): """Pixelates an image.""" if user is None: if not ctx.message.attachments: await ctx.send("请上传一张图片,或者指定一个用户来像素化头像!") return for attachment in ctx.message.attachments: img = await self.bot.dagpi.image_process( asyncdagpi.ImageFeatures.pixel(), attachment.proxy_url ) file = discord.File(fp=img.image, filename=f"pixel.{img.format}") await ctx.send(file=file) else: userID = re.sub("[^0-9]", "", user) try: user = await ctx.guild.fetch_member(userID) except BaseException: await ctx.send("No user found.") return # 根据你的 discord.py 版本选择下面其中一种写法 # 写法1:适用于 discord.py v2.x 版本 url = user.display_avatar.with_format("png").with_size(1024).url # 写法2:适用于 discord.py v1.x 版本(如果你的环境是旧版本) # url = str(user.avatar_url_as(format="png", size=1024)) img = await self.bot.dagpi.image_process( asyncdagpi.ImageFeatures.pixel(), url ) file = discord.File(fp=img.image, filename=f"pixel.{img.format}") await ctx.send(file=file)
额外说明
- 确保你的虚拟环境中安装了对应版本的依赖:
pip install discord.py asyncdagpi - 新增了无附件且未指定用户时的提示逻辑,优化交互体验
内容的提问来源于stack exchange,提问作者user21343500
相关产品推荐
相关产品推荐

