Spaces:
Runtime error
Runtime error
Download sniper_engine.py from CLASSZhao2653/yahoo_2_test: direct link, hf CLI and curl.
- Browser
- Download file 7.12 kB
-
https://huggingface.co/spaces/CLASSZhao2653/yahoo_2_test/resolve/main/sniper_engine.py
- Command line
-
hf download hf://spaces/CLASSZhao2653/yahoo_2_test/sniper_engine.py
-
curl -L -o sniper_engine.py https://huggingface.co/spaces/CLASSZhao2653/yahoo_2_test/resolve/main/sniper_engine.py
7.12 kB
| """ | |
| 秒杀引擎 - 支持立即开火与亚毫秒级高精度定时连击 | |
| """ | |
| import time | |
| import threading | |
| from datetime import datetime, timezone, timedelta | |
| from collections import deque | |
| import requests | |
| from brm_api import BrmApi | |
| BJ_TZ = timezone(timedelta(hours=8)) | |
| # 内存日志缓冲区 | |
| LOG_BUFFER = deque(maxlen=200) | |
| def append_log(msg: str): | |
| now_str = datetime.now(BJ_TZ).strftime("%H:%M:%S.%f")[:-3] | |
| entry = f"[{now_str}] {msg}" | |
| print(entry) | |
| LOG_BUFFER.append(entry) | |
| def get_recent_logs(): | |
| return "\n".join(LOG_BUFFER) | |
| def get_ntp_offset(): | |
| """获取与淘宝/京东授时中心的毫秒级偏差""" | |
| apis = [ | |
| ("淘宝", "http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp", lambda r: int(r.json()["data"]["t"])), | |
| ("京东", "https://api.m.jd.com/client.action?functionId=queryMaterialProducts&client=wh5", lambda r: int(r.json()["currentTime2"])) | |
| ] | |
| best_offset = 0.0 | |
| min_rtt = 999.0 | |
| for _, url, parser in apis: | |
| try: | |
| t1 = time.time() | |
| resp = requests.get(url, timeout=1.2, verify=False) | |
| t2 = time.time() | |
| rtt = t2 - t1 | |
| server_ts = parser(resp) / 1000.0 | |
| if rtt < min_rtt: | |
| min_rtt = rtt | |
| best_offset = (server_ts + (rtt / 2.0)) - t2 | |
| except: | |
| pass | |
| return best_offset | |
| class SniperEngine: | |
| def __init__(self): | |
| self.scheduled_tasks = {} # {task_id: {"name": ..., "target_time": ..., "stop_event": ...}} | |
| self._lock = threading.Lock() | |
| def flash_fire_once(self, api: BrmApi, activity_id: str, shop_name: str = ""): | |
| """【流水线合体技】下单 ➔ 毫秒级直接扣费""" | |
| t0 = time.time() | |
| append_log(f"⚡ 开始冲击目标: [{shop_name or activity_id}] (ID: {activity_id})...") | |
| # 1. 抢单 | |
| succ, order_id, msg = api.sign_up(activity_id) | |
| if not succ: | |
| append_log(f"❌ 抢单被拒: {msg}") | |
| return False, f"抢单失败: {msg}" | |
| t_signup = time.time() | |
| append_log(f"🎯 抢单成功!已拿到订单号: {order_id} (耗时 {(t_signup - t0)*1000:.1f}ms),立刻无缝代扣...") | |
| # 2. 自动余额扣款锁定 | |
| pay_succ, pay_msg = api.pay_order(order_id, pay_way=1) | |
| t_pay = time.time() | |
| if pay_succ: | |
| append_log(f"🏆 【完美成单】自动余额扣费成功!订单号: {order_id} (支付耗时: {(t_pay - t_signup)*1000:.1f}ms | 总耗时: {(t_pay - t0)*1000:.1f}ms)") | |
| return True, f"订单抢占并扣款成功! 订单号: {order_id}" | |
| else: | |
| append_log(f"⚠️ 获得名额但扣款失败: {pay_msg}。请在3分钟内进入小程序手动支付!") | |
| return False, f"名额已锁但未扣款成功({pay_msg}),请速去小程序手动支付" | |
| def schedule_fire(self, api: BrmApi, activity_id: str, shop_name: str, target_time_str: str, retry_count: int = 5): | |
| """启动后台定时抢单线程""" | |
| task_id = f"{activity_id}_{int(time.time())}" | |
| stop_event = threading.Event() | |
| def _worker(): | |
| try: | |
| # 检查余额安全阈值 | |
| succ, u_info = api.get_user_info() | |
| if succ: | |
| append_log(f"👤 当前抢单账号: {u_info['nickname']} (余额: ¥{u_info['balance']:.2f})") | |
| if u_info['balance'] < 1.0: | |
| append_log("⚠️ 警告: 账号余额不足 1 元!余额自动代扣极大概率失败,请确保预充值!") | |
| # 计算绝对时间 | |
| if "-" in target_time_str: | |
| target_dt = datetime.strptime(target_time_str, "%Y-%m-%d %H:%M:%S") | |
| else: | |
| today_str = datetime.now(BJ_TZ).strftime("%Y-%m-%d") | |
| target_dt = datetime.strptime(f"{today_str} {target_time_str}", "%Y-%m-%d %H:%M:%S") | |
| target_dt = target_dt.replace(tzinfo=BJ_TZ) | |
| offset = get_ntp_offset() | |
| append_log(f"⏰ 定时任务已就位: [{shop_name}] 目标时间: {target_dt.strftime('%H:%M:%S')} (网络时间偏移: {offset:+.3f}s)") | |
| # 精准倒计时 | |
| while not stop_event.is_set(): | |
| current_accurate = time.time() + offset | |
| diff = target_dt.timestamp() - current_accurate | |
| if diff <= 0.005: # 提前 5ms 抵消网络建连消耗 | |
| append_log("💥 时间到达!全弹齐射!!") | |
| break | |
| elif diff > 3.0: | |
| time.sleep(1.0) | |
| elif diff > 0.3: | |
| time.sleep(0.05) | |
| else: | |
| time.sleep(0.001) # 最后 300ms 纳秒自旋 | |
| if stop_event.is_set(): | |
| append_log(f"🛑 定时任务已被人为取消: [{shop_name}]") | |
| return | |
| # 重试循环 | |
| for attempt in range(1, retry_count + 1): | |
| if stop_event.is_set(): | |
| break | |
| append_log(f"🚀 发动第 {attempt}/{retry_count} 波冲击...") | |
| succ, _ = self.flash_fire_once(api, activity_id, shop_name) | |
| if succ: | |
| break | |
| time.sleep(0.15) | |
| except Exception as e: | |
| append_log(f"❌ 调度异常: {e}") | |
| finally: | |
| with self._lock: | |
| self.scheduled_tasks.pop(task_id, None) | |
| with self._lock: | |
| self.scheduled_tasks[task_id] = { | |
| "activity_id": activity_id, | |
| "shop_name": shop_name, | |
| "target_time": target_time_str, | |
| "stop_event": stop_event | |
| } | |
| t = threading.Thread(target=_worker, daemon=True) | |
| t.start() | |
| return task_id | |
| def cancel_task(self, task_id: str): | |
| with self._lock: | |
| if task_id in self.scheduled_tasks: | |
| self.scheduled_tasks[task_id]["stop_event"].set() | |
| self.scheduled_tasks.pop(task_id, None) | |
| return True | |
| return False | |
| def list_tasks(self): | |
| with self._lock: | |
| return [ | |
| { | |
| "任务ID": tid, | |
| "店铺名称": t["shop_name"], | |
| "活动ID": t["activity_id"], | |
| "预定开抢时间": t["target_time"] | |
| } | |
| for tid, t in self.scheduled_tasks.items() | |
| ] | |
| GLOBAL_ENGINE = SniperEngine() | |
| def clear_logs(): | |
| LOG_BUFFER.clear() | |
| return "" |