0

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 Answers1

4

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.

Ellisein
  • 878
  • 6
  • 17
  • Thanks for the help, I didn't know about re, but it doesn't work. I got an error on the first line giving me : TypeError: expected string or bytes-like object – Scanderbek123 Feb 25 '19 at 17:51
  • 1
    It also doesn't work for custom emojis not from the server. – Scanderbek123 Feb 25 '19 at 19:13
  • sorry i didn't use `msg.content` instead of `msg`. Because the second argument of `re.findall` is `str`, you should change `msg` to `msg.content`. – Ellisein Feb 26 '19 at 00:19