-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
87 lines (69 loc) Β· 2.79 KB
/
main.py
File metadata and controls
87 lines (69 loc) Β· 2.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import os
import sys
import json
import time
from scraper import fetch_products, MAX_PAGES, PAGES_PER_RUN
from filters import filter_deals, load_posted, save_posted, MIN_DISCOUNT
from telegram_poster import post_deal
POSTED_FILE = "posted.json"
STATE_FILE = "state.json"
MAX_POSTS_PER_RUN = 50
DELAY_BETWEEN_POSTS = 3
DEFAULT_COUPON_CODE = "gado1996"
def _load_state() -> dict:
try:
with open(STATE_FILE) as f:
return json.load(f)
except Exception:
return {"next_page": 1}
def _save_state(state: dict) -> None:
with open(STATE_FILE, "w") as f:
json.dump(state, f, indent=2)
def run(dry_run: bool = False) -> None:
bot_token = os.environ.get("TELEGRAM_BOT_TOKEN")
channel_id = os.environ.get("TELEGRAM_CHANNEL_ID", "@noon_hot_deals")
coupon = os.environ.get("NOON_COUPON_CODE", DEFAULT_COUPON_CODE).strip()
if not bot_token and not dry_run:
raise ValueError("TELEGRAM_BOT_TOKEN is required")
state = _load_state()
start_page = state.get("next_page", 1)
print(f"Fetching Noon Egypt deals (pages {start_page}β{start_page + PAGES_PER_RUN - 1})...")
products = fetch_products(start_page=start_page)
print(f"Found {len(products)} products")
if not products:
print("No products found β resetting page cursor to 1 for next run.")
_save_state({"next_page": 1})
return
already_posted = load_posted(POSTED_FILE)
new_deals = filter_deals(products, already_posted)
print(f"{len(new_deals)} new qualifying deals (>={MIN_DISCOUNT}% off)")
if not new_deals:
print("Nothing new to post.")
return
new_deals.sort(key=lambda x: x["discount_pct"], reverse=True)
to_post = new_deals[:MAX_POSTS_PER_RUN]
posted = 0
for product in to_post:
if dry_run:
print(f"[DRY RUN] {product['name']} ({product['discount_pct']}% off) -> {product['url']} [coupon: {coupon}]")
already_posted[product["sku"]] = True
posted += 1
continue
if post_deal(product, bot_token, channel_id, coupon=coupon):
already_posted[product["sku"]] = True
posted += 1
print(f"Posted: {product['name']} ({product['discount_pct']}% off)")
if posted < len(to_post):
time.sleep(DELAY_BETWEEN_POSTS)
else:
print(f"Failed: {product['name']}")
next_page = start_page + PAGES_PER_RUN
if next_page > MAX_PAGES:
next_page = 1
already_posted = {}
print("Full cycle complete β resetting posted history for next round.")
_save_state({"next_page": next_page})
save_posted(already_posted, POSTED_FILE)
print(f"Done. Posted {posted} deals. Next run starts at page {next_page}.")
if __name__ == "__main__":
run(dry_run="--dry-run" in sys.argv)