0

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.

Mike
  • 17
  • 5
  • Please dont spam the site by just sharing code since its a platform to help others by asking a question and getting a answer. – boez Aug 27 '23 at 01:57

1 Answers1

0
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))
Mike
  • 17
  • 5
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Diego Borba Aug 28 '23 at 13:05