如何正确解析我的 Discord 机器人中的标记用户?

2022-01-15 00:00:00 python python-3.x string discord discord.py

问题描述

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

I am adding profile cards onto my Discord bot, but I've come across one issue. When someone types !profile @user I am not sure how to properly parse for @user so the bot knows which profile card to lookup.

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

I first parse message.content and then remove the 9 first chars of the message content (which is always !profile) but the rest of the message content returns the user_id which looks <@289583108183948460> instead of the user's discrim. I have tried using re.sub to remove the special characters (@, >, and <) like this:

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

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

But the weird characters are still there when I only want the number so I can search it in the database easily. I'm sure there's a way better way to do this though but I can't figure it out.


解决方案

discord.py 的消息对象包含 Message.mentions 属性,因此您可以遍历 Member.以下是 async 和 的文档列表href="https://discordpy.readthedocs.io/en/rewrite/api.html#discord.Message.mentions" rel="nofollow noreferrer">重写.

discord.py's message objects include a Message.mentions attribute so you can iterate over a list of Member. Here are the doc listings for async and rewrite.

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

With this you can simply iterate over the mentions as so:

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

你真正想要的

discord.py 允许您从带有 discord.Member 对象"nofollow noreferrer">类型提示.只需将以下内容添加到命令中

what you actually want

discord.py allows you to grab discord.Member objects from messages with type hinting. simply add the following to the command

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

相关文章