translatomat/main.py

93 lines
2.7 KiB
Python

import os
import googletrans
import discord
from discord import app_commands
from discord.ext import commands
discord_bot_token = os.environ['TOKEN_DISCORD']
intents = discord.Intents.all()
bot_client = discord.Client(intents=intents)
tree = app_commands.CommandTree(bot_client)
"""
My Bots Overview:
https://discordapp.com/developers/applications
Discord Bot API Documentation:
https://discordpy.readthedocs.io/en/latest/api.html
Changelog:
https://discordpy.readthedocs.io/en/latest/whats_new.html
"""
###
# Discord Events
###
@bot_client.event
async def on_ready():
print("Discord.py version {}".format(discord.__version__))
print("googletrans version {}".format(googletrans.__version__))
await tree.sync()
await bot_client.change_presence(activity=discord.Game(name="Translating only for you!"))
@bot_client.event
async def on_message(ctx: discord.Message):
if ctx.author.bot:
return
translator = googletrans.Translator()
detected_language = translator.detect(ctx.content)
detected_language = detected_language.lang
translator_category = discord.utils.find(lambda c: c.name == "Translatomat", ctx.guild.categories)
for channel in translator_category.channels:
language_to_translate_to = channel.name
if detected_language != language_to_translate_to:
translated_message = translator.translate(str(ctx.clean_content), language_to_translate_to).text
if str(ctx.clean_content).lower() == str(translated_message).lower():
return
embed = discord.Embed(color=0x04a1ff)
embed.add_field(name="Translated Message", value=translated_message, inline=False)
embed.add_field(name="Original Message", value=ctx.content, inline=False)
embed.add_field(name="Author", value=ctx.author.mention, inline=True)
embed.add_field(name="Channel", value=ctx.channel.mention, inline=True)
embed.add_field(name="Message Link", value=ctx.jump_url, inline=True)
await channel.send(embed=embed)
await bot_client.process_commands(ctx)
###
# Commands
###
@bot_client.command(name="translate", aliases=['t'], pass_content=True)
async def __command_translate(ctx: commands.Context, language: str, *text: str):
try:
translator = googletrans.Translator()
message_text = " ".join(text)
translated_text = translator.translate(message_text, language).text
await ctx.reply(translated_text)
except:
await ctx.reply("Error: Translation failed somehow\n"
"Format has to be: +translate [language] [text]")
if __name__ == "__main__":
bot_client.run(discord_bot_token )