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

Discord机器人发送图片后add_reaction方法未执行问题求助

问题解决:Discord机器人发送图片后无法添加表情反应

核心问题

直接硬编码完整URL进行相等判断的方式不可靠:URL中的过期参数(ex、is)会随时间变化,代码里的URL可能和实际返回的不一致;另外长字符串比较容易出现细微拼写错误(比如末尾的&符号),导致条件永远不成立。

解决方案

方案1:用类型标记替代URL直接比较

通过返回元组区分回复类型,避免依赖易变的URL:

  1. 先定义图片URL常量(方便维护):
VELHA_IMAGE_URL = 'https://cdn.discordapp.com/attachments/1229895715657093166/1241841726998446250/New_Piskel-1.png.png?ex=665830fc&is=6656df7c&hm=8cfac1651800f80f61a4c5820b5214605f275a0eb12d56cba42f225315a83d50&'
  1. 修改get_responses函数,返回类型标记+内容的元组:
def get_responses(user_input: str) -> tuple | str:
    lowered: str = user_input.lower()

    if lowered == '':
        return 'fala algo'
    elif 'oi' in lowered:
        return 'salve'
    elif 'gamble' in lowered:
        return f'You rolled: {randint(1,6)}'
    elif 'velha' in lowered:
        return ('image', VELHA_IMAGE_URL)
  1. 在on_message中根据类型处理:
async def on_message(self, message):
    if message.author == self.user:
        return
        
    response = get_responses(message.content)
    if response:
        if isinstance(response, tuple) and response[0] == 'image':
            sent_message = await message.channel.send(response[1])
            await sent_message.add_reaction('👍')
        else:
            await message.channel.send(response)

方案2:检查URL特征而非完整匹配

如果不想修改返回结构,可以通过URL的固定特征判断,比如图片文件名:

async def on_message(self, message):
    if message.author == self.user:
        return
        
    response = get_responses(message.content)
    if response:
        sent_message = await message.channel.send(response)
        # 检查是否包含目标图片的文件名
        if 'New_Piskel-1.png.png' in response:
            await sent_message.add_reaction('👍')

额外排查点

  • 确认机器人在服务器中拥有添加反应的权限,否则代码逻辑正确也无法执行。
  • 可以添加异常捕获调试,排查是否有隐藏错误:
try:
    await sent_message.add_reaction('👍')
except Exception as e:
    print(f"添加反应失败: {e}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 01:10:13