如何在Discord.py开发中获取服务器成员的加入日期?
Discord.py 获取成员加入服务器日期实现方案
前置配置
你需要先开启成员网关意图,否则无法获取成员的加入日期属性:
- 前往Discord开发者后台的对应Bot设置页,在「Privileged Gateway Intents」分类下开启
Server Members Intent开关 - 代码实例化Bot时显式开启成员意图:
import discord from discord.ext import commands intents = discord.Intents.default() intents.members = True # 必须开启,否则无法获取成员加入时间 intents.message_content = True # 适配前缀指令读取消息内容需要 bot = commands.Bot(command_prefix="r!", intents=intents)
核心实现
Discord.py的discord.Member对象自带joined_at属性,直接调用即可获取成员加入当前服务器的UTC时间,返回值为Python标准datetime.datetime类型,可自行格式化输出格式。
完整的r!info user指令示例:
@bot.command(name="info") async def get_user_info(ctx, user: discord.Member = None): # 未指定用户时默认返回指令调用者的信息 user = user or ctx.author # 格式化加入时间 join_time = user.joined_at.strftime("%Y-%m-%d %H:%M:%S") + " UTC" # 其他你需要返回的用户信息可以在这里补充,比如账号注册时间是user.created_at await ctx.send(f""" 用户:{user.mention} 用户名:{user.name} 用户ID:{user.id} 加入服务器时间:{join_time} """)
常见问题排查
- 若
joined_at返回None:确认已按上述步骤开启Server Members Intent,且Bot在服务器内拥有足够权限 - 时间时区不符:可通过
user.joined_at.astimezone()方法转换为你需要的本地时区时间
内容的提问来源于stack exchange,提问作者Tushar Singh
相关产品推荐
相关产品推荐

