Large refactor
This commit is contained in:
59
modules/app.py
Normal file
59
modules/app.py
Normal file
@@ -0,0 +1,59 @@
|
||||
import logging
|
||||
from os import getpid
|
||||
from time import time
|
||||
|
||||
import pyrogram
|
||||
from libbot import config_get
|
||||
from pyrogram.client import Client
|
||||
from pyrogram.errors import BadRequest
|
||||
from pyrogram.raw.all import layer
|
||||
from ujson import loads
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class PyroClient(Client):
|
||||
def __init__(self):
|
||||
with open("config.json", "r", encoding="utf-8") as f:
|
||||
config = loads(f.read())
|
||||
super().__init__(
|
||||
name="bwtbot",
|
||||
api_id=config["bot"]["api_id"],
|
||||
api_hash=config["bot"]["api_hash"],
|
||||
bot_token=config["bot"]["bot_token"],
|
||||
workers=config["bot"]["workers"],
|
||||
plugins=dict(root="plugins", exclude=config["disabled_plugins"]),
|
||||
sleep_threshold=120,
|
||||
)
|
||||
|
||||
async def start(self):
|
||||
await super().start()
|
||||
|
||||
self.start_time = time()
|
||||
|
||||
logger.info(
|
||||
"Bot is running with Pyrogram v%s (Layer %s) and has started as @%s on PID %s.",
|
||||
pyrogram.__version__,
|
||||
layer,
|
||||
self.me.username,
|
||||
getpid(),
|
||||
)
|
||||
|
||||
try:
|
||||
await self.send_message(
|
||||
chat_id=await config_get("chat_id", "reports"),
|
||||
text=f"Bot started PID `{getpid()}`",
|
||||
)
|
||||
except BadRequest:
|
||||
logger.warning("Unable to send message to report chat.")
|
||||
|
||||
async def stop(self):
|
||||
try:
|
||||
await self.send_message(
|
||||
chat_id=await config_get("chat_id", "reports"),
|
||||
text=f"Bot stopped with PID `{getpid()}`",
|
||||
)
|
||||
except BadRequest:
|
||||
logger.warning("Unable to send message to report chat.")
|
||||
await super().stop()
|
||||
logger.warning(f"Bot stopped with PID {getpid()}.")
|
@@ -1,13 +1,17 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import logging
|
||||
from os import makedirs, path
|
||||
from subprocess import check_output
|
||||
from traceback import format_exc
|
||||
from uuid import uuid4
|
||||
from functions import *
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
config = jsonLoad("config.json")
|
||||
from bs4 import BeautifulSoup
|
||||
from libbot import config_get
|
||||
|
||||
from modules.utils import *
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class EmptyCardException(Exception):
|
||||
@@ -21,9 +25,9 @@ async def getWaterLeft(cardid, filename, app=None):
|
||||
# if path.exists(f"data/pages/{str(filename)}.html") is False:
|
||||
# run(["touch", f"data/pages/{str(filename)}.html"])
|
||||
|
||||
appendLog(f"Trying to get liters for url '{url}'")
|
||||
logger.info(f"Trying to get liters for url '{url}'")
|
||||
|
||||
if config["use_compiled_page_saver"] is True:
|
||||
if await config_get("use_compiled_page_saver") is True:
|
||||
proc = check_output(
|
||||
[
|
||||
"PageSaver/pageSaver",
|
||||
@@ -58,12 +62,14 @@ async def getWaterLeft(cardid, filename, app=None):
|
||||
.replace(" л", "")
|
||||
)
|
||||
|
||||
appendLog(
|
||||
logger.info(
|
||||
f"Parsed {output} liters of water remaining (user: {str(filename)}, cardid: {cardid})"
|
||||
)
|
||||
|
||||
except Exception as exp:
|
||||
appendLog(f"Exception occured: {exp} (user: {str(filename)}, cardid: {cardid})")
|
||||
logger.exception(
|
||||
f"Exception occured: {exp} (user: {str(filename)}, cardid: {cardid})", exp
|
||||
)
|
||||
|
||||
try:
|
||||
tmp_name = str(uuid4())
|
||||
@@ -72,16 +78,16 @@ async def getWaterLeft(cardid, filename, app=None):
|
||||
f.write(html_file)
|
||||
except NameError:
|
||||
tmp_name = "N/A"
|
||||
appendLog(f"'html_file' is not defined so I won't gather any tmp data")
|
||||
logger.warning(f"'html_file' is not defined so I won't gather any tmp data")
|
||||
|
||||
if app != None:
|
||||
await app.send_message(
|
||||
config["owner_id"],
|
||||
await config_get("owner_id"),
|
||||
f"**Exception occured:**\n • User: `{str(filename)}`\n • Card: [{cardid}]({url})\n • Exception: `{exp}`\n • TMP UUID: `{tmp_name}`\n • Traceback: `{format_exc()}`",
|
||||
disable_web_page_preview=True,
|
||||
)
|
||||
else:
|
||||
appendLog(f"Exception occured and could not send to user: {exp}")
|
||||
logger.warning(f"Exception occurred and could not send to user: {exp}")
|
||||
|
||||
output = "Failure"
|
||||
|
||||
|
@@ -1,22 +0,0 @@
|
||||
RESET = "\u001b[0m"
|
||||
|
||||
BLACK = "\u001b[30m"
|
||||
RED = "\u001b[31m"
|
||||
GREEN = "\u001b[32m"
|
||||
YELLOW = "\u001b[33m"
|
||||
BLUE = "\u001b[34m"
|
||||
MAGENTA = "\u001b[35m"
|
||||
CYAN = "\u001b[36m"
|
||||
WHITE = "\u001b[37m"
|
||||
|
||||
BBLACK = "\u001b[30;1m"
|
||||
BRED = "\u001b[31;1m"
|
||||
BGREEN = "\u001b[32;1m"
|
||||
BYELLOW = "\u001b[33;1m"
|
||||
BBLUE = "\u001b[34;1m"
|
||||
BMAGENTA = "\u001b[35;1m"
|
||||
BCYAN = "\u001b[36;1m"
|
||||
BWHITE = "\u001b[37;1m"
|
||||
|
||||
ULINE = "\u001b[4m"
|
||||
REVERSE = "\u001b[7m"
|
35
modules/utils.py
Normal file
35
modules/utils.py
Normal file
@@ -0,0 +1,35 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from libbot import json_read, sync
|
||||
|
||||
|
||||
async def string(key: str, *args: str, userlocale="uk"):
|
||||
locales = await json_read("strings.json")
|
||||
strings = locales[userlocale]
|
||||
string = strings
|
||||
for dict_key in args:
|
||||
string = string[dict_key]
|
||||
return string[key]
|
||||
|
||||
|
||||
def userSet(userid, key: str, value):
|
||||
database = sync.json_read("data/database.json")
|
||||
if str(userid) not in database:
|
||||
database[str(userid)] = {}
|
||||
database[str(userid)][key] = value
|
||||
sync.json_write(database, "data/database.json")
|
||||
|
||||
|
||||
def userReset(userid, key: str):
|
||||
database = sync.json_read("data/database.json")
|
||||
del database[str(userid)][key]
|
||||
sync.json_write(database, "data/database.json")
|
||||
|
||||
|
||||
def userGet(userid, key: str):
|
||||
try:
|
||||
return sync.json_read("data/database.json")[str(userid)][key]
|
||||
except KeyError:
|
||||
return None
|
||||
except FileNotFoundError:
|
||||
return None
|
Reference in New Issue
Block a user