You need to enable JavaScript to run this app. 如何让Discord机器人正确转发私信内容,解决消息对象输出异常
优惠活动
大模型
产品
解决方案
定价
更多

如何让Discord机器人正确转发私信内容,解决消息对象输出异常

问题根源

你调用channel.send()时直接传入了完整的Message类实例,该方法会将非字符串参数自动转为对象的结构化字符串表示,因此输出的是对象的原始属性打印结果,而非用户发送的实际内容。

修正方案

基础调整逻辑

  • 过滤无效消息:跳过服务器内消息、机器人自身发送的消息,避免重复处理或递归触发
  • 提取实际消息内容:通过message.content获取用户输入的文本
  • 附加发送者身份标识:避免转发后无法区分私信来源

修正后基础代码

@client.event
async def on_message(message):
    # 仅处理用户发来的私信,排除服务器消息、机器人自身消息
    if message.guild or message.author.bot:
        return
    target_channel = client.get_channel(793586177328283660)
    # 拼接发送者信息与实际消息内容
    forward_text = f"私信来自 {message.author}(用户ID:{message.author.id}):\n{message.content}"
    await target_channel.send(forward_text)

扩展适配场景

如果需要处理仅发送附件/无文本内容的私信,可补充空内容判断与附件转发逻辑:

@client.event
async def on_message(message):
    if message.guild or message.author.bot:
        return
    target_channel = client.get_channel(793586177328283660)
    # 处理无文本的情况
    base_text = f"私信来自 {message.author}(用户ID:{message.author.id}):"
    content_part = f"\n{message.content}" if message.content else "\n[无文本内容]"
    # 拼接附件链接
    attachment_part = ""
    if message.attachments:
        attachment_part = "\n附件列表:\n" + "\n".join([f"- {att.url}" for att in message.attachments])
    forward_text = base_text + content_part + attachment_part
    await target_channel.send(forward_text)

注:如果使用discord.py 2.x版本,需确保已在开发者门户与代码中开启message_content意图,否则会出现无法读取消息内容的问题,你当前能正常触发接收事件,说明该配置已生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.03 16:36:03