【问题标题】:How do I mention a user in discord.py?如何在 discord.py 中提及用户?
【发布时间】:2017-10-13 08:14:41
【问题描述】:

我正在尝试使用 discord.py 编写一个简单的机器人,所以我从有趣的命令开始熟悉这个库。

import discord

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 message.channel.send(f"hugs {message.author.mention}")

    if message.content.startswith('!best'):
        user_id = "201909896357216256"
        user_mention = ???  # How to convert user_id into a mention
        await message.channel.send(f'{user_mention} is the best')

【问题讨论】:

    标签: python discord.py


    【解决方案1】:

    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')
    

    【讨论】:

    • 文件“\client.py”,第 307 行,在 _run_event 中从 getattr(self, event)(*args, **kwargs) 文件“bot.py”,第 39 行,on_message id = User.id('ZERO#6885').format(message) # 或者你正在做什么来获取 id NameError: name 'User' is not defined
    • 嗯,是的,您获取 id 的方法不起作用——抱歉,我没有说得更清楚。我将用一种有效的方法进行编辑
    • @ItachiSama 进一步阅读后,您实际上没有用户的 ID:您有他们的用户名和鉴别器。我已经更改了代码以反映这一点,并留下了如果您在评论中有 ID 时可以使用的方法。
    • 我非常感谢你所做的所有努力,但实际上我花了 5 多个小时阅读文档和在线搜索只是提到一个 id 或用户名,新代码给了我这个错误忽略 on_message Traceback 中的异常(最后一次调用):文件“C:\Python35\lib\site-packages\discord\client.py”,第 307 行,在 getattr(self, event)(*args, * *kwargs) 文件“it.py”,第 48 行,on_message 等待 client.send_message(message.channel, user.mention() + '提到') AttributeError: 'NoneType' 对象没有属性 'mention'
    • 似乎 ZERO#6885 在您的机器人所在的服务器上不在线。根本不可能提及不在线的人(至少以编程方式)。
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      如果你在处理命令,最好使用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()))
      

      这是假设您在代码的开头做了类似的事情:

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

      【讨论】:

      • 我在尝试使用 .author.mention() 发送消息时遇到了这个错误:await coro(*args, **kwargs) File "alfred-bot.py", line 69, in on_message TypeError: 'str' object is not callable,但解决了从提及中删除 () 的问题
      【解决方案4】:

      discord.py 1.x - 2.x (2021) 的更新答案:

      其他一些解决方案现在已经过时,因为 discord.py 的语法已经改变,旧版本不再有效。

      如果您只有用户 ID,那么它是:

      user_id = "201909896357216256"
      await message.channel.send(f"<@{user_id}> is the best")
      

      如果你有用户/成员对象,那么它是:

      await message.channel.send(f"{user.mention} is the best")
      

      如果您只有用户名和鉴别器(机器人和用户必须共享服务器并且必须打开成员缓存):

      user = discord.utils.get(client.users, name="USERNAME", discriminator="1234")
      if user is None:
          print("User not found")
      else:
          await message.channel.send(f"{user.mention} is the best")
      

      如果使用命令而不是on_message 时有ctx,请替换message.channel

      【讨论】:

        【解决方案5】:

        如果你只是想从 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)
        

        【讨论】:

          【解决方案6】:

          虽然 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))
          

          如果您想显示“作者”(调用该命令的人)的昵称,您可以使用它来代替“:

          @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))
          

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2023-03-24
            • 2019-04-01
            • 2020-09-07
            • 2021-02-19
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-01-25
            相关资源
            最近更新 更多