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

How can I properly parse for a tagged user in my Discord bot?(如何正确解析我的 Discord 机器人中的标记用户?)
本文介绍了如何正确解析我的 Discord 机器人中的标记用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在向我的 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

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do I make a list of all members in a discord server using discord.py?(如何使用 discord.py 列出不和谐服务器中的所有成员?)
how to change discord.py bot activity(如何更改 discord.py 机器人活动)
Issues with getting VoiceChannel.members and Guild.members to return a full list(让 VoiceChannel.members 和 Guild.members 返回完整列表的问题)
Add button components to a message (discord.py)(将按钮组件添加到消息(discord.py))
on_message() and @bot.command issue(on_message() 和@bot.command 问题)
How to edit a message in discord.py(如何在 discord.py 中编辑消息)