mcp-telegram-bridge 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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Antonio Castellon / Castellon.CH
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,199 @@
1
+ Metadata-Version: 2.4
2
+ Name: mcp-telegram-bridge
3
+ Version: 0.1.0
4
+ Summary: Stdio MCP server: controlled Telegram Bot API bridge for any MCP host.
5
+ Author-email: Antonio Castellon <hello@castellon.ch>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/antonio-castellon/mcp-telegram-bridge
8
+ Project-URL: Issues, https://github.com/antonio-castellon/mcp-telegram-bridge/issues
9
+ Keywords: mcp,telegram,bot,stdio,bridge
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Communications :: Chat
18
+ Requires-Python: >=3.11
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: mcp<2,>=1.9.0
22
+ Requires-Dist: httpx<1,>=0.27.0
23
+ Requires-Dist: pydantic<3,>=2.7.0
24
+ Provides-Extra: dev
25
+ Requires-Dist: pytest>=8.0; extra == "dev"
26
+ Requires-Dist: pytest-asyncio>=0.24; extra == "dev"
27
+ Requires-Dist: respx>=0.21; extra == "dev"
28
+ Dynamic: license-file
29
+
30
+ # mcp-telegram-bridge
31
+
32
+ **Controlled Telegram channel bridge for any MCP host.**
33
+
34
+ A small stdio [Model Context Protocol](https://modelcontextprotocol.io/) server that sits between your local agent (Cursor, Claude Desktop, Windsurf, Grok/Cursor agents, and others) and the Telegram Bot API. The agent owns conversation logic; this process handles I/O, always-on outbound scrubbing, and chat allowlist enforcement. Optional strict inbound classification is disabled by default.
35
+
36
+ Built for client-owned deployments — the bridge runs on **your machine**, not on a hosted Grok VM. Games and game-master flows are one demo use case, not the product.
37
+
38
+ Owner context: [Antonio Castellon](https://castellon.ch) / Castellon.CH — Swiss freelance architect. The same bridge shape is useful for SME lab patterns (notify channels, specialist handoff, moderated drafts) alongside email or ERP connectors.
39
+
40
+ ## What / why
41
+
42
+ Agents are good at reasoning and poor at holding a raw Bot API session by themselves. Telegram is a convenient human surface (groups, buttons, mobile). This project gives you a **narrow, reviewable bridge**:
43
+
44
+ - **Client-owned** — stdio MCP on the workstation or CI runner that already hosts your agent.
45
+ - **Host-agnostic** — any MCP client that can launch a local command.
46
+ - **Controlled** — outbound scrubbing and optional `ALLOWED_CHAT_IDS`; optional strict inbound classification for untrusted groups.
47
+ - **Minimal tools** — send, edit markup, answer callbacks, get updates, getMe / getChat. No game engine, no inbox file, no wake-RPC.
48
+
49
+ Pitch pattern for SMEs: start with a Telegram notify or triage channel using the same architecture you would later apply to email or ERP.
50
+
51
+ ## Architecture
52
+
53
+ ```
54
+ ┌─────────────────────────┐
55
+ │ MCP host / agents │ Cursor · Claude Desktop · Windsurf · …
56
+ │ (conversation logic) │
57
+ └───────────┬─────────────┘
58
+ │ MCP (stdio)
59
+ â–¼
60
+ ┌─────────────────────────┐
61
+ │ mcp-telegram-bridge │ tools + safety scrub/classify
62
+ │ (this process) │
63
+ └───────────┬─────────────┘
64
+ │ HTTPS Bot API
65
+ â–¼
66
+ ┌─────────────────────────┐
67
+ │ api.telegram.org │
68
+ └───────────┬─────────────┘
69
+ â–¼
70
+ Telegram chats / groups
71
+ ```
72
+
73
+ The **agent** owns polling offsets, handoffs between specialists, and product policy. This server enforces destination controls and sends scrubbed text; inbound classification is opt-in.
74
+
75
+ ## Install
76
+
77
+ Requirements: Python 3.11+, a Telegram bot token from [@BotFather](https://t.me/BotFather).
78
+
79
+ ```bash
80
+ git clone https://github.com/antonio-castellon/mcp-telegram-bridge.git
81
+ cd mcp-telegram-bridge
82
+ python -m venv .venv
83
+ source .venv/bin/activate # Windows: .venv\Scripts\activate
84
+ pip install -e ".[dev]"
85
+ cp .env.example .env # set TELEGRAM_BOT_TOKEN (never commit .env)
86
+ ```
87
+
88
+ Or without cloning, once published:
89
+
90
+ ```bash
91
+ uvx --from mcp-telegram-bridge mcp-telegram-bridge
92
+ # or: pipx run mcp-telegram-bridge
93
+ ```
94
+
95
+ ### Cursor / Claude Desktop (`mcp.json`)
96
+
97
+ Example for Cursor (User MCP settings) or Claude Desktop (`claude_desktop_config.json`):
98
+
99
+ ```json
100
+ {
101
+ "mcpServers": {
102
+ "telegram-bridge": {
103
+ "command": "uvx",`r`n "args": ["--from", "mcp-telegram-bridge", "mcp-telegram-bridge"],
104
+ "env": {
105
+ "TELEGRAM_BOT_TOKEN": "YOUR_BOT_TOKEN_HERE",
106
+ "ALLOWED_CHAT_IDS": "-1001234567890"
107
+ }
108
+ }
109
+ }
110
+ }
111
+ ```
112
+
113
+ On Windows, point `command` at your venv Python if needed, for example:
114
+
115
+ `C:\\DEV.Personal\\mcp-telegram-bridge\\.venv\\Scripts\\python.exe`
116
+
117
+ Leave `ALLOWED_CHAT_IDS` empty only if you intentionally accept traffic from every chat the bot can see — document that risk for your deployment.
118
+
119
+ Smoke without a host:
120
+
121
+ ```bash
122
+ python -m mcp_telegram_bridge
123
+ # process waits on stdio for MCP JSON-RPC (Ctrl+C to stop)
124
+ ```
125
+
126
+ ## MCP tools
127
+
128
+ | Tool | Purpose |
129
+ |---|---|
130
+ | `telegram_get_me` | Bot identity / connectivity check |
131
+ | `telegram_send_message` | `chat_id`, `text`, optional `parse_mode`, optional `buttons=[{id,label}]` |
132
+ | `telegram_edit_reply_markup` | Strip or replace inline buttons |
133
+ | `telegram_answer_callback` | Ack a `callback_query_id` (optional toast) |
134
+ | `telegram_get_updates` | `offset`, `limit`, `timeout` — returns messages + callback_queries; **agent owns the loop** |
135
+ | `telegram_get_chat` | Chat metadata |
136
+
137
+ Outbound text is always scrubbed. `ALLOWED_CHAT_IDS` restricts destinations when configured. `telegram_get_updates` runs the heuristic secret/NSFW classifier only when `SAFETY_STRICT=1` (or `true`/`yes`/`on`); strict mode is optional and recommended for public or untrusted groups.
138
+
139
+ ## Usage guide
140
+
141
+ ### Collaborative agents in a Telegram group
142
+
143
+ Run one bridge process per bot (or one bot with clear agent roles). Use the group for standup notes, triage queues, and handoff between specialist agents (“ops acknowledges; billing drafts the reply”). Keep humans in the loop for irreversible actions.
144
+
145
+ ### Game master / tabletop facilitator (demo)
146
+
147
+ Send scene text with `buttons=[{id,label}, …]` for player choices; on `callback_query`, answer the callback, optionally `claim`-style first-tap handling in the agent, then edit markup to clear spent choices. This is a **demo** of buttons + agent loop — not a bundled RPG engine.
148
+
149
+ ### Support / ops notify channel
150
+
151
+ Push alerts with ack buttons (`ack`, `snooze`, `escalate`). The agent records who tapped what; Telegram is the pager surface, not the source of truth.
152
+
153
+ ### Community moderation assistant
154
+
155
+ Draft replies and suggest actions. **Humans still own ban / restrict / delete** in Telegram Admin — say so in your agent prompt. The bridge must not be treated as a moderation authority.
156
+
157
+ ### Lab / SME pattern
158
+
159
+ Same shape as an email or ERP connector: narrow tools, allow-listed destinations, scrubbed egress, explicit inbound warnings. Telegram is the demo channel; swap the transport later without rewriting agent policy.
160
+
161
+ ## What this is NOT
162
+
163
+ - Not a hosted bot SaaS or multi-tenant cloud bridge
164
+ - Not Grok-only (works with any stdio MCP host)
165
+ - Not a full RPG / game engine (no dice ruleset, no campaign DB in this repo)
166
+ - Not an unattended admin bot (no ban tools shipped here)
167
+
168
+ ## Relation to sibling demos
169
+
170
+ Optional context only — this project does **not** require them:
171
+
172
+ - [grokgame](https://github.com/antonio-castellon/grokgame) — tabletop / game demo surface
173
+ - [grok2telegram](https://github.com/antonio-castellon/grok2telegram) — earlier bridge experiment whose safety doctrine informed `SAFETY.md` and `safety.py`
174
+
175
+ `mcp-telegram-bridge` is the reusable, host-agnostic extraction: I/O + safety, no game loop and no Grok VM wake logic.
176
+
177
+ ## Safety
178
+
179
+ See **[SAFETY.md](SAFETY.md)** for the threat model, always-on scrubbing and allowlist controls, token handling, and optional strict mode. Do not put secrets in the repository; prefer `ALLOWED_CHAT_IDS` in production-like setups.
180
+
181
+ ## Development
182
+
183
+ ```bash
184
+ pip install -e ".[dev]"
185
+ pytest
186
+ ```
187
+
188
+ Tests mock Telegram HTTP with `respx` / `httpx`; no live token required.
189
+
190
+ ## MCP Registry
191
+
192
+ Canonical name: `io.github.antonio-castellon/mcp-telegram-bridge`
193
+
194
+ <!-- mcp-name: io.github.antonio-castellon/mcp-telegram-bridge -->
195
+
196
+ ## License
197
+
198
+ MIT © Antonio Castellon / Castellon.CH
199
+
@@ -0,0 +1,170 @@
1
+ # mcp-telegram-bridge
2
+
3
+ **Controlled Telegram channel bridge for any MCP host.**
4
+
5
+ A small stdio [Model Context Protocol](https://modelcontextprotocol.io/) server that sits between your local agent (Cursor, Claude Desktop, Windsurf, Grok/Cursor agents, and others) and the Telegram Bot API. The agent owns conversation logic; this process handles I/O, always-on outbound scrubbing, and chat allowlist enforcement. Optional strict inbound classification is disabled by default.
6
+
7
+ Built for client-owned deployments — the bridge runs on **your machine**, not on a hosted Grok VM. Games and game-master flows are one demo use case, not the product.
8
+
9
+ Owner context: [Antonio Castellon](https://castellon.ch) / Castellon.CH — Swiss freelance architect. The same bridge shape is useful for SME lab patterns (notify channels, specialist handoff, moderated drafts) alongside email or ERP connectors.
10
+
11
+ ## What / why
12
+
13
+ Agents are good at reasoning and poor at holding a raw Bot API session by themselves. Telegram is a convenient human surface (groups, buttons, mobile). This project gives you a **narrow, reviewable bridge**:
14
+
15
+ - **Client-owned** — stdio MCP on the workstation or CI runner that already hosts your agent.
16
+ - **Host-agnostic** — any MCP client that can launch a local command.
17
+ - **Controlled** — outbound scrubbing and optional `ALLOWED_CHAT_IDS`; optional strict inbound classification for untrusted groups.
18
+ - **Minimal tools** — send, edit markup, answer callbacks, get updates, getMe / getChat. No game engine, no inbox file, no wake-RPC.
19
+
20
+ Pitch pattern for SMEs: start with a Telegram notify or triage channel using the same architecture you would later apply to email or ERP.
21
+
22
+ ## Architecture
23
+
24
+ ```
25
+ ┌─────────────────────────┐
26
+ │ MCP host / agents │ Cursor · Claude Desktop · Windsurf · …
27
+ │ (conversation logic) │
28
+ └───────────┬─────────────┘
29
+ │ MCP (stdio)
30
+ â–¼
31
+ ┌─────────────────────────┐
32
+ │ mcp-telegram-bridge │ tools + safety scrub/classify
33
+ │ (this process) │
34
+ └───────────┬─────────────┘
35
+ │ HTTPS Bot API
36
+ â–¼
37
+ ┌─────────────────────────┐
38
+ │ api.telegram.org │
39
+ └───────────┬─────────────┘
40
+ â–¼
41
+ Telegram chats / groups
42
+ ```
43
+
44
+ The **agent** owns polling offsets, handoffs between specialists, and product policy. This server enforces destination controls and sends scrubbed text; inbound classification is opt-in.
45
+
46
+ ## Install
47
+
48
+ Requirements: Python 3.11+, a Telegram bot token from [@BotFather](https://t.me/BotFather).
49
+
50
+ ```bash
51
+ git clone https://github.com/antonio-castellon/mcp-telegram-bridge.git
52
+ cd mcp-telegram-bridge
53
+ python -m venv .venv
54
+ source .venv/bin/activate # Windows: .venv\Scripts\activate
55
+ pip install -e ".[dev]"
56
+ cp .env.example .env # set TELEGRAM_BOT_TOKEN (never commit .env)
57
+ ```
58
+
59
+ Or without cloning, once published:
60
+
61
+ ```bash
62
+ uvx --from mcp-telegram-bridge mcp-telegram-bridge
63
+ # or: pipx run mcp-telegram-bridge
64
+ ```
65
+
66
+ ### Cursor / Claude Desktop (`mcp.json`)
67
+
68
+ Example for Cursor (User MCP settings) or Claude Desktop (`claude_desktop_config.json`):
69
+
70
+ ```json
71
+ {
72
+ "mcpServers": {
73
+ "telegram-bridge": {
74
+ "command": "uvx",`r`n "args": ["--from", "mcp-telegram-bridge", "mcp-telegram-bridge"],
75
+ "env": {
76
+ "TELEGRAM_BOT_TOKEN": "YOUR_BOT_TOKEN_HERE",
77
+ "ALLOWED_CHAT_IDS": "-1001234567890"
78
+ }
79
+ }
80
+ }
81
+ }
82
+ ```
83
+
84
+ On Windows, point `command` at your venv Python if needed, for example:
85
+
86
+ `C:\\DEV.Personal\\mcp-telegram-bridge\\.venv\\Scripts\\python.exe`
87
+
88
+ Leave `ALLOWED_CHAT_IDS` empty only if you intentionally accept traffic from every chat the bot can see — document that risk for your deployment.
89
+
90
+ Smoke without a host:
91
+
92
+ ```bash
93
+ python -m mcp_telegram_bridge
94
+ # process waits on stdio for MCP JSON-RPC (Ctrl+C to stop)
95
+ ```
96
+
97
+ ## MCP tools
98
+
99
+ | Tool | Purpose |
100
+ |---|---|
101
+ | `telegram_get_me` | Bot identity / connectivity check |
102
+ | `telegram_send_message` | `chat_id`, `text`, optional `parse_mode`, optional `buttons=[{id,label}]` |
103
+ | `telegram_edit_reply_markup` | Strip or replace inline buttons |
104
+ | `telegram_answer_callback` | Ack a `callback_query_id` (optional toast) |
105
+ | `telegram_get_updates` | `offset`, `limit`, `timeout` — returns messages + callback_queries; **agent owns the loop** |
106
+ | `telegram_get_chat` | Chat metadata |
107
+
108
+ Outbound text is always scrubbed. `ALLOWED_CHAT_IDS` restricts destinations when configured. `telegram_get_updates` runs the heuristic secret/NSFW classifier only when `SAFETY_STRICT=1` (or `true`/`yes`/`on`); strict mode is optional and recommended for public or untrusted groups.
109
+
110
+ ## Usage guide
111
+
112
+ ### Collaborative agents in a Telegram group
113
+
114
+ Run one bridge process per bot (or one bot with clear agent roles). Use the group for standup notes, triage queues, and handoff between specialist agents (“ops acknowledges; billing drafts the reply”). Keep humans in the loop for irreversible actions.
115
+
116
+ ### Game master / tabletop facilitator (demo)
117
+
118
+ Send scene text with `buttons=[{id,label}, …]` for player choices; on `callback_query`, answer the callback, optionally `claim`-style first-tap handling in the agent, then edit markup to clear spent choices. This is a **demo** of buttons + agent loop — not a bundled RPG engine.
119
+
120
+ ### Support / ops notify channel
121
+
122
+ Push alerts with ack buttons (`ack`, `snooze`, `escalate`). The agent records who tapped what; Telegram is the pager surface, not the source of truth.
123
+
124
+ ### Community moderation assistant
125
+
126
+ Draft replies and suggest actions. **Humans still own ban / restrict / delete** in Telegram Admin — say so in your agent prompt. The bridge must not be treated as a moderation authority.
127
+
128
+ ### Lab / SME pattern
129
+
130
+ Same shape as an email or ERP connector: narrow tools, allow-listed destinations, scrubbed egress, explicit inbound warnings. Telegram is the demo channel; swap the transport later without rewriting agent policy.
131
+
132
+ ## What this is NOT
133
+
134
+ - Not a hosted bot SaaS or multi-tenant cloud bridge
135
+ - Not Grok-only (works with any stdio MCP host)
136
+ - Not a full RPG / game engine (no dice ruleset, no campaign DB in this repo)
137
+ - Not an unattended admin bot (no ban tools shipped here)
138
+
139
+ ## Relation to sibling demos
140
+
141
+ Optional context only — this project does **not** require them:
142
+
143
+ - [grokgame](https://github.com/antonio-castellon/grokgame) — tabletop / game demo surface
144
+ - [grok2telegram](https://github.com/antonio-castellon/grok2telegram) — earlier bridge experiment whose safety doctrine informed `SAFETY.md` and `safety.py`
145
+
146
+ `mcp-telegram-bridge` is the reusable, host-agnostic extraction: I/O + safety, no game loop and no Grok VM wake logic.
147
+
148
+ ## Safety
149
+
150
+ See **[SAFETY.md](SAFETY.md)** for the threat model, always-on scrubbing and allowlist controls, token handling, and optional strict mode. Do not put secrets in the repository; prefer `ALLOWED_CHAT_IDS` in production-like setups.
151
+
152
+ ## Development
153
+
154
+ ```bash
155
+ pip install -e ".[dev]"
156
+ pytest
157
+ ```
158
+
159
+ Tests mock Telegram HTTP with `respx` / `httpx`; no live token required.
160
+
161
+ ## MCP Registry
162
+
163
+ Canonical name: `io.github.antonio-castellon/mcp-telegram-bridge`
164
+
165
+ <!-- mcp-name: io.github.antonio-castellon/mcp-telegram-bridge -->
166
+
167
+ ## License
168
+
169
+ MIT © Antonio Castellon / Castellon.CH
170
+
@@ -0,0 +1,52 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "mcp-telegram-bridge"
7
+ version = "0.1.0"
8
+ description = "Stdio MCP server: controlled Telegram Bot API bridge for any MCP host."
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ requires-python = ">=3.11"
12
+ authors = [
13
+ { name = "Antonio Castellon", email = "hello@castellon.ch" },
14
+ ]
15
+ keywords = ["mcp", "telegram", "bot", "stdio", "bridge"]
16
+ classifiers = [
17
+ "Development Status :: 3 - Alpha",
18
+ "Intended Audience :: Developers",
19
+ "License :: OSI Approved :: MIT License",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Programming Language :: Python :: 3.13",
24
+ "Topic :: Communications :: Chat",
25
+ ]
26
+ dependencies = [
27
+ "mcp>=1.9.0,<2",
28
+ "httpx>=0.27.0,<1",
29
+ "pydantic>=2.7.0,<3",
30
+ ]
31
+
32
+ [project.optional-dependencies]
33
+ dev = [
34
+ "pytest>=8.0",
35
+ "pytest-asyncio>=0.24",
36
+ "respx>=0.21",
37
+ ]
38
+
39
+ [project.scripts]
40
+ mcp-telegram-bridge = "mcp_telegram_bridge.__main__:main"
41
+
42
+ [project.urls]
43
+ Homepage = "https://github.com/antonio-castellon/mcp-telegram-bridge"
44
+ Issues = "https://github.com/antonio-castellon/mcp-telegram-bridge/issues"
45
+
46
+ [tool.setuptools.packages.find]
47
+ where = ["src"]
48
+
49
+ [tool.pytest.ini_options]
50
+ asyncio_mode = "auto"
51
+ testpaths = ["tests"]
52
+ pythonpath = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,5 @@
1
+ """mcp-telegram-bridge — stdio MCP server for Telegram Bot API I/O + safety."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ __all__ = ["__version__"]
@@ -0,0 +1,13 @@
1
+ """python -m mcp_telegram_bridge — start the stdio MCP server."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ def main() -> None:
7
+ from .server import main as run
8
+
9
+ run()
10
+
11
+
12
+ if __name__ == "__main__":
13
+ main()
@@ -0,0 +1,192 @@
1
+ """Inline keyboard helpers and claim_message_tap (first tap wins)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import secrets
7
+ import time
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ # Telegram Bot API: callback_data max 1–64 bytes.
12
+ CALLBACK_DATA_MAX = 64
13
+ _MAP_NAME = "callback_map.json"
14
+ _MAP_MAX_ENTRIES = 2000
15
+ _CLAIM_NAME = "callback_claimed.json"
16
+ _CLAIM_MAX = 500
17
+
18
+
19
+ def normalize_buttons(buttons: list[dict[str, Any]] | None) -> list[dict[str, str]]:
20
+ """Normalize [{id, label}] (label may also be ``text``)."""
21
+ if not buttons:
22
+ return []
23
+ out: list[dict[str, str]] = []
24
+ for i, row in enumerate(buttons):
25
+ if not isinstance(row, dict):
26
+ raise ValueError(f"buttons[{i}] must be an object")
27
+ bid = str(row.get("id") or "").strip()
28
+ label = str(row.get("label") or row.get("text") or "").strip()
29
+ if not bid or not label:
30
+ raise ValueError(f"buttons[{i}] needs id and label")
31
+ out.append({"id": bid, "label": label})
32
+ return out
33
+
34
+
35
+ def parse_buttons_arg(raw: str) -> list[dict[str, str]]:
36
+ """Parse ``id:Label|id:Label`` into ``[{id, label}, ...]``."""
37
+ text = (raw or "").strip()
38
+ if not text:
39
+ return []
40
+ out: list[dict[str, str]] = []
41
+ for part in text.split("|"):
42
+ part = part.strip()
43
+ if not part:
44
+ continue
45
+ if ":" not in part:
46
+ raise ValueError(f"button needs id:Label, got {part!r}")
47
+ bid, label = part.split(":", 1)
48
+ bid = bid.strip()
49
+ label = label.strip()
50
+ if not bid or not label:
51
+ raise ValueError(f"empty id or label in {part!r}")
52
+ out.append({"id": bid, "label": label})
53
+ return out
54
+
55
+
56
+ def _map_path(data_dir: Path) -> Path:
57
+ data_dir.mkdir(parents=True, exist_ok=True)
58
+ return data_dir / _MAP_NAME
59
+
60
+
61
+ def _load_map(data_dir: Path) -> dict[str, Any]:
62
+ p = _map_path(data_dir)
63
+ if not p.exists():
64
+ return {}
65
+ try:
66
+ data = json.loads(p.read_text(encoding="utf-8"))
67
+ return data if isinstance(data, dict) else {}
68
+ except Exception:
69
+ return {}
70
+
71
+
72
+ def _save_map(data_dir: Path, mapping: dict[str, Any]) -> None:
73
+ if len(mapping) > _MAP_MAX_ENTRIES:
74
+ items = sorted(
75
+ mapping.items(),
76
+ key=lambda kv: float((kv[1] or {}).get("ts") or 0),
77
+ )
78
+ mapping = dict(items[-_MAP_MAX_ENTRIES:])
79
+ _map_path(data_dir).write_text(
80
+ json.dumps(mapping, ensure_ascii=False, indent=2),
81
+ encoding="utf-8",
82
+ )
83
+
84
+
85
+ def _callback_data_for(button_id: str, chat_id: int, data_dir: Path | None) -> str:
86
+ """Return callback_data ≤64 bytes; map long ids via short token."""
87
+ raw = (button_id or "").strip()
88
+ encoded = raw.encode("utf-8")
89
+ if 1 <= len(encoded) <= CALLBACK_DATA_MAX and "\n" not in raw:
90
+ return raw
91
+ if data_dir is None:
92
+ raise ValueError(
93
+ f"button id exceeds {CALLBACK_DATA_MAX} bytes; configure data_dir for mapping"
94
+ )
95
+ token = secrets.token_hex(4)
96
+ key = f"{chat_id}:{token}"
97
+ mapping = _load_map(data_dir)
98
+ mapping[key] = {"id": raw, "ts": time.time()}
99
+ _save_map(data_dir, mapping)
100
+ cb = f"t:{token}"
101
+ assert len(cb.encode("utf-8")) <= CALLBACK_DATA_MAX
102
+ return cb
103
+
104
+
105
+ def resolve_callback_data(data_dir: Path, chat_id: int, callback_data: str) -> str:
106
+ """Map callback_data back to the agent-facing button id."""
107
+ raw = (callback_data or "").strip()
108
+ if raw.startswith("t:") and len(raw) > 2:
109
+ token = raw[2:]
110
+ key = f"{chat_id}:{token}"
111
+ mapping = _load_map(data_dir)
112
+ row = mapping.get(key)
113
+ if isinstance(row, dict) and row.get("id"):
114
+ return str(row["id"])
115
+ return raw
116
+
117
+
118
+ def build_inline_keyboard(
119
+ buttons: list[dict[str, str]],
120
+ *,
121
+ chat_id: int,
122
+ data_dir: Path | None = None,
123
+ row_width: int = 2,
124
+ ) -> dict[str, Any]:
125
+ """Build Telegram InlineKeyboardMarkup from [{id, label}, ...]."""
126
+ if not buttons:
127
+ raise ValueError("buttons list is empty")
128
+ rows: list[list[dict[str, str]]] = []
129
+ row: list[dict[str, str]] = []
130
+ for btn in buttons:
131
+ bid = str(btn.get("id") or "").strip()
132
+ label = str(btn.get("label") or btn.get("text") or "").strip()
133
+ if not bid or not label:
134
+ raise ValueError(f"invalid button: {btn!r}")
135
+ text = label[:64]
136
+ cb = _callback_data_for(bid, chat_id, data_dir)
137
+ row.append({"text": text, "callback_data": cb})
138
+ if len(row) >= max(1, row_width):
139
+ rows.append(row)
140
+ row = []
141
+ if row:
142
+ rows.append(row)
143
+ return {"inline_keyboard": rows}
144
+
145
+
146
+ def _claim_path(data_dir: Path) -> Path:
147
+ data_dir.mkdir(parents=True, exist_ok=True)
148
+ return data_dir / _CLAIM_NAME
149
+
150
+
151
+ def claim_message_tap(
152
+ data_dir: Path,
153
+ chat_id: int,
154
+ message_id: int,
155
+ *,
156
+ verb: str,
157
+ uid: int,
158
+ ) -> bool:
159
+ """First tap on a message wins. Return True if claimed; False if duplicate."""
160
+ path = _claim_path(data_dir)
161
+ try:
162
+ data = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
163
+ except Exception:
164
+ data = {}
165
+ if not isinstance(data, dict):
166
+ data = {}
167
+ key = f"{int(chat_id)}:{int(message_id)}"
168
+ if key in data:
169
+ return False
170
+ data[key] = {"verb": verb, "uid": int(uid), "ts": time.time()}
171
+ if len(data) > _CLAIM_MAX:
172
+ items = sorted(data.items(), key=lambda kv: float((kv[1] or {}).get("ts") or 0))
173
+ data = dict(items[-_CLAIM_MAX:])
174
+ path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
175
+ return True
176
+
177
+
178
+ def label_from_callback_message(msg: dict[str, Any], callback_data: str) -> str | None:
179
+ """Best-effort label from the tapped message's inline keyboard."""
180
+ raw = (callback_data or "").strip()
181
+ markup = (msg or {}).get("reply_markup") or {}
182
+ rows = markup.get("inline_keyboard") or []
183
+ for row in rows:
184
+ if not isinstance(row, list):
185
+ continue
186
+ for btn in row:
187
+ if not isinstance(btn, dict):
188
+ continue
189
+ if str(btn.get("callback_data") or "") == raw:
190
+ text = str(btn.get("text") or "").strip()
191
+ return text or None
192
+ return None