Search code examples
pythondiscorddiscord.pycommandemoji

Trying to make my bot create the chosen emojis into the server


how do i code a bot where running the command $steal (emoji) triggers the bot to automatically create the emoji into the server the command was run in. (BY EMOJIS I MEAN DISCORD EMOJIS - THE ONES YOU NEED NITRO TO USE)

@bot.command(brief='Allows you to steal an emoji', description='Will return the image file for a requested emoji', usage='[emoji](can be from anywhere and animated if you have nitro)')
async def steal(ctx, emoji: discord.PartialEmoji):   
    await ctx.send(emoji.url)

I coded this expecting it to create the emojis in the server but instead it just sent me the image of the emoji rather than adding it to the servers emojis.


Solution

  • You can use the create_custom_emoji function to create the emoji. You will also need to install and import aiohttp to make asynchronous requests. We use that for downloading the emoji image and using the image bytes to create the new emoji.

    @bot.command(brief='Allows you to steal an emoji', description='Will return the image file for a requested emoji', usage='[emoji](can be from anywhere and animated if you have nitro)')
    @client.command()
    async def steal(ctx, emoji: discord.PartialEmoji):
        guild = ctx.guild
        async with aiohttp.ClientSession() as session:
            async with session.get(emoji.url) as response:
                data = await response.content.read()
                created_emoji = await guild.create_custom_emoji(
                    name=emoji.name,
                    image=data,
                    reason="Created from command"
                )
                await ctx.send(created_emoji)
    

    I've tested this and it works. The bot will need the manage_emojis permission in the guild. Not sure what's going to happen if an emoji exists with the name already but you'll have to figure that out! Tested it with animated emojis as well and it's fine.