How do I make a Discord bot respond to a message with a custom emoji in on_message

Viewed 3315

How am I able to make my bot respond when a cutstom server emoji is in the string?
My code currently looks like this:

if message.content.startswith(":emoji: Hello"):
      await client.get_channel(123456789).send("Hello to you, too!")

If I post the emoji and the sentence in Discord, the command won't trigger. What do I need to change?

1 Answers

When using a custom emoji, it has a unique ID, and this is what appears in the message's content, not just the name of the emoji. You can access this in a couple of different ways, but the easiest might be \:emoji:, which you can see working here:

enter image description here

enter image description here

enter image description here


And the final part is what the message's content is going to contain. So in my case, the correct statement would look like:

if message.content.lower().startswith("<:statue:709925980029845565> hello"):
    await message.channel.send("Hello to you too!") # sends to the same channel the message came from

You can also retrieve the emoji without using its ID:

emoji = discord.utils.get(message.guild.emojis, name="statue")
if message.content.lower().startswith(f"{emoji} hello"):
    await message.channel.send("Hello to you too!")

Note that I also used .lower() which makes the command case-insensitive, so it'll work whether the user types HelLo, HELLO or hElLo


References:

Related