简体   繁体   中英

How can I convert a string with the emoji name into a discord emoji?

Let's say I have a string with an emoji name, for example emoji = 'fishing_pole_and_fish' .

Is there a way to do msg.add_reaction(emoji) without getting the error:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 10014): Unknown Emoji

Or can I convert the string to a discord.Emoji ?

I know I could use '\\N{FISHING POLE AND FISH}' , but I need it as 'fishing_pole_and_fish' so I can do other things with it. Also, fishing pole and fish is just an example emoji

Have you looked in to the emoji module ?

For the bot to be able to react with the standard built in emojis, it needs the emojis to be the symbol "🎣 ", not ":fishing_pole:", that only works with custom emojis <:name:id> .

import emoji

string = ":fishing_pole:"
demoji = emoji.demojize("🎣 ")   # This takes the emoji and gives--> :fishing_pole:
emoji = emoji.emojize(string)    # This takes :fishing_pole: and gives--> 🎣    
print(demoji)
print(emoji)

It does require having ":" on either side, otherwise it wont work. But that you can add with ''.join(":"+string+":") if needed

You can use the unicodedata.lookup function:

from unicodedata import lookup

def emoji_from_name(name):
    return lookup(name.replace("_", " "))

For custom emojis in the guild you can use this. keep in mind you must have the emoji in the guild.

emoji = discord.utils.get(ctx.guild.emojis, name="CUSTOM EMOJI NAME")

Other alternative is to use the bot.get_emoji which takes the id of the emoji, you can use this to have across guild custom emojis

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM