我只是想分享和帮助其他人使用我的翻译任何句子的代码。
这段代码是用 cog 编写的,所以看起来就像它看起来的样子。
pip 安装 googletrans==4.0.0-rc1
我希望我没有违反网站协议的任何规则,如果是这样,我立即道歉并会采取必要的措施,谢谢。
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))