Making sure multilanguage is possible

This commit is contained in:
Profitroll 2022-09-15 00:16:38 +02:00
parent 390e6f326e
commit bd47790b0d
5 changed files with 99 additions and 38 deletions

26
bot.py
View File

@ -1,8 +1,8 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import os
import subprocess import subprocess
from sys import exit from sys import exit
from os import getpid, listdir, sep, system
from modules.functions import * from modules.functions import *
from modules.functions_bot import * from modules.functions_bot import *
from pyrogram import Client, filters, idle from pyrogram import Client, filters, idle
@ -10,7 +10,7 @@ from pyrogram.types import ForceReply, BotCommand, BotCommandScopeChat
from pyrogram.enums.chat_action import ChatAction from pyrogram.enums.chat_action import ChatAction
if configGet("bot_token") != "12345678:asdfghjklzxcvbnm": if configGet("bot_token") != "12345678:asdfghjklzxcvbnm":
pid = os.getpid() pid = getpid()
app = Client("auto_zoom_public_bot", api_id=configGet("api_id"), api_hash=configGet("api_hash"), bot_token=configGet("bot_token")) app = Client("auto_zoom_public_bot", api_id=configGet("api_id"), api_hash=configGet("api_hash"), bot_token=configGet("bot_token"))
else: else:
logWrite("Could not start the bot. Please, configure token in config.json") logWrite("Could not start the bot. Please, configure token in config.json")
@ -28,9 +28,11 @@ def start(app, msg):
app.send_chat_action(chat_id=msg.chat.id, action=ChatAction.TYPING) app.send_chat_action(chat_id=msg.chat.id, action=ChatAction.TYPING)
if f"{msg.from_user.id}.json" not in os.listdir("data/users/"): user_locale = msg.from_user.language_code
if f"{msg.from_user.id}.json" not in listdir(f"data{sep}users{sep}"):
logWrite(f'Creating blank data file for {msg.from_user.id}') logWrite(f'Creating blank data file for {msg.from_user.id}')
jsonSave( f"data/users/{msg.from_user.id}.json", {"api_key": None, "linked": False, "context": {"action": None, "data": None}} ) jsonSave( f"data{sep}users{sep}{msg.from_user.id}.json", {"api_key": None, "linked": False, "context": {"action": None, "data": None}} )
if not userGet(msg.from_user.id, "linked"): if not userGet(msg.from_user.id, "linked"):
msg.reply_text(locale("link_input", "msg"), reply_markup=ForceReply(placeholder=locale("link", "fry"))) msg.reply_text(locale("link_input", "msg"), reply_markup=ForceReply(placeholder=locale("link", "fry")))
@ -45,13 +47,15 @@ def unlink(app, msg):
app.send_chat_action(chat_id=msg.chat.id, action=ChatAction.TYPING) app.send_chat_action(chat_id=msg.chat.id, action=ChatAction.TYPING)
user_locale = msg.from_user.language_code
if not userGet(msg.from_user.id, "linked"): if not userGet(msg.from_user.id, "linked"):
msg.reply_text(locale("not_linked", "msg")) msg.reply_text(locale("not_linked", "msg"))
else: else:
try: try:
keys_storage = jsonLoad("data/keys_storage.json") keys_storage = jsonLoad(f"data{sep}keys_storage.json")
del keys_storage[userGet(msg.from_user.id, "api_key")] del keys_storage[userGet(msg.from_user.id, "api_key")]
jsonSave("data/keys_storage.json", keys_storage) jsonSave(f"data{sep}keys_storage.json", keys_storage)
except: except:
pass pass
userClear(msg.from_user.id, "api_key") userClear(msg.from_user.id, "api_key")
@ -63,6 +67,8 @@ def cancel(app, msg):
app.send_chat_action(chat_id=msg.chat.id, action=ChatAction.TYPING) app.send_chat_action(chat_id=msg.chat.id, action=ChatAction.TYPING)
user_locale = msg.from_user.language_code
if userGet(msg.from_user.id, "context") is not None: if userGet(msg.from_user.id, "context") is not None:
userClear(msg.from_user.id, "context") userClear(msg.from_user.id, "context")
userClear(msg.from_user.id, "context_content") userClear(msg.from_user.id, "context_content")
@ -76,7 +82,7 @@ def kill(app, msg):
if msg.from_user.id == configGet("admin"): if msg.from_user.id == configGet("admin"):
msg.reply_text(f"Shutting down bot with pid `{pid}`") msg.reply_text(f"Shutting down bot with pid `{pid}`")
os.system('kill -9 '+str(pid)) system('kill -9 '+str(pid)) # REFACTOR
@app.on_message(~ filters.scheduled) @app.on_message(~ filters.scheduled)
@ -84,13 +90,15 @@ def any_message_handler(app, msg):
if userGet(msg.from_user.id, "context") == "link_key": if userGet(msg.from_user.id, "context") == "link_key":
user_locale = msg.from_user.language_code
if msg.text in jsonLoad(configGet("api_keys"))["autozoom"]: if msg.text in jsonLoad(configGet("api_keys"))["autozoom"]:
msg.reply_text(locale("key_correct", "msg")) msg.reply_text(locale("key_correct", "msg"))
userSet(msg.from_user.id, "api_key", msg.text) userSet(msg.from_user.id, "api_key", msg.text)
userSet(msg.from_user.id, "linked", True) userSet(msg.from_user.id, "linked", True)
keys_storage = jsonLoad("data/keys_storage.json") keys_storage = jsonLoad(f"data{sep}keys_storage.json")
keys_storage[msg.text] = msg.from_user.id keys_storage[msg.text] = msg.from_user.id
jsonSave("data/keys_storage.json", keys_storage) jsonSave(f"data{sep}keys_storage.json", keys_storage)
logWrite(f"Added apikey {msg.text} for user {msg.from_user.id}") logWrite(f"Added apikey {msg.text} for user {msg.from_user.id}")
else: else:
logWrite(f"User {msg.from_user.id} tried to pair with invalid apikey {msg.text}") logWrite(f"User {msg.from_user.id} tried to pair with invalid apikey {msg.text}")

View File

@ -1,4 +1,5 @@
{ {
"locale": "en",
"admin": 123456789, "admin": 123456789,
"api_id": 1234567, "api_id": 1234567,
"api_hash": "01234567890qwertyuiop", "api_hash": "01234567890qwertyuiop",

View File

@ -1,12 +1,11 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""Some set of functions needed for discord/telegram bots and other types of apps""" """Some set of functions needed for discord/telegram bots and other types of apps"""
import gzip from os import sep, stat, makedirs
import os
import shutil
from datetime import datetime from datetime import datetime
from ujson import loads, dumps from ujson import loads, dumps
from shutil import copyfileobj
from gzip import open as gzipopen
def nowtimeGet(format="%H:%M:%S | %d.%m.%Y"): 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) 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. """Checks latest log file size and rotates it if needed.
### Args: ### Args:
@ -31,11 +30,11 @@ def checkSize(logs_folder="logs/", log_size=1024):
i = 0 i = 0
while i < 2: while i < 2:
try: try:
log = os.stat(logs_folder + 'latest.log') log = stat(logs_folder + 'latest.log')
if (log.st_size / 1024) > log_size: if (log.st_size / 1024) > log_size:
with open(logs_folder + 'latest.log', 'rb') as f_in: 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: with gzipopen(f'{logs_folder}{datetime.now().strftime("%d.%m.%Y_%H:%M:%S")}.zip', 'wb') as f_out:
shutil.copyfileobj(f_in, f_out) copyfileobj(f_in, f_out)
open(logs_folder + 'latest.log', 'w').close() open(logs_folder + 'latest.log', 'w').close()
i = 2 i = 2
except FileNotFoundError: except FileNotFoundError:
@ -44,7 +43,7 @@ def checkSize(logs_folder="logs/", log_size=1024):
open(logs_folder + 'latest.log', 'a').close() open(logs_folder + 'latest.log', 'a').close()
except: except:
try: try:
os.mkdir(logs_folder) makedirs(logs_folder, exist_ok=True)
log = open(logs_folder + 'latest.log', 'a') log = open(logs_folder + 'latest.log', 'a')
open(logs_folder + 'latest.log', 'a').close() open(logs_folder + 'latest.log', 'a').close()
except: except:
@ -52,7 +51,7 @@ def checkSize(logs_folder="logs/", log_size=1024):
i += 1 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. """Append some message to latest log file.
### Args: ### Args:
@ -68,7 +67,7 @@ def logWrite(message, logs_folder="logs/", level="INFO"):
open(logs_folder + 'latest.log', 'a').close() open(logs_folder + 'latest.log', 'a').close()
except: except:
try: try:
os.mkdir(logs_folder) makedirs(logs_folder, exist_ok=True)
log = open(logs_folder + 'latest.log', 'a') log = open(logs_folder + 'latest.log', 'a')
open(logs_folder + 'latest.log', 'a').close() open(logs_folder + 'latest.log', 'a').close()
except: except:

View File

@ -1,21 +1,41 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""Essential set of functions needed for discord/telegram bots and other types of apps"""
from modules.functions import jsonLoad, jsonSave from modules.functions import jsonLoad, jsonSave
from os import sep
def locale(key, *args): def configGet(key: str, *args: str):
strings = jsonLoad("strings.json") """Get value of the config key
string = strings 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: for dict_key in args:
string = string[dict_key] this_key = this_key[dict_key]
return string[key] return this_key[key]
def configAppend(key: str, value, *args: str):
def configGet(key): """Set key to a value
return jsonLoad("config.json")[key] Args:
* key (str): The last key of the keys path.
def configAppend(key, value): * value (str/int/float/list/dict/None): Some needed value.
config = jsonLoad("config.json") * *args (str): Path to key like: dict[args][key].
config[key].append(value) """
jsonSave("config.json", config) 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): def configRemove(key, value):
config = jsonLoad("config.json") config = jsonLoad("config.json")
@ -23,14 +43,47 @@ def configRemove(key, value):
jsonSave("config.json", config) 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): def userSet(userid, key, value):
user = jsonLoad(f"data/users/{userid}.json") user = jsonLoad(f"data{sep}users{sep}{userid}.json")
user[key] = value user[key] = value
jsonSave(f"data/users/{userid}.json", user) jsonSave(f"data{sep}users{sep}{userid}.json", user)
def userGet(userid, key): def userGet(userid, key):
try: try:
return jsonLoad(f"data/users/{userid}.json")[key] return jsonLoad(f"data{sep}users{sep}{userid}.json")[key]
except KeyError: except KeyError:
return None return None
except FileNotFoundError: except FileNotFoundError:
@ -38,8 +91,8 @@ def userGet(userid, key):
def userClear(userid, key): def userClear(userid, key):
try: try:
user = jsonLoad(f"data/users/{userid}.json") user = jsonLoad(f"data{sep}users{sep}{userid}.json")
del user[key] del user[key]
jsonSave(f"data/users/{userid}.json", user) jsonSave(f"data{sep}users{sep}{userid}.json", user)
except KeyError: except KeyError:
pass pass