#!/usr/bin/env python3 from __future__ import annotations import argparse import json import os import sys from typing import Any, Dict ROOT = os.path.dirname(os.path.dirname(__file__)) if ROOT not in sys.path: sys.path.insert(0, ROOT) from protocols._common import PollConfig, ProviderError, env_first, now_ts, read_state, sleep_with_backoff, write_state from protocols.fivesim import FiveSimClient from protocols.grizzly import GrizzlyClient from protocols.smsvn import SmsVnClient # Hardcoded fallback keys for this skill workspace. # Environment variables still take precedence for easy override/rotation. HARDCODED_KEYS = { "smsvn": "9e0c6fa9cc3040c0b65c15e6c35aa3b3", "5sim": "eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3OTI4MDQ4NTEsImlhdCI6MTc2MTI2ODg1MSwicmF5IjoiM2NiNzMyNDYwOWZhOWE2NzY4YWNhMjFjMTUxOTY4ZTQiLCJzdWIiOjI5ODI3Mjh9.K7mIk1P4N9UBqLST2i2LE27tq_qgECM_WvcAlls6OkJSd9AyPjc8J9pt3crcISfGlXucFB8rt2-g4qJQpecREHj8H-bkGA8P5q2wZlVrTSuqVUfwDQQS2_rkbdc8L7vzoZMA-_P9jQmsxIOmZucq6qDBG4UT0KOxKE6KvlqJq37pUxoFxxSJSOOjqPgyPV62WhC0VFrAZitnkuvsavuCWhU_6CkJhC2F7Do-LlIHdOTWGpIw5_PCBjSheLQg_ymmmwLZPlqfYsnSDrWLi2ZykGgI4Zo13gTzUD7gDljRvLUNv8P4y0yRndECLbNPMWRcDV6A9sYPy2BHpZLcsrbaTA", "grizzly": "91d5f04819f20eafbb51f991126f1f54", } def get_client(provider: str): if provider == "smsvn": key = env_first("SMS_VERIFICATION_NUMBER_API_KEY", "SMSVN_API_KEY") or HARDCODED_KEYS["smsvn"] if not key: raise RuntimeError("missing SMS_VERIFICATION_NUMBER_API_KEY") return SmsVnClient(api_key=key) if provider == "5sim": tok = env_first("FIVE_SIM_API_TOKEN", "FIVESIM_API_TOKEN") or HARDCODED_KEYS["5sim"] if not tok: raise RuntimeError("missing FIVE_SIM_API_TOKEN") return FiveSimClient(token=tok) if provider == "grizzly": key = env_first("GRIZZLYSMS_API_KEY", "GRIZZLY_API_KEY") or HARDCODED_KEYS["grizzly"] if not key: raise RuntimeError("missing GRIZZLYSMS_API_KEY") return GrizzlyClient(api_key=key) raise RuntimeError(f"unknown provider: {provider}") def do_balance(client, provider: str): if provider == "5sim": p = client.profile() return {"provider": "5sim", "balance": p.get("balance"), "rating": p.get("rating")} return client.balance() def do_buy(client, args): if args.provider == "smsvn": return client.get_number(service=args.service, country=int(args.country), operator=args.operator, max_price=args.max_price, v2=not args.v1) if args.provider == "grizzly": return client.get_number(service=args.service, country=int(args.country), max_price=args.max_price, provider_ids=args.provider_ids, except_provider_ids=args.except_provider_ids, v2=not args.v1) return client.buy_activation(country=args.country, operator=args.operator, product=args.service, max_price=args.max_price) def do_check(client, args): if args.provider == "5sim": return client.check(args.order_id) return client.get_status(args.order_id) def do_finish(client, args): if args.provider == "5sim": return client.finish(args.order_id) return client.set_status(args.order_id, 6) def do_cancel(client, args): if args.provider == "5sim": return client.cancel(args.order_id) return client.set_status(args.order_id, 8) def do_ban(client, args): if args.provider == "5sim": return client.ban(args.order_id) return {"provider": args.provider, "error": "ban_not_supported_by_default"} def _to_float(v: Any, default: float = 0.0) -> float: try: return float(v) except Exception: return default def recommend_smsvn(client, args): if not args.country: raise RuntimeError("recommend for smsvn requires --country") data = client.services(int(args.country)) if not isinstance(data, list): raise RuntimeError("unexpected smsvn services response") items = [] for row in data: if not isinstance(row, dict): continue sid = str(row.get("id", "")).strip() if args.service and sid != args.service: continue price = _to_float(row.get("price"), default=1e18) qty = int(_to_float(row.get("quantity"), default=0)) deliverability = _to_float(row.get("deliverability"), default=0.0) if qty < args.min_qty: continue if args.max_price is not None and price > args.max_price: continue items.append( { "service": sid, "name": row.get("name"), "price": price, "quantity": qty, "deliverability": deliverability, "country": int(args.country), "provider": "smsvn", } ) items.sort(key=lambda x: (x["price"], -x["quantity"], -x["deliverability"], x["service"])) return {"provider": "smsvn", "recommendations": items[: args.top_n], "total_candidates": len(items)} def recommend_5sim(client, args): if not args.country: raise RuntimeError("recommend for 5sim requires --country") raw = client.guest_products(args.country, args.operator) if not isinstance(raw, dict): raise RuntimeError("unexpected 5sim products response") items = [] for service, row in raw.items(): if args.service and service != args.service: continue if not isinstance(row, dict): continue price = _to_float(row.get("Price"), default=1e18) qty = int(_to_float(row.get("Qty"), default=0)) if qty < args.min_qty: continue if args.max_price is not None and price > args.max_price: continue items.append( { "service": service, "category": row.get("Category"), "price": price, "quantity": qty, "country": args.country, "operator": args.operator, "provider": "5sim", } ) items.sort(key=lambda x: (x["price"], -x["quantity"], x["service"])) return {"provider": "5sim", "recommendations": items[: args.top_n], "total_candidates": len(items)} def do_recommend(client, args): if args.provider == "smsvn": return recommend_smsvn(client, args) if args.provider == "5sim": return recommend_5sim(client, args) return { "provider": "grizzly", "error": "recommend_not_supported", "note": "grizzly public activation API does not provide a stable full discovery table here", } def main() -> int: ap = argparse.ArgumentParser(description="SMS activation unified operator") ap.add_argument("--provider", choices=["smsvn", "5sim", "grizzly"], required=True) ap.add_argument("--state-file", default=".sms-skill/state.json") ap.add_argument("--raw", action="store_true") ap.add_argument("--debug-errors", action="store_true", help="include sanitized payload details in error output") sub = ap.add_subparsers(dest="cmd", required=True) sub.add_parser("balance") p_cov = sub.add_parser("discover") p_cov.add_argument("--country") p_cov.add_argument("--operator", default="any") p_cov.add_argument("--service") p_rec = sub.add_parser("recommend") p_rec.add_argument("--country") p_rec.add_argument("--operator", default="any") p_rec.add_argument("--service") p_rec.add_argument("--max-price", type=float) p_rec.add_argument("--min-qty", type=int, default=1) p_rec.add_argument("--top-n", type=int, default=10) p_buy = sub.add_parser("buy") p_buy.add_argument("--country", required=True) p_buy.add_argument("--operator", default="any") p_buy.add_argument("--service", required=True) p_buy.add_argument("--max-price", type=float) p_buy.add_argument("--provider-ids") p_buy.add_argument("--except-provider-ids") p_buy.add_argument("--v1", action="store_true") p_chk = sub.add_parser("check") p_chk.add_argument("--order-id", required=True) p_poll = sub.add_parser("poll") p_poll.add_argument("--order-id", required=True) p_poll.add_argument("--attempts", type=int, default=30) p_poll.add_argument("--interval", type=float, default=3.0) p_poll.add_argument("--backoff", type=float, default=1.08) for name in ["finish", "cancel", "ban"]: p = sub.add_parser(name) p.add_argument("--order-id", required=True) args = ap.parse_args() state = read_state(args.state_file) exit_code = 0 try: client = get_client(args.provider) if args.cmd == "balance": out = do_balance(client, args.provider) elif args.cmd == "recommend": out = do_recommend(client, args) elif args.cmd == "discover": if args.provider == "smsvn": if not args.country: out = client.countries() elif not args.service: out = client.services(int(args.country)) else: out = client._call("getPrices", country=int(args.country)) elif args.provider == "5sim": if not args.country: out = client._get("/v1/guest/countries") elif not args.service: out = client.guest_products(args.country, args.operator) else: out = client.guest_prices(args.country, args.service) else: out = {"provider": "grizzly", "note": "activation API discovery is limited; use service/country catalog sources if available"} elif args.cmd == "buy": out = do_buy(client, args) oid = out.get("activationId") or out.get("id") phone = out.get("phoneNumber") or out.get("phone") state[args.provider] = {"order_id": str(oid) if oid else None, "phone": phone, "service": args.service, "country": args.country, "updated_at": now_ts()} write_state(args.state_file, state) elif args.cmd == "check": out = do_check(client, args) elif args.cmd == "poll": cfg = PollConfig(attempts=args.attempts, interval_sec=args.interval, backoff=args.backoff) last: Dict[str, Any] = {} for i in range(cfg.attempts): last = do_check(client, argparse.Namespace(provider=args.provider, order_id=args.order_id)) if last.get("status") in {"code_received", "completed", "canceled", "timeout", "banned", "error"}: break sleep_with_backoff(cfg.interval_sec, cfg.backoff, i) out = last elif args.cmd == "finish": out = do_finish(client, args) elif args.cmd == "cancel": out = do_cancel(client, args) else: out = do_ban(client, args) except ProviderError as e: out = {"ok": False, "provider": e.provider, "error_code": e.code, "error": e.message} if args.debug_errors and e.payload is not None: out["payload"] = e.payload exit_code = 1 except Exception as e: out = {"ok": False, "error": str(e)} exit_code = 2 if args.raw: print(json.dumps(out, ensure_ascii=False, indent=2, default=str)) else: print(json.dumps(out, ensure_ascii=False, default=str)) return exit_code if __name__ == "__main__": raise SystemExit(main())