From c4481c8baac922a4660c047d10d0686e6fb55150 Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Thu, 15 Sep 2022 00:20:38 +0200 Subject: [PATCH] Making sure multilanguage is possible --- bot.py | 14 +++--- config.json | 1 + strings.json => locale/en.json | 0 modules/functions.py | 21 ++++---- modules/functions_bot.py | 89 +++++++++++++++++++++++++++------- 5 files changed, 89 insertions(+), 36 deletions(-) rename strings.json => locale/en.json (100%) diff --git a/bot.py b/bot.py index 4bccd6a..80774b7 100644 --- a/bot.py +++ b/bot.py @@ -1,11 +1,11 @@ # -*- coding: utf-8 -*- -import os import discord from sys import exit from discord import Embed from modules.functions import * from modules.functions_bot import * +from os import sep, listdir intents = discord.Intents().all() client = discord.Bot(intents=intents) @@ -28,18 +28,18 @@ async def link(ctx: discord.ApplicationContext, code: discord.Option(str, "Code logWrite(f'Got command start/link from {ctx.author.id}') - if f"{ctx.author.id}.json" not in os.listdir("data/users/"): + if f"{ctx.author.id}.json" not in listdir(f"data{sep}users{sep}"): logWrite(f'Creating blank data file for {ctx.author.id}') - jsonSave( f"data/users/{ctx.author.id}.json", {"api_key": None, "linked": False, "context": {"action": None, "data": None}} ) + jsonSave( f"data{sep}users{sep}{ctx.author.id}.json", {"api_key": None, "linked": False, "context": {"action": None, "data": None}} ) if not userGet(ctx.author.id, "linked"): if code in jsonLoad(configGet("api_keys"))["autozoom"]: await ctx.respond(embed=makeEmbed(title=locale("key_correct", "msg"), description=locale("key_correct_text", "msg"), color=0x45d352)) userSet(ctx.author.id, "api_key", code) userSet(ctx.author.id, "linked", True) - keys_storage = jsonLoad("data/keys_storage.json") + keys_storage = jsonLoad(f"data{sep}keys_storage.json") keys_storage[code] = ctx.author.id - jsonSave("data/keys_storage.json", keys_storage) + jsonSave(f"data{sep}keys_storage.json", keys_storage) logWrite(f"Added apikey {code} for user {ctx.author.id}") else: logWrite(f"User {ctx.author.id} tried to pair with invalid apikey {code}") @@ -56,9 +56,9 @@ async def unlink(ctx: discord.ApplicationContext): await ctx.respond(embed=makeEmbed(title=locale("not_linked", "msg"), description=locale("not_linked_text", "msg"), color=0xe06044)) else: try: - keys_storage = jsonLoad("data/keys_storage.json") + keys_storage = jsonLoad(f"data{sep}keys_storage.json") del keys_storage[userGet(ctx.author.id, "api_key")] - jsonSave("data/keys_storage.json", keys_storage) + jsonSave(f"data{sep}keys_storage.json", keys_storage) except: pass userClear(ctx.author.id, "api_key") diff --git a/config.json b/config.json index bcea93f..dec8477 100644 --- a/config.json +++ b/config.json @@ -1,4 +1,5 @@ { + "locale": "en", "api_keys": "data/api_keys.json", "token": "INSERT-TOKEN" } diff --git a/strings.json b/locale/en.json similarity index 100% rename from strings.json rename to locale/en.json diff --git a/modules/functions.py b/modules/functions.py index 733c268..55eb072 100644 --- a/modules/functions.py +++ b/modules/functions.py @@ -1,12 +1,11 @@ # -*- coding: utf-8 -*- """Some set of functions needed for discord/telegram bots and other types of apps""" -import gzip -import os -import shutil - +from os import sep, stat, makedirs from datetime import datetime from ujson import loads, dumps +from shutil import copyfileobj +from gzip import open as gzipopen def nowtimeGet(format="%H:%M:%S | %d.%m.%Y"): @@ -21,7 +20,7 @@ def nowtimeGet(format="%H:%M:%S | %d.%m.%Y"): return datetime.now().strftime(format) -def checkSize(logs_folder="logs/", log_size=1024): +def checkSize(logs_folder=f"logs{sep}", log_size=1024): """Checks latest log file size and rotates it if needed. ### Args: @@ -31,11 +30,11 @@ def checkSize(logs_folder="logs/", log_size=1024): i = 0 while i < 2: try: - log = os.stat(logs_folder + 'latest.log') + log = stat(logs_folder + 'latest.log') if (log.st_size / 1024) > log_size: with open(logs_folder + 'latest.log', 'rb') as f_in: - with gzip.open(f'{logs_folder}{datetime.now().strftime("%d.%m.%Y_%H:%M:%S")}.zip', 'wb') as f_out: - shutil.copyfileobj(f_in, f_out) + with gzipopen(f'{logs_folder}{datetime.now().strftime("%d.%m.%Y_%H:%M:%S")}.zip', 'wb') as f_out: + copyfileobj(f_in, f_out) open(logs_folder + 'latest.log', 'w').close() i = 2 except FileNotFoundError: @@ -44,7 +43,7 @@ def checkSize(logs_folder="logs/", log_size=1024): open(logs_folder + 'latest.log', 'a').close() except: try: - os.mkdir(logs_folder) + makedirs(logs_folder, exist_ok=True) log = open(logs_folder + 'latest.log', 'a') open(logs_folder + 'latest.log', 'a').close() except: @@ -52,7 +51,7 @@ def checkSize(logs_folder="logs/", log_size=1024): i += 1 -def logWrite(message, logs_folder="logs/", level="INFO"): +def logWrite(message, logs_folder=f"logs{sep}", level="INFO"): """Append some message to latest log file. ### Args: @@ -68,7 +67,7 @@ def logWrite(message, logs_folder="logs/", level="INFO"): open(logs_folder + 'latest.log', 'a').close() except: try: - os.mkdir(logs_folder) + makedirs(logs_folder, exist_ok=True) log = open(logs_folder + 'latest.log', 'a') open(logs_folder + 'latest.log', 'a').close() except: diff --git a/modules/functions_bot.py b/modules/functions_bot.py index ded028e..efac870 100644 --- a/modules/functions_bot.py +++ b/modules/functions_bot.py @@ -1,21 +1,41 @@ # -*- coding: utf-8 -*- +"""Essential set of functions needed for discord/telegram bots and other types of apps""" + from modules.functions import jsonLoad, jsonSave +from os import sep -def locale(key, *args): - strings = jsonLoad("strings.json") - string = strings +def configGet(key: str, *args: str): + """Get value of the config key + Args: + * key (str): The last key of the keys path. + * *args (str): Path to key like: dict[args][key]. + Returns: + * any: Value of provided key + """ + this_dict = jsonLoad("config.json") + this_key = this_dict for dict_key in args: - string = string[dict_key] - return string[key] + this_key = this_key[dict_key] + return this_key[key] - -def configGet(key): - return jsonLoad("config.json")[key] - -def configAppend(key, value): - config = jsonLoad("config.json") - config[key].append(value) - jsonSave("config.json", config) +def configAppend(key: str, value, *args: str): + """Set key to a value + Args: + * key (str): The last key of the keys path. + * value (str/int/float/list/dict/None): Some needed value. + * *args (str): Path to key like: dict[args][key]. + """ + this_dict = jsonLoad("config.json") + string = "this_dict" + for arg in args: + string += f'["{arg}"]' + if type(value) in [str]: + string += f'["{key}"].append("{value}")' + else: + string += f'["{key}"].append({value})' + exec(string) + jsonSave(this_dict, "config.json") + return def configRemove(key, value): config = jsonLoad("config.json") @@ -23,14 +43,47 @@ def configRemove(key, value): jsonSave("config.json", config) +def locale(key: str, *args: str, locale=configGet("locale")): + """Get value of locale string + Args: + * key (str): The last key of the locale's keys path. + * *args (list): Path to key like: dict[args][key]. + * locale (str): Locale to looked up in. Defaults to config's locale value. + Returns: + * any: Value of provided locale key + """ + if (locale == None): + locale = configGet("locale") + + try: + this_dict = jsonLoad(f'{configGet("locale", "locations")}{sep}{locale}.json') + except FileNotFoundError: + try: + this_dict = jsonLoad(f'{configGet("locale", "locations")}{sep}{configGet("locale")}.json') + except FileNotFoundError: + try: + this_dict = jsonLoad(f'{configGet("locale_fallback", "locations")}{sep}{configGet("locale")}.json') + except: + return f'⚠️ Locale in config is invalid: could not get "{key}" in {str(args)} from locale "{locale}"' + + this_key = this_dict + for dict_key in args: + this_key = this_key[dict_key] + + try: + return this_key[key] + except KeyError: + return f'⚠️ Locale in config is invalid: could not get "{key}" in {str(args)} from locale "{locale}"' + + def userSet(userid, key, value): - user = jsonLoad(f"data/users/{userid}.json") + user = jsonLoad(f"data{sep}users{sep}{userid}.json") user[key] = value - jsonSave(f"data/users/{userid}.json", user) + jsonSave(f"data{sep}users{sep}{userid}.json", user) def userGet(userid, key): try: - return jsonLoad(f"data/users/{userid}.json")[key] + return jsonLoad(f"data{sep}users{sep}{userid}.json")[key] except KeyError: return None except FileNotFoundError: @@ -38,8 +91,8 @@ def userGet(userid, key): def userClear(userid, key): try: - user = jsonLoad(f"data/users/{userid}.json") + user = jsonLoad(f"data{sep}users{sep}{userid}.json") del user[key] - jsonSave(f"data/users/{userid}.json", user) + jsonSave(f"data{sep}users{sep}{userid}.json", user) except KeyError: pass \ No newline at end of file