Python 我如何在 discord.py 中使用用户 ID 提及用户

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43964328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:34:13  来源:igfitidea点击:

how do i mention a user using user's id in discord.py

pythondiscord.py

提问by Itachi Sama

I'm trying to code a simple bot using discord.py so i started with the fun commands like just to get the hang of the api

我正在尝试使用 discord.py 编写一个简单的机器人,所以我开始使用有趣的命令,例如只是为了掌握 api

import discord
import asyncio
client = discord.Client()


@client.event
async def on_message(message):
    # we do not want the bot to reply to itself
    if message.author == client.user:
        return

    if message.content.startswith('!hug'):
        await client.send_message(message.channel, "hugs {0.author.mention}".format(message))

    # Greetings
    if message.content.startswith('hello'):
        msg = 'Hello {0.author.mention}'.format(message)
        await client.send_message(message.channel, msg)        

    # say (id) is the best
    # This is where I am lost. how to mention someone's name or id ?
    if message.content.startswith('!best'):
        mid = User.id('ZERO#6885').format(message)
        await client.send_message(message.channel, '{mid} mentioned')

回答by Itachi Sama

So I finally figured out how to do this after few days of trial and error hoping others would benefit from this and have less pain than I actually had.. The solution was ultimately easy..

因此,经过几天的反复试验,我终于想出了如何做到这一点,希望其他人能从中受益,并且痛苦比我实际的痛苦要少.. 解决方案最终很简单..

  if message.content.startswith('!best'):
        myid = '<@201909896357216256>'
        await client.send_message(message.channel, ' : %s is the best ' % myid)

回答by JayTurnr

If you're working on commands, you're best to use discord.py's built in command functions, your hug command will become:

如果您正在处理命令,最好使用 discord.py 的内置命令函数,您的拥抱命令将变为:

import discord
from discord.ext import commands

@commands.command(pass_context=True)
async def hug(self, ctx):
    await self.bot.say("hugs {}".format(ctx.message.author.mention()))

This is assuming you've done something like this at the start of your code:

这是假设您在代码开始时已经完成了这样的操作:

def __init__(self):
    self.bot = discord.Client(#blah)

回答by Peter G

From a Userobject, use the attribute User.mentionto get a string that represents a mention for the user. To get a user object from their ID, you need Client.get_user_info(id). To get the a user from a username ('ZERO') and discriminator ('#6885') use the utility function discord.utils.get(iterable, **attrs). In context:

User对象中,使用该属性User.mention获取表示用户提及的字符串。要从用户的 ID 中获取用户对象,您需要Client.get_user_info(id). 要从用户名 ('ZERO') 和鉴别器 ('#6885') 中获取用户,请使用效用函数discord.utils.get(iterable, **attrs)。在上下文中:

if message.content.startswith('!best'):
    user = discord.utils.get(message.server.members, name = 'ZERO', discriminator = 6885)
    # user = client.get_user_info(id) is used to get User from ID, but OP doesn't need that
    await client.send_message(message.channel, user.mention + ' mentioned')

回答by abccd

To mention an user and have their username to display (not their id), you'll need to add a !to the accepted self-answer.

要提及用户并显示他们的用户名(而不是他们的 ID),您需要!在接受的自我回答中添加一个。

await client.send_message(message, '<@!20190989635716256>, hi!')

When you only have the id and not the Member or User object, I'd recommend against using Peter G's answer where they used get()or get_user_info(id)to actually fetch the User/Member object first. These operations are very time consuming and not needed since .mentiononly return this very string.

当您只有 id 而不是 Member 或 User 对象时,我建议不要在他们使用的地方使用 Peter G 的答案,get()或者get_user_info(id)首先实际获取 User/Member 对象。这些操作非常耗时并且不需要,因为.mention只返回这个字符串。

回答by lustig

If you just want to respond from the on_message callback, you can grab the mention string from the author like so:

如果您只想从 on_message 回调中响应,您可以像这样从作者那里获取提及字符串:

@bot.event
async def on_message(message):
    # No infinite bot loops
    if message.author == bot.user or message.author.bot:
        return

    mention = message.author.mention
    response = f"hey {mention}, you're great!"
    await message.channel.send(response)

回答by user2863294

While OP's issue is long resolved (and likely forgotten) -- If you're building a Discord bot in Python, it's still a bit difficult to find this information - hopefully this helps someone. If you're trying to use the @bot.command method - the following will work (in python3):

虽然 OP 的问题早已解决(并且可能被遗忘)——如果你正在用 Python 构建一个 Discord 机器人,找到这些信息仍然有点困难——希望这对某人有所帮助。如果您尝试使用 @bot.command 方法 - 以下将起作用(在 python3 中):

@bot.command(name='ping', help='Ping the bot to text name')
async def ping(ctx):
    await ctx.send('Pong ' + format(ctx.author))
    print("debug: " + dir(ctx.author))

If you want to display the nicknameof the "author" (who called the command) you can use this instead":

如果你想显示“作者”(谁调用命令)的昵称,你可以使用这个代替“:

@bot.command(name='ping', help='Ping the bot to text name')
async def ping(ctx):
    # await ctx.send('Pong {0}'.format(ctx.author))
    await ctx.send('Pong ' + format(ctx.author.display_name))
    print("debug: " + dir(ctx.author))

Another helpful tip: You can use dir(ctx.author)to see the attributesof the ctx.authorobject.

另一个有用的提示:您可以使用dir(ctx.author)看到属性的的ctx.author对象