From 9fb509fc2bdaaf49a5706c1c83ad6591f0c5d9be Mon Sep 17 00:00:00 2001 From: profitroll Date: Sat, 18 Mar 2023 01:15:21 +0100 Subject: [PATCH] Changed conversation handler to convopyro --- bwtbot.py | 192 ++++++++++++++++++++--------------------------- requirements.txt | 3 +- strings.json | 12 +-- 3 files changed, 87 insertions(+), 120 deletions(-) diff --git a/bwtbot.py b/bwtbot.py index 70ec35a..36c13e7 100644 --- a/bwtbot.py +++ b/bwtbot.py @@ -5,8 +5,15 @@ 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 +from pyrogram.types import ( + ForceReply, + BotCommand, + BotCommandScopeChat, + Message, + ReplyKeyboardRemove, +) from pyrogram.enums.chat_action import ChatAction +from convopyro import Conversation, listen_message from functions import * from modules.colors import * from modules.bwt import * @@ -22,31 +29,29 @@ app = Client( bot_token=config["bot_token"], ) +Conversation(app) + @app.on_message( ~filters.scheduled & filters.command(["setcard", "задать карту"], prefixes=["/", ""]) ) async def setcard(_: Client, msg: Message): - 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")), - ) - else: - await msg.reply_text(string("cancel_first")) - - -@app.on_message( - ~filters.scheduled & filters.command(["cancel", "відміна"], prefixes=["/", ""]) -) -async def cancel(_: Client, msg: Message): - if userGet(msg.from_user.id, "context") is not None: - userReset(msg.from_user.id, "context") - await msg.reply_text(string("cancel")) - else: - await msg.reply_text(string("cancel_none")) + await msg.reply_text( + string("send_number"), + reply_markup=ForceReply(placeholder=string("enter_number")), + ) + answer = await listen_message(_, msg.chat.id, timeout=None) + if answer is None: + return + elif answer.text.strip() in ["/cancel", "cancel", "/відміна", "відміна"]: + await msg.reply_text(string("cancel"), reply_markup=ReplyKeyboardRemove()) + return + userSet(answer.from_user.id, "card", answer.text) + appendLog(f"User {str(msg.from_user.id)} set card id to {answer.text}") + await msg.reply_text( + string("card_linked").format(answer.text), reply_markup=ReplyKeyboardRemove() + ) @app.on_message( @@ -54,69 +59,57 @@ async def cancel(_: Client, msg: Message): & filters.command(["resetcard", "забути картку"], prefixes=["/", ""]) ) async def resetcard(_: Client, msg: Message): - 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") - await msg.reply_text(string("card_unlinked")) - appendLog(f"User {str(msg.from_user.id)} reseted his card") - else: - await msg.reply_text(string("card_not_linked").format(string("get_number"))) - appendLog(f"User {str(msg.from_user.id)} tried to reset non-existent card") + if "card" in jsonLoad("data/database.json")[str(msg.from_user.id)]: + userReset(msg.from_user.id, "card") + await msg.reply_text(string("card_unlinked")) + appendLog(f"User {str(msg.from_user.id)} reseted his card") else: - await msg.reply_text(string("cancel_first")) + await msg.reply_text(string("card_not_linked").format(string("get_number"))) + appendLog(f"User {str(msg.from_user.id)} tried to reset non-existent card") @app.on_message( ~filters.scheduled & filters.command(["balance", "баланс"], prefixes=["/", ""]) ) async def balance(_: Client, msg: Message): - if userGet(msg.from_user.id, "context") is None: - try: - if "card" in jsonLoad("data/database.json")[str(msg.from_user.id)]: - await app.send_chat_action( - chat_id=msg.chat.id, action=ChatAction.TYPING - ) - water_left = await getWaterLeft( - userGet(msg.from_user.id, "card"), msg.from_user.id, app - ) - if water_left == "": - await msg.reply_text( - string("error_new").format( - f'https://bwtaqua.com.ua/card-topup/?id={userGet(msg.from_user.id, "card")}' - ) - ) - # raise EmptyCardException("Card information is empty") - elif water_left == "Failure": - await msg.reply_text( - string("error_occured").format(string("get_number")) - ) - appendLog( - f"User {str(msg.from_user.id)} could not get left water amount" - ) - else: - await msg.reply_text(string("card_balance").format(water_left)) - appendLog( - f"User {str(msg.from_user.id)} has {water_left} liters remaining" - ) - else: + try: + if "card" in jsonLoad("data/database.json")[str(msg.from_user.id)]: + await app.send_chat_action(chat_id=msg.chat.id, action=ChatAction.TYPING) + water_left = await getWaterLeft( + userGet(msg.from_user.id, "card"), msg.from_user.id, app + ) + if water_left == "": await msg.reply_text( - string("card_not_linked").format(string("get_number")) + string("error_new").format( + f'https://bwtaqua.com.ua/card-topup/?id={userGet(msg.from_user.id, "card")}' + ) ) - 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"]: + # raise EmptyCardException("Card information is empty") + elif water_left == "Failure": 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()}`", + appendLog( + f"User {str(msg.from_user.id)} could not get left water amount" + ) + else: + await msg.reply_text(string("card_balance").format(water_left)) + appendLog( + f"User {str(msg.from_user.id)} has {water_left} liters remaining" + ) + else: + 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" ) - appendLog(f"User {str(msg.from_user.id)} could not get left water amount") - else: - await msg.reply_text(string("cancel_first")) + 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()}`", + ) + appendLog(f"User {str(msg.from_user.id)} could not get left water amount") @app.on_message( @@ -124,27 +117,20 @@ async def balance(_: Client, msg: Message): & filters.command(["topup", "refill", "поповнити"], prefixes=["/", ""]) ) async def topup_cmd(_: Client, msg: Message): - if userGet(msg.from_user.id, "context") is None: - try: - if "card" in jsonLoad("data/database.json")[str(msg.from_user.id)]: - await app.send_chat_action( - chat_id=msg.chat.id, action=ChatAction.TYPING - ) - await msg.reply_text( - string("top_up").format(str(userGet(msg.from_user.id, "card"))) - ) - appendLog(f"User {str(msg.from_user.id)} requested top up") - else: - 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)) - else: - await msg.reply_text(string("cancel_first")) + try: + if "card" in jsonLoad("data/database.json")[str(msg.from_user.id)]: + await app.send_chat_action(chat_id=msg.chat.id, action=ChatAction.TYPING) + await msg.reply_text( + string("top_up").format(str(userGet(msg.from_user.id, "card"))) + ) + appendLog(f"User {str(msg.from_user.id)} requested top up") + else: + 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)) @app.on_message( @@ -152,14 +138,11 @@ async def topup_cmd(_: Client, msg: Message): & filters.command(["start", "help", "допомога"], prefixes=["/", ""]) ) async def help(_: Client, msg: Message): - 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"): - userSet(msg.from_user.id, "locale", msg.from_user.language_code) - else: - userSet(msg.from_user.id, "locale", "en") + await msg.reply_text(string("welcome").format(string("get_number"))) + if msg.from_user.language_code in jsonLoad("strings.json"): + userSet(msg.from_user.id, "locale", msg.from_user.language_code) else: - await msg.reply_text(string("cancel_first")) + userSet(msg.from_user.id, "locale", "en") pid = getpid() @@ -174,15 +157,6 @@ async def kill(_: Client, msg: Message): system(f"kill -9 {pid}") -@app.on_message(~filters.scheduled) -async def any_message_handler(app, msg): - if userGet(msg.from_user.id, "context") == "set": - userSet(msg.from_user.id, "card", msg.text) - userReset(msg.from_user.id, "context") - appendLog(f"User {str(msg.from_user.id)} set card id to {msg.text}") - await msg.reply_text(string("card_linked").format(msg.text)) - - print(f"{nowtime()} {WHITE}Starting with PID {YELLOW}{pid}{RESET}") app.start() # type: ignore @@ -195,7 +169,6 @@ app.set_bot_commands( BotCommand("topup", "Поповнити картку"), BotCommand("setcard", "Прив'язати картку"), BotCommand("resetcard", "Відв'язати картку"), - BotCommand("cancel", "Відмінити операцію"), ], language_code="uk", ) # type: ignore @@ -207,7 +180,6 @@ app.set_bot_commands( BotCommand("topup", "Поповнити картку"), BotCommand("setcard", "Прив'язати картку"), BotCommand("resetcard", "Відв'язати картку"), - BotCommand("cancel", "Відмінити операцію"), ], language_code="ru", ) # type: ignore @@ -219,7 +191,6 @@ app.set_bot_commands( BotCommand("topup", "Refill card"), BotCommand("setcard", "Link card"), BotCommand("resetcard", "Unlink card"), - BotCommand("cancel", "Cancel operation"), ] ) # type: ignore @@ -231,7 +202,6 @@ app.set_bot_commands( BotCommand("setcard", "Link card"), BotCommand("resetcard", "Unlink card"), BotCommand("shutdown", "Turn off the bot"), - BotCommand("cancel", "Cancel operation"), ], scope=BotCommandScopeChat(chat_id=owner_id), ) # type: ignore diff --git a/requirements.txt b/requirements.txt index be0cc61..178b2c2 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,5 +1,6 @@ beautifulsoup4~=4.11.2 +convopyro==0.5 pyrogram~=2.0.102 -pathlib~=1.0.1 tgcrypto~=1.2.5 +pathlib~=1.0.1 ujson~=5.7.0 \ No newline at end of file diff --git a/strings.json b/strings.json index 65a85f6..45ebba3 100644 --- a/strings.json +++ b/strings.json @@ -4,16 +4,14 @@ "get_number": "**Get card number (Var. 1):**\nOn the front bottom side of your card, number may be found\n\n**Get card number (Var. 2):**\n1. Scan QR on the card\n2. Open webpage from code\n3. Numer should be found in **Номер карти \"Здорова Вода\"** or **Номер карти BWT Aqua** fields", "card_linked": "Linked card: `{0}`\n\nPlease, make sure the number is correct before using the bot", "card_unlinked": "Card was unlinked from your Telegram", - "card_not_linked": "You don't have any linked card.\n\nВы можете задать её с помощью команды /setcard\n\n{0}", + "card_not_linked": "You don't have any linked card.\n\nВYou can set it using /setcard\n\n{0}", "error_occured": "An error occurred while getting the amount of remaining water on the card.\n\nPlease make sure the linked card number is correct. If you are sure that the bot is broken, please contact @profitroll.\n\nLink your card: /setcard\n\n{0}", "error_new": "An error occurred while getting the amount of remaining water on the card.\n\nLast a few weeks BWT seems to return empty string to balance request from our server. We assume that our server has been blacklisted.\n\nTo check your balance you can use official [BWT App](https://bwtaqua.com.ua/en/#app) or simply bookmark this page: {0}.", "card_balance": "Card's balance is {0} l. of water", "top_up": "[Click here to top up](https://bwtaqua.com.ua/card-topup/?id={0})", "cancel": "Operation cancelled", - "cancel_none": "Nothing to cancel", - "cancel_first": "Operation ongoing. Cancel the current one using /cancel to run this action", "enter_number": "Enter card number", - "send_number": "Please, send your card number" + "send_number": "Please, send your card number\nIf you want to abort this operation, use /cancel" }, "uk": { "welcome": "Привіт-привіт!\n\nЦей бот дозволяє дізнатись скільки літрів залишилось на вашій карточці.\n\n**Команди:**\n • /balance – дізнатись баланс карти\n • /setcard – приав'язати карту\n • /resetcard – відв'язати карту\n\n{0}\n\nРозробник **не має жодного відношення до BWT Aqua**, а бот створений лише для особистого, некомерційного використання.", @@ -25,10 +23,8 @@ "error_new": "При отриманні води на карточці виникла помилка.\n\nОстанні тижні BWT повертає нашому серверу порожні строки замість балансу. Є підозри, що сервер потрапив у блеклист.\n\nДля перевірки балансу рекомендуємо користуватись офіційним [додатком BWT](https://bwtaqua.com.ua/#app) або просто додати цю сторінку у закладки: {0}.", "card_balance": "На карточці {0} л. води", "top_up": "[Натисніть для поповнення](https://bwtaqua.com.ua/card-topup/?id={0})", - "cancel": "Операція відмінена", - "cancel_none": "Нема що відміняти", - "cancel_first": "Триває інша операція. Відмініть триваючу операцію командою /cancel щоб запустити іншу дію", + "cancel": "Операцію скасовано", "enter_number": "Введіть номер картки", - "send_number": "Будь ласка, надішліть номер вашої картки" + "send_number": "Будь ласка, надішліть номер вашої картки\nЯкщо ви хочете скасувати цю операцію, використовуйте /cancel" } } \ No newline at end of file