【问题标题】:How do I get the ID of an user in Discord.py如何在 Discord.py 中获取用户的 ID
【发布时间】:2019-04-02 19:35:59
【问题描述】:

我们正在为我们的 Discord 服务器编写一个机器人,它应该提到启动特定命令的人。为此,我需要用户的 ID,但不知道如何获取它。

@bot.command()
async def name():

author = discord.User.id

await bot.say(str(author))

我们尝试过这种方式,因为文档说,用户的 ID 在 User 类中。但我们唯一得到的是

<member 'id' of 'User' objects>

在我们看来,我们获得了正确的参数,但无法获得 ID 本身?我们需要以某种方式转换它吗?

【问题讨论】:

  • 如果你想提及一个用户,你可以直接使用user.mention得到一个字符串,当包含在一个消息中时会提及这个用户。
  • discord.User.id 没有获得id 类实例的id,而是从基类本身获得该属性。您需要正确实例化User 对象,并从它的实例中读取值。如果您还没有实例化它,您如何期望您的代码甚至知道您想要哪个用户的 ID?
  • @PatrickHaugh 在这两种情况下,我都只得到“ctx 是缺少的必需参数”。
  • @RandomDavis 正如它所说,我期待作者的 ID。我想,它会返回发送消息的用户的 ID。

标签: python python-3.x discord discord.py


【解决方案1】:

要让机器人在异步分支中提及消息的作者,您需要通过调用命令的消息ctx.message 来引用该作者:

@bot.command(pass_context=True)
async def name(ctx):
    await bot.say("{} is your name".format(ctx.message.author.mention))

要获取他们的 ID:

@bot.command(pass_context=True)
async def myid(ctx):
    await bot.say("{} is your id".format(ctx.message.author.id))

【讨论】:

  • 好的,我们也有这个版本,但似乎我打错了。在这里工作正常并解释了很多。感谢您的解决方案和帮助。
【解决方案2】:

您需要在函数名中提供一个参数。每个 bot.command 都需要至少有一个称为“上下文”的参数。如:

async def name(ctx):
   author = ctx.message.author
   user_name = author.name

【讨论】:

  • 试过这个并得到“命令引发异常:AttributeError:'str'对象没有属性'author'
  • 对此进行了调整以包含消息参数。再试一次
猜你喜欢
  • 2021-05-07
  • 2019-04-01
  • 2020-09-07
  • 1970-01-01
  • 2021-07-18
  • 2017-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多