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

使用discord.py获取服务器频道历史消息content字段问题求助

解决Discord机器人无法获取消息content字段的问题

1. 显式提取content字段

你当前代码中打印的是discord.Message对象的默认字符串表示,它不会自动展示content属性,需要主动提取该字段:

  • 如果只需要消息内容:
@bot.event
async def on_message(message):
    channel = discord.utils.get(message.guild.text_channels, name="general")
    messages = [msg.content async for msg in channel.history()]
    print(messages)
  • 如果需要保留完整消息对象并查看content:
@bot.event
async def on_message(message):
    channel = discord.utils.get(message.guild.text_channels, name="general")
    messages = [msg async for msg in channel.history()]
    for msg in messages:
        print(f"消息ID: {msg.id}, 内容: {msg.content}")

2. 修复变量名冲突

代码中on_message的参数message和循环变量message重名,会覆盖外部变量,建议改成不同名称(比如msg),避免逻辑混淆。

3. 启用message_content意图(Discord.py 2.0+)

从Discord.py 2.0版本开始,必须显式启用message_content意图才能读取消息内容:

  1. 登录Discord开发者门户,进入你的应用→「Bot」选项卡,开启「Message Content Intent」开关。
  2. 在代码中初始化Bot时配置intents:
import discord

# 初始化意图
intents = discord.Intents.default()
intents.message_content = True

# 初始化Bot(根据你使用的Bot类型调整,比如commands.Bot)
bot = discord.Bot(intents=intents)

4. 检查机器人权限

确保你的机器人在目标服务器中拥有「读取消息历史」权限,并且目标频道的权限设置允许机器人查看消息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 21:34:52