better-tg-cli 0.39.6 → 0.40.0-rc.2

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,136 @@
1
+ # Setup, MCP server and troubleshooting
2
+
3
+ - [Install](#install)
4
+ - [How each client gets it](#how-each-client-gets-it)
5
+ - [Log in](#log-in)
6
+ - [Profiles, secrets and cloud computers](#profiles-secrets-and-cloud-computers)
7
+ - [MCP server](#mcp-server)
8
+ - [Exit codes and errors](#exit-codes-and-errors)
9
+ - [Troubleshooting](#troubleshooting)
10
+
11
+ ## Install
12
+
13
+ Before the first shell use, `telegram help-all -g read` checks that the right program is installed
14
+ (it is local and needs no login). If `telegram` is missing, or has no `help-all`, another program
15
+ owns that name. Ask the user before installing anything, then one of:
16
+
17
+ ```bash
18
+ brew install thevilfer/tap/better-tg-cli # macOS, Linux
19
+ npm install -g better-tg-cli # Node 20 or newer, any OS
20
+ curl -q --proto '=https' --tlsv1.2 -fsSL https://github.com/TheVilfer/better-tg-cli/releases/latest/download/install.sh | sh # no Homebrew, Node or sudo: ~/.local/bin
21
+ scoop bucket add thevilfer https://github.com/TheVilfer/scoop-bucket && scoop install better-tg-cli # Windows
22
+ ```
23
+
24
+ Never install `@skillhq/telegram`: it is an old build, and bot replies come back as `(no text)`.
25
+ `telegram update` upgrades an install (`update --check` only reports). `telegram skill
26
+ install|uninstall [-a <agent>]` copies this skill into coding agents or removes it, and `telegram
27
+ skill status [--json]` shows where it is; run them only when the user asks.
28
+
29
+ ## How each client gets it
30
+
31
+ | Client | What it installs | How the agent reaches Telegram |
32
+ |---|---|---|
33
+ | Claude Code (marketplace plugin) | the skill | the installed `telegram` CLI in the shell |
34
+ | Codex, Cursor (plugin) | the skill and an MCP server | MCP tools (`npx better-tg-cli@<version> mcp`, pinned) |
35
+ | Hermes Agent (plugin catalog) | the skill and an MCP server | MCP tools |
36
+ | Claude Desktop (`.mcpb`), other MCP clients | an MCP server | MCP tools |
37
+ | any agent with a shell | the skill (`telegram skill install`, skills.sh) | the CLI |
38
+
39
+ Use whatever tools the client exposes: MCP tools when they are there, the CLI otherwise.
40
+
41
+ ## Log in
42
+
43
+ `Not configured`, `Not authenticated`, `session_expired` or exit 5 mean the user has to log in.
44
+
45
+ - **Shell:** run `telegram onboard --json` (in the background if your tool times out before
46
+ ~15 minutes). It opens a page on 127.0.0.1 where the user gets a login key (or enters their own
47
+ API keys), scans a QR code, types the 2FA password and picks the write mode. Relay the `url`
48
+ event if no browser opened. Events: `url`, `waiting_invite`, `waiting_scan`, `need_password`,
49
+ `logged_in`, `waiting_mode`, `mode`, then `done` (exit 0); `timeout` (exit 1). An `error` before
50
+ `url` (the stored login could not be checked: locked store, no network) ends the process with
51
+ exit 1: tell the user the message. An `error` after `url`, while the process still runs, means
52
+ that attempt failed and the page offers a retry, so keep waiting. A stored session that Telegram no
53
+ longer accepts gives `session_expired` and a new login on the same page. `already_logged_in`
54
+ exits 0 without a `done`: check with `telegram whoami`.
55
+ - **MCP:** call `telegram_setup` and give the user the link. Nothing reports when they finish: wait
56
+ for their message, then check `telegram_read {"args":["whoami"]}` and `["write-access"]`. The page
57
+ opens on the machine that runs the MCP server.
58
+ - **SSH or no browser:** ask the user to run `telegram auth --qr` (own API keys) or
59
+ `telegram auth --login-key --qr` in their own terminal. It is interactive; never run it for them.
60
+
61
+ Never run `telegram auth` yourself, never fill in the page, and never ask for a login code, 2FA
62
+ password, login key or api_hash in the chat. `telegram check` connects and checks the session;
63
+ `whoami` shows the account.
64
+
65
+ ## Profiles, secrets and cloud computers
66
+
67
+ - `TG_PROFILE=<name>` gives a separate account: its own folder (`~/.config/tg-<name>`, on Windows
68
+ `%APPDATA%\tg-<name>`) and its own secrets. Log in and set the mode on the profile and machine
69
+ the agent actually uses.
70
+ - The session and the write mode normally live in the OS secret store (macOS Keychain, Linux
71
+ Secret Service, Windows DPAPI, or 1Password). If the store is unavailable or a save fails, the
72
+ session can end up in `config.json5`; `telegram check --json` → `sessionStore` says where it is
73
+ (no need to open the config, which holds secrets). A locked store gives an error with one step
74
+ for this OS (unlock the keychain, …), then `telegram check`.
75
+ - A computer without a secret store (cloud agent computers, headless Linux) keeps the mode in a
76
+ 0600 file in the profile, marked "unprotected". Never install a keyring or `libsecret-tools`
77
+ there. The mode is still the user's to set; `on` opens a local page for them to choose.
78
+
79
+ ## MCP server
80
+
81
+ `telegram mcp` (stdio) or `telegram mcp --http` (`POST /mcp` on 127.0.0.1:8787, `Authorization:
82
+ Bearer <token>`) serves four tools. `telegram mcp --token` prints a live bearer token: the user runs
83
+ it in their own terminal and pastes it into the MCP client; never run it or handle the token
84
+ yourself.
85
+
86
+ | Tool | Use |
87
+ |---|---|
88
+ | `telegram_help {"grep":"thread"}` | find a command or flag |
89
+ | `telegram_read {"args":["inbox","-n","10"]}` | read commands, `schema`, any `--help`, `write-access` status |
90
+ | `telegram_write {"args":["send","-1004001","-"],"stdin":"…","approval"?}` | everything that changes the account or saves files (`download`, `sync`, `avatar`) |
91
+ | `telegram_setup {}` | the login or write-mode page, for the user |
92
+
93
+ - A server started with `--read-only` drops `telegram_write`: tell the user writes are off on this
94
+ server, and don't look for a way around it.
95
+ - Never over MCP: `auth`, `onboard`, `logout`, `transfer-owner`, `update`, `skill`, and changing
96
+ `write-access`. A misrouted call says which tool to use (`"send" changes something; use
97
+ telegram_write`).
98
+ - The result text is the CLI's stdout; `structuredContent` has `{exitCode, stderr?}`, so a failure
99
+ keeps its exit code. A write waiting for approval is not an error: `{status:"approval_required", …}`
100
+ ([writing.md](writing.md#approval-in-mode-ask)).
101
+ - Calls run one at a time, time out after 120 s and are capped at 100 KB of output. `watch` needs
102
+ `-t` or `-n`.
103
+
104
+ ## Exit codes and errors
105
+
106
+ | Code | Meaning | What to do |
107
+ |---|---|---|
108
+ | 0 | ok | |
109
+ | 1 | runtime: Telegram refused, network, chat or message not found, rate limit | read `error.code` |
110
+ | 2 | usage: unknown option, bad value, ambiguous chat name | fix the arguments or pick a candidate |
111
+ | 3 | approval needed (mode `ask`) | [writing.md](writing.md#approval-in-mode-ask) |
112
+ | 4 | write access is off | [writing.md](writing.md#write-modes) |
113
+ | 5 | not logged in, or the session ended | [log in](#log-in) |
114
+
115
+ With `--json` stdout holds exactly one JSON value, the result or
116
+ `{"error":{"code","message","hint"?,"command"?,"candidates"?,"retryAfterSeconds"?}}`. Stable codes include
117
+ `chat_not_found`, `ambiguous_chat`, `chat_not_exact`, `ambiguous_or_unverified`, `not_a_forum`,
118
+ `invalid_argument`, `usage`, `write_disabled`, `not_configured`, `session_expired`, `network`,
119
+ `flood_wait`, `telegram_rpc` and `refused`. Exit 3 has its own line, `{"error":"approval_required",…}`.
120
+ Exceptions: `onboard --json` and `watch --json` print JSON Lines (one event or message per line),
121
+ and `avatar --json` for a chat with no profile photo prints a plain text line. `telegram api`
122
+ takes no `--json` (exit 2, `usage`); see [api.md](api.md#errors).
123
+ A bad number or value exits 2 before anything is sent or approved.
124
+
125
+ ## Troubleshooting
126
+
127
+ - **`FLOOD_WAIT` / `flood_wait`:** the CLI waits out limits of up to 60 s by itself (stderr says
128
+ so). A longer one fails with the wait in `retryAfterSeconds`: tell the user and stop. Retrying in
129
+ a loop extends the ban.
130
+ - **`network`, `NetSocket was closed`, connect timeouts:** the CLI retries over WebSocket
131
+ (`wss://*.web.telegram.org`) by itself and remembers it for the profile; `TG_TRANSPORT=wss|tcp`
132
+ forces one. A network error is not a reason to log in again.
133
+ - **`session_expired` (exit 5)** at connect or on any call: Telegram ended the session; log in again.
134
+ - **`CHANNELS_TOO_MUCH` on `join`:** the account is in too many channels; the user leaves some.
135
+ - **`Could not find the input entity`:** the ID is not among the user's dialogs; use `@username`.
136
+ - **Bot replies show `(no text)`:** an old build (`@skillhq/telegram`) is installed; see Install.
@@ -0,0 +1,195 @@
1
+ # Writing: approvals, sending, buttons, chat admin
2
+
3
+ Every write changes the user's account in front of other people, and most can't be undone. The
4
+ rules in SKILL.md come first; this file has the details. Examples are real output of the mock
5
+ account (`TG_MOCK`, approvals rehearsed with `TG_MOCK_ASK=1`), in UTC.
6
+
7
+ - [Write modes](#write-modes)
8
+ - [Approval in mode ask](#approval-in-mode-ask)
9
+ - [Don't get the account banned](#dont-get-the-account-banned)
10
+ - [Sending text](#sending-text)
11
+ - [Bot buttons](#bot-buttons)
12
+ - [Other writes](#other-writes)
13
+ - [What the user does in the app](#what-the-user-does-in-the-app)
14
+ - [Results](#results)
15
+ - [Audit log](#audit-log)
16
+
17
+ ## Write modes
18
+
19
+ `telegram write-access` (over MCP `telegram_read {"args":["write-access","--json"]}`) shows the
20
+ mode; its JSON has `writeMode` and `writes` (`without-confirmation`, `with-approval` or `off`).
21
+ `telegram check` puts the same on its own line, e.g. `Writes: ON — messages are sent without
22
+ confirmation`.
23
+
24
+ | Mode | A write… | Next step for you |
25
+ |---|---|---|
26
+ | `read-only` | stops with exit 4 (`write_disabled`) | stop and tell the user writes are off. Only the user changes the mode: on the `telegram_setup` page or with `telegram write-access ask` in their own terminal. Never change it on your own or as a step toward another request. The one exception: the user tells you in their own words to switch to `ask` (a cloud computer where they have no terminal); then run `telegram write-access ask`, never `on` |
27
+ | `ask` | stops with exit 3 and an approval code | show the action, wait for a yes, repeat with the code |
28
+ | `on` | runs at once | agree on the exact action with the user before the first call |
29
+
30
+ The status query itself exits 0 in every mode; exit 4 comes from a write. `on` needs the user's own
31
+ confirmation in a terminal or a system dialog. `write-access ask --for 2h` and `on --for 30m` fall
32
+ back to read-only afterwards. A `--read-only` MCP server is a hard stop: `telegram_setup` there
33
+ offers no mode, and writes stay off. Without a secret store (cloud agent
34
+ computers, headless Linux) the mode lives in a 0600 file in the profile, labelled "unprotected";
35
+ never install a keyring there.
36
+
37
+ ## Approval in mode ask
38
+
39
+ 1. Run the write once, without a code. The CLI looks the recipient up and stops:
40
+
41
+ ```
42
+ $ printf '%s' 'See you at 7' | telegram reply 1001 3 -
43
+ Approval needed: write mode is "ask", so the user approves each write.
44
+ Show the user this action word for word and ask for an explicit yes:
45
+ Reply to a message
46
+ To: Alice Example (user, @alice_example, id 1001)
47
+ msg-id: #3
48
+ Text (12 characters):
49
+ | See you at 7
50
+ Command: telegram reply 1001 3 -
51
+ After a yes, run the same command again with the same text on stdin with TG_APPROVE=38HR4Y in its environment:
52
+ TG_APPROVE=38HR4Y telegram reply 1001 3 -
53
+ (PowerShell: $env:TG_APPROVE='38HR4Y'; telegram reply 1001 3 -; Remove-Item Env:TG_APPROVE)
54
+ The code works once, for this exact action and text, for 10 minutes; flag order and --json may differ. Never approve on the user's behalf.
55
+ [exit 3]
56
+ ```
57
+
58
+ 2. Show the user that action word for word: what happens, the recipient, the full text.
59
+ 3. Only after a separate, explicit yes to that action, repeat the same arguments and the same stdin
60
+ with the code. A "no", a changed request or silence ends the attempt.
61
+
62
+ ```
63
+ $ printf '%s' 'See you at 7' | TG_APPROVE=38HR4Y telegram reply 1001 3 - --json
64
+ {"ok":true,"action":"reply","chatId":"1001","chatTitle":"Alice","messageId":6,"id":6,"replyToMsgId":3,"date":"2026-11-20T01:12:49.000Z","text":"See you at 7"}
65
+ ```
66
+
67
+ (`--json` was added on the retry; flag order and `--json` may differ, nothing else.) With `--json`
68
+ the stop itself is one line on stdout, here for another message:
69
+ `{"error":"approval_required","code":"93N87X","action":{"description":…,"recipients":[…],"argv":["send","1001","-","--json"],"stdin":"Running late"},"expiresInMinutes":10,"retry":{"argv":["telegram","send","1001","-","--json"],"env":{"TG_APPROVE":"93N87X"}}}`.
70
+
71
+ - **Over MCP**, either the client shows the user a dialog (they answer it; you never pass a code,
72
+ and a code you pass is refused), or the result is not an error but `structuredContent`
73
+ `{status:"approval_required", code, action, retry:{tool, arguments}}`. After the yes, make exactly
74
+ the `retry.arguments` call:
75
+
76
+ ```
77
+ telegram_write {"args":["send","-1004001","-"],"stdin":"See you at 7"}
78
+ → structuredContent: {"status":"approval_required","code":"H5SCNT","action":{"description":" Send a message\n To: Team (supergroup, @mock_team, id -1004001)\n Text (12 characters):\n | See you at 7\n Command: telegram send -1004001 -",…},"expiresInMinutes":10,"retry":{"tool":"telegram_write","arguments":{"args":["send","-1004001","-"],"stdin":"See you at 7","approval":"H5SCNT"}}}
79
+ ```
80
+
81
+ If the call held a login code or a gift link, `retry` is `{tool, sameArgumentsAsThisCall: true,
82
+ arguments: {approval}, note}`: the secret is not echoed back. Such an action is for the user to
83
+ do (in the Telegram app or their own terminal): tell them, and don't follow the `note` that says
84
+ to call again. Never ask for, reconstruct or re-send the code or link. The check also fires on
85
+ ordinary text such as `promo code: SUMMER` that the user asked you to send; then, after their
86
+ yes, repeat your own call with the same args and stdin plus `"approval":"<code>"`.
87
+ - A code works once, for 10 minutes, for this action: command, recipient (by ID), options, the exact
88
+ stdin text and files. A code that doesn't hold comes back with a new one and `rejected.reason`
89
+ (`unknown_or_expired`, `different_action`, `another_account`, `not_genuine`): show the new action
90
+ and ask again.
91
+ - A recipient that can't be resolved, a file that can't be read, and for `delete` and `click` a
92
+ missing message or button get no code: `Not sent, nothing to approve: …` with the real error.
93
+ `edit` and `reply` don't check the message first: they may ask for approval for a message ID that
94
+ turns out not to exist.
95
+
96
+ ## Don't get the account banned
97
+
98
+ Telegram limits and freezes accounts that behave like bots.
99
+
100
+ - Never send the same or similar text to many chats.
101
+ - Never join, invite or add people in bulk.
102
+ - Ask before anything that touches more than a few chats or messages.
103
+ - On `FLOOD_WAIT` (exit 1, `retryAfterSeconds` in JSON) tell the user how long and stop. The CLI
104
+ already waits out short limits (up to 60 s) by itself; retrying in a loop extends the ban.
105
+
106
+ ## Sending text
107
+
108
+ - Writes need an ID, @username or exact title; a near match is refused with candidates:
109
+
110
+ ```
111
+ $ telegram send Tea hi --json
112
+ {"error":{"code":"chat_not_exact","message":"Not sent, nothing to approve: No chat is titled exactly \"Tea\"; writes need an ID, @username or the exact title","hint":"Run the command again with one of these IDs.","candidates":[{"id":"-1004001","title":"Team","type":"supergroup"},{"id":"-1004002","title":"Team Design","type":"supergroup"}]}}
113
+ [exit 2]
114
+ ```
115
+
116
+ - Pass `-` as the text and put the text on stdin (`send`, `reply`, `edit`, `send-file -c -`), or
117
+ `stdin` over MCP: `printf '%s' "$text" | telegram send <chat> -`. No quoting bugs, and the user
118
+ approves exactly that text.
119
+ - Without `--html` or `--markdown` the text goes out exactly as typed (`__init__.py` stays as is).
120
+ - `--html` is the reliable formatting (`<b>`, `<i>`, `<a href>`, `<code>`, `<pre>`). `--markdown` is
121
+ GramJS Markdown: bold, italic and code, but `[text](url)` links do not work.
122
+ - `send` takes `--reply-to <id>`, `--topic <id>`, `--silent` and `--schedule 2h` (or an ISO date).
123
+ A bad number or value exits 2 before anything is sent or approved.
124
+ - `send-file <chat> <path> -c <caption>` sends a file; over MCP the path is on the server's machine.
125
+
126
+ ## Bot buttons
127
+
128
+ `click <chat> <msgId> <label|index>` presses a button (a write). Press by label: indices are
129
+ counted on the current menu, which changes after each press. `click` prints the bot's answer and
130
+ the new menu, so you don't need another `read`:
131
+
132
+ ```
133
+ $ telegram click @demo_bot 2 Catalog
134
+ ✓ Pressed [1] Catalog (callback)
135
+
136
+ ↻ Message #2 updated by the bot:
137
+ Catalog: 3 items
138
+ ⌨ inline keyboard:
139
+ [1] « Back — callback
140
+ ```
141
+
142
+ | Button type | `click` does |
143
+ |---|---|
144
+ | callback | sends the callback, shows the answer and the updated message |
145
+ | reply-keyboard text | sends the label as a message |
146
+ | url, url_auth, webview | prints the URL, never opens it |
147
+ | game | asks the bot for the game (`messages.GetBotCallbackAnswer` with `game:true`); the answer may hold its URL. Use `buttons` to look without pressing |
148
+ | switch-inline | prints the query, does not send it |
149
+ | copy | prints the text |
150
+ | request phone, geo, poll or peer; buy | refused on purpose |
151
+
152
+ A button that asks for the 2FA password is pressed by the user in the Telegram app: stop and tell
153
+ them. Never ask for the password and never pass it on a command line.
154
+
155
+ ## Other writes
156
+
157
+ - `edit <chat> <id> -` replaces the text. `delete <chat> <id,id>` deletes **for everyone** by
158
+ default; `--just-me` only on the user's side (private chats and basic groups).
159
+ - `react <chat> <id> 👍` (`me` is Saved Messages). `pin` is silent unless `--notify`;
160
+ `unpin <chat>` with no ID unpins **every** pinned message.
161
+ - `forward <from> <ids> <to>` (`--drop-author` hides the source).
162
+ - `poll <chat> "Q" A B C` (`--multiple`, `--quiz --correct N`) and `vote <chat> <id> 2` count
163
+ options from 1.
164
+ - `mark-read`, `mark-unread`, `mute -d 8h`, `pin-chat`, `archive`: the user's own view of a chat.
165
+ - `delete-dialog <chat>` clears a private or basic-group history (`--revoke` also for the other
166
+ side) or leaves a supergroup or channel.
167
+ - Admin: `edit-permissions <chat> [user] --mute|--ban|--lift|--deny send,media [--until 1d]`,
168
+ `promote`, `kick`, `topic create|edit|close|reopen|pin|unpin`. Check rights first with
169
+ `permissions`.
170
+
171
+ ## What the user does in the app
172
+
173
+ Some actions stay with the user, in the Telegram app or their own terminal:
174
+
175
+ - buttons and actions that ask for the 2FA password;
176
+ - transferring ownership of a group or channel (irreversible);
177
+ - logging in, changing the 2FA password or phone, ending sessions, deleting the account, paying.
178
+ The raw API refuses these too ([api.md](api.md)).
179
+
180
+ ## Results
181
+
182
+ | Command | `--json` result |
183
+ |---|---|
184
+ | `send`, `reply`, `send-file`, `edit`, `delete`, `react`, `pin`, `unpin` | `{ok: true, action, chatId, chatTitle, messageId \| messageIds, …}` |
185
+ | `forward` | `{ok: true, action, chatId, chatTitle, fromChatId, messageIds, forwardedIds, count, …}`: `messageIds` are the **source** IDs in `fromChatId`; `forwardedIds` are the copies in `chatId`, use them to reply or edit |
186
+ | `mark-read` | `{ok: true, action, chatId, chatTitle, chat, read: true}` (no message ID) |
187
+
188
+ Confirm to the user where it went: the `chatTitle` and ID from the result, not the name you typed.
189
+
190
+ ## Audit log
191
+
192
+ Commands with audit try to record the result in `audit.jsonl` in the active profile's folder
193
+ (`~/.config/tg/` for the default profile on macOS and Linux; another `TG_PROFILE` or OS has its
194
+ own). A write that stops for approval or because writes are off ends before the log, not every
195
+ write keeps one, and a failed log write is ignored, so a missing entry proves nothing.