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

如何实现Discord机器人根据消息ID回复指定消息?

Discord机器人指定消息ID回复功能实现

核心实现步骤

  • 从用户指令中提取目标消息ID
  • 验证ID格式有效性
  • 通过ID获取目标消息对象
  • 执行回复操作并处理异常

完整代码实现

async def on_message(message):
    if client.user.mentioned_in(message) and client.user in message.mentions:
        if message.author.bot:
            return

        if message.content.startswith("!!") and message.content.endswith("/"):
            if message.content.startswith("!!reply/"):
                # 提取消息ID:切割指令字符串,剔除前后无关字符
                msg_id_str = message.content[len("!!reply/"):-1].strip()
                # 验证ID是否为有效数字格式
                if not msg_id_str.isdigit():
                    await message.channel.send("请输入有效的消息ID!")
                    return
                
                msg_id = int(msg_id_str)
                try:
                    # 根据ID获取目标消息对象
                    target_message = await message.channel.fetch_message(msg_id)
                    # 直接回复目标消息(自动引用原消息)
                    await target_message.reply("这是机器人的回复内容!")
                    # 可选:也可以在当前频道发送提示并附带原消息跳转链接
                    # await message.reply(f"已完成回复:{target_message.jump_url}", mention_author=False)
                except discord.NotFound:
                    await message.channel.send("未找到该ID对应的消息!")
                except discord.Forbidden:
                    await message.channel.send("机器人无权限获取该消息!")
                except Exception as e:
                    await message.channel.send(f"处理失败:{str(e)}")

关键代码说明

  • msg_id_str = message.content[len("!!reply/"):-1].strip():精准截取指令中的消息ID,避免多余字符干扰
  • isdigit():快速校验ID格式,过滤非数字的无效输入
  • fetch_message(msg_id):从当前频道拉取目标消息,若目标消息在其他频道,需先获取对应频道对象再调用该方法
  • target_message.reply():遵循Discord交互逻辑,自动引用原消息进行回复
  • 异常捕获:覆盖消息不存在、权限不足等常见场景,提升机器人容错性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 11:42:02