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

Discord.py Bot开发:_userinfo用户信息查询命令问题求助

解决方案

问题1:获取「用户名#0000」格式的完整标识

你可以直接拼接Member对象的两个内置属性得到目标格式:

  • name:用户的基础用户名
  • discriminator:账号后缀的4位识别码
    拼接代码为 f"{message.author.name}#{message.author.discriminator}",discord.py v2.0及以上版本也可以直接调用 str(message.author) 直接输出该格式。

问题2:获取注册日期与服务器加入日期

两个时间都可以直接从Member对象中读取:

  • Discord账号注册时间:message.author.created_at,返回UTC标准时间的datetime对象
  • 加入当前服务器的时间:message.author.joined_at,同样返回UTC datetime对象,仅服务器场景下可用,私信触发命令时不存在该属性
修正后可直接运行的代码
import datetime

if message.content.startswith("_userinfo"):
    # 过滤私信场景,避免报错
    if not message.guild:
        await message.channel.send("该命令仅支持在服务器内使用")
        return

    target_user = message.author
    # 格式化时间为易读格式
    create_time = target_user.created_at.strftime("%Y-%m-%d %H:%M UTC")
    join_time = target_user.joined_at.strftime("%Y-%m-%d %H:%M UTC")
    full_username = f"{target_user.name}#{target_user.discriminator}"

    emb14 = discord.Embed(
        title=f"{target_user.mention} 的用户信息",
        colour=discord.Colour.dark_blue()
    )
    # 头像用缩略图更符合用户信息卡片的展示逻辑,需要大图可替换为set_image
    emb14.set_thumbnail(url=target_user.avatar_url)
    emb14.add_field(name="完整用户名", value=full_username, inline=True)
    emb14.add_field(name="服务器昵称", value=target_user.nick if target_user.nick else "无", inline=True)
    emb14.add_field(name="注册Discord时间", value=create_time, inline=False)
    emb14.add_field(name="加入本服务器时间", value=join_time, inline=False)

    await message.channel.send(embed=emb14)

注:若你使用的是discord.py v2.0及以上版本,avatar_url属性已被废弃,将其替换为target_user.avatar.url即可正常获取头像链接。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 17:09:02