From 8072e5f49e90fa7fcd6a97bd6095ab37c8f22615 Mon Sep 17 00:00:00 2001 From: Archie Date: Sun, 15 Nov 2020 16:31:58 +0500 Subject: [PATCH] color fixes, refactor, better error handling --- api.py | 7 +++++ auth.py | 8 ++---- main.py | 88 +++++++++++++++++++++++++------------------------------- utils.py | 21 ++++++++++++++ 4 files changed, 69 insertions(+), 55 deletions(-) create mode 100644 utils.py diff --git a/api.py b/api.py index 446dc42..5dd1349 100644 --- a/api.py +++ b/api.py @@ -1,4 +1,5 @@ from aiohttp import ClientSession +from time import sleep class Tele2Api: @@ -52,10 +53,16 @@ async def sell_lot(self, lot): 'volume': {'value': lot['amount'], 'uom': 'min' if lot['lot_type'] == 'voice' else 'gb'} }) + # TODO: вместо ожидания 0.5 поставить что-то более полезное, + # одновременно не получается выставлять больше ((( + sleep(0.5) return await response.json() async def return_lot(self, lot_id): response = await self.session.delete(f'{self.market_api}/{lot_id}') + # TODO: вместо ожидания 0.5 поставить что-то более полезное, + # одновременно не получается выставлять больше ((( + sleep(0.5) return await response.json() async def get_active_lots(self): diff --git a/auth.py b/auth.py index c2ad251..c038334 100644 --- a/auth.py +++ b/auth.py @@ -1,12 +1,11 @@ -import asyncio import json import re -import os from datetime import datetime import inquirer as console from colorama import init as colorama_init, Fore from api import Tele2Api +from utils import run_main def input_phone_number(): @@ -69,10 +68,7 @@ async def main(): async with Tele2Api(phone_number) as api: access_token = await get_access_token(api, phone_number) save_config(phone_number, access_token) - os.system('pause') if __name__ == '__main__': - event_loop = asyncio.get_event_loop() - future = asyncio.ensure_future(main()) - event_loop.run_until_complete(future) + run_main(main) diff --git a/main.py b/main.py index 2c5deff..66c63d9 100644 --- a/main.py +++ b/main.py @@ -2,16 +2,13 @@ import json import math import re -import os from datetime import datetime, timedelta import inquirer as console from colorama import init as colorama_init, Fore -from api import Tele2Api - -def print_version(): - print('tele2-profit v1.2.0') +from api import Tele2Api +from utils import run_main def load_config(): @@ -27,7 +24,7 @@ async def check_auth(api: Tele2Api): code = await api.check_auth_code() if code == 401: print(Fore.RED + - 'Token invalid or expired. Get new with ' + Fore.BLUE + 'auth.py') + 'Token invalid or expired. Get new with ' + Fore.YELLOW + 'auth.py') exit() elif code != 200: print(Fore.RED + @@ -46,14 +43,14 @@ def print_token_time(date): async def delete_active_lots(api: Tele2Api): tasks = [] - print('Checking active lots...') + print(Fore.WHITE + 'Checking active lots...') active_lots = await api.get_active_lots() count = len(active_lots) if count: print(Fore.MAGENTA + f'You have {count} active lot{"s" if count > 1 else ""}:') for lot in active_lots: - color = Fore.BLUE if lot['trafficType'] == 'voice' else Fore.GREEN + color = Fore.YELLOW if lot['trafficType'] == 'voice' else Fore.GREEN print(color + f'\t{lot["volume"]["value"]} {lot["volume"]["uom"]} ' f'for {int(lot["cost"]["amount"])} rub') @@ -61,7 +58,7 @@ async def delete_active_lots(api: Tele2Api): task = asyncio.ensure_future(api.return_lot(lot['id'])) tasks.append(task) await asyncio.gather(*tasks) - print('All active lots have been deleted!') + print(Fore.GREEN + 'All active lots have been deleted!') else: print(Fore.MAGENTA + 'You don\'t have any active lots.') return active_lots @@ -72,10 +69,10 @@ async def print_rests(api: Tele2Api): print(Fore.CYAN + 'note: only plan (not market-bought ones nor transferred)' ' rests can be sold') rests = await api.get_rests() - print('You have') - print(Fore.BLUE + f'\t{rests["voice"]} min') + print(Fore.WHITE + 'You have') + print(Fore.YELLOW + f'\t{rests["voice"]} min') print(Fore.GREEN + f'\t{rests["data"]} gb') - print('\t\tavailable to sell.') + print(Fore.WHITE + '\t\tavailable to sell.') return rests @@ -83,9 +80,8 @@ def input_lots(data_left, display_name, min_amount, max_multiplier, price_multiplier, lot_type): lots_to_sell = [] index = 1 - while data_left >= min_amount: - user_input = input(f'\t{display_name}s lot {index} >>> ') + user_input = input(Fore.WHITE + f'\t{display_name}s lot {index} >>> ') if user_input == '': break @@ -100,11 +96,11 @@ def input_lots(data_left, display_name, min_amount, max_multiplier, amount = lot_data[0] if amount < min_amount: print(Fore.RED + - f'\tErr: {display_name.capitalize()} lot amount must be ' + f'\tOops: {display_name.capitalize()} lot amount must be ' f'> {min_amount}') continue elif amount > data_left: - print(Fore.RED + f'\tErr: You only have {data_left} left') + print(Fore.RED + f'\tOops: You only have {data_left} left') continue if len(lot_data) == 1: @@ -113,12 +109,12 @@ def input_lots(data_left, display_name, min_amount, max_multiplier, price = lot_data[1] if price < math.ceil(amount * price_multiplier): print(Fore.RED + - f'\tErr: {display_name.capitalize()} lot price must be >=' + f'\tOops: {display_name.capitalize()} lot price must be >=' f' ({price_multiplier} * amount)') continue elif price > max_multiplier * amount: print(Fore.RED + - f'\tErr: {display_name.capitalize()} lot price must be <=' + f'\tOops: {display_name.capitalize()} lot price must be <=' f' ({max_multiplier} * amount)') continue @@ -141,7 +137,7 @@ def input_lots(data_left, display_name, min_amount, max_multiplier, async def prepare_lots(rests): lots_to_sell = [] if rests['voice'] >= 50: - print(Fore.BLUE + '1. Prepare minute lots:') + print(Fore.YELLOW + '1. Prepare minute lots:') lots_to_sell += input_lots(rests['voice'], 'minute', 50, 2, 0.8, 'voice') if rests['data'] >= 1: @@ -157,7 +153,7 @@ def print_prepared_lots(prepared_lots): print(Fore.LIGHTMAGENTA_EX + f'Ok. You have prepared {count} lot{"s" if count > 1 else ""}:') for lot in prepared_lots: - color = Fore.BLUE if lot['lot_type'] == 'voice' else Fore.GREEN + color = Fore.YELLOW if lot['lot_type'] == 'voice' else Fore.GREEN print(color + f'\t{lot["amount"]} {lot["name"]} ' f'for {lot["price"]} rub') @@ -175,13 +171,18 @@ def prepare_old_lots(old_lots: list): def print_lot_listing_status(lots: list): for lot in lots: - if lot['meta']['status'] == 'OK': + lot_status = lot['meta']['status'] + if lot_status == 'OK': + color = Fore.YELLOW if lot['data']['trafficType'] == 'voice' \ + else Fore.GREEN amount = lot['data']['volume']['value'] uom = lot['data']['volume']['uom'] cost = lot['data']['cost']['amount'] - print(Fore.GREEN + f'Successful listing {amount} {uom} for {cost} rub.') + print(color + + f'Successful listing {amount} {uom} for {cost} rub.') else: - print(Fore.RED + 'Error during listing. Try again') + print(Fore.RED + + f'Error during listing: {lot_status}') async def sell_prepared_lots(api: Tele2Api, lots: list): @@ -192,11 +193,6 @@ async def sell_prepared_lots(api: Tele2Api, lots: list): print('Listing...') lots = await asyncio.gather(*tasks) print_lot_listing_status(lots) - if any(lot['meta']['status'] == 'bp_err_limDay' for lot in lots): - print(Fore.MAGENTA + - 'Day listing limit (100) reached. Try again tomorrow.') - else: - print(Fore.BLUE + 'Lots have been listed to sell.') async def display_menu(have_lots_returned: bool): @@ -209,13 +205,13 @@ async def display_menu(have_lots_returned: bool): async def menu_new_action(api): rests = await print_rests(api) prepared_lots = await prepare_lots(rests) - print(Fore.YELLOW + '-----') + print(Fore.MAGENTA + '-----') if len(prepared_lots): print_prepared_lots(prepared_lots) if console.confirm('Sell prepared lots?', default=True): await sell_prepared_lots(api, prepared_lots) else: - print(Fore.BLUE + 'You did not prepared any lots.') + print(Fore.YELLOW + 'You did not prepared any lots.') async def menu_again_action(api, deleted_lots): @@ -225,40 +221,34 @@ async def menu_again_action(api, deleted_lots): async def print_balance(api): balance = await api.get_balance() - print(Fore.BLUE + f'Balance: {balance} rub.') - - -def init_script(): - colorama_init(False) - print_version() + print(Fore.YELLOW + 'Balance: ' + Fore.MAGENTA + f'{balance} rub.') async def main(): access_token, date, phone_number = load_config() async with Tele2Api(phone_number, access_token) as api: - # script initialization - - init_script() - + # script initialization: + + colorama_init(False) + # logic pipeline: - + await check_auth(api) print_token_time(date) await print_balance(api) deleted_lots = await delete_active_lots(api) - print(Fore.YELLOW + '-----') - option = await display_menu(len(deleted_lots) > 0) + + print(Fore.MAGENTA + '-----') + + option = await display_menu(have_lots_returned=len(deleted_lots) > 0) + if option == 'new': await menu_new_action(api) elif option == 'again': await menu_again_action(api, deleted_lots) elif option == 'Exit': - exit() - os.system('pause') + pass if __name__ == '__main__': - event_loop = asyncio.get_event_loop() - future = asyncio.ensure_future(main()) - event_loop.run_until_complete(future) - print(Fore.WHITE + 'Complete.') + run_main(main) diff --git a/utils.py b/utils.py new file mode 100644 index 0000000..352c9e7 --- /dev/null +++ b/utils.py @@ -0,0 +1,21 @@ +import asyncio +import os + +from colorama import Fore + + +def print_version(): + print('tele2-profit v1.2.1') + + +def run_main(main): + try: + print_version() + event_loop = asyncio.get_event_loop() + future = asyncio.ensure_future(main()) + event_loop.run_until_complete(future) + print(Fore.WHITE + 'Script done.') + if 'system' in dir(os): + os.system('pause') + except KeyboardInterrupt: + pass