Answer | Code for translator in disnake.py

50 Views Asked by At

I just want to share and help others with my code that translates any sentences.

This code is written in cog, so it looks the way it looks.

  1. In the console of your computer, add this:

pip install googletrans==4.0.0-rc1

  1. Then just create a cog file under the name translatorcmd.py (or whatever you want) and paste the code into this file and enjoy the new command in your bot.

I hope I am not violating any rules of the site agreement, if so, I apologize immediately and will do what is necessary, thank you.

1

There are 1 best solutions below

1
Mike On
import disnake
from disnake.ext import commands
import aiohttp
from googletrans import Translator, LANGUAGES, LANGCODES

class TranslatorCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.translator = Translator()

    @commands.slash_command(description="Translator")
    async def translate(self, inter, target_lang: str, *, text: str):
        try:
            translated = self.translator.translate(text, dest=target_lang)
            source_lang = translated.src
            translated_text = translated.text

            embed = disnake.Embed(
                title="Translator",
                color=disnake.Color.orange()
            )
            embed.add_field(name='Input text:', value=f"`{text}`", inline=True)
            embed.add_field(name=' ', value=f" ", inline=True)
            embed.add_field(name='Translated text:', value=f"`{translated_text}`", inline=True)
            embed.set_thumbnail(url="https://cdn-icons-png.flaticon.com/512/3486/3486794.png")

            await inter.response.send_message(embed=embed)

        except Exception:
            embed = disnake.Embed(
                title="The text could not be translated.",
                color=disnake.Color.red()
            )
            embed.set_author(name=f'Error using the command', icon_url="https://cdn-icons-png.flaticon.com/512/10207/10207468.png")
            embed.add_field(name='Example of using the command:', value=f"`/translate target_lang:ru text:How are you?`", inline=True)
            embed.add_field(name='Frequently used language codes:', value="en - English\npl - Polish\nde - German", inline=False)

            await inter.response.send_message(embed=embed, ephemeral=True)

def setup(bot):
    bot.add_cog(TranslatorCog(bot))