求助:如何用discord.py获取服务器内用户的最新消息?
获取Discord服务器指定用户最新消息的解决方案
先给你能直接运行的代码示例,适配Discord.py v2.x版本:
import discord from discord.ext import commands # 初始化Bot,必须开启对应意图 intents = discord.Intents.default() intents.message_content = True intents.guild_messages = True bot = commands.Bot(command_prefix='!', intents=intents) @bot.event async def on_ready(): # 替换成你的目标频道ID和用户ID target_channel_id = 123456789012345678 target_user_id = 876543210987654321 channel = bot.get_channel(target_channel_id) if not channel: print("目标频道不存在,请检查ID是否正确") await bot.close() return # 遍历频道历史,找指定用户的最新消息 async for msg in channel.history(limit=200): # 可根据需求调整查询范围 if msg.author.id == target_user_id: print(f"找到最新消息:\n内容:{msg.content}\n发送时间:{msg.created_at}") await bot.close() return print("在指定历史范围内未找到该用户的消息") await bot.close() # 替换成你的Bot令牌 bot.run('YOUR_BOT_TOKEN_HERE')
常见问题排查
- 权限与意图问题
- 必须在Discord开发者后台的Bot页面开启
Message Content Intent和Server Members Intent,代码里也要同步声明这些意图,否则无法读取消息内容和用户信息。 - 确保Bot在目标服务器拥有
查看频道和读取消息历史的权限,否则channel.history会返回空结果。
- 必须在Discord开发者后台的Bot页面开启
- 调用方式错误
channel.history是异步方法,必须放在async函数内,用async for遍历,不能直接用同步的for循环。
- 范围设置问题
- 如果用户很久没发消息,默认的
limit(默认50)可能覆盖不到,适当调大limit值,但不要超过1000(Discord API的单次查询上限),避免触发速率限制。
- 如果用户很久没发消息,默认的
内容的提问来源于stack exchange,提问作者Unparalleled Innocence
相关产品推荐
相关产品推荐

