【问题标题】:How can I properly parse for a tagged user in my Discord bot?如何正确解析我的 Discord 机器人中的标记用户?
【发布时间】:2018-06-18 20:19:50
【问题描述】:

我正在向我的 Discord 机器人添加个人资料卡,但我遇到了一个问题。当有人键入!profile @user 时,我不确定如何正确解析@user,以便机器人知道要查找哪个个人资料卡。

我首先解析 message.content,然后删除消息内容的前 9 个字符(始终为 !profile),但消息内容的其余部分返回看起来为 <@289583108183948460> 的 user_id,而不是用户的区分。我曾尝试使用 re.sub 删除特殊字符(@、> 和

a = str(message.content[9:])
removeSpecialChars = re.sub("[!@#$%^&*()[]{};:,./<>?\|`~-=_+]", " ", a)
print(removeSpecialChars)

但是当我只想要数字时,奇怪的字符仍然存在,因此我可以轻松地在数据库中搜索它。我确信有更好的方法可以做到这一点,但我想不通。

【问题讨论】:

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


    【解决方案1】:

    discord.py 的消息对象包含一个Message.mentions 属性,因此您可以遍历Member 的列表。以下是 asyncrewrite 的文档列表。

    有了这个,你可以简单地迭代提及:

    for member in ctx.message.mentions:
        # do stuff with member
    

    你真正想要的

    discord.py 允许您从带有type hinting 的消息中获取discord.Member 对象。只需将以下内容添加到命令中

    @bot.command()
    async def profile(ctx, member: discord.Member=None):
        member = member or ctx.message.author
    

    【讨论】:

      猜你喜欢
      • 2021-01-02
      • 2021-03-23
      • 1970-01-01
      • 2021-02-24
      • 2021-04-14
      • 2021-09-15
      • 2018-06-07
      • 1970-01-01
      • 2021-12-18
      相关资源
      最近更新 更多