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

如何获取Discord机器人发送消息的ID并转发至其他频道?

解决方案:捕获Discord消息ID并转发到指定频道

当然可行!我们先解决你现有代码里的问题,再给出两种贴合需求的实现方式。

你的代码问题分析

你当前的代码有几个关键错误导致无法触发:

  1. 事件参数错误:on_message 事件接收的参数是 message 对象,而非 ctx(ctx 是命令装饰器 @bot.command() 里用的上下文)。
  2. ID类型不匹配:Discord用户/消息ID是整数类型,你用字符串 "1006858614369177711" 去和整数比较,条件永远不成立。
  3. 机器人身份判断:如果你的需求是捕获机器人自己发送的消息ID,那应该判断 message.author.id == bot.user.id,而非指定用户ID。

场景1:机器人发送消息时直接获取ID并转发

这是最直接的方式,不需要监听事件——当机器人发送消息后,await channel.send() 会返回发送完成的 Message 对象,直接提取它的ID即可:

# 示例:机器人发送消息并转发ID到目标频道
async def send_message_and_forward_id(bot):
    # 1. 发送目标消息到原频道
    source_channel = bot.get_channel(原频道ID)  # 替换成你的原频道ID
    sent_msg = await source_channel.send("这是机器人要发送的消息")
    
    # 2. 获取消息ID并转发到指定频道
    target_channel = bot.get_channel(目标频道ID)  # 替换成你的目标频道ID
    await target_channel.send(f"刚才发送的消息ID是:{sent_msg.id}")

场景2:监听指定消息(用户/机器人)并转发ID

如果你需要监听频道内的特定消息(比如某个用户发送的,或者机器人自己的消息),修正后的 on_message 事件代码如下:

@bot.listen()
async def on_message(message):
    # 场景A:监听特定用户的消息(替换成目标用户ID)
    if message.author.id == 1006858614369177711:
        msg_id = message.id
        target_channel = bot.get_channel(目标频道ID)
        await target_channel.send(f"捕获到用户消息ID:{msg_id}")
    
    # 场景B:监听机器人自己发送的消息
    # if message.author.id == bot.user.id:
    #     msg_id = message.id
    #     target_channel = bot.get_channel(目标频道ID)
    #     await target_channel.send(f"捕获到机器人消息ID:{msg_id}")
    
    # 重要:如果你的机器人同时使用命令(@bot.command()),必须加上这一行,否则命令会失效
    await bot.process_commands(message)

额外注意事项

  • 确保你的机器人开启了 Message Content Intent:在Discord开发者门户的机器人设置里,开启"Message Content Intent",并在代码中初始化机器人时传入intents:
    intents = discord.Intents.default()
    intents.message_content = True
    bot = commands.Bot(command_prefix="你的前缀", intents=intents)
    
  • 使用 bot.get_channel() 时,确保频道ID是整数,且机器人有权限访问该频道。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 17:36:10