You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让discord.py机器人获取用户头像并修复现有不生效代码?

问题原因

  • 命令定义逻辑错误:你将avatar功能函数嵌套在了关键词检测的if分支内部,只声明了函数没有调用逻辑,代码自然不会执行。如果使用discord.py的命令框架,命令需要全局注册才能生效,不能嵌套在普通消息判断逻辑里。
  • 接口版本不兼容:如果你使用的是discord.py 2.0及以上版本,Member.avatar_url属性已经被官方废弃,替换为Member.avatar.url,旧接口会返回空值导致无输出。
  • 缺少异常兼容:没有对avamember为空、用户无自定义头像的情况做回退处理,会出现取值报错。

修复后可用代码

import discord
from discord.ext import commands

# 机器人基础配置
intents = discord.Intents.default()
intents.message_content = True # 必须开启消息内容读取权限,否则无法检测消息关键词
bot = commands.Bot(command_prefix='!', intents=intents)

# 你自定义的头像查询触发词列表
avatar_words = ["头像", "avatar", "查头像"]

# 方式1:前缀命令触发,使用格式 !avatar @用户
@bot.command(name='avatar')
async def get_avatar(ctx, *, avamember: discord.Member = None):
    # 未@用户时默认返回消息发送者的头像
    target_user = avamember if avamember else ctx.author
    # 兼容无自定义头像的用户,返回平台默认头像
    avatar_url = target_user.avatar.url if target_user.avatar else target_user.default_avatar.url
    await ctx.send(avatar_url)

# 方式2:关键词直接触发,不需要加前缀,发送包含触发词的消息@用户即可
@bot.event
async def on_message(msg):
    # 过滤机器人自己发送的消息
    if msg.author.bot:
        return
    if any(word in msg.content for word in avatar_words):
        # 取消息中@的第一个用户,无@则取发送者本人
        target_user = msg.mentions[0] if msg.mentions else msg.author
        avatar_url = target_user.avatar.url if target_user.avatar else target_user.default_avatar.url
        await msg.channel.send(avatar_url)
    # 保留这行代码,否则前缀命令会失效
    await bot.process_commands(msg)

bot.run("你的机器人TOKEN")

功能说明

  • 两种触发方式可按需选择,都支持获取被@用户的头像,未@用户时默认返回发送者自身头像
  • 自动兼容无自定义头像的用户,不会出现空值报错

内容的提问来源于stack exchange,提问作者tazzan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 15:57:04