如何用Python获取Discord指定频道最早消息?解决代码报错问题
解决Discord Bot获取频道最早消息的异步错误问题
错误原因解析
RuntimeWarning: coroutine 'getfirstmessage' was never awaited
直接调用异步函数但未使用await关键字,异步函数调用后返回协程对象,必须通过await等待其执行完成。SyntaxError: 'await' outside function
await关键字只能在async def定义的异步函数内部使用,不能在全局作用域或普通函数中直接使用。
修正后的完整代码
import discord from discord import Client # 替换为你的Bot令牌、目标服务器ID和频道ID BOT_TOKEN = "你的Bot令牌" GUILD_ID = 1234567890 # 替换成实际服务器ID CHANNEL_ID = 0987654321 # 替换成实际频道ID client = Client(intents=discord.Intents.all()) async def get_first_message(): # 获取目标服务器 guild = client.get_guild(GUILD_ID) if not guild: print("无法找到指定服务器") return # 获取目标频道 channel = guild.get_channel(CHANNEL_ID) if not channel: print("无法找到指定频道") return # 拉取频道最早的1条消息 messages = [message async for message in channel.history(limit=1, oldest_first=True)] if messages: msg = messages[0] print(f"最早消息内容: {msg.content}") print(f"发送者: {msg.author.name}") print(f"发送时间: {msg.created_at}") else: print("该频道暂无消息") @client.event async def on_ready(): print(f"已登录为: {client.user}") # 在Bot登录完成后调用异步函数获取消息 await get_first_message() # 获取消息后自动退出Bot await client.close() # 启动Bot client.run(BOT_TOKEN)
关键修正点
- 必须在异步上下文(如
on_ready事件函数,由discord.py异步触发)中使用await调用get_first_message - 等待Bot完成登录后再执行频道和消息查询,否则
get_guild/get_channel会返回None - 新增服务器和频道存在性检查,避免空对象报错
- 通过
client.close()在获取消息后自动终止Bot运行
内容的提问来源于stack exchange,提问作者Ian Weed
相关产品推荐
相关产品推荐

