How can I properly parse for a tagged user in my Discord bot?

你说的曾经没有我的故事 提交于 2019-12-13 00:53:09

问题


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.

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.


回答1:


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

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


来源:https://stackoverflow.com/questions/48174271/how-can-i-properly-parse-for-a-tagged-user-in-my-discord-bot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!