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