问题
I'm fairly new at using python and I'm trying to code a discord bot with basics functions, and I want for one of them to be that after someone uses a prefix if they post an emoji that the bot replies with the url of the emoji, but I have trouble trying to make it work. I don't know how to use on_message to check if a message contains an emoji. Could anyone help me? Thanks.
#if message.content[0] == "!" and message.content[1:4] == " <:":
#print(message.content[4:-1])
#emoji_name = ""
#for i in str(message.content[4:-1]):
#if i != ":":
#emoji_name += i
#if i == ":":
#print(emoji_name)
#break
#await client.send_message(message.channel, get(client.get_all_emojis(), name=emoji_name).url)
回答1:
Discord custom emoji has a form of <:name:id>
. So if you use re
, Python regex library, you can find all the custom emojis in the given message.
import re
import discord
@client.event
async def on_message(msg):
custom_emojis = re.findall(r'<:\w*:\d*>', msg.content)
custom_emojis = [int(e.split(':')[1].replace('>', '')) for e in custom_emojis]
custom_emojis = [discord.utils.get(client.get_all_emojis(), id=e) for e in custom_emojis]
# From now, `custom_emojis` is `list` of `discord.Emoji` that `msg` contains.
I didn't test this code now, but i used this method before and found it worked. So please give me feedback if this doesn't work, then i will find if i mis-typed.
来源:https://stackoverflow.com/questions/54859876/how-check-on-message-if-message-has-emoji-for-discord-py