如何在Discord机器人中正确解析标记的用户? [英] How can I properly parse for a tagged user in my Discord bot?

查看:112
本文介绍了如何在Discord机器人中正确解析标记的用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将配置卡添加到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 ),但其余消息内容返回看起来像< @ 289583108183948460> 的user_id,而不是用户的辨别力。我尝试使用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 属性,因此您可以遍历成员的列表。这是 async 重写

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 对象/ peps / pep-0484 / rel = 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

这篇关于如何在Discord机器人中正确解析标记的用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆