如何使用discord.py读取线程中的消息?
获取Discord线程消息的方法
在discord.py中,你不需要通过创建线程的消息直接调用fetch_messages(),正确的做法是利用该消息的thread属性获取对应的线程对象,再通过线程对象的history()方法获取消息历史,和操作普通频道一致。
修改你的代码如下:
async for message in channel.history(after=start, before=end): if message.type == discord.MessageType.public_thread: # 获取创建的线程对象 thread = message.thread # 遍历线程内的消息 async for thread_msg in thread.history(after=start, before=end): # 处理线程消息,例如打印内容 print(thread_msg.content)
变通方案:通过线程ID直接获取线程
如果已知线程ID,也可以跳过遍历频道消息的步骤,直接从频道中获取线程:
# 替换为实际的线程ID thread_id = 123456789012345678 # 从当前频道获取线程对象 thread = await channel.fetch_thread(thread_id) # 读取线程消息历史 async for msg in thread.history(limit=100): print(msg.content)
注意:确保你的discord.py版本为2.0及以上,旧版本对线程的支持存在缺失。
内容的提问来源于stack exchange,提问作者belkarx
相关产品推荐
相关产品推荐

