fix merge conf

Kaveen Kumarasinghe 2 years ago
commit f3fbdfb6bc

@ -3,10 +3,15 @@ from pycord.multicog import add_to_group
from services.environment_service import EnvService from services.environment_service import EnvService
from models.check_model import Check from models.check_model import Check
from models.autocomplete_model import Settings_autocompleter, File_autocompleter, Translations_autocompleter from models.autocomplete_model import (
Settings_autocompleter,
File_autocompleter,
Translations_autocompleter,
)
ALLOWED_GUILDS = EnvService.get_allowed_guilds() ALLOWED_GUILDS = EnvService.get_allowed_guilds()
class Commands(discord.Cog, name="Commands"): class Commands(discord.Cog, name="Commands"):
"""Cog containing all slash and context commands as one-liners""" """Cog containing all slash and context commands as one-liners"""
@ -507,33 +512,55 @@ class Commands(discord.Cog, name="Commands"):
""" """
Translation commands and actions Translation commands and actions
""" """
@discord.slash_command(name="translate", description="Translate text to a given language", guild_ids=ALLOWED_GUILDS,
checks=[Check.check_translator_roles()], @discord.slash_command(
) name="translate",
description="Translate text to a given language",
guild_ids=ALLOWED_GUILDS,
checks=[Check.check_translator_roles()],
)
@discord.option(name="text", description="The text to translate", required=True) @discord.option(name="text", description="The text to translate", required=True)
@discord.option(name="target_language", description="The language to translate to", required=True, autocomplete=Translations_autocompleter.get_languages) @discord.option(
name="target_language",
description="The language to translate to",
required=True,
autocomplete=Translations_autocompleter.get_languages,
)
@discord.guild_only() @discord.guild_only()
async def translate(self, ctx: discord.ApplicationContext, text: str, target_language: str): async def translate(
self, ctx: discord.ApplicationContext, text: str, target_language: str
):
if self.translations_cog: if self.translations_cog:
await self.translations_cog.translate_command(ctx, text, target_language) await self.translations_cog.translate_command(ctx, text, target_language)
else: else:
await ctx.respond("Translations are disabled on this server.", ephemeral=True) await ctx.respond(
"Translations are disabled on this server.", ephemeral=True
)
@discord.slash_command(name="languages", description="View the supported languages for translation", guild_ids=ALLOWED_GUILDS, @discord.slash_command(
checks=[Check.check_translator_roles()],) name="languages",
description="View the supported languages for translation",
guild_ids=ALLOWED_GUILDS,
checks=[Check.check_translator_roles()],
)
@discord.guild_only() @discord.guild_only()
async def languages(self, ctx: discord.ApplicationContext): async def languages(self, ctx: discord.ApplicationContext):
if self.translations_cog: if self.translations_cog:
await self.translations_cog.languages_command(ctx) await self.translations_cog.languages_command(ctx)
else: else:
await ctx.respond("Translations are disabled on this server.", ephemeral=True) await ctx.respond(
"Translations are disabled on this server.", ephemeral=True
)
@discord.message_command( @discord.message_command(
name="Translate", guild_ids=ALLOWED_GUILDS, checks=[Check.check_translator_roles()] name="Translate",
guild_ids=ALLOWED_GUILDS,
checks=[Check.check_translator_roles()],
) )
async def translate_action(self, ctx, message: discord.Message): async def translate_action(self, ctx, message: discord.Message):
if self.translations_cog: if self.translations_cog:
await self.translations_cog.translate_action(ctx, message) await self.translations_cog.translate_action(ctx, message)
else: else:
await ctx.respond("Translations are disabled on this server.", ephemeral=True) await ctx.respond(
"Translations are disabled on this server.", ephemeral=True
)

@ -12,6 +12,7 @@ from models.deepl_model import TranslationModel
from services.environment_service import EnvService from services.environment_service import EnvService
from services.image_service import ImageService from services.image_service import ImageService
from services.text_service import TextService from services.text_service import TextService
ALLOWED_GUILDS = EnvService.get_allowed_guilds() ALLOWED_GUILDS = EnvService.get_allowed_guilds()
@ -25,10 +26,15 @@ def build_translation_embed( text, translated_text, translated_language):
embed.add_field(name="Translated Text", value=translated_text, inline=False) embed.add_field(name="Translated Text", value=translated_text, inline=False)
return embed return embed
class TranslationService(discord.Cog, name="TranslationService"): class TranslationService(discord.Cog, name="TranslationService"):
"""Cog containing a draw commands and file management for saved images""" """Cog containing a draw commands and file management for saved images"""
def __init__( def __init__(
self, bot, translation_model, self,
bot,
translation_model,
): ):
super().__init__() super().__init__()
self.bot = bot self.bot = bot
@ -45,10 +51,7 @@ class TranslationService(discord.Cog, name="TranslationService"):
embed.add_field( embed.add_field(
name="Languages", name="Languages",
value=", ".join( value=", ".join(
[ [f"{name}" for name in TranslationModel.get_all_country_names()]
f"{name}"
for name in TranslationModel.get_all_country_names()
]
), ),
inline=False, inline=False,
) )
@ -60,14 +63,19 @@ class TranslationService(discord.Cog, name="TranslationService"):
await ctx.defer() await ctx.defer()
# TODO Add pagination! # TODO Add pagination!
if target_language.lower().strip() not in TranslationModel.get_all_country_names(lower=True): if (
target_language.lower().strip()
not in TranslationModel.get_all_country_names(lower=True)
):
await ctx.respond( await ctx.respond(
f"The language {target_language} is not recognized or supported. Please use `/languages` to see the list of supported languages." f"The language {target_language} is not recognized or supported. Please use `/languages` to see the list of supported languages."
) )
return return
try: try:
response = await self.translation_model.send_translate_request(text, TranslationModel.get_country_code_from_name(target_language)) response = await self.translation_model.send_translate_request(
text, TranslationModel.get_country_code_from_name(target_language)
)
except aiohttp.ClientResponseError as e: except aiohttp.ClientResponseError as e:
await ctx.respond(f"There was an error with the DeepL API: {e.message}") await ctx.respond(f"There was an error with the DeepL API: {e.message}")
return return
@ -76,40 +84,59 @@ class TranslationService(discord.Cog, name="TranslationService"):
async def translate_action(self, ctx, message): async def translate_action(self, ctx, message):
await ctx.defer(ephemeral=True) await ctx.defer(ephemeral=True)
selection_message = await ctx.respond("Select language", ephemeral=True, delete_after=60) selection_message = await ctx.respond(
await selection_message.edit(view=TranslateView(self.translation_model, message, selection_message)) "Select language", ephemeral=True, delete_after=60
)
await selection_message.edit(
view=TranslateView(self.translation_model, message, selection_message)
)
async def languages_command(self, ctx): async def languages_command(self, ctx):
"""Show all languages supported for translation""" """Show all languages supported for translation"""
await ctx.defer() await ctx.defer()
await ctx.respond(embed=self.build_supported_language_embed()) await ctx.respond(embed=self.build_supported_language_embed())
class TranslateView(discord.ui.View):
class TranslateView(discord.ui.View):
def __init__(self, translation_model, message, selection_message): def __init__(self, translation_model, message, selection_message):
super().__init__() super().__init__()
self.translation_model = translation_model self.translation_model = translation_model
self.message = message self.message = message
self.selection_message = selection_message self.selection_message = selection_message
@discord.ui.select( # the decorator that lets you specify the properties of the select menu @discord.ui.select( # the decorator that lets you specify the properties of the select menu
placeholder = "Language", # the placeholder text that will be displayed if nothing is selected placeholder="Language", # the placeholder text that will be displayed if nothing is selected
min_values = 1, # the minimum number of values that must be selected by the users min_values=1, # the minimum number of values that must be selected by the users
max_values = 1, # the maximum number of values that can be selected by the users max_values=1, # the maximum number of values that can be selected by the users
options = [ # the list of options from which users can choose, a required field options=[ # the list of options from which users can choose, a required field
discord.SelectOption( discord.SelectOption(
label=name, label=name,
) for name in TranslationModel.get_all_country_names() )
] for name in TranslationModel.get_all_country_names()
],
) )
async def select_callback(self, select, interaction): # the function called when the user is done selecting options async def select_callback(
self, select, interaction
): # the function called when the user is done selecting options
try: try:
response = await self.translation_model.send_translate_request(self.message.content, TranslationModel.get_country_code_from_name(select.values[0])) response = await self.translation_model.send_translate_request(
await self.message.reply(mention_author=False, embed=build_translation_embed(self.message.content, response, select.values[0])) self.message.content,
TranslationModel.get_country_code_from_name(select.values[0]),
)
await self.message.reply(
mention_author=False,
embed=build_translation_embed(self.message.content, response, select.values[0]),
)
await self.selection_message.delete() await self.selection_message.delete()
except aiohttp.ClientResponseError as e: except aiohttp.ClientResponseError as e:
await interaction.response.send_message(f"There was an error with the DeepL API: {e.message}", ephemeral=True, delete_after=15) await interaction.response.send_message(
f"There was an error with the DeepL API: {e.message}",
ephemeral=True,
delete_after=15,
)
return return
except Exception as e: except Exception as e:
await interaction.response.send_message(f"There was an error: {e}", ephemeral=True, delete_after=15) await interaction.response.send_message(
f"There was an error: {e}", ephemeral=True, delete_after=15
)
return return

@ -166,7 +166,6 @@ async def main():
) )
) )
apply_multicog(bot) apply_multicog(bot)
await bot.start(os.getenv("DISCORD_TOKEN")) await bot.start(os.getenv("DISCORD_TOKEN"))

@ -74,6 +74,7 @@ class Settings_autocompleter:
if channel.name.startswith(ctx.value.lower()) if channel.name.startswith(ctx.value.lower())
] ]
class Translations_autocompleter: class Translations_autocompleter:
"""autocompleter for the translations command""" """autocompleter for the translations command"""

@ -68,7 +68,9 @@ class Check:
async def inner(ctx: discord.ApplicationContext): async def inner(ctx: discord.ApplicationContext):
if TRANSLATOR_ROLES == [None]: if TRANSLATOR_ROLES == [None]:
return True return True
if not any(role.name.lower() in TRANSLATOR_ROLES for role in ctx.user.roles): if not any(
role.name.lower() in TRANSLATOR_ROLES for role in ctx.user.roles
):
await ctx.defer(ephemeral=True) await ctx.defer(ephemeral=True)
await ctx.respond( await ctx.respond(
f"You don't have permission, list of roles is {TRANSLATOR_ROLES}", f"You don't have permission, list of roles is {TRANSLATOR_ROLES}",

@ -31,8 +31,9 @@ COUNTRY_CODES = {
"UK": "Ukrainian", "UK": "Ukrainian",
"ZH": "Chinese (simplified)", "ZH": "Chinese (simplified)",
} }
class TranslationModel:
class TranslationModel:
def __init__(self): def __init__(self):
self.deepl_token = os.getenv("DEEPL_TOKEN") self.deepl_token = os.getenv("DEEPL_TOKEN")
@ -64,7 +65,9 @@ class TranslationModel:
"Authorization": f"DeepL-Auth-Key {self.deepl_token}", "Authorization": f"DeepL-Auth-Key {self.deepl_token}",
} }
async with session.post( async with session.post(
"https://api-free.deepl.com/v2/translate", params=payload, headers=headers "https://api-free.deepl.com/v2/translate",
params=payload,
headers=headers,
) as resp: ) as resp:
response = await resp.json() response = await resp.json()
print(response) print(response)
@ -75,10 +78,15 @@ class TranslationModel:
print(response) print(response)
traceback.print_exc() traceback.print_exc()
return response return response
@staticmethod @staticmethod
def get_all_country_names(lower=False): def get_all_country_names(lower=False):
"""Get a list of all the country names""" """Get a list of all the country names"""
return list(COUNTRY_CODES.values()) if not lower else [name.lower() for name in COUNTRY_CODES.values()] return (
list(COUNTRY_CODES.values())
if not lower
else [name.lower() for name in COUNTRY_CODES.values()]
)
@staticmethod @staticmethod
def get_all_country_codes(): def get_all_country_codes():
@ -95,4 +103,4 @@ class TranslationModel:
"""Get the country code from the name""" """Get the country code from the name"""
for code, country_name in COUNTRY_CODES.items(): for code, country_name in COUNTRY_CODES.items():
if country_name.lower().strip() == name.lower().strip(): if country_name.lower().strip() == name.lower().strip():
return code return code

Loading…
Cancel
Save