Skip to content

Commit

Permalink
Adding command line options, with --verbose and --dryrun, while remov…
Browse files Browse the repository at this point in the history
…ing the global variable in the TenbisLogic.py file.
  • Loading branch information
kfiry77 committed Oct 29, 2023
1 parent 4ba5ccc commit f866166
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 20 deletions.
4 changes: 2 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,8 @@ dmypy.json
# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/
# Cython self.args.verbose symbols
cython_self.args.verbose/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
Expand Down
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,17 @@ apt install weasyprint
PATH=%PATH%;C:\Program Files\GTK3-Runtime Win64\bin
```

Execute script ``main``` initially, to acquire authentication tokens, you will get SMS with OTP, type it on the command line.
Execute script ```main``` to acquire authentication tokens, you will get SMS with OTP, type it on the command line.

note:purchase won't be submitted if -d is specified.
```sh
python3 main.py
python3 main.py -d
```

Add the script to the system crontab, by typing ```crontab -e ``` and adding the following line to it.
```
crontab -e
0 23 * * * usr/bin/python3 /path/to/your/script/main.py >> /path/to/your/log/10bot.log 2>&1 &
0 23 * * * usr/bin/python3 /path/to/your/script/main.py [-v] [-d] >> /path/to/your/log/10bot.log 2>&1 &
```

## references:
Expand Down
24 changes: 12 additions & 12 deletions TenbisLogic.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
TENBIS_FQDN = "https://www.10bis.co.il"
CWD = os.getcwd()
DEBUG = False
DRYRUN = True


def print_hebrew(heb_txt):
Expand Down Expand Up @@ -41,7 +39,8 @@ class Tenbis:
SESSION_PATH = f"{CWD}/sessions.pickle"
LAST_STATE_PATH = f"{CWD}/last_state.pickle"

def __init__(self):
def __init__(self, args):
self.args = args
self.session = None
self.cart_guid = None
self.user_id = None
Expand All @@ -59,7 +58,7 @@ def post_next_api(self, endpoint, payload):
resp_json = json.loads(response.text)
error_msg = resp_json['Errors']
success_code = resp_json['Success']
if DEBUG:
if self.args.verbose:
print("Request:" + endpoint + "\nHeaders:" + json.dumps(headers) + "\n" +
"Request Payload:" + json.dumps(payload))
print("Response: " + str(response.status_code))
Expand Down Expand Up @@ -119,7 +118,7 @@ def is_budget_available(self):
# check if it is a working day, if not return
today = datetime.today()
if today.weekday() == 5 or today.weekday() == 4:
if DEBUG:
if self.args.verbose:
print(f'{today} Is Non working day')
return False

Expand All @@ -135,7 +134,7 @@ def is_budget_available(self):
h_ends = datetime.strptime(h['HolidayEnds'], date_format)
h_name = h['Name']
if h_start <= today <= h_ends:
if DEBUG:
if self.args.verbose:
print(f'{today} is {h_name}')
return False

Expand All @@ -145,22 +144,21 @@ def is_budget_available(self):
# option1 - check the last order, and check
last_order_is_today = (report['Data']['orderList'][-1]['orderDateStr'] == datetime.today().strftime("%d.%m.%y"))
if last_order_is_today:
if DEBUG:
if self.args.verbose:
print(f'last_order_check:{last_order_is_today}')
return False

# check if usage for today > 0
daily_usage = report['Data']['moneycards'][0]['usage']['daily']
if daily_usage > 0:
if DEBUG:
if self.args.verbose:
print(f'Today usage is:{daily_usage}')
return False

return True

def buy_coupon(self, coupon):
session = self.session

payload = {"culture": "he-IL", "uiCulture": "he"}
resp_json = self.post_next_api('GetUser', payload)
self.cart_guid = resp_json['ShoppingCartGuid']
Expand Down Expand Up @@ -203,7 +201,7 @@ def buy_coupon(self, coupon):
if not success_code:
print_hebrew((error_msg[0]['ErrorDesc']))
return
if DEBUG:
if self.args.verbose:
print("Request:" + endpoint)
print("Response: " + str(response.status_code))
print(resp_json)
Expand All @@ -217,13 +215,15 @@ def buy_coupon(self, coupon):
"expirationDate": None, "isDisabled": False, "editMode": False}]}
self.post_next_api('SetPaymentsInOrder', payload)

if DRYRUN:
if self.args.dryrun:
print("Dry Run success, purchase will be skipped.")
return

# SubmitOrder
payload = {"shoppingCartGuid": self.cart_guid, "culture": "he-IL", "uiCulture": "he", "isMobileDevice": True,
"dontWantCutlery": False, "orderRemarks": None}
resp_json = self.post_next_api('SubmitOrder', payload)
print("Order submitted successfully")

session.cart_guid = resp_json['ShoppingCartGuid']
# save the last session state to the pickle file for next auth.
Expand Down Expand Up @@ -253,7 +253,7 @@ def get_unused_coupons(self):
f"/NextApi/GetOrderBarcode?culture=he-IL&uiCulture=he&orderId={order_id}&resId={res_id}")
headers = {"content-type": "application/json"}
response = self.session.get(endpoint, headers=headers)
if DEBUG:
if self.args.verbose:
print(endpoint + "\n" + str(response.status_code) + "\n" + response.text)
r = json.loads(response.text)
error_msg = r['Error']
Expand Down
9 changes: 6 additions & 3 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
from TenbisLogic import *
from CouponsFormatter import *
from ReportWriter import *
from sys import platform
import sys
import argparse


def main(argv):
ten_bis = Tenbis()
parser = argparse.ArgumentParser(prog='10Bot')
parser.add_argument('-v', '--verbose', help='enable detailed logging', action='store_true')
parser.add_argument('-d', '--dryrun', help='Dry run to test all HTTP calls to NextAPI', action='store_true')
args = parser.parse_args()

ten_bis = Tenbis(args)
budget_available = ten_bis.is_budget_available()
print('budget available=', budget_available)
if budget_available:
ten_bis.buy_coupon(40)
coupons = ten_bis.get_unused_coupons()

formatter = CouponFormatter(coupons)
pdf_writer = None
pdf_writer = ReportWriterPdf()
html_writer = ReportWriterHtml()

Expand Down

0 comments on commit f866166

Please sign in to comment.