获取被标记用户的用户 ID

Getting the userid of a user that was tagged

我正在使用 discordpy 构建一个 discord 机器人。我希望它具有的功能之一是能够给出有关用户的随机百分比。

示例:

用户 1: !w @user2

机器人:@user2 是 x% y

我不确定如何从user1发送的消息中提取user2的userid。有人有什么建议吗?

你在标题中提出了一个问题,但描述与它不符;-;

根据您在描述中的要求,这里是一个基本代码,您可以根据自己的喜好进行自定义:)

确保将 'client' 替换为您使用过的任何内容

@client.command()
async def cool(ctx, user: discord.Member = None):
    pctg = (random.randint(0, 100))
    if user == None:
        await ctx.send('Mention a user')
    else:
        await ctx.send(f"{user.name} is {pctg}% cool")

如果您希望将提到的用户 ID 作为机器人的回复,请使用以下 -

@client.command()
async def uid(ctx, user: discord.Member):
    uid = user.id
    await ctx.send(uid)

您可以使用 id attribute of discord.Member.

示例:

@bot.command()
def w(ctx, user: discord.Member):
    user_id = user.id
    print(user_id)

@client.event
async def on_message(message):
    if message.content.startswith('w!cool '):
        if message.mentions == []:
            await message.channel.send("You should mention someone!\n```\nw!cool <mention>\n```")
            return
        coolness_tosend=""
        for i in message.mentions:
            coolness_tosend=coolness_tosend+"<@" + str(i.id) + "> is " + str(random.choice(range(100))) + "\% cool.\n"
        await message.channel.send(coolness_tosend)

链接:

discord.Message.mentions in API reference

discord.Message in API reference

但请注意,仅 w!cool 不带参数是行不通的。它可以防止与 w!coolpic 等命令发生冲突。不要忘记做一个 import random!