managebetcodes 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,22 @@
1
+ """Official SDK for the Manage Bet Codes public API v1."""
2
+
3
+ from .client import Client, __version__
4
+ from .errors import (
5
+ APIError,
6
+ AuthenticationError,
7
+ QuotaError,
8
+ RateLimitError,
9
+ ValidationError,
10
+ )
11
+ from .webhooks import verify_webhook
12
+
13
+ __all__ = [
14
+ "APIError",
15
+ "AuthenticationError",
16
+ "Client",
17
+ "QuotaError",
18
+ "RateLimitError",
19
+ "ValidationError",
20
+ "verify_webhook",
21
+ "__version__",
22
+ ]
managebetcodes/cli.py ADDED
@@ -0,0 +1,121 @@
1
+ """The `mbc` command: convert and view codes from a terminal."""
2
+
3
+ import argparse
4
+ import json
5
+ import os
6
+ import sys
7
+ import urllib.error
8
+ import urllib.request
9
+ from typing import Any, Dict, List, Optional, Sequence
10
+
11
+ from .client import BASE_URL, Client, __version__
12
+ from .errors import APIError
13
+
14
+
15
+ def build_parser() -> argparse.ArgumentParser:
16
+ """Build the `mbc` argument parser."""
17
+
18
+ common = argparse.ArgumentParser(add_help=False)
19
+ common.add_argument(
20
+ "--api-key",
21
+ default=os.environ.get("MBC_API_KEY"),
22
+ help="API key (or set MBC_API_KEY). Not needed for capabilities.",
23
+ )
24
+ common.add_argument(
25
+ "--base-url",
26
+ default=os.environ.get("MBC_BASE_URL", BASE_URL),
27
+ help="API base URL (or set MBC_BASE_URL).",
28
+ )
29
+ parser = argparse.ArgumentParser(
30
+ prog="mbc",
31
+ description="Manage Bet Codes public API v1",
32
+ parents=[common],
33
+ )
34
+ parser.add_argument(
35
+ "--version",
36
+ action="version",
37
+ version=f"%(prog)s {__version__}",
38
+ )
39
+ sub = parser.add_subparsers(dest="command", required=True, metavar="command")
40
+
41
+ convert = sub.add_parser(
42
+ "convert", parents=[common], help="Convert a code to one or more targets."
43
+ )
44
+ convert.add_argument("code", help="Source booking code.")
45
+ convert.add_argument("--from", dest="source", required=True, help="Source bookmaker.")
46
+ convert.add_argument(
47
+ "--to",
48
+ dest="targets",
49
+ required=True,
50
+ help="Comma-separated target list, e.g. 1xng or 1xng,msport.",
51
+ )
52
+
53
+ view = sub.add_parser("view", parents=[common], help="View a slip as text.")
54
+ view.add_argument("code", help="Booking code.")
55
+ view.add_argument("--bookmaker", required=True, help="Bookmaker of the code.")
56
+
57
+ sub.add_parser("capabilities", parents=[common], help="Show the API manifest.")
58
+ sub.add_parser("usage", parents=[common], help="Show plan, credits, and limits.")
59
+ return parser
60
+
61
+
62
+ def _targets(raw: str) -> List[str]:
63
+ return [part.strip() for part in raw.split(",") if part.strip()]
64
+
65
+
66
+ def _public_capabilities(base_url: str) -> int:
67
+ """Read the public manifest without an API key."""
68
+
69
+ url = base_url.rstrip("/") + "/capabilities"
70
+ request = urllib.request.Request(url, headers={"Accept": "application/json"})
71
+ try:
72
+ with urllib.request.urlopen(request, timeout=30) as response:
73
+ print(json.dumps(json.loads(response.read().decode("utf-8")), indent=2))
74
+ return 0
75
+ except urllib.error.HTTPError as exc:
76
+ print(f"mbc: HTTP {exc.code} [http_{exc.code}]: the manifest read failed.",
77
+ file=sys.stderr)
78
+ return 1
79
+ except (urllib.error.URLError, TimeoutError) as exc:
80
+ print(f"mbc: the request to the API failed: {exc}", file=sys.stderr)
81
+ return 1
82
+
83
+
84
+ def _print(payload: Dict[str, Any]) -> int:
85
+ print(json.dumps(payload, indent=2))
86
+ return 0
87
+
88
+
89
+ def main(argv: Optional[Sequence[str]] = None) -> int:
90
+ """Run the `mbc` command. Returns the process exit code."""
91
+
92
+ args = build_parser().parse_args(argv)
93
+ if args.command == "capabilities":
94
+ return _public_capabilities(args.base_url)
95
+ if not args.api_key:
96
+ print("mbc: set --api-key or MBC_API_KEY.", file=sys.stderr)
97
+ return 2
98
+ client = Client(args.api_key, base_url=args.base_url)
99
+ try:
100
+ if args.command == "convert":
101
+ targets = _targets(args.targets)
102
+ if not targets:
103
+ print("mbc: --to needs at least one target.", file=sys.stderr)
104
+ return 2
105
+ target = targets[0] if len(targets) == 1 else targets
106
+ return _print(client.convert(args.code, args.source, target))
107
+ if args.command == "view":
108
+ return _print(client.view(args.code, args.bookmaker))
109
+ if args.command == "capabilities":
110
+ return _print(client.capabilities())
111
+ if args.command == "usage":
112
+ return _print(client.usage())
113
+ except APIError as error:
114
+ print(f"mbc: {error}", file=sys.stderr)
115
+ return 1
116
+ print(f"mbc: unknown command {args.command}.", file=sys.stderr)
117
+ return 2
118
+
119
+
120
+ if __name__ == "__main__":
121
+ raise SystemExit(main())
@@ -0,0 +1,701 @@
1
+ """Synchronous client for the Manage Bet Codes public API v1."""
2
+
3
+ import json
4
+ import time
5
+ import urllib.error
6
+ import urllib.parse
7
+ import urllib.request
8
+ import uuid
9
+ from datetime import datetime, timezone
10
+ from email.utils import parsedate_to_datetime
11
+ from typing import Any, Dict, List, Mapping, Optional, Tuple, Union
12
+
13
+ from .errors import APIError, error_from_response
14
+
15
+ __version__ = "1.0.0"
16
+
17
+ BASE_URL = "https://api.managebetcodes.app/v1"
18
+ RETRY_STATUSES = {429, 502, 503, 504}
19
+ # A 429 for an exhausted quota is not transient. Retrying it cannot succeed
20
+ # until the window resets, so the caller must see the error, not sleep on it.
21
+ NON_RETRYABLE_CODES = {
22
+ "api_quota_exhausted",
23
+ "plan_quota_exhausted",
24
+ "search_quota_exhausted",
25
+ }
26
+ DEFAULT_BACKOFF = 0.5
27
+ MAX_BACKOFF = 30.0
28
+
29
+
30
+ class _EventsNamespace:
31
+ """Dotted event calls: search, markets, and the single-query list."""
32
+
33
+ def __init__(self, client: "Client") -> None:
34
+ self._client = client
35
+
36
+ def __call__(self, *args: Any, **kwargs: Any) -> Dict[str, Any]:
37
+ return self._client._events_single(*args, **kwargs)
38
+
39
+ def list(self, *args: Any, **kwargs: Any) -> Dict[str, Any]:
40
+ return self._client._events_single(*args, **kwargs)
41
+
42
+ def search(self, *args: Any, **kwargs: Any) -> Dict[str, Any]:
43
+ return self._client.events_search(*args, **kwargs)
44
+
45
+ def markets(self, *args: Any, **kwargs: Any) -> Dict[str, Any]:
46
+ return self._client.event_markets(*args, **kwargs)
47
+
48
+
49
+ class _MarketsNamespace:
50
+ """Dotted market calls. Calling it reads the catalog too."""
51
+
52
+ def __init__(self, client: "Client") -> None:
53
+ self._client = client
54
+
55
+ def __call__(self) -> Dict[str, Any]:
56
+ return self._client._markets_catalog()
57
+
58
+ def list(self) -> Dict[str, Any]:
59
+ return self._client._markets_catalog()
60
+
61
+
62
+ class _BooksNamespace:
63
+ """Dotted book calls. Calling it lists books too."""
64
+
65
+ def __init__(self, client: "Client") -> None:
66
+ self._client = client
67
+
68
+ def __call__(self, *args: Any, **kwargs: Any) -> Dict[str, Any]:
69
+ return self._client._books_list(*args, **kwargs)
70
+
71
+ def list(self, *args: Any, **kwargs: Any) -> Dict[str, Any]:
72
+ return self._client._books_list(*args, **kwargs)
73
+
74
+ def get(self, book_id: str) -> Dict[str, Any]:
75
+ return self._client.book_get(book_id)
76
+
77
+
78
+ class _WebhooksNamespace:
79
+ """Dotted webhook calls: create, list, delete, and test."""
80
+
81
+ def __init__(self, client: "Client") -> None:
82
+ self._client = client
83
+
84
+ def __call__(self) -> Dict[str, Any]:
85
+ return self._client.webhooks_list()
86
+
87
+ def create(
88
+ self,
89
+ url: str,
90
+ *,
91
+ events: Optional[List[str]] = None,
92
+ idempotency_key: Optional[str] = None,
93
+ ) -> Dict[str, Any]:
94
+ return self._client.webhooks_create(
95
+ url, events=events, idempotency_key=idempotency_key
96
+ )
97
+
98
+ def list(self) -> Dict[str, Any]:
99
+ return self._client.webhooks_list()
100
+
101
+ def delete(self, webhook_id: str) -> Dict[str, Any]:
102
+ return self._client.webhook_delete(webhook_id)
103
+
104
+ def test(
105
+ self,
106
+ webhook_id: str,
107
+ *,
108
+ idempotency_key: Optional[str] = None,
109
+ ) -> Dict[str, Any]:
110
+ return self._client.webhook_test(
111
+ webhook_id, idempotency_key=idempotency_key
112
+ )
113
+
114
+
115
+ class Client:
116
+ """Client for the Manage Bet Codes public API v1."""
117
+
118
+ def __init__(
119
+ self,
120
+ api_key: str,
121
+ base_url: str = BASE_URL,
122
+ timeout: float = 30.0,
123
+ max_retries: int = 3,
124
+ ) -> None:
125
+ if not api_key:
126
+ raise ValueError("api_key is required")
127
+ if max_retries < 0:
128
+ raise ValueError("max_retries must be zero or more")
129
+
130
+ self.api_key = api_key
131
+ self.base_url = base_url.rstrip("/")
132
+ self.timeout = timeout
133
+ self.max_retries = max_retries
134
+ self.events = _EventsNamespace(self)
135
+ self.markets = _MarketsNamespace(self)
136
+ self.books = _BooksNamespace(self)
137
+ self.webhooks = _WebhooksNamespace(self)
138
+
139
+ def convert(
140
+ self,
141
+ code: str,
142
+ source: str,
143
+ target: Union[str, List[str]],
144
+ *,
145
+ idempotency_key: Optional[str] = None,
146
+ ) -> Dict[str, Any]:
147
+ """Convert one code to one target or to a batch of 2 to 6 targets."""
148
+
149
+ return self._post(
150
+ "/convert",
151
+ {"code": code, "from": source, "to": target},
152
+ idempotency_key,
153
+ )
154
+
155
+ def convert_to_all(
156
+ self,
157
+ code: str,
158
+ source: str,
159
+ *,
160
+ to: Optional[Union[str, List[str]]] = None,
161
+ include_card: Optional[bool] = None,
162
+ idempotency_key: Optional[str] = None,
163
+ ) -> Dict[str, Any]:
164
+ """Convert one code to all eligible bookmakers (or a custom subset)."""
165
+
166
+ payload: Dict[str, Any] = {"code": code, "from": source}
167
+ if to is not None:
168
+ payload["to"] = to
169
+ if include_card is not None:
170
+ payload["include_card"] = include_card
171
+ return self._post("/convert/all", payload, idempotency_key)
172
+
173
+ def convert_bulk(
174
+ self,
175
+ codes: List[Mapping[str, str]],
176
+ *,
177
+ to: Optional[Union[str, List[str]]] = None,
178
+ include_card: Optional[bool] = None,
179
+ idempotency_key: Optional[str] = None,
180
+ ) -> Dict[str, Any]:
181
+ """Convert 2 to 4 source codes across eligible bookmakers."""
182
+
183
+ payload: Dict[str, Any] = {"codes": [dict(entry) for entry in codes]}
184
+ if to is not None:
185
+ payload["to"] = to
186
+ if include_card is not None:
187
+ payload["include_card"] = include_card
188
+ return self._post("/convert/bulk", payload, idempotency_key)
189
+
190
+ def view(self, code: str, bookmaker: str) -> Dict[str, Any]:
191
+ """Read one slip as text."""
192
+
193
+ return self._get("/view", {"code": code, "bookmaker": bookmaker})
194
+
195
+ def view_image(self, code: str, bookmaker: str) -> bytes:
196
+ """Read one slip as PNG bytes."""
197
+
198
+ return self._request(
199
+ "GET",
200
+ "/view/image",
201
+ params={"code": code, "bookmaker": bookmaker},
202
+ raw=True,
203
+ accept="image/png",
204
+ )
205
+
206
+ def split(
207
+ self,
208
+ code: str,
209
+ bookmaker: str,
210
+ count: int = 2,
211
+ pattern: str = "equal",
212
+ order: str = "mixed",
213
+ *,
214
+ target_odds: Optional[float] = None,
215
+ counts: Optional[List[int]] = None,
216
+ idempotency_key: Optional[str] = None,
217
+ ) -> Dict[str, Any]:
218
+ """Split one slip into 2 to 20 parts using equal, by_batches, target_odds, or custom."""
219
+
220
+ payload: Dict[str, Any] = {
221
+ "code": code,
222
+ "bookmaker": bookmaker,
223
+ "count": count,
224
+ "pattern": pattern,
225
+ "order": order,
226
+ }
227
+ if target_odds is not None:
228
+ payload["target_odds"] = target_odds
229
+ if counts is not None:
230
+ payload["counts"] = list(counts)
231
+ return self._post(
232
+ "/split",
233
+ payload,
234
+ idempotency_key,
235
+ )
236
+
237
+ def merge(
238
+ self,
239
+ pairs: List[Mapping[str, str]],
240
+ target: Optional[str] = None,
241
+ *,
242
+ idempotency_key: Optional[str] = None,
243
+ ) -> Dict[str, Any]:
244
+ """Merge 2 to 30 codes into one code."""
245
+
246
+ payload: Dict[str, Any] = {"pairs": [dict(pair) for pair in pairs]}
247
+ if target is not None:
248
+ payload["target"] = target
249
+ return self._post("/merge", payload, idempotency_key)
250
+
251
+ def book(
252
+ self,
253
+ bookmaker: str,
254
+ *,
255
+ plan_id: Optional[str] = None,
256
+ picks: Optional[List[Mapping[str, Any]]] = None,
257
+ to: Optional[List[str]] = None,
258
+ strict: Optional[bool] = None,
259
+ accept_odds_change: Optional[bool] = None,
260
+ idempotency_key: Optional[str] = None,
261
+ ) -> Dict[str, Any]:
262
+ """Create a code from a plan or from direct picks."""
263
+
264
+ payload: Dict[str, Any] = {"bookmaker": bookmaker}
265
+ for key, value in (
266
+ ("plan_id", plan_id),
267
+ ("picks", picks),
268
+ ("to", to),
269
+ ("strict", strict),
270
+ ("accept_odds_change", accept_odds_change),
271
+ ):
272
+ if value is not None:
273
+ payload[key] = value
274
+ return self._post("/book", payload, idempotency_key)
275
+
276
+ def events_search(
277
+ self,
278
+ bookmaker: str,
279
+ queries: List[Mapping[str, Any]],
280
+ *,
281
+ sport: Optional[str] = None,
282
+ include_markets: Optional[bool] = None,
283
+ market_filter: Optional[List[str]] = None,
284
+ include_unbookable: Optional[bool] = None,
285
+ detail: Optional[str] = None,
286
+ idempotency_key: Optional[str] = None,
287
+ ) -> Dict[str, Any]:
288
+ """Search up to 20 event queries in one call."""
289
+
290
+ payload: Dict[str, Any] = {
291
+ "bookmaker": bookmaker,
292
+ "queries": [dict(query) for query in queries],
293
+ }
294
+ for key, value in (
295
+ ("sport", sport),
296
+ ("include_markets", include_markets),
297
+ ("market_filter", market_filter),
298
+ ("include_unbookable", include_unbookable),
299
+ ("detail", detail),
300
+ ):
301
+ if value is not None:
302
+ payload[key] = value
303
+ return self._post("/events/search", payload, idempotency_key)
304
+
305
+ def _events_single(
306
+ self,
307
+ q: Optional[str] = None,
308
+ *,
309
+ bookmaker: Optional[str] = None,
310
+ sport: Optional[str] = None,
311
+ date_from: Optional[str] = None,
312
+ date_to: Optional[str] = None,
313
+ limit: Optional[int] = None,
314
+ offset: Optional[int] = None,
315
+ ) -> Dict[str, Any]:
316
+ """Search events with the single-query human wrapper."""
317
+
318
+ return self._get(
319
+ "/events",
320
+ {
321
+ "q": q,
322
+ "bookmaker": bookmaker,
323
+ "sport": sport,
324
+ "from": date_from,
325
+ "to": date_to,
326
+ "limit": limit,
327
+ "offset": offset,
328
+ },
329
+ )
330
+
331
+ def event_markets(
332
+ self,
333
+ event_id: str,
334
+ *,
335
+ bookmaker: Optional[str] = None,
336
+ detail: Optional[str] = None,
337
+ ) -> Dict[str, Any]:
338
+ """List the markets of one event on one bookmaker."""
339
+
340
+ return self._get(
341
+ f"/events/{urllib.parse.quote(event_id, safe='')}/markets",
342
+ {"bookmaker": bookmaker, "detail": detail},
343
+ )
344
+
345
+ def resolve(
346
+ self,
347
+ bookmaker: str,
348
+ picks: List[Mapping[str, Any]],
349
+ *,
350
+ strict: Optional[bool] = None,
351
+ accept_odds_change: Optional[bool] = None,
352
+ detail: Optional[str] = None,
353
+ idempotency_key: Optional[str] = None,
354
+ ) -> Dict[str, Any]:
355
+ """Resolve up to 50 picks into a 10-minute plan."""
356
+
357
+ payload: Dict[str, Any] = {
358
+ "bookmaker": bookmaker,
359
+ "picks": [dict(pick) for pick in picks],
360
+ }
361
+ for key, value in (
362
+ ("strict", strict),
363
+ ("accept_odds_change", accept_odds_change),
364
+ ("detail", detail),
365
+ ):
366
+ if value is not None:
367
+ payload[key] = value
368
+ return self._post("/resolve", payload, idempotency_key)
369
+
370
+ def _markets_catalog(self) -> Dict[str, Any]:
371
+ """Read the public canonical market catalog."""
372
+
373
+ return self._get("/markets")
374
+
375
+ def _books_list(
376
+ self,
377
+ *,
378
+ limit: Optional[int] = None,
379
+ offset: Optional[int] = None,
380
+ ) -> Dict[str, Any]:
381
+ """List the caller's books."""
382
+
383
+ return self._get("/books", {"limit": limit, "offset": offset})
384
+
385
+ def events_list(self, *args: Any, **kwargs: Any) -> Dict[str, Any]:
386
+ """Flat alias for client.events.list."""
387
+
388
+ return self._events_single(*args, **kwargs)
389
+
390
+ def markets_list(self) -> Dict[str, Any]:
391
+ """Flat alias for client.markets.list."""
392
+
393
+ return self._markets_catalog()
394
+
395
+ def books_list(self, *args: Any, **kwargs: Any) -> Dict[str, Any]:
396
+ """Flat alias for client.books.list."""
397
+
398
+ return self._books_list(*args, **kwargs)
399
+
400
+ def book_get(self, book_id: str) -> Dict[str, Any]:
401
+ """Read one book row by ID."""
402
+
403
+ return self._get(f"/books/{urllib.parse.quote(str(book_id), safe='')}")
404
+
405
+ def bookmakers(self) -> Dict[str, Any]:
406
+ """Read the public bookmaker capability catalog."""
407
+
408
+ return self._get("/bookmakers")
409
+
410
+ def errors(self) -> Dict[str, Any]:
411
+ """Read the public error catalog."""
412
+
413
+ return self._get("/errors")
414
+
415
+ def capabilities(self) -> Dict[str, Any]:
416
+ """Read the public machine manifest."""
417
+
418
+ return self._get("/capabilities")
419
+
420
+ def usage(self) -> Dict[str, Any]:
421
+ """Read the caller's plan, credits, and limits."""
422
+
423
+ return self._get("/usage")
424
+
425
+ def history(
426
+ self,
427
+ *,
428
+ limit: Optional[int] = None,
429
+ offset: Optional[int] = None,
430
+ bookmaker: Optional[str] = None,
431
+ target: Optional[str] = None,
432
+ status: Optional[str] = None,
433
+ date_from: Optional[str] = None,
434
+ date_to: Optional[str] = None,
435
+ ) -> Dict[str, Any]:
436
+ """List the caller's conversion history."""
437
+
438
+ return self._get(
439
+ "/history",
440
+ {
441
+ "limit": limit,
442
+ "offset": offset,
443
+ "bookmaker": bookmaker,
444
+ "target": target,
445
+ "status": status,
446
+ "from": date_from,
447
+ "to": date_to,
448
+ },
449
+ )
450
+
451
+ def history_get(self, row_id: str) -> Dict[str, Any]:
452
+ """Read one conversion history row by ID."""
453
+
454
+ return self._get(f"/history/{urllib.parse.quote(str(row_id), safe='')}")
455
+
456
+ def webhooks_create(
457
+ self,
458
+ url: str,
459
+ *,
460
+ events: Optional[List[str]] = None,
461
+ idempotency_key: Optional[str] = None,
462
+ ) -> Dict[str, Any]:
463
+ """Register a webhook endpoint."""
464
+
465
+ payload: Dict[str, Any] = {"url": url}
466
+ if events is not None:
467
+ payload["events"] = list(events)
468
+ return self._post("/webhooks", payload, idempotency_key)
469
+
470
+ def webhooks_list(self) -> Dict[str, Any]:
471
+ """List registered webhooks."""
472
+
473
+ return self._get("/webhooks")
474
+
475
+ def webhook_delete(self, webhook_id: str) -> Dict[str, Any]:
476
+ """Delete one webhook."""
477
+
478
+ return self._request(
479
+ "DELETE", f"/webhooks/{urllib.parse.quote(str(webhook_id), safe='')}"
480
+ )
481
+
482
+ def webhook_test(
483
+ self,
484
+ webhook_id: str,
485
+ *,
486
+ idempotency_key: Optional[str] = None,
487
+ ) -> Dict[str, Any]:
488
+ """Queue a test delivery for one active webhook."""
489
+
490
+ return self._post(
491
+ f"/webhooks/{urllib.parse.quote(str(webhook_id), safe='')}/test",
492
+ {},
493
+ idempotency_key,
494
+ )
495
+
496
+ def jobs_create(
497
+ self,
498
+ payload: Mapping[str, Any],
499
+ *,
500
+ idempotency_key: Optional[str] = None,
501
+ ) -> Dict[str, Any]:
502
+ """Create a convert, split, merge, or book job."""
503
+
504
+ return self._post("/jobs", dict(payload), idempotency_key)
505
+
506
+ def job(self, job_id: str) -> Dict[str, Any]:
507
+ """Read one job."""
508
+
509
+ return self._get(f"/jobs/{urllib.parse.quote(job_id, safe='')}")
510
+
511
+ def jobs(
512
+ self,
513
+ *,
514
+ limit: Optional[int] = None,
515
+ offset: Optional[int] = None,
516
+ status: Optional[str] = None,
517
+ ) -> Dict[str, Any]:
518
+ """List recent jobs."""
519
+
520
+ return self._get("/jobs", {"limit": limit, "offset": offset, "status": status})
521
+
522
+ def cancel_job(self, job_id: str) -> Dict[str, Any]:
523
+ """Cancel a queued or running job."""
524
+
525
+ return self._request("DELETE", f"/jobs/{urllib.parse.quote(job_id, safe='')}")
526
+
527
+ def track_start(
528
+ self,
529
+ code: str,
530
+ bookmaker: str,
531
+ *,
532
+ mode: Optional[str] = None,
533
+ label: Optional[str] = None,
534
+ webhook_url: Optional[str] = None,
535
+ idempotency_key: Optional[str] = None,
536
+ ) -> Dict[str, Any]:
537
+ """Start live tracking for one ticket."""
538
+
539
+ payload: Dict[str, Any] = {"code": code, "bookmaker": bookmaker}
540
+ for key, value in (
541
+ ("mode", mode),
542
+ ("label", label),
543
+ ("webhook_url", webhook_url),
544
+ ):
545
+ if value is not None:
546
+ payload[key] = value
547
+ return self._post("/track", payload, idempotency_key)
548
+
549
+ def track(self, track_id: str) -> Dict[str, Any]:
550
+ """Read one track."""
551
+
552
+ return self._get(f"/track/{urllib.parse.quote(track_id, safe='')}")
553
+
554
+ def tracks(
555
+ self,
556
+ *,
557
+ status: Optional[str] = None,
558
+ limit: Optional[int] = None,
559
+ offset: Optional[int] = None,
560
+ ) -> Dict[str, Any]:
561
+ """List tracks."""
562
+
563
+ return self._get("/tracks", {"status": status, "limit": limit, "offset": offset})
564
+
565
+ def stop_track(self, track_id: str) -> Dict[str, Any]:
566
+ """Stop one track."""
567
+
568
+ return self._request("DELETE", f"/track/{urllib.parse.quote(track_id, safe='')}")
569
+
570
+ def _get(self, path: str, params: Optional[Mapping[str, Any]] = None) -> Dict[str, Any]:
571
+ return self._request("GET", path, params=params)
572
+
573
+ def _post(
574
+ self,
575
+ path: str,
576
+ payload: Mapping[str, Any],
577
+ idempotency_key: Optional[str] = None,
578
+ ) -> Dict[str, Any]:
579
+ return self._request(
580
+ "POST",
581
+ path,
582
+ body=dict(payload),
583
+ idempotency_key=idempotency_key,
584
+ )
585
+
586
+ def _request(
587
+ self,
588
+ method: str,
589
+ path: str,
590
+ *,
591
+ params: Optional[Mapping[str, Any]] = None,
592
+ body: Optional[Mapping[str, Any]] = None,
593
+ idempotency_key: Optional[str] = None,
594
+ raw: bool = False,
595
+ accept: str = "application/json",
596
+ ) -> Any:
597
+ url = self.base_url + path
598
+ query = _encode_query(params or {})
599
+ if query:
600
+ url = f"{url}?{query}"
601
+
602
+ data = None
603
+ headers = {
604
+ "X-API-Key": self.api_key,
605
+ "Accept": accept,
606
+ "User-Agent": f"managebetcodes-python/{__version__}",
607
+ }
608
+ if body is not None:
609
+ data = json.dumps(body).encode("utf-8")
610
+ headers["Content-Type"] = "application/json"
611
+ if method == "POST":
612
+ headers["Idempotency-Key"] = idempotency_key or f"sdk_{uuid.uuid4().hex}"
613
+
614
+ for attempt in range(self.max_retries + 1):
615
+ request = urllib.request.Request(url, data=data, headers=headers, method=method)
616
+ try:
617
+ with urllib.request.urlopen(request, timeout=self.timeout) as response:
618
+ content = response.read()
619
+ if raw:
620
+ return content
621
+ if not content:
622
+ return {}
623
+ return json.loads(content.decode("utf-8"))
624
+ except urllib.error.HTTPError as exc:
625
+ content = exc.read()
626
+ exc.close()
627
+ payload = _decode_json(content)
628
+ retry_after = _retry_after(exc.headers.get("Retry-After"))
629
+ if (
630
+ exc.code in RETRY_STATUSES
631
+ and attempt < self.max_retries
632
+ and _error_code(payload) not in NON_RETRYABLE_CODES
633
+ ):
634
+ time.sleep(_retry_delay(exc.headers.get("Retry-After"), attempt))
635
+ continue
636
+ raise error_from_response(
637
+ exc.code,
638
+ payload,
639
+ retry_after,
640
+ ) from None
641
+ except (urllib.error.URLError, TimeoutError) as exc:
642
+ reason = getattr(exc, "reason", exc)
643
+ raise APIError(
644
+ f"The request to the API failed: {reason}",
645
+ code="network_error",
646
+ details={"reason": str(reason)},
647
+ ) from exc
648
+
649
+ raise APIError("The API retry loop ended without a response.", code="retry_exhausted")
650
+
651
+
652
+ def _encode_query(params: Mapping[str, Any]) -> str:
653
+ pairs: List[Tuple[str, str]] = []
654
+ for key, value in params.items():
655
+ if value is None or value == "":
656
+ continue
657
+ if isinstance(value, bool):
658
+ pairs.append((key, "true" if value else "false"))
659
+ elif isinstance(value, (list, tuple)):
660
+ pairs.extend((key, str(item)) for item in value)
661
+ else:
662
+ pairs.append((key, str(value)))
663
+ return urllib.parse.urlencode(pairs)
664
+
665
+
666
+ def _decode_json(content: bytes) -> Any:
667
+ try:
668
+ return json.loads(content.decode("utf-8"))
669
+ except (UnicodeDecodeError, ValueError):
670
+ return None
671
+
672
+
673
+ def _error_code(payload: Any) -> str:
674
+ if isinstance(payload, dict):
675
+ error = payload.get("error")
676
+ if isinstance(error, dict):
677
+ return str(error.get("code") or "")
678
+ return ""
679
+
680
+
681
+ def _retry_after(value: Optional[str]) -> Optional[float]:
682
+ if not value:
683
+ return None
684
+ try:
685
+ return max(0.0, float(value))
686
+ except ValueError:
687
+ pass
688
+ try:
689
+ when = parsedate_to_datetime(value)
690
+ except (TypeError, ValueError):
691
+ return None
692
+ if when.tzinfo is None:
693
+ when = when.replace(tzinfo=timezone.utc)
694
+ return max(0.0, (when - datetime.now(timezone.utc)).total_seconds())
695
+
696
+
697
+ def _retry_delay(value: Optional[str], attempt: int) -> float:
698
+ delay = _retry_after(value)
699
+ if delay is not None:
700
+ return min(delay, MAX_BACKOFF)
701
+ return min(DEFAULT_BACKOFF * (2**attempt), MAX_BACKOFF)
@@ -0,0 +1,88 @@
1
+ """Typed errors for the Manage Bet Codes API."""
2
+
3
+ from typing import Any, Dict, Optional
4
+
5
+ QUOTA_CODES = {
6
+ "api_quota_exhausted",
7
+ "plan_quota_exhausted",
8
+ "search_quota_exhausted",
9
+ }
10
+
11
+
12
+ class APIError(Exception):
13
+ """Base error for every API failure."""
14
+
15
+ def __init__(
16
+ self,
17
+ message: str,
18
+ *,
19
+ status: Optional[int] = None,
20
+ code: Optional[str] = None,
21
+ request_id: Optional[str] = None,
22
+ docs: Optional[str] = None,
23
+ details: Any = None,
24
+ ) -> None:
25
+ super().__init__(message)
26
+ self.message = message
27
+ self.status = status
28
+ self.code = code or "api_error"
29
+ self.request_id = request_id
30
+ self.docs = docs
31
+ self.details = details
32
+
33
+ def __str__(self) -> str:
34
+ if self.status is None:
35
+ return self.message
36
+ return f"HTTP {self.status} [{self.code}]: {self.message}"
37
+
38
+
39
+ class AuthenticationError(APIError):
40
+ """The key is missing, unknown, revoked, or not allowed."""
41
+
42
+
43
+ class QuotaError(APIError):
44
+ """The plan credits or the search cap are finished."""
45
+
46
+
47
+ class RateLimitError(APIError):
48
+ """The request rate is too high."""
49
+
50
+ def __init__(self, message: str, *, retry_after: Optional[float] = None, **kwargs: Any) -> None:
51
+ super().__init__(message, **kwargs)
52
+ self.retry_after = retry_after
53
+
54
+
55
+ class ValidationError(APIError):
56
+ """The request body or a parameter is invalid."""
57
+
58
+
59
+ def error_from_response(
60
+ status: int,
61
+ payload: Any,
62
+ retry_after: Optional[float] = None,
63
+ ) -> APIError:
64
+ """Map an HTTP status and an error envelope to a typed error."""
65
+
66
+ envelope: Dict[str, Any] = {}
67
+ if isinstance(payload, dict) and isinstance(payload.get("error"), dict):
68
+ envelope = payload["error"]
69
+
70
+ code = envelope.get("code") or f"http_{status}"
71
+ message = envelope.get("message") or f"The API returned HTTP {status}."
72
+ options = {
73
+ "status": status,
74
+ "code": code,
75
+ "request_id": envelope.get("request_id"),
76
+ "docs": envelope.get("docs"),
77
+ "details": envelope.get("details"),
78
+ }
79
+
80
+ if status in (401, 403):
81
+ return AuthenticationError(message, **options)
82
+ if status == 429 and code in QUOTA_CODES:
83
+ return QuotaError(message, **options)
84
+ if status == 429:
85
+ return RateLimitError(message, retry_after=retry_after, **options)
86
+ if status in (400, 422):
87
+ return ValidationError(message, **options)
88
+ return APIError(message, **options)
@@ -0,0 +1,23 @@
1
+ """Webhook signature checks."""
2
+
3
+ import hashlib
4
+ import hmac
5
+ from typing import Union
6
+
7
+ SIGNATURE_PREFIX = "sha256="
8
+
9
+
10
+ def verify_webhook(secret: Union[str, bytes], body: bytes, signature: str) -> bool:
11
+ """Return True when the signature matches the raw request body."""
12
+
13
+ if not secret or not signature or not signature.strip():
14
+ return False
15
+ if not isinstance(body, (bytes, bytearray)):
16
+ raise TypeError("body must be bytes")
17
+
18
+ key = secret.encode("utf-8") if isinstance(secret, str) else secret
19
+ expected = hmac.new(key, bytes(body), hashlib.sha256).hexdigest()
20
+ provided = signature.strip()
21
+ if provided.lower().startswith(SIGNATURE_PREFIX):
22
+ provided = provided[len(SIGNATURE_PREFIX) :]
23
+ return hmac.compare_digest(expected, provided.lower())
@@ -0,0 +1,270 @@
1
+ Metadata-Version: 2.4
2
+ Name: managebetcodes
3
+ Version: 1.0.0
4
+ Summary: Official Python SDK for the Manage Bet Codes public API v1
5
+ Author: Manage Bet Codes
6
+ License: MIT
7
+ Project-URL: Documentation, https://managebetcodes.app/developers/sdk/python
8
+ Project-URL: Source, https://github.com/kayceepeece/Viewbetbot
9
+ Keywords: betting,bet-codes,sportybet,1xbet
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Operating System :: OS Independent
14
+ Requires-Python: >=3.9
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest>=7; extra == "dev"
19
+ Dynamic: license-file
20
+
21
+ # Manage Bet Codes Python SDK
22
+
23
+ The official Python SDK for the Manage Bet Codes public API v1.
24
+
25
+ - Python 3.9 or later.
26
+ - No runtime dependencies. The SDK uses the Python standard library.
27
+ - Synchronous client.
28
+
29
+ ## Install
30
+
31
+ ```bash
32
+ pip install managebetcodes
33
+ ```
34
+
35
+ ## Command line
36
+
37
+ The package installs an `mbc` command with the same client.
38
+
39
+ ```bash
40
+ export MBC_API_KEY=mbc_live_your_key
41
+ mbc convert 7B9A2F --from sportybet --to 1xng
42
+ mbc view 7B9A2F --bookmaker sportybet
43
+ mbc usage
44
+ ```
45
+
46
+ ## Quick start
47
+
48
+ ```python
49
+ from managebetcodes import Client
50
+
51
+ client = Client("mbc_live_your_key")
52
+
53
+ result = client.convert("7B9A2F", "sportybet", "1xng")
54
+ print(result["target"]["code"])
55
+ ```
56
+
57
+ The client uses this base URL by default:
58
+
59
+ ```text
60
+ https://api.managebetcodes.app/v1
61
+ ```
62
+
63
+ Change the base URL for a test server:
64
+
65
+ ```python
66
+ client = Client("mbc_live_your_key", base_url="http://127.0.0.1:8000/v1")
67
+ ```
68
+
69
+ ## Authentication
70
+
71
+ Pass the API key to the constructor.
72
+ The SDK sends the key in the `X-API-Key` header.
73
+ Keys start with `mbc_live_`.
74
+ Keep the key on the server.
75
+ Do not put the key in browser code.
76
+
77
+ ## Client options
78
+
79
+ ```python
80
+ Client(
81
+ api_key,
82
+ base_url="https://api.managebetcodes.app/v1",
83
+ timeout=30,
84
+ max_retries=3,
85
+ )
86
+ ```
87
+
88
+ - `timeout` is the socket timeout in seconds.
89
+ - `max_retries` is the number of extra attempts.
90
+
91
+ ## Methods
92
+
93
+ | Method | Call | Price |
94
+ |---|---|---|
95
+ | `convert(code, source, target)` | `POST /convert` | 2 credits per target |
96
+ | `convert_to_all(code, source, to=...)` | `POST /convert/all` | 2 credits per target |
97
+ | `convert_bulk(codes, to=...)` | `POST /convert/bulk` | 2 credits per pair |
98
+ | `view(code, bookmaker)` | `GET /view` | 1 credit |
99
+ | `view_image(code, bookmaker)` | `GET /view/image` | 2 credits |
100
+ | `split(code, bookmaker, count=2, ...)` | `POST /split` | 2 credits plus 1 per extra part |
101
+ | `merge(pairs, target=None)` | `POST /merge` | 2 credits plus 1 per extra code |
102
+ | `book(bookmaker, plan_id=..., picks=...)` | `POST /book` | 2 credits per code |
103
+ | `events_search(bookmaker, queries)` | `POST /events/search` | 0 credits |
104
+ | `events(q=...)` | `GET /events` | 0 credits |
105
+ | `event_markets(event_id)` | `GET /events/{id}/markets` | 0 credits |
106
+ | `resolve(bookmaker, picks)` | `POST /resolve` | 0 credits |
107
+ | `markets()` | `GET /markets` | 0 credits |
108
+ | `books(limit=..., offset=...)` | `GET /books` | 0 credits |
109
+ | `capabilities()` | `GET /capabilities` | 0 credits |
110
+ | `usage()` | `GET /usage` | 0 credits |
111
+ | `history(limit=..., offset=...)` | `GET /history` | 0 credits |
112
+ | `jobs_create(payload)` | `POST /jobs` | Job price |
113
+ | `job(job_id)` | `GET /jobs/{id}` | 0 credits |
114
+ | `jobs()` | `GET /jobs` | 0 credits |
115
+ | `cancel_job(job_id)` | `DELETE /jobs/{id}` | 0 credits |
116
+ | `track_start(code, bookmaker)` | `POST /track` | 1 credit |
117
+ | `track(track_id)` | `GET /track/{id}` | 0 credits |
118
+ | `tracks()` | `GET /tracks` | 0 credits |
119
+ | `stop_track(track_id)` | `DELETE /track/{id}` | 0 credits |
120
+
121
+ The methods return the JSON response as a `dict`.
122
+ `view_image` returns `bytes`.
123
+
124
+ ## Convert
125
+
126
+ Convert one code to one target:
127
+
128
+ ```python
129
+ client.convert("7B9A2F", "sportybet", "1xng")
130
+ ```
131
+
132
+ Convert one code to a batch:
133
+
134
+ ```python
135
+ client.convert("7B9A2F", "sportybet", ["1xng", "msport", "bet9ja"])
136
+ ```
137
+
138
+ A batch accepts 2 to 6 targets.
139
+ Use a job for more targets.
140
+
141
+ ## Book
142
+
143
+ Book from a resolve plan:
144
+
145
+ ```python
146
+ client.book("sportybet", plan_id="plan_123")
147
+ ```
148
+
149
+ Book from direct picks:
150
+
151
+ ```python
152
+ client.book(
153
+ "sportybet",
154
+ picks=[{"event_id": "sr:match:123", "market_id": "18",
155
+ "outcome_id": "12", "odds": "1.90"}],
156
+ )
157
+ ```
158
+
159
+ ## Jobs
160
+
161
+ `jobs_create` accepts a job body:
162
+
163
+ ```python
164
+ job = client.jobs_create({
165
+ "kind": "convert",
166
+ "code": "7B9A2F",
167
+ "from": "sportybet",
168
+ "to": ["1xng", "msport", "bet9ja", "melbet"],
169
+ })
170
+ client.job(job["id"])
171
+ ```
172
+
173
+ ## Image
174
+
175
+ ```python
176
+ png = client.view_image("7B9A2F", "sportybet")
177
+ with open("slip.png", "wb") as file:
178
+ file.write(png)
179
+ ```
180
+
181
+ The method returns the image bytes.
182
+ It raises a typed error when the API returns an error envelope.
183
+
184
+ ## Idempotency
185
+
186
+ The SDK adds an `Idempotency-Key` header to every POST call.
187
+ Pass your own key when you need a stable value:
188
+
189
+ ```python
190
+ client.convert("7B9A2F", "sportybet", "1xng", idempotency_key="order-123")
191
+ ```
192
+
193
+ The SDK sends the same key on a retry.
194
+
195
+ ## Retries
196
+
197
+ The SDK retries on these status codes:
198
+
199
+ - `429`
200
+ - `502`
201
+ - `503`
202
+ - `504`
203
+
204
+ The SDK reads the `Retry-After` header.
205
+ If the header is absent, the SDK uses exponential backoff.
206
+
207
+ ## Errors
208
+
209
+ All errors inherit from `APIError`:
210
+
211
+ | Error | Status | Meaning |
212
+ |---|---|---|
213
+ | `AuthenticationError` | 401, 403 | The key is missing, bad, or not allowed |
214
+ | `QuotaError` | 429 | The plan credits or search cap are finished |
215
+ | `RateLimitError` | 429 | The request rate is too high |
216
+ | `ValidationError` | 400, 422 | A parameter or the body is invalid |
217
+ | `APIError` | Other | Any other API error |
218
+
219
+ Each error has these attributes:
220
+
221
+ - `status`
222
+ - `code`
223
+ - `message`
224
+ - `request_id`
225
+ - `docs`
226
+ - `details`
227
+
228
+ `RateLimitError` also has `retry_after`.
229
+
230
+ ```python
231
+ from managebetcodes import RateLimitError, ValidationError
232
+
233
+ try:
234
+ client.convert("BAD", "sportybet", "1xng")
235
+ except ValidationError as error:
236
+ print(error.code, error.details)
237
+ except RateLimitError as error:
238
+ print("Retry after", error.retry_after)
239
+ ```
240
+
241
+ ## Webhooks
242
+
243
+ Verify the raw request body before you trust a webhook:
244
+
245
+ ```python
246
+ from managebetcodes import verify_webhook
247
+
248
+ if not verify_webhook(secret, raw_body, request.headers["X-MBC-Signature"]):
249
+ return "invalid signature", 400
250
+ ```
251
+
252
+ `raw_body` must be `bytes`.
253
+ Do not parse the body before the check.
254
+ The function returns `True` for a valid signature.
255
+ It returns `False` for a bad signature.
256
+
257
+ ## Pagination
258
+
259
+ Pass `limit` and `offset` to `history`, `jobs`, `books`, and `events`.
260
+ The response returns `next_offset` when another page exists.
261
+
262
+ ```python
263
+ page = client.history(limit=20, offset=0)
264
+ for item in page["items"]:
265
+ print(item["id"])
266
+ ```
267
+
268
+ ## License
269
+
270
+ MIT
@@ -0,0 +1,11 @@
1
+ managebetcodes/__init__.py,sha256=N2Jb6X1YxgGXPzVHrfRkST6r5z5Edq2qxMlEGLtV2ac,433
2
+ managebetcodes/cli.py,sha256=4XAHSbDRjkh8xXnHv3swR98f9qByV4D_mHAv_2HmH4w,4215
3
+ managebetcodes/client.py,sha256=0udYhNJ0SoFdVWNQ9DsBGWZoJqIyL0d7NulLrLaUh7o,21754
4
+ managebetcodes/errors.py,sha256=nE8GK9KevPRO4eN6c6x9y3IiqttPjoPNM77c-x9fzsM,2517
5
+ managebetcodes/webhooks.py,sha256=-CVbZ41zFIcLe451dG66fX57KI4LHhz4p45on8PKRoA,792
6
+ managebetcodes-1.0.0.dist-info/licenses/LICENSE,sha256=x9S0ETcF0Xb6iCq3KVOs-OjYWlmDSrEuxZPCIp9hVoA,1073
7
+ managebetcodes-1.0.0.dist-info/METADATA,sha256=rLDWlTM5wGa4HiSHkNeN_NWKnbB3TqxPdGqtnIYpnFs,6713
8
+ managebetcodes-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
+ managebetcodes-1.0.0.dist-info/entry_points.txt,sha256=iIEVU6BKmUWVTnYT_GGMBf8cpFat66cADOAtTlrxmts,48
10
+ managebetcodes-1.0.0.dist-info/top_level.txt,sha256=P__lkFknCHkw9wPnaWh1bjS3YE3HFzrbGVbST7uu9sA,15
11
+ managebetcodes-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ mbc = managebetcodes.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Manage Bet Codes
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ managebetcodes