Compare commits

..

No commits in common. "27e204d3cc84033fa009a9ed742005141e900ef0" and "fa8bdc0e1f9e17a4a8e36684b6bfd4c18caab056" have entirely different histories.

4 changed files with 59 additions and 72 deletions

@ -1,15 +1,14 @@
#-*- coding: utf-8 -*-
from os import getpid, system
from subprocess import call
from pyrogram import filters
from pyrogram.client import Client
from pyrogram.sync import idle
from pyrogram.types import ForceReply, BotCommand, BotCommandScopeChat, Message
import traceback
from pyrogram import Client, filters, idle
from pyrogram.types import ForceReply, BotCommand, BotCommandScopeChat
from pyrogram.enums.chat_action import ChatAction
from functions import *
from modules.colors import *
from modules.bwt import *
import subprocess
import os
config = jsonLoad("config.json")
@ -19,7 +18,7 @@ app = Client(config["bot_name"], api_id=config["api_id"], api_hash=config["api_h
@app.on_message(~ filters.scheduled & filters.command(["setcard", "задать карту"], prefixes=["/", ""]))
async def setcard(_: Client, msg: Message):
async def setcard(_, msg):
if userGet(msg.from_user.id, "context") is None:
userSet(msg.from_user.id, "context", "set")
await msg.reply_text(string("send_number"), reply_markup=ForceReply(placeholder=string("enter_number")))
@ -28,7 +27,7 @@ async def setcard(_: Client, msg: Message):
@app.on_message(~ filters.scheduled & filters.command(["cancel", "відміна"], prefixes=["/", ""]))
async def cancel(_: Client, msg: Message):
async def cancel(_, msg):
if userGet(msg.from_user.id, "context") is not None:
userReset(msg.from_user.id, "context")
await msg.reply_text(string("cancel"))
@ -37,7 +36,7 @@ async def cancel(_: Client, msg: Message):
@app.on_message(~ filters.scheduled & filters.command(["resetcard", "забути картку"], prefixes=["/", ""]))
async def resetcard(_: Client, msg: Message):
async def resetcard(_, msg):
if userGet(msg.from_user.id, "context") is None:
if "card" in jsonLoad("data/database.json")[str(msg.from_user.id)]:
userReset(msg.from_user.id, "card")
@ -51,7 +50,7 @@ async def resetcard(_: Client, msg: Message):
@app.on_message(~ filters.scheduled & filters.command(["balance", "баланс"], prefixes=["/", ""]))
async def balance(_: Client, msg: Message):
async def balance(_, msg):
if userGet(msg.from_user.id, "context") is None:
try:
if "card" in jsonLoad("data/database.json")[str(msg.from_user.id)]:
@ -69,16 +68,15 @@ async def balance(_: Client, msg: Message):
await msg.reply_text(string("card_not_linked").format(string("get_number")))
appendLog(f"User {str(msg.from_user.id)} tried to get balance without card set")
except Exception as exp:
if msg.from_user.id != config["owner_id"]:
await msg.reply_text(string("error_occured").format(string("get_number")))
await app.send_message(owner_id, f"Error occured by {str(msg.from_user.id)}:\nException: `{exp}`\nTraceback: `{format_exc()}`")
await msg.reply_text(string("error_occured").format(string("get_number")))
await app.send_message(owner_id, f"Error occured by {str(msg.from_user.id)}:\nException: `{exp}`\nTraceback: `{traceback.format_exc()}`")
appendLog(f"User {str(msg.from_user.id)} could not get left water amount")
else:
await msg.reply_text(string("cancel_first"))
@app.on_message(~ filters.scheduled & filters.command(["topup", "refill", "поповнити"], prefixes=["/", ""]))
async def topup_cmd(_: Client, msg: Message):
async def topup_cmd(_, msg):
if userGet(msg.from_user.id, "context") is None:
try:
if "card" in jsonLoad("data/database.json")[str(msg.from_user.id)]:
@ -89,13 +87,13 @@ async def topup_cmd(_: Client, msg: Message):
await msg.reply_text(string("card_not_linked").format(string("get_number")))
appendLog(f"User {str(msg.from_user.id)} tried to request top up without card set")
except Exception as exp:
await msg.reply_text(str(exp))
await msg.reply_text(exp)
else:
await msg.reply_text(string("cancel_first"))
@app.on_message(~ filters.scheduled & filters.command(["start", "help", "допомога"], prefixes=["/", ""]))
async def help(_: Client, msg: Message):
async def help(_, msg):
if userGet(msg.from_user.id, "context") is None:
await msg.reply_text(string("welcome").format(string("get_number")))
if msg.from_user.language_code in jsonLoad("strings.json"):
@ -105,13 +103,13 @@ async def help(_: Client, msg: Message):
else:
await msg.reply_text(string("cancel_first"))
pid = getpid()
pid = os.getpid()
@app.on_message(~ filters.scheduled & filters.command(["kill", "die", "shutdown"], prefixes="/"))
async def kill(_: Client, msg: Message):
async def kill(_, msg):
if msg.from_user.id == owner_id:
await msg.reply_text(f"Shutting down bot with pid **{pid}**")
system(f"kill -9 {pid}")
os.system(f"kill -9 {pid}")
@app.on_message(~ filters.scheduled)
@ -124,8 +122,8 @@ async def any_message_handler(app, msg):
print(f'{nowtime()} {WHITE}Starting with PID {YELLOW}{pid}{RESET}')
app.start() # type: ignore
app.send_message(owner_id, f"Starting bot with pid **{pid}**") # type: ignore
app.start()
app.send_message(owner_id, f"Starting bot with pid **{pid}**")
app.set_bot_commands([
BotCommand("help", "Меню допомоги"),
@ -135,7 +133,7 @@ app.set_bot_commands([
BotCommand("resetcard", "Відв'язати картку"),
BotCommand("cancel", "Відмінити операцію"),
],
language_code="uk") # type: ignore
language_code="uk")
app.set_bot_commands([
BotCommand("help", "Меню допомоги"),
@ -145,7 +143,7 @@ app.set_bot_commands([
BotCommand("resetcard", "Відв'язати картку"),
BotCommand("cancel", "Відмінити операцію"),
],
language_code="ru") # type: ignore
language_code="ru")
app.set_bot_commands([
BotCommand("help", "Help menu"),
@ -154,7 +152,7 @@ app.set_bot_commands([
BotCommand("setcard", "Link card"),
BotCommand("resetcard", "Unlink card"),
BotCommand("cancel", "Cancel operation"),
]) # type: ignore
])
app.set_bot_commands([
BotCommand("help", "Help menu"),
@ -165,11 +163,11 @@ app.set_bot_commands([
BotCommand("shutdown", "Turn off the bot"),
BotCommand("cancel", "Cancel operation"),
],
scope=BotCommandScopeChat(chat_id=owner_id)) # type: ignore
scope=BotCommandScopeChat(chat_id=owner_id))
idle()
app.send_message(owner_id, f"Shutting down bot with pid **{pid}**") # type: ignore
app.send_message(owner_id, f"Shutting down bot with pid **{pid}**")
print(f'\n{nowtime()} {WHITE}Shutting down with PID {YELLOW}{pid}{RESET}')
call(f'kill -9 {pid}', shell=True)
subprocess.call(f'kill -9 {pid}', shell=True)

@ -1,29 +1,34 @@
#-*- coding: utf-8 -*-
from os import makedirs, stat
from gzip import open as gzipopen
from shutil import copyfileobj
from time import sleep
from ujson import loads, dumps
import json
import os
import shutil
import gzip
import time
from modules.colors import *
from datetime import datetime
from pathlib import Path
users_path = "users/"
logs_folder = "logs/"
path = Path(__file__).resolve().parent
days_path = str(path)+"/assets/days/"
users_path = str(path)+"/users/"
logs_folder = str(path)+"/logs/"
def jsonSave(filename, value):
with open(filename, 'w', encoding="utf-8") as f:
f.write(dumps(value, indent=4, ensure_ascii=False))
json.dump(value, f, indent=4, ensure_ascii=False)
f.close()
def jsonLoad(filename):
with open(filename, 'r', encoding="utf-8") as f:
value = loads(f.read())
value = json.load(f)
f.close()
return value
config = jsonLoad(f"config.json")
config = jsonLoad(f"{path}/config.json")
log_size = config["log_size"]
owner_id = config["owner_id"]
@ -39,12 +44,12 @@ def checkSize():
while i < 2:
try:
log = stat(logs_folder + 'latest.log')
log = os.stat(logs_folder + 'latest.log')
if (log.st_size / 1024) > log_size:
with open(logs_folder + 'latest.log', 'rb') as f_in:
with gzipopen(f'{logs_folder}{datetime.now().strftime("%d.%m.%Y_%H:%M:%S")}.zip', 'wb') as f_out:
copyfileobj(f_in, f_out)
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)
open(logs_folder + 'latest.log', 'w').close()
@ -57,7 +62,7 @@ def checkSize():
open(logs_folder + 'latest.log', 'a').close()
except:
try:
makedirs(logs_folder, exist_ok=True)
os.mkdir(logs_folder)
log = open(logs_folder + 'latest.log', 'a')
open(logs_folder + 'latest.log', 'a').close()
except:
@ -75,15 +80,14 @@ def appendLog(message):
open(logs_folder + 'latest.log', 'a').close()
except:
try:
makedirs(logs_folder, exist_ok=True)
os.mkdir(logs_folder)
log = open(logs_folder + 'latest.log', 'a')
open(logs_folder + 'latest.log', 'a').close()
except:
sleep(2)
time.sleep(2)
print('Log file could not be created')
return
print(message, flush=True)
log.write(f'[{datetime.now().strftime("%H:%M:%S | %d.%m.%Y")}] {message}\n')
log.close()

@ -1,9 +1,7 @@
#-*- coding: utf-8 -*-
from os import makedirs, path
from subprocess import check_output
from traceback import format_exc
from uuid import uuid4
import os
import traceback
from functions import *
from bs4 import BeautifulSoup
@ -18,19 +16,16 @@ async def getWaterLeft(cardid, filename, app=None):
try:
# if path.exists(f"data/pages/{str(filename)}.html") is False:
# run(["touch", f"data/pages/{str(filename)}.html"])
os.system(f'touch data/pages/{str(filename)}.html')
if config["use_compiled_page_saver"] is True:
proc = check_output(["PageSaver/pageSaver", f"https://bwtaqua.com.ua/card-topup/?id={cardid}"]) #, ">", f"data/pages/{str(filename)}.html"])
html_file = proc.decode("utf-8")
if config["use_compiled_page_saver"]:
os.system(f'PageSaver/pageSaver "https://bwtaqua.com.ua/card-topup/?id={cardid}" > data/pages/{str(filename)}.html')
else:
proc = check_output(["node", "./PageSaver/pageSaver.js", f"https://bwtaqua.com.ua/card-topup/?id={cardid}"]) #, ">", f"data/pages/{str(filename)}.html"])
html_file = proc.decode("utf-8")
os.system(f'node ./PageSaver/pageSaver.js "https://bwtaqua.com.ua/card-topup/?id={cardid}" > data/pages/{str(filename)}.html')
# with open(f'data/pages/{str(filename)}.html') as f:
# html_file = f.read()
# f.close()
with open(f'data/pages/{str(filename)}.html') as f:
html_file = f.read()
f.close()
soup = BeautifulSoup(html_file, 'html.parser')
@ -41,20 +36,11 @@ async def getWaterLeft(cardid, filename, app=None):
except Exception as exp:
appendLog(f"Exception occured: {exp} (user: {str(filename)}, cardid: {cardid})")
try:
tmp_name = str(uuid4())
makedirs("tmp", exist_ok=True)
with open(path.join("tmp", tmp_name), "w", encoding="utf-8") as f:
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")
if app != None:
await app.send_message(config["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)
await app.send_message(config["owner_id"], f"**Exception occured:**\n • User: `{str(filename)}`\n • Card: [{cardid}]({url})\n • Exception: `{exp}`\n • Traceback: `{traceback.format_exc()}`", disable_web_page_preview=True)
else:
appendLog(f'Exception occured and could not send to user: {exp}')
print(f'Exception occured and could not send to user: {exp}')
output = "Failure"

@ -1,4 +1,3 @@
beautifulsoup4~=4.11.1
pyrogram~=2.0.80
pathlib~=1.0.1
ujson~=5.6.0
pyrogram~=2.0.70
pathlib~=1.0.1