forked from Muklaszin/shopee-flash-sale-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflash_sale_v4.py
More file actions
1581 lines (1357 loc) · 56.9 KB
/
Copy pathflash_sale_v4.py
File metadata and controls
1581 lines (1357 loc) · 56.9 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Shopee Flash Sale Sniper Bot v4 — Ultimate Edition
New features:
- 📂 Multi-account support (accounts/ directory, parallel execution)
- 📋 YAML config file (config.yaml — all settings externalized)
- 🔍 Keyword filter (include/exclude keywords, case-insensitive)
- 🗄️ SQLite database (purchase history tracking)
- 👁️ Always-on monitor mode (--monitor flag, auto-buy on price drop)
- 📝 File-based logging (rotation, both console and file handlers)
- 🐳 Docker support (Dockerfile + docker-compose.yml)
"""
import argparse
import asyncio
import hashlib
import json
import logging
import logging.handlers
import os
import random
import re
import signal
import sys
import time
from dataclasses import dataclass, field
from datetime import datetime, timezone, timedelta
from logging.handlers import RotatingFileHandler
from pathlib import Path
from typing import Any, Optional
from urllib.parse import urlparse, parse_qs
import aiohttp
import yaml
try:
import ntplib as _ntplib
HAS_NTP = True
except ImportError:
HAS_NTP = False
import sqlite3
from functools import partial
# ═══════════════════════════════════════════════════════════
# SHOPEE API ENDPOINTS
# ═══════════════════════════════════════════════════════════
BASE = "https://shopee.co.id"
API = {
"item_info": f"{BASE}/api/v2/item/get",
"flash_sale": f"{BASE}/api/v4/flash_sale/flash_sale_batch_get_items",
"flash_sessions": f"{BASE}/api/v4/flash_sale/get_all_sessions",
"account_info": f"{BASE}/api/v2/user/account_info",
"addresses": f"{BASE}/api/v1/addresses",
"add_cart": f"{BASE}/api/v4/cart/add_to_cart",
"checkout_get": f"{BASE}/api/v4/checkout/get_quick",
"place_order": f"{BASE}/api/v4/checkout/place_order",
}
HEADERS_BASE = {
"User-Agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/131.0.0.0 Safari/537.36"
),
"Accept": "application/json",
"Content-Type": "application/json",
"Referer": "https://shopee.co.id/",
"Origin": "https://shopee.co.id",
"X-Requested-With": "XMLHttpRequest",
"X-API-Source": "pc",
"X-Shopee-Language": "id",
"af-ac-enc-dat": "null",
}
# ═══════════════════════════════════════════════════════════
# CONFIG — YAML-based configuration with defaults
# ═══════════════════════════════════════════════════════════
@dataclass
class Config:
"""Loads configuration from YAML file with sensible defaults."""
# Main settings
cookie_dir: str = "accounts"
default_max_price: int = 1000
scan_pages: int = 5
concurrent_requests: int = 5
request_delay: float = 0.02
subtract_seconds: float = 0.5
max_retries: int = 10
payment_channel_id: int = 8001400
# Keyword filter
include_keywords: list[str] = field(default_factory=list)
exclude_keywords: list[str] = field(default_factory=list)
# Proxy
proxy_file: str = "proxies.txt"
proxy_protocol: str = "http"
proxy_rotate: bool = True
# Telegram
telegram_bot_token: str = ""
telegram_chat_id: str = ""
# Database
database: str = "shopee_sniper.db"
# Monitor mode
monitor_interval: int = 60
monitor_price_drop_threshold: float = 0.9
# Logging
log_dir: str = "logs"
log_level: str = "INFO"
def __post_init__(self) -> None:
# Normalize log level
self.log_level = self.log_level.upper()
@classmethod
def load(cls, path: str = "config.yaml") -> "Config":
"""Load config from YAML file. Missing keys use defaults."""
cfg = cls()
if not os.path.exists(path):
print(f"⚠️ Config file {path} not found, using defaults")
return cfg
try:
with open(path, "r") as f:
data = yaml.safe_load(f) or {}
except Exception as e:
print(f"⚠️ Error loading config: {e}, using defaults")
return cfg
for key, value in data.items():
if hasattr(cfg, key):
setattr(cfg, key, value)
cfg.__post_init__()
return cfg
def account_config(self, account_dir: str) -> dict:
"""Load per-account config override from account_dir/config.yaml."""
override_path = os.path.join(account_dir, "config.yaml")
overrides: dict[str, Any] = {}
if os.path.exists(override_path):
try:
with open(override_path, "r") as f:
overrides = yaml.safe_load(f) or {}
except Exception as e:
print(f"⚠️ Error loading account config {override_path}: {e}")
result: dict[str, Any] = {
"max_price": overrides.get("max_price", self.default_max_price),
"payment_channel_id": overrides.get("payment_channel_id", self.payment_channel_id),
"include_keywords": overrides.get("include_keywords", self.include_keywords),
"exclude_keywords": overrides.get("exclude_keywords", self.exclude_keywords),
}
return result
# ═══════════════════════════════════════════════════════════
# DATABASE — SQLite purchase attempt logger
# ═══════════════════════════════════════════════════════════
class Database:
"""Async SQLite database for logging purchase attempts.
Uses stdlib sqlite3 with asyncio.to_thread() — no external dependencies needed.
"""
def __init__(self, db_path: str = "shopee_sniper.db"):
self.db_path = db_path
self._conn: "sqlite3.Connection | None" = None
async def connect(self) -> None:
def _open() -> sqlite3.Connection:
conn = sqlite3.connect(self.db_path)
conn.row_factory = sqlite3.Row
return conn
self._conn = await asyncio.to_thread(_open)
await self._create_tables()
print(f"🗄️ SQLite database: {self.db_path}")
async def _create_tables(self) -> None:
def _create(conn: sqlite3.Connection) -> None:
conn.execute("""
CREATE TABLE IF NOT EXISTS purchases (
id INTEGER PRIMARY KEY AUTOINCREMENT,
item_id INTEGER NOT NULL,
shop_id INTEGER NOT NULL,
model_id INTEGER NOT NULL,
item_name TEXT DEFAULT '',
price_idr REAL DEFAULT 0,
account_name TEXT DEFAULT '',
success INTEGER DEFAULT 0,
error_message TEXT DEFAULT '',
latency_ms REAL DEFAULT 0,
timestamp TEXT DEFAULT (datetime('now', '+7 hours')),
mode TEXT DEFAULT 'auto'
)
""")
conn.commit()
if self._conn is not None:
await asyncio.to_thread(_create, self._conn)
async def log_purchase(
self,
item_id: int,
shop_id: int,
model_id: int,
item_name: str,
price_idr: float,
account_name: str,
success: bool,
error_message: str = "",
latency_ms: float = 0,
mode: str = "auto",
) -> None:
if self._conn is None:
return
def _log(conn: sqlite3.Connection) -> None:
try:
conn.execute(
"""INSERT INTO purchases
(item_id, shop_id, model_id, item_name, price_idr,
account_name, success, error_message, latency_ms, mode)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(
item_id, shop_id, model_id, item_name, price_idr,
account_name, 1 if success else 0, error_message,
round(latency_ms, 2), mode,
),
)
conn.commit()
except Exception as e:
print(f"⚠️ DB log error: {e}")
await asyncio.to_thread(_log, self._conn)
async def recent_purchases(self, limit: int = 10) -> list[dict]:
if self._conn is None:
return []
def _recent(conn: sqlite3.Connection) -> list[dict]:
cursor = conn.execute(
"SELECT * FROM purchases ORDER BY id DESC LIMIT ?", (limit,)
)
return [dict(row) for row in cursor.fetchall()]
return await asyncio.to_thread(_recent, self._conn)
async def stats(self) -> dict:
if self._conn is None:
return {}
def _stats(conn: sqlite3.Connection) -> dict:
cursor = conn.execute(
"SELECT COUNT(*) as total, SUM(success) as successes FROM purchases"
)
row = cursor.fetchone()
return dict(row) if row else {}
return await asyncio.to_thread(_stats, self._conn)
async def close(self) -> None:
if self._conn:
def _close(conn: sqlite3.Connection) -> None:
conn.close()
await asyncio.to_thread(_close, self._conn)
self._conn = None
# ═══════════════════════════════════════════════════════════
# LOGGING SETUP
# ═══════════════════════════════════════════════════════════
def setup_logging(config: Config) -> logging.Logger:
"""Configure rotating file + console logging."""
log_dir = config.log_dir
os.makedirs(log_dir, exist_ok=True)
logger = logging.getLogger("shopee_sniper")
logger.setLevel(getattr(logging, config.log_level, logging.INFO))
logger.handlers.clear()
# Formatter
fmt = logging.Formatter(
"%(asctime)s [%(levelname)s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
# File handler with rotation (5MB per file, 3 backups)
file_handler = RotatingFileHandler(
os.path.join(log_dir, "sniper.log"),
maxBytes=5 * 1024 * 1024,
backupCount=3,
)
file_handler.setFormatter(fmt)
logger.addHandler(file_handler)
# Console handler
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(fmt)
logger.addHandler(console_handler)
return logger
# ═══════════════════════════════════════════════════════════
# STATISTICS TRACKER
# ═══════════════════════════════════════════════════════════
@dataclass
class Stats:
attempts: int = 0
successes: int = 0
failures: int = 0
rate_limits: int = 0
total_latency: float = 0
start_time: float = field(default_factory=time.time)
proxy_rotations: int = 0
def record(self, success: bool, latency: float = 0, rate_limited: bool = False) -> None:
self.attempts += 1
if success:
self.successes += 1
self.total_latency += latency
else:
self.failures += 1
if rate_limited:
self.rate_limits += 1
def summary(self) -> str:
elapsed = time.time() - self.start_time
avg_lat = (self.total_latency / self.successes * 1000) if self.successes else 0
return (
f"📊 Stats: {self.attempts} attempts | "
f"✅ {self.successes} success | ❌ {self.failures} fail | "
f"🚫 {self.rate_limits} rate-limited | "
f"⚡ {avg_lat:.0f}ms avg latency | "
f"🔄 {self.proxy_rotations} proxy rotations | "
f"⏱️ {elapsed:.0f}s total"
)
# ═══════════════════════════════════════════════════════════
# PROXY MANAGER
# ═══════════════════════════════════════════════════════════
class ProxyManager:
"""Manages proxy rotation and dead proxy tracking."""
def __init__(
self,
proxy_file: str = "",
protocol: str = "http",
single_proxy: str = "",
logger: Optional[logging.Logger] = None,
stats: Optional[Stats] = None,
):
self.proxies: list[str] = []
self.current_idx = 0
self.protocol = protocol
self.dead_proxies: set[str] = set()
self.log = logger or logging.getLogger("shopee_sniper")
self._stats = stats
if single_proxy:
self.proxies = [single_proxy]
elif proxy_file and os.path.exists(proxy_file):
with open(proxy_file) as f:
self.proxies = [
line.strip()
for line in f
if line.strip() and not line.startswith("#")
]
random.shuffle(self.proxies)
self.log.info("🔄 Loaded %d proxies from %s", len(self.proxies), proxy_file)
def get_proxy(self) -> Optional[str]:
if not self.proxies:
return None
alive = [p for p in self.proxies if p not in self.dead_proxies]
if not alive:
self.dead_proxies.clear()
alive = self.proxies
proxy = alive[self.current_idx % len(alive)]
self.current_idx += 1
return f"{self.protocol}://{proxy}"
def mark_dead(self, proxy: str) -> None:
clean = proxy.replace(f"{self.protocol}://", "")
self.dead_proxies.add(clean)
if self._stats:
self._stats.proxy_rotations += 1
@property
def has_proxies(self) -> bool:
return len(self.proxies) > 0
# ═══════════════════════════════════════════════════════════
# TELEGRAM NOTIFIER
# ═══════════════════════════════════════════════════════════
class TelegramNotifier:
"""Send purchase notifications via Telegram bot."""
def __init__(
self,
token: str = "",
chat_id: str = "",
logger: Optional[logging.Logger] = None,
):
self.token = token
self.chat_id = chat_id
self.enabled = bool(token and chat_id)
self.log = logger or logging.getLogger("shopee_sniper")
if self.enabled:
self.log.info("📱 Telegram notifications enabled → chat %s", chat_id)
async def send(self, message: str, parse_mode: str = "HTML") -> None:
if not self.enabled:
return
try:
async with aiohttp.ClientSession() as session:
url = f"https://api.telegram.org/bot{self.token}/sendMessage"
await session.post(
url,
json={
"chat_id": self.chat_id,
"text": message,
"parse_mode": parse_mode,
},
)
except Exception as e:
self.log.warning("⚠️ Telegram error: %s", e)
async def notify_success(
self,
item_name: str,
price: float,
elapsed: float,
account_name: str = "",
) -> None:
account_tag = f"👤 {account_name}\n" if account_name else ""
msg = (
f"⚡ <b>FLASH SALE BERHASIL!</b>\n\n"
f"{account_tag}"
f"🛒 {item_name}\n"
f"💰 Rp {price:,.0f}\n"
f"⏱️ {elapsed:.2f}s"
)
await self.send(msg)
async def notify_failure(
self,
item_name: str,
errors: list[str],
account_name: str = "",
) -> None:
account_tag = f"👤 {account_name}\n" if account_name else ""
msg = (
f"❌ <b>Flash Sale Gagal</b>\n\n"
f"{account_tag}"
f"🛒 {item_name}\n"
f"🚫 Errors: {', '.join(errors[:3])}"
)
await self.send(msg)
async def notify_scan(self, items: list, account_name: str = "") -> None:
if not items:
return
account_tag = f"👤 {account_name}\n" if account_name else ""
lines = [
f"🔍 <b>Flash Sale Scan — {len(items)} item ditemukan:</b>\n",
account_tag,
]
for i, item in enumerate(items[:10], 1):
lines.append(
f" {i}. Rp {item['price_idr']:,.0f} — {item['name'][:40]}"
)
await self.send("\n".join(lines))
async def notify_monitor_purchase(
self,
item_name: str,
price: float,
old_price: float,
account_name: str = "",
) -> None:
account_tag = f"👤 {account_name}\n" if account_name else ""
msg = (
f"📉 <b>Monitor Mode — Auto Buy!</b>\n\n"
f"{account_tag}"
f"🛒 {item_name}\n"
f"💰 Rp {old_price:,.0f} → Rp {price:,.0f}\n"
f"📉 Drop: {(1 - price/old_price)*100:.1f}%"
)
await self.send(msg)
# ═══════════════════════════════════════════════════════════
# HELPERS
# ═══════════════════════════════════════════════════════════
def generate_if_none_match(body_str: str) -> str:
h1 = hashlib.md5(body_str.encode()).hexdigest()
inner = hashlib.md5(("55b03" + h1 + "55b03").encode()).hexdigest()
return f"55b03-{inner}"
def get_ntp_offset() -> float:
if not HAS_NTP:
print("⚠️ ntplib not installed — using local time")
return 0.0
try:
c = _ntplib.NTPClient()
resp = c.request("pool.ntp.org", version=3, timeout=5)
return resp.offset
except Exception as e:
print(f"⚠️ NTP sync failed ({e}), using local time")
return 0.0
def get_accurate_timestamp(offset: float) -> float:
return time.time() + offset
def load_cookies(path: str) -> dict:
with open(path, "r") as f:
raw = json.load(f)
if isinstance(raw, list):
return {c["name"]: c["value"] for c in raw}
return raw
def cookie_string(cookies: dict) -> str:
return "; ".join(f"{k}={v}" for k, v in cookies.items())
def get_csrf_token(cookies: dict) -> str:
return cookies.get("csrftoken", "")
def parse_shopee_url(url: str) -> tuple[int, int]:
parsed = urlparse(url)
params = parse_qs(parsed.query)
if "itemid" in params and "shopid" in params:
return int(params["itemid"][0]), int(params["shopid"][0])
match = re.search(r"i\.(\d+)\.(\d+)", url)
if match:
return int(match.group(2)), int(match.group(1))
raise ValueError(f"Could not parse Shopee URL: {url}")
def format_price(price_raw: int) -> str:
return f"Rp {price_raw / 100000:,.0f}"
def matches_keywords(name: str, include: list[str], exclude: list[str]) -> bool:
"""Check if item name matches keyword filter rules.
- If include is non-empty, at least one keyword must match (OR logic).
- If exclude is non-empty, none of the keywords must match.
- Empty include list = include all.
- All comparisons are case-insensitive.
"""
name_lower = name.lower()
if include:
if not any(kw.lower() in name_lower for kw in include):
return False
if exclude:
if any(kw.lower() in name_lower for kw in exclude):
return False
return True
def scan_accounts(cookie_dir: str) -> list[dict]:
"""Scan cookie_dir for account subdirectories with cookies.json."""
accounts: list[dict] = []
if not os.path.isdir(cookie_dir):
print(f"⚠️ Account directory '{cookie_dir}' not found")
return accounts
for entry in sorted(os.listdir(cookie_dir)):
subpath = os.path.join(cookie_dir, entry)
if not os.path.isdir(subpath):
continue
cookie_file = os.path.join(subpath, "cookies.json")
if os.path.exists(cookie_file):
accounts.append({
"name": entry,
"dir": subpath,
"cookie_file": cookie_file,
})
print(f"👤 Found account: {entry}")
print(f"📂 Total accounts loaded: {len(accounts)}")
return accounts
# ═══════════════════════════════════════════════════════════
# SHOPEE API CLIENT (ENHANCED)
# ═══════════════════════════════════════════════════════════
class ShopeeClient:
"""Async Shopee API client with proxy support, rate limit handling, logging."""
def __init__(
self,
cookies: dict,
proxy_manager: Optional[ProxyManager] = None,
logger: Optional[logging.Logger] = None,
stats: Optional[Stats] = None,
config: Optional[Config] = None,
):
self.cookies = cookies
self.csrf_token = get_csrf_token(cookies)
self.cookie_str = cookie_string(cookies)
self.session: Optional[aiohttp.ClientSession] = None
self.address_id = 0
self.account_info: Optional[dict] = None
self.proxy_manager = proxy_manager
self.log = logger or logging.getLogger("shopee_sniper")
self._stats = stats or Stats()
self._config = config or Config()
async def _init_session(self) -> None:
if not self.session:
timeout = aiohttp.ClientTimeout(total=10)
self.session = aiohttp.ClientSession(
headers={
**HEADERS_BASE,
"Cookie": self.cookie_str,
"X-Csrftoken": self.csrf_token,
},
timeout=timeout,
)
async def _request(self, method: str, url: str, **kwargs: Any) -> dict:
await self._init_session()
body = kwargs.get("json", {})
body_str = json.dumps(body, separators=(",", ":")) if body else url
headers = kwargs.pop("headers", {})
headers["If-None-Match-"] = generate_if_none_match(body_str)
for attempt in range(3):
proxy = None
if self.proxy_manager and self.proxy_manager.has_proxies:
proxy = self.proxy_manager.get_proxy()
try:
start = time.time()
async with self.session.request(
method, url, headers=headers, proxy=proxy, **kwargs
) as resp:
latency = time.time() - start
if resp.status == 429:
self._stats.record(False, rate_limited=True)
if proxy:
self.proxy_manager.mark_dead(proxy)
self.log.warning(
"🚫 Rate limited (429), attempt %d/3", attempt + 1
)
await asyncio.sleep(0.5 * (attempt + 1))
continue
data = await resp.json()
# Check for Shopee rate limit in response body
error = data.get("error")
error_msg = str(data.get("error_msg", ""))
if error == 99999 or "rate" in error_msg.lower():
self._stats.record(False, rate_limited=True)
if proxy:
self.proxy_manager.mark_dead(proxy)
self.log.warning("🚫 Rate limited (body), attempt %d/3", attempt + 1)
await asyncio.sleep(1)
continue
self._stats.record(True, latency)
return data
except (aiohttp.ClientError, asyncio.TimeoutError) as e:
if proxy:
self.proxy_manager.mark_dead(proxy)
if attempt == 2:
self._stats.record(False)
self.log.error("Request failed after 3 retries: %s", e)
return {"error": -1, "error_msg": str(e)}
await asyncio.sleep(0.3)
async def get_account_info(self) -> dict:
data = await self._request("GET", API["account_info"] + "?skip_address=1")
if data.get("error"):
raise Exception(f"Auth failed: {data}")
self.account_info = data.get("data", {})
return self.account_info
async def get_addresses(self) -> list:
data = await self._request("GET", API["addresses"])
addresses = data.get("data", {}).get("addresses", [])
if addresses and not self.address_id:
for addr in addresses:
if addr.get("is_default"):
self.address_id = addr["addressid"]
break
if not self.address_id and addresses:
self.address_id = addresses[0]["addressid"]
return addresses
async def get_item_info(self, item_id: int, shop_id: int) -> dict:
url = f"{API['item_info']}?itemid={item_id}&shopid={shop_id}"
return await self._request("GET", url)
async def get_flash_sale_sessions(self, scan_pages: int = 5) -> list:
all_sessions = []
for page in range(scan_pages):
offset = page * 20
url = (
f"{API['flash_sessions']}"
f"?limit=20&offset={offset}&need_items=1&with_dp_items=1"
)
data = await self._request("GET", url)
sessions = data.get("data", {}).get("sessions", [])
if not sessions:
break
all_sessions.extend(sessions)
await asyncio.sleep(0.3)
return all_sessions
async def get_flash_sale_items(
self, session_id: int, item_ids: list[int]
) -> list:
ids_str = ",".join(str(i) for i in item_ids[:50])
url = (
f"{API['flash_sale']}"
f"?session_id={session_id}&item_ids={ids_str}&need_detail=1"
)
data = await self._request("GET", url)
return data.get("data", {}).get("items", [])
async def add_to_cart(
self, item_id: int, shop_id: int, model_id: int, qty: int = 1
) -> dict:
body = {
"checkout": True,
"client_source": 1,
"donot_add_checkout": 0,
"itemid": item_id,
"modelid": model_id,
"quantity": qty,
"shopid": shop_id,
}
return await self._request("POST", API["add_cart"], json=body)
async def get_checkout(
self, item_id: int, shop_id: int, model_id: int, qty: int, payment_channel_id: int = 8001400
) -> dict:
body = {
"selected_address_id": self.address_id,
"shoporders": [
{
"shop": {"shopid": shop_id},
"items": [
{
"itemid": item_id,
"modelid": model_id,
"quantity": qty,
}
],
"shipping": {"channel_id": 0},
}
],
"channel_payment_option_list": [
{"payment_channel_id": payment_channel_id}
],
}
return await self._request("POST", API["checkout_get"], json=body)
async def place_order(self, checkout_data: dict) -> dict:
return await self._request("POST", API["place_order"], json=checkout_data)
async def close(self) -> None:
if self.session:
await self.session.close()
# ═══════════════════════════════════════════════════════════
# FLASH SALE SCANNER
# ═══════════════════════════════════════════════════════════
async def scan_flash_sale(
client: ShopeeClient,
config: Config,
max_price: int,
include_keywords: list[str],
exclude_keywords: list[str],
logger: logging.Logger,
) -> list[dict]:
"""Scan flash sale sessions for items matching criteria."""
logger.info("🔍 Scanning flash sale (max price: Rp %s)", f"{max_price:,}")
sessions = await client.get_flash_sale_sessions(config.scan_pages)
if not sessions:
logger.warning("❌ No flash sale sessions found.")
return []
logger.info("📦 Found %d sessions", len(sessions))
cheap_items: list[dict] = []
for session in sessions:
session_id = session.get("session_id", 0)
start_time = session.get("start_time", 0)
items = session.get("items", [])
if not items:
continue
item_ids = [i.get("item_id", i.get("itemid", 0)) for i in items]
detailed = await client.get_flash_sale_items(session_id, item_ids)
for item in detailed:
price = item.get("price", 0)
price_idr = price / 100000 if price > 100000 else price
stock = item.get("stock", 0)
promo_id = item.get("promotion_id", 0)
name = item.get("name", "Unknown")
# Keyword filter
if not matches_keywords(name, include_keywords, exclude_keywords):
continue
if price_idr <= max_price and stock > 0:
cheap_items.append({
"item_id": item.get("item_id", item.get("itemid", 0)),
"shop_id": item.get("shop_id", item.get("shopid", 0)),
"model_id": item.get("model_id", item.get("modelid", 0)),
"name": name,
"price": price,
"price_idr": price_idr,
"stock": stock,
"start_time": start_time,
"session_id": session_id,
"promo_id": promo_id,
})
cheap_items.sort(key=lambda x: x["price_idr"])
return cheap_items
# ═══════════════════════════════════════════════════════════
# CHECKOUT ENGINE
# ═══════════════════════════════════════════════════════════
async def single_checkout(
client: ShopeeClient,
item_id: int,
shop_id: int,
model_id: int,
attempt: int,
quantity: int = 1,
payment_channel_id: int = 8001400,
) -> dict:
"""Execute a single checkout flow: add to cart → get checkout → place order."""
try:
cart = await client.add_to_cart(item_id, shop_id, model_id, quantity)
if cart.get("error"):
return {
"success": False,
"error": f"cart: {cart.get('error')} - {cart.get('error_msg', '')}",
"attempt": attempt,
}
checkout = await client.get_checkout(
item_id, shop_id, model_id, quantity, payment_channel_id
)
if checkout.get("error"):
return {
"success": False,
"error": f"checkout: {checkout.get('error')}",
"attempt": attempt,
}
order = await client.place_order(checkout)
if order.get("error"):
err = order.get("error")
if err in [2, 9, 110]:
return {
"success": False,
"error": f"FATAL: {err}",
"attempt": attempt,
"fatal": True,
}
return {
"success": False,
"error": f"order: {err}",
"attempt": attempt,
}
return {"success": True, "data": order, "attempt": attempt}
except Exception as e:
return {"success": False, "error": str(e), "attempt": attempt}
async def delayed_checkout(
client: ShopeeClient,
item_id: int,
shop_id: int,
model_id: int,
delay: float,
attempt: int,
quantity: int = 1,
payment_channel_id: int = 8001400,
) -> dict:
if delay > 0:
await asyncio.sleep(delay)
return await single_checkout(
client, item_id, shop_id, model_id, attempt,
quantity=quantity, payment_channel_id=payment_channel_id,
)
async def snipe_item(
client: ShopeeClient,
item: dict,
ntp_offset: float,
notifier: TelegramNotifier,
config: Config,
logger: logging.Logger,
account_name: str = "",
mode: str = "auto",
payment_channel_id: int = 8001400,
db: Optional[Database] = None,
) -> bool:
"""Snipe a single flash sale item with concurrent checkout requests."""
item_id = item["item_id"]
shop_id = item["shop_id"]
model_id = item["model_id"]
name = item["name"][:60]
price = item["price_idr"]
start_time = item.get("start_time", 0)
logger.info("🎯 Target: %s | Rp %s", name, f"{price:,.0f}")
logger.info("📦 Item: %s | Shop: %s | Model: %s", item_id, shop_id, model_id)
# Wait for flash sale start time
if start_time > 0:
now = get_accurate_timestamp(ntp_offset)
wait = start_time - config.subtract_seconds - now
if wait > 0:
wib = timezone(timedelta(hours=7))
start_str = datetime.fromtimestamp(start_time, tz=wib).strftime("%H:%M:%S")
logger.info("⏳ Waiting until %s WIB (%ds)...", start_str, int(wait))
while wait > 2:
await asyncio.sleep(min(wait - 1, 2))
now = get_accurate_timestamp(ntp_offset)
wait = start_time - config.subtract_seconds - now
# Precision wait
while get_accurate_timestamp(ntp_offset) < start_time - config.subtract_seconds:
await asyncio.sleep(0.001)
logger.info("🚀 Firing %d checkout requests...", config.concurrent_requests)
start = time.time()
tasks = [
asyncio.create_task(
delayed_checkout(
client, item_id, shop_id, model_id,
i * config.request_delay, i + 1,
quantity=1,
payment_channel_id=payment_channel_id,
)
)
for i in range(config.concurrent_requests)
]
results = await asyncio.gather(*tasks, return_exceptions=True)
elapsed = time.time() - start
errors: list[str] = []
success = False
for r in results:
if isinstance(r, dict) and r.get("success"):
success = True
logger.info("✅ SUKSES! (%.2fs)", elapsed)
await notifier.notify_success(name, price, elapsed, account_name)
break
elif isinstance(r, dict):
errors.append(r.get("error", "unknown"))
if not success:
for e in errors[:3]:
logger.error("❌ %s", e)
await notifier.notify_failure(name, errors, account_name)
# Log to database