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

discord.py中查找服务器成员最早消息以估算原始加入日期的方法

解决方案

你调用的member.history()本身用于拉取你和该成员的私信会话历史,自然只会返回私信相关消息。要获取成员在指定服务器内的消息,需要遍历服务器下的所有可访问文本频道,逐个拉取频道历史后筛选指定用户的消息,再取时间最早的条目即可。

示例实现代码

from datetime import datetime
import discord
from discord.ext import commands

# 必须开启消息内容权限,否则无法读取消息发送者等元数据
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)

async def get_guild_member_earliest_message(guild: discord.Guild, member: discord.Member) -> tuple[datetime | None, discord.Message | None]:
    earliest_time = None
    earliest_msg = None
    # 遍历服务器所有文本频道
    for channel in guild.text_channels:
        # 跳过机器人无读历史权限的频道
        if not channel.permissions_for(guild.me).read_message_history:
            continue
        try:
            # 从最早的消息开始拉取当前频道历史
            async for msg in channel.history(limit=None, oldest_first=True):
                if msg.author.id == member.id:
                    # 更新最早消息记录
                    if earliest_time is None or msg.created_at < earliest_time:
                        earliest_time = msg.created_at
                        earliest_msg = msg
                    # 当前频道最早的用户消息已经找到,无需继续遍历该频道
                    break
        except Exception:
            # 跳过无法访问的特殊频道
            continue
    return earliest_time, earliest_msg

使用注意事项

  • 需在Discord开发者后台给机器人开启 Message Content Intent 权限,否则代码无法正常生效
  • 若服务器消息量极大,全频道遍历会有较高耗时,可按需给channel.history添加after参数限定查询时间范围,降低性能开销
  • 该方案存在局限性:如果成员从未在服务器发过消息、或是最早发送的消息已被删除,会返回空结果,可搭配member.joined_at作为兜底估算值使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 08:54:00