[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"])
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")
async def rank(self, inter: discord.Interaction, user: discord.Member = None):

View File

@ -1,4 +1,5 @@
import discord
from bot import db
from discord import app_commands
from typing import Optional
from loguru import logger
@ -10,21 +11,55 @@ import json
class MeowTranslator(app_commands.Translator):
async def load(self):
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 translate(self, string: app_commands.locale_str, locale: discord.Locale, context: app_commands.TranslationContext) -> Optional[str]:
logger.debug(f"{locale}\t{string.message}")
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]
if context.data is str:
search_dict = {'locale': str(locale), 'type': context.location.value, 'context': context.data, 'string': string.message}
else:
search_dict = {'locale': str(locale), 'type': context.location.value, 'string': string.message}
data = await self.db.find_one(search_dict)
if data:
return data['translate']
if str(locale) == 'en-US': return
if str(locale) == 'uk': search_dict['locale'] = 'ru'
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):

View File

@ -1,161 +1,192 @@
{
"ru": {
"translate": "Перевести",
"cats": "котики",
"are cutes": "милахи",
"0": {
"rank": "ранг",
"top": "топ",
"graph": "график",
"dif_graph": "разн_график",
"Top members of the guild": "Топ участников сервера",
"Category": "Категория",
"Balance": "Баланс",
"Experience": "Опыт",
"Time in voice channel": "Время в войсе",
"activity": "активность",
"Comparison of exp with other members": "Сравнения опыта с другими пользователями",
"period": "период",
"Per the entire period": "За весь период",
"Per month": "За месяц",
"Per day": "За день",
"about": "о_боте",
"user": "участник",
"View balance and level": "Просмотр баланса и уровня",
"Experience gain statistics": "Статиcтика получения опыта",
"play": "запустить",
"stop": "остановить",
"pause": "пауза",
"resume": "продолжить",
"queue": "очередь",
"disconnect": "отключиться",
"next": "следующий",
"rank": "ранг",
"top": "топ",
"graph": "график",
"dif_graph": "разн_график",
"make_music": "синтезатор",
"activity": "активность",
"hentai": "хентай",
"make_music": "синтезатор",
"Music MIDI synthesis": "Синтезация MIDI мелодии",
"MIDI notes (comma separated)": "MIDI ноты (через запятую)",
"notes": "ноты",
"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": "Об этом боте вкратце"
"format": "формат",
"Image": "Изображение",
"Video": "Видео",
"GIF": "Гифка",
"hentai": "хентай",
"Random hentai": "Случайный хентай",
},
"2": {
"music": "музыка",
"statistics": "статистика"
},
"3": {
},
"4": {
"period": "период",
"user": "участник",
"notes": "ноты",
"format": "формат"
"about": "о_боте",
"About this bot": "Об этом боте вкратце",
"info": "Мяв! Я ~~очередной~~ дискорд бот, ~~который в очередной раз попытается захватить мир~~.\nСоздатель: Сладкий Хлеб#1199\nНаписан на: Discord.py\nХост: </host:981229566804774944>",
},
"5": {
"MIDI notes (comma separated)": "MIDI ноты (через запятую)"
"music": "музыка",
"play": "запустить",
"stop": "остановить",
"pause": "пауза",
"resume": "продолжить",
"queue": "очередь",
"disconnect": "отключиться",
"next": "следующий",
"activity.Avarage": "В среднем",
"activity.Max": "Максимально",
"activity.On this day\nof the week": "В этот день\nнедели",
"activity.Today": "Сегодня",
"activity.Hours": "Часы",
"activity.Messages": "Сообщения",
},
"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>",
"rank.Info about": "Данные о",
"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": "Опять кошки уронили вазу и что-то сломали; Сегодня не тот день, оно не заработает; Мне слишком лень делать это; Что-то сломалось. Я ничего не трогала!"
"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": {
"translate": "Traduire",
"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",
"0": {
"rank": "rang",
"top": "classement",
"graph": "graphique",
"dif_graph": "graph_de_comp",
"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",
"period": "période",
"Per the entire period": "Par toute la période",
"Per month": "Per mois",
"Per day": "Per jour",
"Image": "Image",
"Video": "Vidéo",
"GIF": "GIF"
},
"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": {
"Time in voice channel": "Zeit im Sprachcanal",
"Per the entire period": "Für den gesamten Zeitraum",
"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"
"7": {
"Time in voice channel": "Zeit im Sprachcanal",
"Per the entire period": "Für den gesamten Zeitraum",
"Per month": "Monatsüber",
"Per day": "Tagsüber",
"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"
}
}
}
}