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

使用Discord.py的channel.history()获取消息ID/内容时遇下标错误

解决Discord.py中Message对象无法下标访问的问题

你遇到的TypeError: 'Message' object is not subscriptable错误,是因为channel.history()返回的是Message类的实例,不是列表、字典这类可通过下标([])访问的结构,不能用message['id']或message[0]这种方式获取属性。

正确获取消息属性的方式

Message对象提供了直接的属性来获取所需信息:

  • 消息ID:message.id
  • 消息内容:message.content
  • 消息作者名称:message.author.name
  • 消息发送时间:message.created_at

修改后的示例代码

把你原代码中的print(message)替换为直接访问属性的代码即可:

token = "你的Token"
import discord
import nest_asyncio
nest_asyncio.apply()
listus = []
listus2 = []

kanal = 1044396925635534848

intents = discord.Intents.default()
intents.message_content = True

client = discord.Client(intents=intents)


@client.event
async def on_ready():
    channel = client.get_channel(kanal)
    async for message in channel.history(limit=200):
        if message.author:
            # 打印消息ID和内容
            print(f"消息ID: {message.id}")
            print(f"消息内容: {message.content}")
            # 如果需要存入列表
            listus.append(message.id)
            listus2.append(message.content)


client.run(token)

补充说明

如果需要批量收集消息数据,直接将message.id或message.content添加到列表即可,无需下标操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 08:35:18