从 discord.py 中的提及中获取用户 ID

时间:2021-06-30 05:19:30

标签: python discord discord.py

当我尝试使用以下代码运行命令 $getUserId @user 时,它按预期工作,但在尝试传递参数时发送类似 $getUserId 123 的内容时会出现错误。 我想要一个不会出错的机器人。

import discord

client = commands.Bot(command_prefix = "$")

@client.command()
async def getUserId(ctx, *user: discord.User):
if not arg:
    userId = ctx.author.id
else:
    userId = arg.id
await ctx.send(userId)

我将如何处理这个问题:将提到的用户作为参数并在给出 $getUserId 命令时处理所有异常?

是否有更简单的方法可以从提及中获取用户 ID?必须有一个简单的方法来做到这一点,对吧? 无论如何,非常感谢所有帮助。

2 个答案:

答案 0 :(得分:0)

如果问题或代码中有错误,但您的缩进混乱且 arg 不存在,请确认


def convert_mention_to_id(mention):
    return int(mention[1:][:len(mention)-2].replace("@","").replace("!",""))

@client.command(name="getUserId")
async def getUserId(ctx ,*arg):
    if not arg:
        await ctx.send(ctx.author.id)
    else:
        try:
            await ctx.send({i:convert_mention_to_id(arg[i]) for i in arg})
        except ValueError:
            await ctx.send("Invalid ID")

convert_mention_to_id 是一个实用函数,提及以 <@!id> 格式传递,该函数只是从中获取 id。

该 ID 在 discord API 中用作 int,因此它会在传递无效 ID 时引发值错误的函数中进行转换

您可以使用 client.get_user() 获取提到的用户,但它需要成员意图是真实的

答案 1 :(得分:0)

您的代码有一些问题。

  1. 使用 arg:您没有在您提供的代码中的任何地方定义 arg。相反,将 arg 替换为 user。
  2. 如果不是用户:如果您将用户留空,则会引发错误,例如“用户是缺少的必需参数”。解决此问题的一种方法是将其默认为 None

您可以在下面的代码以及经过测试的示例中查看上述观察结果。

@client.command()
async def getUserId(ctx, user: discord.User=None): # defaults user to None if nothing is passed
    if not user: # you are not using an arg variable, you're using user
        userId = ctx.author.id
    else:
        userId = user.id # same as previous
    await ctx.send(userId)

Code working