ebay-sniper 0.1.0__tar.gz

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.

Potentially problematic release.


This version of ebay-sniper might be problematic. Click here for more details.

@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Vincenzo Imperati
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,117 @@
1
+ Metadata-Version: 2.4
2
+ Name: ebay-sniper
3
+ Version: 0.1.0
4
+ Summary: Bid on an eBay auction once, as late as eBay still records it
5
+ Keywords: ebay,auction,sniper,bid-sniping,bidding,cli
6
+ Author: Vincenzo Imperati
7
+ Author-email: Vincenzo Imperati <61617279+VincenzoImp@users.noreply.github.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: End Users/Desktop
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Internet :: WWW/HTTP :: Browsers
16
+ Requires-Dist: drissionpage>=4.1.1.4
17
+ Requires-Python: >=3.11
18
+ Project-URL: Homepage, https://github.com/VincenzoImp/ebay-sniper
19
+ Project-URL: Issues, https://github.com/VincenzoImp/ebay-sniper/issues
20
+ Description-Content-Type: text/markdown
21
+
22
+ # eBay Sniper
23
+
24
+ [![CI](https://github.com/VincenzoImp/ebay-sniper/actions/workflows/ci.yml/badge.svg)](https://github.com/VincenzoImp/ebay-sniper/actions/workflows/ci.yml)
25
+ [![PyPI](https://img.shields.io/pypi/v/ebay-sniper)](https://pypi.org/project/ebay-sniper/)
26
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue)](LICENSE)
27
+
28
+ Places one bid with your maximum on an eBay auction, timed so eBay records it in the last half second.
29
+
30
+ ```sh
31
+ uvx ebay-sniper 'https://www.ebay.com/itm/123456789012' --max 120
32
+ ```
33
+
34
+ A real run, with the auction's end set to 13:50:22:
35
+
36
+ ```text
37
+ Clock checked: off by +0.002 s, corrected.
38
+ Rehearsing the bid on eBay (nothing is confirmed)…
39
+
40
+ Item Apple Mac mini 16 GB, 1 TB SSD
41
+ Ends Mon 30 Nov 13:50:22 (in 0:02:50)
42
+ Maximum 117, bid once, at the last moment eBay still records it
43
+
44
+ Place this bid? [y/N] y
45
+
46
+ Scheduled. Nothing else to do: keep this window, the browser and the computer on.
47
+ Ready. eBay needs 175 ms to receive the bid and up to 1.83 s to record it: bidding 2.21 s before the end.
48
+ Bid sent -2.206 s from the end.
49
+ eBay received it -1.957 s from the end.
50
+ eBay answered -0.009 s from the end.
51
+ Status: HIGHBIDDER, current price EUR 113.04.
52
+ ```
53
+
54
+ eBay's bid history recorded the bid at 13:50:21.
55
+
56
+ ## How it works
57
+
58
+ eBay records a bid 1.3–1.6 s after the request arrives, not on arrival (measured with real bids against eBay's server clock). A bid sent half a second before the end is recorded too late.
59
+
60
+ The bot:
61
+
62
+ 1. Opens the auction in a visible Chrome, Brave, Edge or Chromium window and checks you are signed in.
63
+ 2. Rehearses the bid: enters your maximum, goes through eBay's review step, stops before confirming. Errors such as a too-low amount show up immediately.
64
+ 3. One minute before the end, prepares the bid again and times eBay's review request to measure eBay's current delay.
65
+ 4. Clicks confirm about 2 s before the end, so eBay records the bid about 0.5 s before it.
66
+ 5. Prints eBay's answer, for example "You're the highest bidder".
67
+
68
+ It works on every eBay site and language. The clock is corrected against NTP.
69
+
70
+ ## Install
71
+
72
+ Requires Chrome, Brave, Edge or Chromium, and [uv](https://docs.astral.sh/uv/getting-started/installation/) or pip.
73
+
74
+ ```sh
75
+ uv tool install ebay-sniper # or: pip install ebay-sniper
76
+ ```
77
+
78
+ `uvx ebay-sniper …` runs it without installing.
79
+
80
+ ## Use
81
+
82
+ ```sh
83
+ ebay-sniper '<item link>' --max <amount>
84
+ ```
85
+
86
+ - Quote the link: it contains `&` and `?`. Or run `ebay-sniper` alone and paste it when asked.
87
+ - On the first run on a site, sign in to eBay in the browser window. The session is kept in `~/.ebay-sniper/profile`.
88
+ - Answer `y` to the summary, then keep the terminal, browser and computer on until the end.
89
+ - For several auctions, run one command per auction. They share the browser, each in its own tab.
90
+ - If eBay shows a human check, complete it in the browser. The bot waits.
91
+
92
+ Options:
93
+
94
+ - `--at HH:MM:SS` treats that local time as the end. Use it for a test bid. The bid is real.
95
+ - `--browser PATH` sets the browser if it is not found automatically.
96
+
97
+ Each bid is logged to `~/.ebay-sniper/history.jsonl`.
98
+
99
+ ## Limits
100
+
101
+ - The browser must stay visible. eBay blocks headless browsers.
102
+ - eBay [allows sniping](https://www.ebay.com/help/buying/bidding/bid-sniping?id=4224) but its [User Agreement](https://www.ebay.com/help/policies/member-behaviour-policies/user-agreement?id=5414) prohibits automated access without permission. Use at your own risk.
103
+ - If eBay changes its pages, update the constants at the top of [`browser.py`](src/ebay_sniper/browser.py).
104
+
105
+ ## Develop
106
+
107
+ ```sh
108
+ uv sync
109
+ uv run ruff check . && uv run ruff format --check .
110
+ uv run pytest
111
+ ```
112
+
113
+ `tests/test_offline.py` tests parsing and timing with data captured from eBay. `tests/test_live.py` runs eBay's real bid flow up to the confirm button and never confirms:
114
+
115
+ ```sh
116
+ EBAY_ITEM='<item link>' EBAY_MAX=<amount> uv run pytest tests/test_live.py -s
117
+ ```
@@ -0,0 +1,96 @@
1
+ # eBay Sniper
2
+
3
+ [![CI](https://github.com/VincenzoImp/ebay-sniper/actions/workflows/ci.yml/badge.svg)](https://github.com/VincenzoImp/ebay-sniper/actions/workflows/ci.yml)
4
+ [![PyPI](https://img.shields.io/pypi/v/ebay-sniper)](https://pypi.org/project/ebay-sniper/)
5
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue)](LICENSE)
6
+
7
+ Places one bid with your maximum on an eBay auction, timed so eBay records it in the last half second.
8
+
9
+ ```sh
10
+ uvx ebay-sniper 'https://www.ebay.com/itm/123456789012' --max 120
11
+ ```
12
+
13
+ A real run, with the auction's end set to 13:50:22:
14
+
15
+ ```text
16
+ Clock checked: off by +0.002 s, corrected.
17
+ Rehearsing the bid on eBay (nothing is confirmed)…
18
+
19
+ Item Apple Mac mini 16 GB, 1 TB SSD
20
+ Ends Mon 30 Nov 13:50:22 (in 0:02:50)
21
+ Maximum 117, bid once, at the last moment eBay still records it
22
+
23
+ Place this bid? [y/N] y
24
+
25
+ Scheduled. Nothing else to do: keep this window, the browser and the computer on.
26
+ Ready. eBay needs 175 ms to receive the bid and up to 1.83 s to record it: bidding 2.21 s before the end.
27
+ Bid sent -2.206 s from the end.
28
+ eBay received it -1.957 s from the end.
29
+ eBay answered -0.009 s from the end.
30
+ Status: HIGHBIDDER, current price EUR 113.04.
31
+ ```
32
+
33
+ eBay's bid history recorded the bid at 13:50:21.
34
+
35
+ ## How it works
36
+
37
+ eBay records a bid 1.3–1.6 s after the request arrives, not on arrival (measured with real bids against eBay's server clock). A bid sent half a second before the end is recorded too late.
38
+
39
+ The bot:
40
+
41
+ 1. Opens the auction in a visible Chrome, Brave, Edge or Chromium window and checks you are signed in.
42
+ 2. Rehearses the bid: enters your maximum, goes through eBay's review step, stops before confirming. Errors such as a too-low amount show up immediately.
43
+ 3. One minute before the end, prepares the bid again and times eBay's review request to measure eBay's current delay.
44
+ 4. Clicks confirm about 2 s before the end, so eBay records the bid about 0.5 s before it.
45
+ 5. Prints eBay's answer, for example "You're the highest bidder".
46
+
47
+ It works on every eBay site and language. The clock is corrected against NTP.
48
+
49
+ ## Install
50
+
51
+ Requires Chrome, Brave, Edge or Chromium, and [uv](https://docs.astral.sh/uv/getting-started/installation/) or pip.
52
+
53
+ ```sh
54
+ uv tool install ebay-sniper # or: pip install ebay-sniper
55
+ ```
56
+
57
+ `uvx ebay-sniper …` runs it without installing.
58
+
59
+ ## Use
60
+
61
+ ```sh
62
+ ebay-sniper '<item link>' --max <amount>
63
+ ```
64
+
65
+ - Quote the link: it contains `&` and `?`. Or run `ebay-sniper` alone and paste it when asked.
66
+ - On the first run on a site, sign in to eBay in the browser window. The session is kept in `~/.ebay-sniper/profile`.
67
+ - Answer `y` to the summary, then keep the terminal, browser and computer on until the end.
68
+ - For several auctions, run one command per auction. They share the browser, each in its own tab.
69
+ - If eBay shows a human check, complete it in the browser. The bot waits.
70
+
71
+ Options:
72
+
73
+ - `--at HH:MM:SS` treats that local time as the end. Use it for a test bid. The bid is real.
74
+ - `--browser PATH` sets the browser if it is not found automatically.
75
+
76
+ Each bid is logged to `~/.ebay-sniper/history.jsonl`.
77
+
78
+ ## Limits
79
+
80
+ - The browser must stay visible. eBay blocks headless browsers.
81
+ - eBay [allows sniping](https://www.ebay.com/help/buying/bidding/bid-sniping?id=4224) but its [User Agreement](https://www.ebay.com/help/policies/member-behaviour-policies/user-agreement?id=5414) prohibits automated access without permission. Use at your own risk.
82
+ - If eBay changes its pages, update the constants at the top of [`browser.py`](src/ebay_sniper/browser.py).
83
+
84
+ ## Develop
85
+
86
+ ```sh
87
+ uv sync
88
+ uv run ruff check . && uv run ruff format --check .
89
+ uv run pytest
90
+ ```
91
+
92
+ `tests/test_offline.py` tests parsing and timing with data captured from eBay. `tests/test_live.py` runs eBay's real bid flow up to the confirm button and never confirms:
93
+
94
+ ```sh
95
+ EBAY_ITEM='<item link>' EBAY_MAX=<amount> uv run pytest tests/test_live.py -s
96
+ ```
@@ -0,0 +1,49 @@
1
+ [project]
2
+ name = "ebay-sniper"
3
+ version = "0.1.0"
4
+ description = "Bid on an eBay auction once, as late as eBay still records it"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ keywords = [
9
+ "ebay",
10
+ "auction",
11
+ "sniper",
12
+ "bid-sniping",
13
+ "bidding",
14
+ "cli",
15
+ ]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Environment :: Console",
19
+ "Intended Audience :: End Users/Desktop",
20
+ "Operating System :: OS Independent",
21
+ "Programming Language :: Python :: 3",
22
+ "Topic :: Internet :: WWW/HTTP :: Browsers",
23
+ ]
24
+ requires-python = ">=3.11"
25
+ dependencies = ["drissionpage>=4.1.1.4"]
26
+
27
+ [[project.authors]]
28
+ name = "Vincenzo Imperati"
29
+ email = "61617279+VincenzoImp@users.noreply.github.com"
30
+
31
+ [project.urls]
32
+ Homepage = "https://github.com/VincenzoImp/ebay-sniper"
33
+ Issues = "https://github.com/VincenzoImp/ebay-sniper/issues"
34
+
35
+ [project.scripts]
36
+ ebay-sniper = "ebay_sniper.cli:main"
37
+
38
+ [tool.ruff]
39
+ line-length = 100
40
+
41
+ [build-system]
42
+ requires = ["uv_build>=0.13.9,<0.14.0"]
43
+ build-backend = "uv_build"
44
+
45
+ [dependency-groups]
46
+ dev = [
47
+ "pytest>=9.2.0",
48
+ "ruff>=0.17.6",
49
+ ]
@@ -0,0 +1,43 @@
1
+ [project]
2
+ name = "ebay-sniper"
3
+ version = "0.1.0"
4
+ description = "Bid on an eBay auction once, as late as eBay still records it"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ keywords = ["ebay", "auction", "sniper", "bid-sniping", "bidding", "cli"]
9
+ classifiers = [
10
+ "Development Status :: 4 - Beta",
11
+ "Environment :: Console",
12
+ "Intended Audience :: End Users/Desktop",
13
+ "Operating System :: OS Independent",
14
+ "Programming Language :: Python :: 3",
15
+ "Topic :: Internet :: WWW/HTTP :: Browsers",
16
+ ]
17
+ authors = [
18
+ { name = "Vincenzo Imperati", email = "61617279+VincenzoImp@users.noreply.github.com" }
19
+ ]
20
+ requires-python = ">=3.11"
21
+ dependencies = [
22
+ "drissionpage>=4.1.1.4",
23
+ ]
24
+
25
+ [project.urls]
26
+ Homepage = "https://github.com/VincenzoImp/ebay-sniper"
27
+ Issues = "https://github.com/VincenzoImp/ebay-sniper/issues"
28
+
29
+ [project.scripts]
30
+ ebay-sniper = "ebay_sniper.cli:main"
31
+
32
+ [tool.ruff]
33
+ line-length = 100
34
+
35
+ [build-system]
36
+ requires = ["uv_build>=0.13.9,<0.14.0"]
37
+ build-backend = "uv_build"
38
+
39
+ [dependency-groups]
40
+ dev = [
41
+ "pytest>=9.2.0",
42
+ "ruff>=0.17.6",
43
+ ]
File without changes
@@ -0,0 +1,36 @@
1
+ """Keep the computer awake while a bid is scheduled."""
2
+
3
+ import atexit
4
+ import os
5
+ import platform
6
+ import shutil
7
+ import subprocess
8
+
9
+
10
+ def keep_awake() -> bool:
11
+ """Prevent idle sleep until this process exits. Returns False if unsupported."""
12
+ system = platform.system()
13
+ if system == "Darwin":
14
+ subprocess.Popen(["caffeinate", "-i", "-w", str(os.getpid())])
15
+ return True
16
+ if system == "Windows":
17
+ import ctypes
18
+
19
+ es_continuous, es_system_required = 0x80000000, 0x00000001
20
+ ctypes.windll.kernel32.SetThreadExecutionState(es_continuous | es_system_required)
21
+ return True
22
+ if shutil.which("systemd-inhibit"):
23
+ process = subprocess.Popen(
24
+ [
25
+ "systemd-inhibit",
26
+ "--what=idle:sleep",
27
+ "--why=eBay bid scheduled",
28
+ "sleep",
29
+ "infinity",
30
+ ],
31
+ stdout=subprocess.DEVNULL,
32
+ stderr=subprocess.DEVNULL,
33
+ )
34
+ atexit.register(process.terminate)
35
+ return True
36
+ return False
@@ -0,0 +1,333 @@
1
+ """Drive a visible Chromium-based browser that holds the user's eBay session.
2
+
3
+ Everything here relies on markup and data that are the same on every eBay site
4
+ (checked on ebay.com, .co.uk, .de, .fr and .it): element ids, page structure and
5
+ the bid service's JSON. Never on button text, which is translated.
6
+ """
7
+
8
+ import platform
9
+ import re
10
+ import shutil
11
+ import time
12
+ from contextlib import suppress
13
+ from pathlib import Path
14
+
15
+ from DrissionPage import Chromium, ChromiumOptions
16
+ from DrissionPage.errors import BaseError
17
+
18
+ DEFAULT_PROFILE = Path.home() / ".ebay-sniper" / "profile"
19
+ # A fixed debugging port: DrissionPage keeps the profile above only with a fixed
20
+ # port, and every run connects to the same browser and eBay session.
21
+ PORT = 9531
22
+
23
+ # eBay's markup and endpoints. When eBay changes its pages, this is the place to update.
24
+ BID_BUTTON = "#bidBtn_btn" # "Place bid" on the item page
25
+ CONFIRM_BUTTON = "#confirmBid" # "Confirm bid" at the end of the review step
26
+ HEADER = "#gh" # the site header
27
+ SIGN_IN_LINK = 'a[href*="signin.ebay."]' # in the header only when signed out
28
+ REVIEW_REQUEST = "action=reviewbid"
29
+ CONFIRM_REQUEST = "action=confirmbid"
30
+ # eBay's log id header ends with the server time in hexadecimal milliseconds.
31
+ SERVER_TIME = re.compile(r"-([0-9a-f]{11})-0x[0-9a-f]+$")
32
+
33
+ _HELPERS = """
34
+ const visible = e => {
35
+ if (!e || !e.checkVisibility({checkOpacity: true, checkVisibilityCSS: true})) return false;
36
+ const r = e.getBoundingClientRect();
37
+ return r.width > 0 && r.height > 0 && !e.disabled && e.getAttribute('aria-disabled') !== 'true';
38
+ };
39
+ const mark = (e, name) => {
40
+ document.querySelectorAll('[data-snipe="' + name + '"]')
41
+ .forEach(o => o.removeAttribute('data-snipe'));
42
+ if (e) e.setAttribute('data-snipe', name);
43
+ return e;
44
+ };
45
+ const fieldIn = d => [...d.querySelectorAll('input')]
46
+ .find(e => visible(e) && ['tel', 'text', 'number'].includes(e.type));
47
+ const dialogs = () => [...document.querySelectorAll('[role="dialog"]')].filter(visible);
48
+ const bidDialog = () => dialogs().find(fieldIn) || dialogs()[0] || null;
49
+ """
50
+
51
+ _FIND = _HELPERS + "return visible(mark(document.querySelector(arguments[0]), arguments[1]));"
52
+
53
+ # The amount field of the bid dialog. Returns its value, or null.
54
+ _FIND_FIELD = (
55
+ _HELPERS
56
+ + """
57
+ const dialog = bidDialog(), field = dialog && fieldIn(dialog);
58
+ mark(field, 'field');
59
+ return field ? field.value : null;
60
+ """
61
+ )
62
+
63
+ # The first enabled button after the amount field: it opens the review step.
64
+ # It stays disabled until an amount is typed.
65
+ _FIND_NEXT = (
66
+ _HELPERS
67
+ + """
68
+ const field = document.querySelector('[data-snipe="field"]');
69
+ const next = field && [...field.closest('[role="dialog"]').querySelectorAll('button')]
70
+ .find(b => visible(b) && (field.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING));
71
+ return !!mark(next, 'next');
72
+ """
73
+ )
74
+
75
+ _SIGNED_IN = (
76
+ _HELPERS
77
+ + f"""
78
+ const header = document.querySelector('{HEADER}');
79
+ return !!header && ![...header.querySelectorAll('{SIGN_IN_LINK}')].some(visible);
80
+ """
81
+ )
82
+
83
+ # Short messages eBay shows inside the bid dialog, such as the minimum bid.
84
+ _ALERTS = (
85
+ _HELPERS
86
+ + """
87
+ const root = bidDialog();
88
+ if (!root) return [];
89
+ const seen = new Set();
90
+ for (const e of root.querySelectorAll('[role="alert"], [aria-live="assertive"], [id$="__error"]')) {
91
+ const text = (e.innerText || '').trim().replace(/\\s+/g, ' ');
92
+ if (visible(e) && text.length > 3 && text.length < 300) seen.add(text);
93
+ }
94
+ return [...seen].filter(t => ![...seen].some(o => o !== t && t.includes(o)));
95
+ """
96
+ )
97
+
98
+ # Centre of the confirm button, scrolled into view.
99
+ _TARGET = f"""
100
+ const e = document.querySelector('{CONFIRM_BUTTON}');
101
+ if (!e) return null;
102
+ e.scrollIntoView({{block: 'center', behavior: 'instant'}});
103
+ const r = e.getBoundingClientRect();
104
+ return r.width > 0 ? {{x: r.x + r.width / 2, y: r.y + r.height / 2}} : null;
105
+ """
106
+
107
+ # Client-side times of the latest request whose URL contains a string, in Unix ms
108
+ # (system clock).
109
+ _REQUEST_TIMES = """
110
+ const e = performance.getEntriesByType('resource').filter(e => e.name.includes(arguments[0])).pop();
111
+ return e ? {sent: performance.timeOrigin + e.requestStart,
112
+ answered: performance.timeOrigin + e.responseStart} : null;
113
+ """
114
+
115
+
116
+ def find_browser() -> str | None:
117
+ """Return the first installed Chrome, Brave, Edge or Chromium."""
118
+ candidates = {
119
+ "Darwin": [
120
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
121
+ "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
122
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
123
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
124
+ ],
125
+ "Windows": [
126
+ r"C:\Program Files\Google\Chrome\Application\chrome.exe",
127
+ r"C:\Program Files\BraveSoftware\Brave-Browser\Application\brave.exe",
128
+ r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
129
+ ],
130
+ }.get(platform.system(), [])
131
+ for path in candidates:
132
+ if Path(path).exists():
133
+ return path
134
+ for name in [
135
+ "google-chrome",
136
+ "brave-browser",
137
+ "microsoft-edge",
138
+ "chromium",
139
+ "chromium-browser",
140
+ ]:
141
+ if found := shutil.which(name):
142
+ return found
143
+ return None
144
+
145
+
146
+ def server_time(headers: dict) -> float | None:
147
+ """eBay's server time, in Unix seconds, from a bid service response."""
148
+ log_id = next((v for k, v in (headers or {}).items() if k.lower() == "rlogid"), "")
149
+ match = SERVER_TIME.search(log_id)
150
+ return int(match.group(1), 16) / 1000 if match else None
151
+
152
+
153
+ def bid_outcome(body) -> dict:
154
+ """The parts of eBay's confirm-bid response that say what happened."""
155
+ modules = body.get("model", {}).get("modules", {}) if isinstance(body, dict) else {}
156
+ data = modules.get("BID_SEMANTIC_DATA", {})
157
+ messages = [
158
+ module.get("message") or {}
159
+ for name, module in modules.items()
160
+ if name != "BID_FALLBACK_ERROR" and isinstance(module, dict)
161
+ ]
162
+ message = next((m for m in messages if m.get("messageType")), {})
163
+ price = data.get("currentPrice") or {}
164
+ return {
165
+ "status": message.get("messageType"), # SUCCESS, ERROR, …
166
+ "message": "".join(
167
+ s.get("text", "") for s in message.get("title", {}).get("textSpans", [])
168
+ ),
169
+ "relation": data.get("viewerItemRelation"), # HIGHBIDDER, …
170
+ "price": f"{price.get('currency', '')} {price.get('value', '')}".strip() or None,
171
+ "maximum": (data.get("maximumBid") or {}).get("value"),
172
+ }
173
+
174
+
175
+ class Browser:
176
+ def __init__(self, browser_path: str | None, profile: Path = DEFAULT_PROFILE, notify=print):
177
+ path = browser_path or find_browser()
178
+ if not path:
179
+ raise RuntimeError(
180
+ "No Chrome, Brave, Edge or Chromium found. Install one or pass --browser."
181
+ )
182
+ profile.mkdir(parents=True, exist_ok=True)
183
+ options = ChromiumOptions().set_browser_path(path).set_user_data_path(str(profile))
184
+ options.set_local_port(PORT)
185
+ self.browser = Chromium(options)
186
+ # Each run works in its own tab: several runs can share the browser and session.
187
+ self.tab = self.browser.new_tab()
188
+ self.notify = notify
189
+ self.target = None
190
+ self.reviews = [] # timings of review requests: what a bid will cost at eBay
191
+
192
+ def _js(self, script, *args, timeout=None):
193
+ """Run a script, retrying while the page is navigating."""
194
+ for _ in range(20):
195
+ with suppress(BaseError):
196
+ return self.tab.run_js(script, *args, timeout=timeout)
197
+ time.sleep(0.25)
198
+ return self.tab.run_js(script, *args, timeout=timeout)
199
+
200
+ def _wait_for(self, check, timeout):
201
+ deadline = time.monotonic() + timeout
202
+ while time.monotonic() < deadline:
203
+ if result := check():
204
+ return result
205
+ time.sleep(0.2)
206
+ return None
207
+
208
+ def _has_header(self) -> bool:
209
+ return bool(self._js(f"return !!document.querySelector('{HEADER}')"))
210
+
211
+ # Pages and session
212
+
213
+ def open(self, url: str) -> None:
214
+ """Load a page. If eBay shows a human check instead, wait for the user."""
215
+ self.tab.get(url)
216
+ if not self._wait_for(self._has_header, 5):
217
+ self.notify("\aeBay wants to check you're human. Complete the check in the browser.")
218
+ while not self._has_header():
219
+ time.sleep(1)
220
+ if not self.tab.url.startswith(url.split("?")[0]):
221
+ self.tab.get(url)
222
+
223
+ def html(self) -> str:
224
+ self._js("return 1") # wait for a loaded page
225
+ return self.tab.html
226
+
227
+ def title(self) -> str:
228
+ return self._js("return document.querySelector('h1')?.innerText.trim() || document.title")
229
+
230
+ def signed_in(self) -> bool:
231
+ return bool(self._js(_SIGNED_IN))
232
+
233
+ def wait_for_sign_in(self, item_url: str) -> None:
234
+ """Open eBay's sign-in page and wait until the user is back, signed in."""
235
+ link = self._js(f"return document.querySelector('{HEADER} {SIGN_IN_LINK}')?.href || null")
236
+ if link:
237
+ self.tab.get(link)
238
+ while "signin." in (self.tab.url or "") or not self.signed_in():
239
+ time.sleep(1)
240
+ self.open(item_url)
241
+
242
+ def decimal_mark(self) -> str:
243
+ """The decimal mark of the page's language."""
244
+ lang = "document.documentElement.lang || undefined"
245
+ return self._js(f"return (1.5).toLocaleString({lang}).charAt(1);") or "."
246
+
247
+ def alerts(self) -> list[str]:
248
+ return self._js(_ALERTS) or []
249
+
250
+ def dialog_text(self) -> str:
251
+ return self._js(_HELPERS + "return (bidDialog() || document.body).innerText") or ""
252
+
253
+ # Preparing the bid
254
+
255
+ def can_bid(self) -> bool:
256
+ return bool(self._js(_FIND, BID_BUTTON, "bid"))
257
+
258
+ def armed(self) -> bool:
259
+ """True if eBay's confirm button is on screen."""
260
+ return bool(self._js(_FIND, CONFIRM_BUTTON, "confirm"))
261
+
262
+ def prepare(self, amount_text: str) -> str | None:
263
+ """Open the bid dialog, type the amount and go through the review step.
264
+
265
+ Stops at the confirm button without clicking it, and records how long
266
+ eBay took to review the bid. Returns None when ready, otherwise what
267
+ went wrong.
268
+ """
269
+ if not self.can_bid():
270
+ return "no bid button on the item page"
271
+ self.tab.ele("css:[data-snipe=bid]").click()
272
+ if self._wait_for(lambda: self._js(_FIND_FIELD) is not None, 10) is None:
273
+ return "the bid dialog didn't open"
274
+ field = self.tab.ele("css:[data-snipe=field]")
275
+ field.click()
276
+ field.clear()
277
+ field.input(amount_text)
278
+ if not self._wait_for(lambda: self._js(_FIND_NEXT), 5):
279
+ return "eBay didn't accept the amount"
280
+ self.tab.listen.start(REVIEW_REQUEST)
281
+ try:
282
+ self.tab.ele("css:[data-snipe=next]").click()
283
+ packet = self.tab.listen.wait(timeout=15)
284
+ finally:
285
+ self.tab.listen.stop()
286
+ if not self._wait_for(self.armed, 5):
287
+ return "eBay didn't show the confirm button after the review step"
288
+ times = self._js(_REQUEST_TIMES, REVIEW_REQUEST)
289
+ arrived = server_time(packet.response.headers) if packet else None
290
+ if times and arrived:
291
+ self.reviews.append({**times, "arrived": arrived})
292
+ return None
293
+
294
+ # The critical moment
295
+
296
+ def aim(self) -> bool:
297
+ """Locate the confirm button and start listening for eBay's answer."""
298
+ self.target = self._js(_TARGET)
299
+ if self.target:
300
+ self.tab.listen.start(CONFIRM_REQUEST)
301
+ return bool(self.target)
302
+
303
+ def warm(self) -> None:
304
+ """Make a small request to eBay so the connection is open when the bid goes."""
305
+ self._js("fetch('/robots.txt', {cache: 'no-store'}).catch(() => {}); return 1")
306
+
307
+ def fire(self) -> None:
308
+ """Click the confirm button with real (trusted) mouse events."""
309
+ x, y = self.target["x"], self.target["y"]
310
+ for kind in ("mousePressed", "mouseReleased"):
311
+ self.tab.run_cdp(
312
+ "Input.dispatchMouseEvent", type=kind, x=x, y=y, button="left", clickCount=1
313
+ )
314
+
315
+ def result(self, timeout: float = 15) -> dict:
316
+ """What eBay answered to the bid, with its timing."""
317
+ try:
318
+ packet = self.tab.listen.wait(timeout=timeout)
319
+ finally:
320
+ self.tab.listen.stop()
321
+ if not packet:
322
+ return {}
323
+ times = self._js(_REQUEST_TIMES, CONFIRM_REQUEST) or {}
324
+ return {
325
+ **bid_outcome(packet.response.body),
326
+ **times,
327
+ "arrived": server_time(packet.response.headers),
328
+ }
329
+
330
+ def close(self) -> None:
331
+ """Close this run's tab, leaving the browser to other runs."""
332
+ with suppress(BaseError):
333
+ self.tab.close()
@@ -0,0 +1,242 @@
1
+ """ebay-sniper: one maximum bid, recorded by eBay as late as safely possible."""
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+ import time
7
+ from datetime import UTC, datetime
8
+ from importlib.metadata import version
9
+
10
+ from . import page
11
+ from .awake import keep_awake
12
+ from .browser import DEFAULT_PROFILE, Browser
13
+ from .clock import Clock
14
+
15
+ PREPARE = 60 # seconds before the end: open the bid dialog and stop at the confirm button
16
+ SESSION_CHECK = 300 # seconds before the end: make sure the eBay session is alive
17
+ # eBay records a bid while processing it: 1.3-1.6 s after the request arrives,
18
+ # and always before it answers (real bids, November 2026). Confirming takes
19
+ # eBay about 0.4 s longer than reviewing (1.65 s against 1.25 s), so the bot
20
+ # times the review request a minute before the end and adds:
21
+ CONFIRM_EXTRA = 0.40 # seconds: confirm processing minus review processing
22
+ SAFETY = 0.15 # seconds of margin on top
23
+ CLICK_COST = 0.01 # measured: trusted click to request on the wire
24
+ UNMEASURED_LEAD = 2.5 # seconds, when the review step couldn't be timed
25
+ HISTORY = DEFAULT_PROFILE.parent / "history.jsonl"
26
+
27
+
28
+ def main(argv: list[str] | None = None) -> int:
29
+ args = parse_args(argv)
30
+ state = {"fired": False, "browser": None}
31
+ try:
32
+ return run(args, state)
33
+ except KeyboardInterrupt:
34
+ print("\nStopped." + ("" if state["fired"] else " No bid was sent."))
35
+ return 130
36
+ except (ValueError, RuntimeError) as error:
37
+ print(f"\nError: {error}", file=sys.stderr)
38
+ return 2
39
+ finally:
40
+ if state["browser"]:
41
+ state["browser"].close()
42
+
43
+
44
+ def parse_args(argv):
45
+ parser = argparse.ArgumentParser(
46
+ prog="ebay-sniper",
47
+ description="Bid your maximum on an eBay auction at the last possible moment.",
48
+ )
49
+ parser.add_argument("url", nargs="?", help="eBay item link (asked if missing)")
50
+ parser.add_argument("--max", help="your maximum bid, e.g. 120 or 120.50 (asked if missing)")
51
+ parser.add_argument(
52
+ "--at",
53
+ metavar="TIME",
54
+ help="bid as if the auction ended at this local time (HH:MM:SS) instead",
55
+ )
56
+ parser.add_argument("--browser", help="path to the browser, if none is found automatically")
57
+ parser.add_argument("--version", action="version", version=version("ebay-sniper"))
58
+ return parser.parse_args(argv)
59
+
60
+
61
+ def run(args, state) -> int:
62
+ url = args.url or input("eBay item link: ")
63
+ site, item_id = page.parse_item_url(url)
64
+ amount = page.parse_amount(args.max or input("Your maximum bid: "))
65
+ url = page.item_url(site, item_id)
66
+
67
+ clock = Clock()
68
+ if clock.sync():
69
+ print(f"Clock checked: off by {clock.offset:+.3f} s, corrected.")
70
+ else:
71
+ print("No time server reachable: using the system clock with a wider margin.")
72
+
73
+ browser = state["browser"] = Browser(args.browser)
74
+ browser.open(url)
75
+ if not browser.signed_in():
76
+ print(f"Sign in to eBay (ebay.{site}) in the browser window. Waiting…")
77
+ browser.wait_for_sign_in(url)
78
+ print("Signed in.")
79
+
80
+ real_end = page.find_end_time(browser.html())
81
+ if args.at:
82
+ end = page.parse_local_time(args.at).timestamp()
83
+ elif real_end:
84
+ end = real_end.timestamp()
85
+ else:
86
+ raise RuntimeError("Couldn't find the end time on the page. Is this an auction?")
87
+ if end - clock.now() < PREPARE / 2:
88
+ raise ValueError(f"Ends at {local(end)}: too soon to schedule a bid.")
89
+ amount_text = page.format_amount(amount, browser.decimal_mark())
90
+
91
+ print("Rehearsing the bid on eBay (nothing is confirmed)…")
92
+ problem = browser.prepare(amount_text)
93
+ if problem or not page.amount_in_text(browser.dialog_text(), amount):
94
+ for alert in browser.alerts():
95
+ print(f"eBay says: {alert}")
96
+ raise RuntimeError(f"eBay won't take this bid: {problem or 'amount not shown'}.")
97
+ browser.open(url) # leave the review step without confirming
98
+
99
+ print(f"\n Item {browser.title()}")
100
+ print(f" Ends {local(end)} (in {duration(end - clock.now())})")
101
+ if args.at and real_end:
102
+ print(f" the auction itself ends {local(real_end.timestamp())}")
103
+ print(f" Maximum {amount_text}, bid once, at the last moment eBay still records it")
104
+ if input("\nPlace this bid? [y/N] ").strip().lower() not in {"y", "yes"}:
105
+ print("Not scheduled.")
106
+ return 1
107
+ keep_awake()
108
+ print("\nScheduled. Nothing else to do: keep this window, the browser and the computer on.")
109
+ print("Ctrl+C cancels.\n")
110
+
111
+ if end - clock.now() > SESSION_CHECK + 30:
112
+ wait_until(clock, end - SESSION_CHECK, "checking your eBay session")
113
+ browser.open(url)
114
+ if not browser.signed_in():
115
+ print("\aYour eBay session expired. Sign in again in the browser window.")
116
+ browser.wait_for_sign_in(url)
117
+
118
+ wait_until(clock, end - PREPARE, "preparing the bid")
119
+ clock.sync()
120
+ browser.open(url)
121
+ if not prepare(browser, amount, amount_text, clock, end):
122
+ print("No bid was sent.")
123
+ return 1
124
+
125
+ lead, latency, processing = plan(browser.reviews, clock)
126
+ fire_at = end - lead
127
+ if latency is None:
128
+ print(f"Ready. Couldn't time eBay's review; bidding {lead:.2f} s before the end.")
129
+ else:
130
+ print(
131
+ f"Ready. eBay needs {1000 * latency:.0f} ms to receive the bid and up to "
132
+ f"{processing:.2f} s to record it: bidding {lead:.2f} s before the end."
133
+ )
134
+
135
+ wait_until(clock, fire_at - 4, "", quiet=True)
136
+ browser.warm()
137
+ wait_until(clock, fire_at - 0.8, "", quiet=True)
138
+ if not browser.aim():
139
+ print("eBay's confirm button disappeared. No bid was sent.")
140
+ return 1
141
+ wait_until(clock, fire_at, "", quiet=True)
142
+ system_click = time.time()
143
+ browser.fire()
144
+ state["fired"] = True
145
+ clicked = system_click + clock.offset
146
+
147
+ outcome = browser.result()
148
+ print(f"Bid sent {clicked - end:+.3f} s from the end.")
149
+ if outcome.get("arrived"):
150
+ print(f"eBay received it {outcome['arrived'] - end:+.3f} s from the end.")
151
+ if outcome.get("answered"):
152
+ print(
153
+ f"eBay answered {outcome['answered'] / 1000 + clock.offset - end:+.3f} s from the end."
154
+ )
155
+ if outcome.get("message"):
156
+ print(f"eBay says: {outcome['message']}")
157
+ if outcome.get("relation"):
158
+ print(f"Status: {outcome['relation']}, current price {outcome.get('price')}.")
159
+ if not outcome:
160
+ print("No answer from eBay was seen. Check the auction on eBay.")
161
+ log(
162
+ item=item_id,
163
+ site=site,
164
+ max=str(amount),
165
+ end=end,
166
+ clicked=clicked,
167
+ lead=lead,
168
+ reviews=browser.reviews,
169
+ clock_offset=clock.offset,
170
+ outcome=outcome,
171
+ )
172
+ return 0
173
+
174
+
175
+ def plan(reviews: list[dict], clock: Clock) -> tuple[float, float | None, float | None]:
176
+ """How long before the end to click, from the timed review requests.
177
+
178
+ Returns (lead, network latency, processing time), all in seconds.
179
+ """
180
+ samples = []
181
+ for review in reviews:
182
+ sent = review["sent"] / 1000 + clock.offset
183
+ answered = review["answered"] / 1000 + clock.offset
184
+ latency = review["arrived"] - sent
185
+ processing = answered - review["arrived"] - latency
186
+ if 0 < latency < 5 and 0 < processing < 10:
187
+ samples.append((latency, processing))
188
+ if not samples:
189
+ return UNMEASURED_LEAD + clock.uncertainty, None, None
190
+ latency = max(s[0] for s in samples)
191
+ processing = max(s[1] for s in samples)
192
+ lead = CLICK_COST + latency + processing + CONFIRM_EXTRA + clock.uncertainty + SAFETY
193
+ return lead, latency, processing + CONFIRM_EXTRA
194
+
195
+
196
+ def prepare(browser, amount, amount_text, clock, end) -> bool:
197
+ """Stop at eBay's confirm button with the amount, or let the user get there."""
198
+ problem = browser.prepare(amount_text)
199
+ if not problem and page.amount_in_text(browser.dialog_text(), amount):
200
+ return True
201
+ for alert in browser.alerts():
202
+ print(f"eBay says: {alert}")
203
+ print(
204
+ f"\a\nCouldn't prepare the bid ({problem or 'amount not shown'}).\n"
205
+ f"If you still want to bid, enter {amount_text} in the browser and go on until eBay's\n"
206
+ "confirm button, without clicking it. The bot will click it on time."
207
+ )
208
+ while clock.now() < end - UNMEASURED_LEAD - 1:
209
+ time.sleep(0.5)
210
+ if browser.armed() and page.amount_in_text(browser.dialog_text(), amount):
211
+ return True
212
+ return False
213
+
214
+
215
+ def wait_until(clock: Clock, moment: float, what: str, quiet: bool = False) -> None:
216
+ """Sleep until a corrected Unix time; the last stretch is a busy wait."""
217
+ target = time.monotonic() + (moment - clock.now())
218
+ while (left := target - time.monotonic()) > 0.02:
219
+ if not quiet and left > 1:
220
+ print(f"\r{duration(left)} until {what} ", end="", flush=True)
221
+ time.sleep(min(left - 0.02, 1))
222
+ while time.monotonic() < target:
223
+ pass
224
+ if not quiet:
225
+ print("\r" + " " * 60 + "\r", end="", flush=True)
226
+
227
+
228
+ def log(**entry) -> None:
229
+ HISTORY.parent.mkdir(parents=True, exist_ok=True)
230
+ with HISTORY.open("a") as file:
231
+ file.write(json.dumps(entry, default=str) + "\n")
232
+
233
+
234
+ def local(moment: float) -> str:
235
+ return datetime.fromtimestamp(moment, UTC).astimezone().strftime("%a %d %b %H:%M:%S")
236
+
237
+
238
+ def duration(seconds: float) -> str:
239
+ seconds = int(seconds)
240
+ days, rest = divmod(seconds, 86400)
241
+ clock = f"{rest // 3600:d}:{rest % 3600 // 60:02d}:{rest % 60:02d}"
242
+ return f"{days}d {clock}" if days else clock
@@ -0,0 +1,63 @@
1
+ """An accurate clock: the system clock corrected against NTP."""
2
+
3
+ import socket
4
+ import struct
5
+ import time
6
+ from dataclasses import dataclass
7
+
8
+ NTP_SERVERS = ("time.apple.com", "time.google.com", "pool.ntp.org")
9
+ NTP_EPOCH = 2208988800 # seconds from 1900 to 1970
10
+
11
+
12
+ @dataclass
13
+ class Clock:
14
+ offset: float = 0.0 # seconds to add to the system clock
15
+ uncertainty: float = 0.5 # seconds; large until synced
16
+ synced: bool = False
17
+
18
+ def now(self) -> float:
19
+ """Corrected Unix time."""
20
+ return time.time() + self.offset
21
+
22
+ def sync(self) -> bool:
23
+ """Measure the system clock against NTP. Keeps the old values on failure."""
24
+ best = None
25
+ for server in NTP_SERVERS:
26
+ for _ in range(4):
27
+ sample = _ntp_sample(server)
28
+ if sample and (best is None or sample[1] < best[1]):
29
+ best = sample
30
+ if best:
31
+ break
32
+ if not best:
33
+ return False
34
+ self.offset, delay = best
35
+ self.uncertainty = delay / 2 + 0.005
36
+ self.synced = True
37
+ return True
38
+
39
+
40
+ def ntp_offset(t1: float, t2: float, t3: float, t4: float) -> tuple[float, float]:
41
+ """Clock offset and round-trip delay from the four NTP timestamps."""
42
+ return ((t2 - t1) + (t3 - t4)) / 2, (t4 - t1) - (t3 - t2)
43
+
44
+
45
+ def _ntp_sample(server: str, timeout: float = 1.0):
46
+ try:
47
+ with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
48
+ sock.settimeout(timeout)
49
+ t1 = time.time()
50
+ sock.sendto(b"\x23" + 47 * b"\0", (server, 123)) # NTPv4 client request
51
+ data, _ = sock.recvfrom(48)
52
+ t4 = time.time()
53
+ except OSError:
54
+ return None
55
+ if len(data) < 48:
56
+ return None
57
+ t2, t3 = (_ntp_time(data[i : i + 8]) for i in (32, 40))
58
+ return ntp_offset(t1, t2, t3, t4)
59
+
60
+
61
+ def _ntp_time(raw: bytes) -> float:
62
+ seconds, fraction = struct.unpack("!II", raw)
63
+ return seconds - NTP_EPOCH + fraction / 2**32
@@ -0,0 +1,93 @@
1
+ """Pure helpers: item URLs, auction end times, bid amounts."""
2
+
3
+ import re
4
+ from datetime import UTC, datetime
5
+ from decimal import Decimal, InvalidOperation
6
+ from urllib.parse import urlsplit
7
+
8
+ ITEM_PATH = re.compile(r"/itm/(?:[^/]+/)?(\d{9,15})/?")
9
+
10
+ # Item pages on every eBay site carry the end time in their inline data, e.g.
11
+ # "endTime":{"value":"2026-12-06T19:38:42.000Z"} or "endDate":"2026-12-06T19:38:42.000Z".
12
+ END_TIME = re.compile(
13
+ r'"(?:endTime|endDate)"\s*:\s*(?:\{\s*"value"\s*:\s*)?"(\d{4}-\d\d-\d\dT[\d:.]+(?:Z|[+-]\d\d:?\d\d))"'
14
+ )
15
+
16
+
17
+ def parse_item_url(url: str) -> tuple[str, str]:
18
+ """Return (site, item id) for an eBay item URL, e.g. ("co.uk", "1234567890")."""
19
+ parts = urlsplit(url.strip())
20
+ host = (parts.hostname or "").removeprefix("www.").removeprefix("m.")
21
+ match = ITEM_PATH.search(parts.path)
22
+ if parts.scheme not in {"http", "https"} or not host.startswith("ebay.") or not match:
23
+ raise ValueError(f"Not an eBay item link: {url}")
24
+ return host.removeprefix("ebay."), match.group(1)
25
+
26
+
27
+ def item_url(site: str, item_id: str) -> str:
28
+ return f"https://www.ebay.{site}/itm/{item_id}"
29
+
30
+
31
+ def find_end_time(html: str) -> datetime | None:
32
+ """The auction end time from an item page, or None."""
33
+ for match in END_TIME.finditer(html):
34
+ try:
35
+ return datetime.fromisoformat(match.group(1)).astimezone(UTC)
36
+ except ValueError:
37
+ continue
38
+ return None
39
+
40
+
41
+ def parse_local_time(text: str, now: datetime | None = None) -> datetime:
42
+ """Parse "HH:MM[:SS]" (today) or "YYYY-MM-DD HH:MM[:SS]" in the local time zone."""
43
+ now = now or datetime.now().astimezone()
44
+ text = text.strip()
45
+ try:
46
+ if len(text) <= 8:
47
+ clock = datetime.strptime(text, "%H:%M:%S" if text.count(":") == 2 else "%H:%M")
48
+ value = now.replace(
49
+ hour=clock.hour, minute=clock.minute, second=clock.second, microsecond=0
50
+ )
51
+ else:
52
+ value = datetime.fromisoformat(text)
53
+ if value.tzinfo is None:
54
+ value = value.replace(tzinfo=now.tzinfo)
55
+ except ValueError:
56
+ raise ValueError(f"Unrecognised time: {text!r}. Use HH:MM:SS.") from None
57
+ return value.astimezone(UTC)
58
+
59
+
60
+ def parse_amount(text: str) -> Decimal:
61
+ try:
62
+ value = Decimal(text.strip().replace(",", "."))
63
+ except InvalidOperation:
64
+ raise ValueError(f"Invalid amount: {text!r}") from None
65
+ if not value.is_finite() or value <= 0 or value != value.quantize(Decimal("0.01")):
66
+ raise ValueError(f"Invalid amount: {text!r}")
67
+ return value.quantize(Decimal("0.01"))
68
+
69
+
70
+ def format_amount(amount: Decimal, decimal_mark: str = ".") -> str:
71
+ """The amount as typed into eBay's bid field: no decimals when whole."""
72
+ if amount == amount.to_integral_value():
73
+ return str(int(amount))
74
+ return f"{amount:.2f}".replace(".", decimal_mark)
75
+
76
+
77
+ def same_amount(shown: str, amount: Decimal) -> bool:
78
+ """True if a number as shown on a page equals the amount, whatever the separators."""
79
+ digits = re.sub(r"[^\d,.]", "", shown or "")
80
+ if not digits:
81
+ return False
82
+ # A final separator followed by one or two digits is the decimal mark.
83
+ match = re.fullmatch(r"(.*?)(?:[.,](\d{1,2}))?", digits)
84
+ whole = re.sub(r"[.,]", "", match.group(1))
85
+ try:
86
+ return Decimal(f"{whole or 0}.{match.group(2) or 0}") == amount
87
+ except InvalidOperation:
88
+ return False
89
+
90
+
91
+ def amount_in_text(text: str, amount: Decimal) -> bool:
92
+ """True if any number in the text equals the amount."""
93
+ return any(same_amount(token, amount) for token in re.findall(r"\d[\d.,]*", text or ""))