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

discord.py如何通过消息ID获取对应的message对象?

问题原因
  1. 初始discord.utils.get用法错误:该方法仅能从机器人本地缓存中检索已加载的对象,且你传入的第一个参数为频道对象而非可迭代的消息列表,本身就无法正确返回消息对象。
  2. 后续fetch_message报10008错误的常见诱因:
  • 目标消息不在当前触发命令的频道内,你持有对应频道ID但未使用,仍然用当前频道拉取其他频道的消息自然返回不存在
  • 目标消息已被删除
  • 机器人没有目标频道的「查看消息历史」权限
  • 存储的消息ID有误,或转整数时格式错误
正确实现方案

首先调整你需要在存储消息ID时同步绑定存储对应频道ID,再按如下实现拉取逻辑,代码示例:

import discord

if split[0] == 'ref':
    if len(split) < 2:
        await message.channel.send("!ref,poll or sg,id number")
    if len(split) == 3:
        if split[1] == "poll":
            for x in db["poll"]:
                # 此处假设你的db["poll"]存储结构为 [消息ID, 服务器ID, 频道ID]
                if x[1] == message.guild.id and x[0] == split[2]:
                    try:
                        # 先获取目标频道对象
                        target_channel = message.guild.get_channel(int(x[2]))
                        if not target_channel:
                            await message.channel.send("无法找到对应频道")
                            continue
                        # 从目标频道拉取指定消息
                        original_msg = await target_channel.fetch_message(int(split[2]))
                        await message.channel.send(original_msg.content)
                    except discord.errors.NotFound:
                        await message.channel.send("目标消息不存在或已被删除")
                    except discord.errors.Forbidden:
                        await message.channel.send("机器人无权限访问该频道或查看消息历史")
                    except ValueError:
                        await message.channel.send("消息ID格式错误")
注意事项
  • 必须在Discord开发者后台给机器人开启Message Content Intent权限,否则无法读取消息内容
  • 给机器人在对应频道的「查看消息历史」权限
  • 所有API调用必须加异常捕获,避免单条消息拉取失败导致整个事件处理逻辑终止

内容的提问来源于stack exchange,提问作者C. Pendergrass

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:57:03