You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Discord.py中如何获取斜杠命令调用用户的ID?

解决斜杠命令中获取用户ID的AttributeError问题

你遇到的问题核心在于:斜杠命令的上下文(SlashContext)并不包含message属性。普通文本命令里的ctx.message对应触发命令的消息对象,但斜杠命令是通过Discord的交互系统触发的,不存在传统意义上的"消息",所以ctx.message的值是None,访问它的author属性自然会抛出'NoneType' object has no attribute 'author'的错误。

正确的获取方式

直接通过ctx.author.id就能拿到触发斜杠命令的用户ID,另外发送消息时记得把ID转为字符串(Discord的消息接口要求传入字符串类型)。

修正后的完整代码

slash = SlashCommand(Bot,sync_commands=True)
@slash.slash(
    name="getid",
    description="获取用户ID",
    guild_ids=[guild id here]
)
async def _getid(ctx:SlashContext):
    author_id = ctx.author.id
    await ctx.send(str(author_id))

补充说明

  • SlashContextauthor属性直接对应触发交互的用户对象,和普通命令里ctx.message.author指向的是同一个用户,但获取路径更直接。
  • 如果需要用户的其他信息(比如用户名、头像链接),也可以通过ctx.author访问,例如ctx.author.namectx.author.avatar.url等。

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

火山引擎 最新活动