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

Discord.py开发反应角色功能无法添加表情反应报错求助

问题修复方案

错误原因分析

  • UnboundLocalError: local variable 'embed1' referenced before assignment:逻辑缩进错误,embed1仅在用户发送!lol命令时才会被定义,你将发送Embed、添加反应的代码全部写在了if判断块外,所有非!lol的消息触发事件时,embed1未定义就被调用,直接触发报错。
  • NameError: name 'ctx' is not defined:on_message是原生消息事件,没有ctx参数,ctx是discord.ext.commands命令框架的上下文对象,仅在自定义命令场景下可用;同时add_reaction方法调用逻辑错误:该方法是消息对象的自带方法,直接由需要添加反应的消息实例调用,仅需传入表情参数即可。

自定义表情无法生效的原因

  • 确认你填写的表情ID正确,且该自定义表情所在的服务器已经邀请了你的机器人加入,否则client.get_emoji会返回None,添加反应就会失败
  • 确认调用add_reaction的消息对象正确,你需要给哪条消息加反应,就用哪条消息的实例调用该方法

修复后的完整代码

@client.event
async def on_message(message):
    # 忽略机器人自身发送的消息,避免触发死循环
    if message.author.bot:
        return

    if message.content.lower().startswith("!lol"):
        embed1 = discord.Embed(
            title="Escolha seu Elo!",
            color=COR,
            description="- Ferro = 👎\n"
                        "- Bronze = 🐤\n"
                        "- Prata  =  📘 \n"
                        "- Ouro  = 📙\n"
                        "- Platina = 👍\n"
                        "- Diamante = ✋\n"
                        "- Mestre = 👊\n"
                        "- Grã-Mestre = ✊\n"
                        "- Desafiante = 🙏\n",)

        botmsg = await message.channel.send(embed=embed1)

        # 添加Unicode表情
        await botmsg.add_reaction("👎")
        await botmsg.add_reaction("🐤")
        await botmsg.add_reaction("📘")
        await botmsg.add_reaction("📙")
        await botmsg.add_reaction("👍")
        await botmsg.add_reaction("✋")
        await botmsg.add_reaction("👊")
        await botmsg.add_reaction("✊")
        await botmsg.add_reaction("🙏")

        # 添加自定义表情示例,加非空判断避免报错
        custom_emoji = client.get_emoji(310177266011340803)
        if custom_emoji:
            await botmsg.add_reaction(custom_emoji)

        global msg_id
        msg_id = botmsg.id

        global msg_user
        msg_user = message.author

额外说明

  • 代码中用到的COR为Embed的颜色值,需要提前全局定义,例如COR = 0xFF0000对应红色
  • 如果要完成完整的反应角色功能,后续还需要监听on_raw_reaction_add和on_raw_reaction_remove事件,根据用户添加/移除的反应对应分配/移除角色

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 04:09:04