[feat]: New translation system

This commit is contained in:
Sweetbread 2023-05-20 21:19:32 +03:00
parent 1f10c788e4
commit 6a99350ac5
3 changed files with 217 additions and 151 deletions

View File

@ -244,7 +244,7 @@ class Economic(commands.Cog, name="Экономика"):
logger.debug(m["guild_stat"][str(guild.id)]["exp"]) logger.debug(m["guild_stat"][str(guild.id)]["exp"])
stat_gr = app_commands.Group(name="statistic", description="Some statistic") stat_gr = app_commands.Group(name="statistics", description="Some statistics")
@stat_gr.command(description="View balance and level") @stat_gr.command(description="View balance and level")
async def rank(self, inter: discord.Interaction, user: discord.Member = None): async def rank(self, inter: discord.Interaction, user: discord.Member = None):

View File

@ -1,4 +1,5 @@
import discord import discord
from bot import db
from discord import app_commands from discord import app_commands
from typing import Optional from typing import Optional
from loguru import logger from loguru import logger
@ -10,21 +11,55 @@ import json
class MeowTranslator(app_commands.Translator): class MeowTranslator(app_commands.Translator):
async def load(self): async def load(self):
with open('translations.json', 'r') as f: with open('translations.json', 'r') as f:
self.translations = json.loads(f.read()) data = json.loads(f.read())
self.db = db.translation
await self.db.delete_many({})
for locale in data.keys():
logger.debug(locale)
for type_ in data[locale].keys():
logger.debug('\t'+type_)
for key in data[locale][type_].keys():
logger.debug('\t\t'+key)
translate = data[locale][type_][key]
if type(translate) is dict:
for tr in translate.keys():
logger.debug('\t\t\t'+tr)
await self.db.insert_one({'locale': locale, 'type': int(type_), 'context': key, 'string': tr, 'translate': translate[tr]})
else:
logger.debug('\t\t '+translate)
await self.db.insert_one({'locale': locale, 'type': int(type_), 'string': key, 'translate': translate})
async def unload(self): pass async def unload(self): pass
async def translate(self, string: app_commands.locale_str, locale: discord.Locale, context: app_commands.TranslationContext) -> Optional[str]: async def translate(self, string: app_commands.locale_str, locale: discord.Locale, context: app_commands.TranslationContext) -> Optional[str]:
logger.debug(f"{locale}\t{string.message}") if context.data is str:
if str(locale) == "uk": locale = "ru" # TODO: make translation for Ukranian search_dict = {'locale': str(locale), 'type': context.location.value, 'context': context.data, 'string': string.message}
if str(locale) not in self.translations.keys(): return else:
if context.location is trans_context.other: search_dict = {'locale': str(locale), 'type': context.location.value, 'string': string.message}
if f"{context.data}.{string.message}" in self.translations[str(locale)].keys(): data = await self.db.find_one(search_dict)
return self.translations[str(locale)][f"{context.data}.{string.message}"] if data:
elif context.data in self.translations[str(locale)].keys(): return data['translate']
return self.translations[str(locale)][context.data]
else: return if str(locale) == 'en-US': return
if string.message not in self.translations[str(locale)].keys(): return if str(locale) == 'uk': search_dict['locale'] = 'ru'
return self.translations[str(locale)][string.message] else: search_dict['locale'] = 'en-US'
if (data := await self.db.find_one(search_dict)):
return data['translate']
return
# if str(locale) == "uk": locale = "ru" # TODO: make translation for Ukranian
# if str(locale) not in self.translations.keys(): return
# if context.location is trans_context.other:
# if f"{context.data}.{string.message}" in self.translations[str(locale)].keys():
# return self.translations[str(locale)][f"{context.data}.{string.message}"]
# elif context.data in self.translations[str(locale)].keys():
# return self.translations[str(locale)][context.data]
# else: return
# if string.message not in self.translations[str(locale)].keys(): return
# return self.translations[str(locale)][string.message]
async def setup(bot): async def setup(bot):

View File

@ -1,26 +1,6 @@
{ {
"ru": { "ru": {
"translate": "Перевести", "0": {
"cats": "котики",
"are cutes": "милахи",
"Top members of the guild": "Топ участников сервера",
"Category": "Категория",
"Balance": "Баланс",
"Experience": "Опыт",
"Time in voice channel": "Время в войсе",
"Comparison of exp with other members": "Сравнения опыта с другими пользователями",
"period": "период",
"Per the entire period": "За весь период",
"Per month": "За месяц",
"Per day": "За день",
"user": "участник",
"View balance and level": "Просмотр баланса и уровня",
"Experience gain statistics": "Статиcтика получения опыта",
"rank": "ранг", "rank": "ранг",
"top": "топ", "top": "топ",
"graph": "график", "graph": "график",
@ -28,23 +8,8 @@
"activity": "активность", "activity": "активность",
"make_music": "синтезатор",
"Music MIDI synthesis": "Синтезация MIDI мелодии",
"MIDI notes (comma separated)": "MIDI ноты (через запятую)",
"notes": "ноты",
"format": "формат",
"Image": "Изображение",
"Video": "Видео",
"GIF": "Гифка",
"hentai": "хентай",
"Random hentai": "Случайный хентай",
"about": "о_боте", "about": "о_боте",
"About this bot": "Об этом боте вкратце",
"info": "Мяв! Я ~~очередной~~ дискорд бот, ~~который в очередной раз попытается захватить мир~~.\nСоздатель: Сладкий Хлеб#1199\nНаписан на: Discord.py\nХост: </host:981229566804774944>",
"music": "музыка",
"play": "запустить", "play": "запустить",
"stop": "остановить", "stop": "остановить",
"pause": "пауза", "pause": "пауза",
@ -53,109 +18,175 @@
"disconnect": "отключиться", "disconnect": "отключиться",
"next": "следующий", "next": "следующий",
"activity.Avarage": "В среднем", "make_music": "синтезатор",
"activity.Max": "Максимально",
"activity.On this day\nof the week": "В этот день\nнедели",
"activity.Today": "Сегодня",
"activity.Hours": "Часы",
"activity.Messages": "Сообщения",
"rank.Info about": "Данные о", "hentai": "хентай",
"rank.Money": "Баланс",
"rank.Global stats": "Глобальная статистика",
"rank.On this guild": "На этом сервере",
"rank.Level": "Уровень",
"rank.Exp": "Опыт",
"rank.Time in voice channels": "Время в голосовых каналах",
"rank.Per hour": "За час",
"rank.Per day": "За день",
"rank.per the past hour": "за прошедший час",
"rank.per the past day": "за прошедший день",
"errors_text": "Опять кошки уронили вазу и что-то сломали; Сегодня не тот день, оно не заработает; Мне слишком лень делать это; Что-то сломалось. Я ничего не трогала!" "translate": "Перевести"
},
"1": {
"Top members of the guild": "Топ участников сервера",
"Comparison of exp with other members": "Сравнения опыта с другими пользователями",
"View balance and level": "Просмотр баланса и уровня",
"Experience gain statistics": "Статиcтика получения опыта",
"Music MIDI synthesis": "Синтезация MIDI мелодии",
"Random hentai": "Случайный хентай",
"About this bot": "Об этом боте вкратце"
},
"2": {
"music": "музыка",
"statistics": "статистика"
},
"3": {
},
"4": {
"period": "период",
"user": "участник",
"notes": "ноты",
"format": "формат"
},
"5": {
"MIDI notes (comma separated)": "MIDI ноты (через запятую)"
},
"6": {
"Category": "Категория",
"Balance": "Баланс",
"Experience": "Опыт",
"Time in voice channel": "Время в войсе",
"Per the entire period": "За весь период",
"Per week": "За неделю",
"Per month": "За месяц",
"Per day": "За день",
"Image": "Изображение",
"Video": "Видео",
"GIF": "Гифка"
},
"7": {
"errors_text": "Опять кошки уронили вазу и что-то сломали; Сегодня не тот день, оно не заработает; Мне слишком лень делать это; Что-то сломалось. Я ничего не трогала!",
"info": "Мяв! Я ~~очередной~~ дискорд бот, ~~который в очередной раз попытается захватить мир~~.\nСоздатель: Сладкий Хлеб#1199\nНаписан на: Discord.py\nХост: </host:981229566804774944>",
"activity": {
"Avarage": "В среднем",
"Max": "Максимально",
"On this day\nof the week": "В этот день\nнедели",
"Today": "Сегодня",
"Hours": "Часы",
"Messages": "Сообщения"
},
"rank": {
"Info about": "Данные о",
"Money": "Баланс",
"Global stats": "Глобальная статистика",
"On this guild": "На этом сервере",
"Level": "Уровень",
"Exp": "Опыт",
"Time in voice channels": "Время в голосовых каналах",
"Per hour": "За час",
"Per day": "За день",
"per the past hour": "за прошедший час",
"per the past day": "за прошедший день"
}
}
}, },
"fr": { "fr": {
"translate": "Traduire", "0": {
"Top members of the guild": "Leaderboard de mebers du serveur",
"Category": "Catégorie",
"Balance": "L'argent",
"Experience": "Expérience",
"Time in voice channel": "Temps dans les salons vocaux",
"Comparison of exp with other members": "Comparaison d'expérience avec d'autres membres",
"period": "période",
"Per the entire period": "Par toute la période",
"Per month": "Per mois",
"Per day": "Per jour",
"user": "membre",
"View balance and level": "Afficher l'argent et le niveau",
"Experience gain statistics": "Statistiques de gain d'expérience",
"rank": "rang", "rank": "rang",
"top": "classement", "top": "classement",
"graph": "graphique", "graph": "graphique",
"dif_graph": "graph_de_comp", "dif_graph": "graph_de_comp",
"about": "a_propos",
"activity": "activité",
"make_music": "synthétiseur", "make_music": "synthétiseur",
"activity": "activité"
},
"1": {
"Top members of the guild": "Leaderboard de mebers du serveur",
"View balance and level": "Afficher l'argent et le niveau",
"Experience gain statistics": "Statistiques de gain d'expérience",
"About this bot": "À propos de ce robot",
"Music MIDI synthesis": "synthétiseur mélodie MIDI", "Music MIDI synthesis": "synthétiseur mélodie MIDI",
"MIDI notes (comma separated)": "Notes MIDI (séparées par des virgules)", "Comparison of exp with other members": "Comparaison d'expérience avec d'autres membres",
"Random hentai": "Hentai aléatoire"
},
"2": {},
"3": {},
"4": {
"period": "période",
"user": "membre",
"notes": "notes", "notes": "notes",
"format": "format", "format": "format",
"hentai": "hentai"
},
"5": {
"MIDI notes (comma separated)": "Notes MIDI (séparées par des virgules)"
},
"6": {
"Per the entire period": "Par toute la période",
"Per month": "Per mois",
"Per day": "Per jour",
"Image": "Image", "Image": "Image",
"Video": "Vidéo", "Video": "Vidéo",
"GIF": "GIF", "GIF": "GIF"
"hentai": "hentai", },
"Random hentai": "Hentai aléatoire", "7": {
"Not enough data. Try later": "Pas assez de données. Essayer plus tard",
"translate": "Traduire",
"Category": "Catégorie",
"Balance": "L'argent",
"Experience": "Expérience",
"Time in voice channel": "Temps dans les salons vocaux",
"activity": {
"Avarage": "Moyen",
"Max": "Maximum",
"On this day\nof the week": "En ce jour de\nla semaine",
"Today": "Aujourd'hui",
"Hours": "Heures",
"Messages": "Messages"
},
"rank": {
"Info about": "Informations sur",
"Money": "L'argent",
"Global stats": "Statistiques mondiales",
"On this guild": "Sur ce serveur",
"Level": "Niveau",
"Exp": "Expérience",
"Time in voice channels": "Temps dans les salons vocaux",
"Per hour": "Dans une heure",
"Per day": "Dans une jour",
"per the past hour": "au cours de la dernière heure",
"per the past day": "au cours de la dernière jour"
}
},
"8": {
"about": "a_propos",
"About this bot": "À propos de ce robot",
"info": "Мяв! Я ~~очередной~~ дискорд бот, ~~который в очередной раз попытается захватить мир~~.\nСоздатель: Сладкий Хлеб#1199\nНаписан на: Discord.py\nХост: </host:981229566804774944>",
"top.Not enough data. Try later": "Pas assez de données. Essayer plus tard", }
"activity.Avarage": "Moyen",
"activity.Max": "Maximum",
"activity.On this day\nof the week": "En ce jour de\nla semaine",
"activity.Today": "Aujourd'hui",
"activity.Hours": "Heures",
"activity.Messages": "Messages",
"rank.Info about": "Informations sur",
"rank.Money": "L'argent",
"rank.Global stats": "Statistiques mondiales",
"rank.On this guild": "Sur ce serveur",
"rank.Level": "Niveau",
"rank.Exp": "Expérience",
"rank.Time in voice channels": "Temps dans les salons vocaux",
"rank.Per hour": "Dans une heure",
"rank.Per day": "Dans une jour",
"rank.per the past hour": "au cours de la dernière heure",
"rank.per the past day": "au cours de la dernière jour"
}, },
"de": { "de": {
"7": {
"Time in voice channel": "Zeit im Sprachcanal", "Time in voice channel": "Zeit im Sprachcanal",
"Per the entire period": "Für den gesamten Zeitraum", "Per the entire period": "Für den gesamten Zeitraum",
"Per month": "Monatsüber", "Per month": "Monatsüber",
"Per day": "Tagsüber", "Per day": "Tagsüber",
"rank.Info about": "Information über", "rank": {
"rank.Money": "Balance", "Info about": "Information über",
"rank.Global stats": "Globale Statistiken", "Money": "Balance",
"rank.On this guild": "Auf diesem Server", "Global stats": "Globale Statistiken",
"rank.Level": "Niveau", "On this guild": "Auf diesem Server",
"rank.Exp": "Erfahrung", "Level": "Niveau",
"rank.Time in voice channels": "Zeit im Sprachcanal", "Exp": "Erfahrung",
"rank.Per hour": "Stundeüber", "Time in voice channels": "Zeit im Sprachcanal",
"rank.Per day": "Tagsüber", "Per hour": "Stundeüber",
"rank.per the past hour": "am letxten Stunde", "Per day": "Tagsüber",
"rank.per the past day": "am letzten Tag" "per the past hour": "am letxten Stunde",
"per the past day": "am letzten Tag"
}
}
} }
} }