Skip to content

Commit

Permalink
Merge branch 'release/1.2.1' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
Archie committed Nov 15, 2020
2 parents 7de96f3 + 8072e5f commit 540a25c
Show file tree
Hide file tree
Showing 4 changed files with 69 additions and 55 deletions.
7 changes: 7 additions & 0 deletions api.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from aiohttp import ClientSession
from time import sleep


class Tele2Api:
Expand Down Expand Up @@ -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):
Expand Down
8 changes: 2 additions & 6 deletions auth.py
Original file line number Diff line number Diff line change
@@ -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():
Expand Down Expand Up @@ -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)
88 changes: 39 additions & 49 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand All @@ -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 +
Expand All @@ -46,22 +43,22 @@ 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')
for lot in active_lots:
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
Expand All @@ -72,20 +69,19 @@ 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


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
Expand All @@ -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:
Expand All @@ -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

Expand All @@ -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:
Expand All @@ -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')

Expand All @@ -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):
Expand All @@ -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):
Expand All @@ -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):
Expand All @@ -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)
21 changes: 21 additions & 0 deletions utils.py
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 540a25c

Please sign in to comment.