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

求助:如何用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会返回空结果。
  • 调用方式错误
    • channel.history是异步方法,必须放在async函数内,用async for遍历,不能直接用同步的for循环。
  • 范围设置问题
    • 如果用户很久没发消息,默认的limit(默认50)可能覆盖不到,适当调大limit值,但不要超过1000(Discord API的单次查询上限),避免触发速率限制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 22:15:36