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.
@@ -1,416 +0,0 @@
1
- # Telegram CLI β€” behaviour reference
2
-
3
- Every flag is listed by `telegram help-all` (or `telegram help-all -g <word>`), generated from the
4
- code. This file only covers behaviour that the flag list can't tell you.
5
-
6
- ## Reading
7
-
8
- - `read` pages through history, so `--since/--until/--before/--after` return exact ranges on busy
9
- chats. `-n` caps the count (default 50). Order is newest first; `--asc` flips it.
10
- - `--unread` starts after the dialog's read marker and still obeys `-n`. It does not mark the
11
- messages read; use `mark-read <chat>` for that.
12
- - `--thread <id>` reads comments under a channel post, or replies to a message in a group.
13
- Channel comments live in the linked discussion group, so the output reports `threadChatId`.
14
- Reply there with `telegram reply <threadChatId> <commentId> ...`.
15
- - `--topic <id>` reads a forum topic. List topics with `telegram topics <chat>`.
16
- - `--from` works with plain reads and threads. `search --from` needs `--chat`, because Telegram
17
- global search has no sender filter.
18
- - `get <chat> <ids...>` fetches exact messages. Missing IDs go to stderr in text mode, or to a
19
- `missing` field in JSON.
20
- - `search "" --chat X --type photo` lists every photo in a chat. Types: photo, video, media,
21
- document, url, voice, audio, gif, round, location, contact, pinned, mentions.
22
- `--type mentions` without `--chat` finds where you were @mentioned.
23
- - Media shows as `[πŸ“· photo]`, `[πŸ“Ž document name.pdf Β· 1.2 MB]`, and so on. `download <chat> <id>`
24
- saves the file. In JSON, `media` has `kind`, `fileName`, `mimeType`, `size`, `width`, `height`
25
- and `duration`.
26
- - A long post costs as many tokens as its text. Use `--max-text 200` for skimming, then
27
- `get <chat> <id>` for the posts that matter.
28
- - **`--full` (alias `--stats`)** on `read`/`get`/`search`/`inbox`/`watch` adds a `full` object to
29
- every message (and a short `πŸ‘ β†ͺ ❀️` suffix in compact output). Default output is unchanged
30
- without it. `full` carries views, forwards, the complete reaction breakdown (each emoji / custom
31
- emoji id / paid reaction with count and whether you reacted), recent reactors, comments/thread
32
- info (`replies.comments`, `channelId`, `maxId`, `readMaxId`, recent repliers), edit date, post
33
- author, pinned/silent/noforwards/post flags, grouped (album) id, via-bot id, TTL, the forward
34
- header, reply-to info (ids, forum topic, quote), and rich media metadata (poll results, geo,
35
- venue, contact, webpage, dice, invoice, file name/size/mime/duration/dimensions). Use it for data
36
- collection β€” it needs no extra API calls. Over MCP, pass `--full` in `telegram_read` args.
37
- - `drafts` lists saved-but-unsent drafts (chat title + text). `profile-photos <user>` lists a
38
- user's profile photos; `avatar <user>` downloads the current one.
39
- - `scheduled <chat>` lists messages queued to send later (create them with `send --schedule`); it
40
- takes `--full` like `read`.
41
- - `sessions` lists active login sessions (device, app, platform, IP, country, last-active; the
42
- current one is flagged). `stars` shows the Telegram Stars balance and recent transactions.
43
- `invites <chat>` lists a chat's exported invite links (`--revoked` for revoked ones) or its
44
- pending join requests (`--requests`). All read-only.
45
- - `admin-log <chat>` shows a supergroup/channel's recent admin actions (Telegram's "Recent
46
- actions"), newest first, with `-n` and `-q <text>`. It needs admin rights in that chat.
47
- - `permissions <chat> [user]` shows a member's status (creator/admin/member/restricted/banned/left)
48
- and rights, or the chat's default permissions when no user is given. Supergroups and channels
49
- only. Change rights with `edit-permissions`.
50
- - `stats <chat>` returns full entity statistics: subscribers/members, online, admins, kicked and
51
- banned counts, linked discussion chat, slow mode, about, creation date, verified/scam/fake/
52
- restricted flags (+ reasons), and β€” where the account has rights β€” aggregate `activity`:
53
- - broadcast (`stats.GetBroadcastStats`): `period`, followers and per-post/per-story
54
- views/shares/reactions each as `{current, previous}`, enabled-notifications %, and
55
- `recentPosts[]` (`{msgId, views, forwards, reactions}`);
56
- - megagroup (`stats.GetMegagroupStats`): members/messages/viewers/posters `{current, previous}`
57
- and resolved `topPosters` `{userId, name, username, messages, avgChars}`, `topAdmins`
58
- `{userId, name, deleted, kicked, banned}`, `topInviters` `{userId, name, invitations}`.
59
- - `--graphs` adds each graph as a parsed JSON series (`graphs[] = {name, data}` or `{name, error}`);
60
- async graphs are loaded via `stats.LoadAsyncGraph`, and a failed graph reports its error without
61
- failing the rest.
62
- - `stats <chat> --message <id>` (or `--story <id>`) returns the post's own views/forwards/reactions,
63
- `publicForwardsCount`, a `publicForwards[]` list (`{chatTitle, msgId, views, date}`, capped by
64
- `--limit`), and β€” with `--graphs` β€” the message's view/reaction graphs.
65
- - Missing rights or unavailable stats are reported in `activity.error` / `note`, never a hard failure.
66
-
67
- ## Output
68
-
69
- - Off a TTY (agents and pipes), output is compact: one line per item with the ID first, JSON on
70
- one line, and null or empty fields dropped. Set `TG_JSON_PRETTY=1` to indent JSON.
71
- - Message line format: `#id YYYY-MM-DD HH:MM Sender ↩replyTo πŸ’¬comments: [media] text`. Continuation lines
72
- are indented. The sender is omitted when it is the chat itself, as in channel posts.
73
- - Chat line format: `id type [muted,archived] unread=N Title @username | preview`.
74
- - JSON shapes:
75
-
76
- | Command | Shape |
77
- |---|---|
78
- | `chats`, `contacts`, `members` | array |
79
- | `read`, `get` | `{chatTitle, messages[], threadChatId?, missing?}` |
80
- | `search` | array of `{chatTitle?, messages[]}`; global hits add `chatId` and `chatTitle` to each message |
81
- | `inbox` | `{totalUnread, chatsWithUnread, chats[]}` (totals cover all chats, `chats` is cut to `-n`) |
82
- | `info` | object |
83
- | `topics` | `{chatTitle, topics[]}` |
84
-
85
- ## Writing (needs write access; every write goes to `~/.config/tg/audit.jsonl`)
86
-
87
- - Three modes: read-only, `ask` (the user approves each write in the chat; set by `telegram onboard`)
88
- and `on` (no questions). `write-access ask [--for …]` needs no confirmation, since every write
89
- then waits for the user's yes. `write-access on [--for 30m|2h|1d]` asks the user: a y/N prompt on a
90
- terminal, otherwise a macOS or Windows dialog (it times out as "no" after 2 minutes). `--for`
91
- goes back to read-only automatically. `write-access off` needs no confirmation. The `onboard`
92
- page lets the user pick another mode. The mode lives in the secret store, not in the config file.
93
- - In mode `ask` a write exits with code 3 and prints the action and a code (with `--json`, a line
94
- `{"error":"approval_required","code":…,"action":…}` on stdout). After the user says yes to that
95
- exact action, rerun it with `TG_APPROVE=<code>`. The code works once, for 10 minutes, and only for
96
- the same arguments and stdin text.
97
- - Without a secret store (cloud agent computers, headless Linux) the mode is kept in a 0600 file in
98
- the profile and labelled "unprotected": an agent could edit it, just as it can read the session
99
- file there. Without a terminal, `write-access on` there opens a local page for the user.
100
-
101
- - Pass `-` as the text argument (`send`, `reply`, `edit`, `send-file -c`) to read the text from
102
- stdin: `printf '%s' "$text" | telegram send @user -`. This avoids shell quoting problems.
103
- - `--html` is the reliable formatting mode: `<b>`, `<i>`, `<a href>`, `<code>`, `<pre>`.
104
- `--markdown` uses the GramJS dialect (`**bold**`, `` `code` ``), where `[text](url)` links do
105
- NOT work.
106
- - `send --schedule 2h` (or an ISO date) schedules a message. `--silent` sends without a
107
- notification sound.
108
- - `delete` revokes for everyone by default. `--just-me` deletes only on your side. IDs are comma
109
- separated.
110
- - `forward <from> <ids> <to>`: `--drop-author` hides the source.
111
- - `pin` is silent by default (`--notify` pings members). `unpin <chat>` with no ID unpins
112
- everything.
113
- - `poll <chat> "Q" A B C` takes `--multiple`, `--quiz --correct N` (1-based) and `--public`.
114
- `vote <chat> <id> 2` also counts options from 1.
115
- - `pin-chat` / `unpin-chat` pin a chat to the top of the dialog list (this is the list position,
116
- not `pin`, which pins a message inside a chat). `mark-unread <chat>` sets the unread mark;
117
- `--read` clears it.
118
- - `delete-dialog <chat>` removes a conversation: it clears a private or basic-group history (with
119
- `--revoke` it also deletes the other person's copy) and leaves a supergroup or channel. Like all
120
- writes it needs the exact title, an @username or an ID.
121
- - `edit-permissions <chat> [user]` sets the chat's default permissions (no user) or restricts one
122
- member (channels.EditBanned / messages.EditChatDefaultBannedRights). `--mute` makes it read-only,
123
- `--ban` removes the member, `--lift` clears restrictions, `--deny send,media,polls,links,…` denies
124
- specific rights, and `--until 1h|1d|1w` makes a per-user restriction temporary. Inspect current
125
- rights with `permissions`.
126
- - `topic create|edit|close|reopen|pin|unpin <chat> …` manages forum topics in a group with Topics
127
- enabled: `topic create <chat> <title>` (`--icon-color`, `--icon-emoji`), `topic edit <chat> <id>`
128
- (`--title`, `--icon-emoji`, `--hide`/`--show`), and `topic close|reopen|pin|unpin <chat> <id>`.
129
- List topics with `topics <chat>`.
130
-
131
- ### Bot buttons
132
-
133
- `read` shows keyboards as `[index] label (type)`. Press one with `click <chat> <msgId> <index|label>`.
134
- After a callback, `click` re-reads the message and prints the bot's toast/alert, the edited text,
135
- new buttons and any new bot messages. Navigate bot menus by pressing a button and reading the new
136
- menu.
137
-
138
- | Button type | `click` does |
139
- |---|---|
140
- | callback | sends the callback, shows the answer and the updated message |
141
- | game | returns the game URL |
142
- | reply-keyboard text | sends the label as a message |
143
- | url / url_auth / webview | prints the URL, never opens it |
144
- | switch-inline | prints the query, does not send it |
145
- | copy | prints the copied text |
146
- | request phone / geo / poll / peer, buy | refused on purpose (privacy, payments) |
147
-
148
- Buttons that need 2FA take `--password`. `--no-wait` skips waiting for the bot's reply.
149
-
150
- ### Admin
151
-
152
- - `promote <group> <user>` takes `--rank "Title"` and `--add-admins`.
153
- - `transfer-owner` is irreversible and interactive: it asks you to retype the group name (`-y`
154
- skips this) and prompts for your 2FA password. It works for supergroups and channels only.
155
- Telegram blocks it for about 24 hours after a new login and about 7 days after a 2FA change.
156
- Never script it.
157
-
158
- ## Live and export
159
-
160
- - `watch [chat] -t 30 -n 10 --json` streams new messages as JSON lines. Always pass `-t` or `-n`
161
- when running unattended. A second `telegram` process that writes while `watch` runs can steal
162
- its update stream.
163
- - `sync --chat X --output DIR` writes markdown. It takes `--days N` (default 7),
164
- `--since/--until` and `--all` for full history. `--media` downloads files into `<chat>/media/`.
165
- - `sync --resume` is incremental. Checkpoints are per chat ID in `DIR/.sync-meta.json`. A resumed
166
- run fetches everything after the checkpoint and ignores the default `--days` window.
167
-
168
- ## Raw API (`telegram api` and `telegram <namespace> <method>`)
169
-
170
- Two ways to reach the whole Telegram client API when no curated command fits. They share one
171
- execution path β€” identical read/write classification, hard refusals and audit log β€” and both print
172
- compact JSON (big integers as strings, bytes as base64). Pick `api` for scripted JSON params, the
173
- typed per-method command for a command line.
174
-
175
- ### `telegram api <namespace.Method> --params '<json>'`
176
-
177
- Builds and sends any request from the schema. The method is case-insensitive (`messages.GetHistory`,
178
- `help.GetConfig`, top-level `InvokeWithLayer`). Inside `--params`, a small convention handles the
179
- awkward fields: `{"_chat": "<id|@user|title|me>"}` resolves a chat the way every command does (strict
180
- under a write), `{"_base64": "…"}` / `{"_hex": "…"}` pass raw bytes, `{"_bigint": "…"}` a `long`.
181
- Other entity-like fields also accept a bare `@username`/ID. `--params -` reads the JSON from stdin.
182
-
183
- ### `telegram <namespace> <method>` β€” one typed command per TL method
184
-
185
- Every TL schema method (all 823, generated into `src/generated/tl-commands.ts`) has its own top-level
186
- command.
187
-
188
- - **Naming.** The TL class name, split at the dot and kebab-cased:
189
- `messages.GetHistory` β†’ `telegram messages get-history`, `help.GetConfig` β†’
190
- `telegram help get-config`, `channels.GetFullChannel` β†’ `telegram channels get-full-channel`.
191
- The 21 root-level invoke/transport wrappers have no namespace and are top-level commands:
192
- `Ping` β†’ `telegram ping`, `InvokeWithLayer` β†’ `telegram invoke-with-layer`, `ReqPq` β†’ `telegram req-pq`.
193
- - **Clash with curated commands.** Six namespace names are also curated commands β€” `stats`,
194
- `stories`, `contacts`, `auth`, `folders`, `help`. The curated command keeps its behaviour, args and
195
- output; the generated methods attach to it as subcommands and are picked **only when the first
196
- operand is exactly a generated method name**. So `telegram stats get-broadcast-stats --channel @c`
197
- is the API method, while `telegram stats "Team"` and `telegram stats @c --message 5` are the curated
198
- `stats`. A chat/user literally named like a method (e.g. a chat called `get-broadcast-stats`) must be
199
- addressed by ID to avoid the method. A clash command's `--help` shows its curated usage plus a list
200
- of its generated methods. (`telegram help <method>` runs a `help.*` method, while `telegram help` and
201
- `telegram help <command>` still show help.)
202
- - **Discovery.** `telegram --help` ends with a "Telegram API" section listing the namespaces and
203
- their method counts (purposes in "Namespace index" below). `telegram <ns> --help` lists a
204
- namespace's methods, each marked `[read]`/`[write]`/`[refused]` with a one-line description.
205
- `telegram <ns> <method> --help` shows the description, access, return type, every param (flag, TL
206
- type, required/optional/default, description), an auto-generated example, common errors and the
207
- core.telegram.org docs link. Those descriptions are the official ones, fetched once into
208
- `scripts/data/tl-docs-layer229.json` (40 methods new in the layer have a fallback line); never
209
- fetched at runtime.
210
- - **Machine-readable: `telegram schema`.** `telegram schema` prints the namespace index as JSON;
211
- `telegram schema <ns>` lists a namespace's methods (`{command, className, access, description}`);
212
- `telegram schema <ns> <method>` (or `telegram schema <ns>.<Method>`) prints the full method schema
213
- `{command, className, access, refusedReason?, returns, params:[{flag,name,type,required,default,description}], example, docsUrl, description}`.
214
- It is a pure local read (no account, no network).
215
- - **Flags.** One `--flag` per parameter, the camelCase param name kebab-cased (`offsetId` β†’
216
- `--offset-id`, `scheduleDate` β†’ `--schedule-date`). Pass each by its TL type:
217
-
218
- | TL type | Flag form | How to pass |
219
- |---|---|---|
220
- | `int`, `double` | `--limit 20` | a number |
221
- | `long`, `int128`, `int256` | `--hash 0` | digits (sent as a big integer) |
222
- | `string` | `--q "term"` | text |
223
- | `Bool` | `--offline true` | `true`/`false` (or `1`/`0`) |
224
- | `true` (flag bit, e.g. `silent`, `noWebpage`) | `--silent`, `--no-webpage` | bare switch; present = set |
225
- | `bytes` | `--file-hash aGk=` | base64, or `hex:…` |
226
- | `InputPeer`/`InputUser`/`InputChannel` | `--peer @durov` | id, `@username`, chat title or `me` |
227
- | vector of a primitive | `--id 100,101,102` | comma list (or a JSON array) |
228
- | vector of a constructor | `--reaction '[{"className":"ReactionEmoji","emoticon":"πŸ‘"}]'` | JSON array |
229
- | constructor type (`InputMedia`, `ReplyMarkup`, `DataJSON`, …) | `--reply-to '{"className":"InputReplyToMessage","replyToMsgId":42}'` | JSON (may use `{"_chat":…}`/`{"_base64":…}` markers) |
230
-
231
- - **`--json-params '<json|->'`** merges a JSON object for anything not worth a flag (e.g. a deep
232
- nested constructor); typed flags override its keys, and `-` reads the JSON from stdin. Example β€”
233
- a nested `replyTo` constructor as JSON, the simple fields as flags:
234
-
235
- ```bash
236
- telegram messages send-message --peer @me --message hi \
237
- --json-params '{"replyTo":{"className":"InputReplyToMessage","replyToMsgId":42}}'
238
- ```
239
-
240
- - **Paging/cache cursors default to 0.** A required `int`/`long` named `offsetId`, `offsetDate`,
241
- `addOffset`, `offsetRate`, `offsetTopic`, `offset`, `maxId`, `minId`, `maxDate`, `minDate` or
242
- `hash` defaults to 0 when omitted (shown as `default 0` in `--help`), so
243
- `telegram messages get-history --peer @durov --limit 20` just works. Only these exact numeric
244
- names β€” ids (`msgId`/`id`/`userId`), `limit`, `offsetPeer` and string hashes are never defaulted.
245
- - **Other required params** are enforced with a clear error (`Missing required option(s): --peer …`);
246
- `randomId` is never required (teleproto generates it). Registration is lazy β€” only the invoked
247
- namespace/method is built β€” so startup, top-level `--help` and `help-all` stay flat.
248
-
249
- ### Read vs write and refusals (both commands)
250
-
251
- - **Read vs write:** methods named `Get*`/`Check*`/`Search*`/`Resolve*` are reads and run without
252
- write access (available through the MCP read tool); everything else is a write that needs
253
- `telegram write-access on` (the `telegram_write` MCP tool), goes through the write guard, and is
254
- logged to the audit file.
255
- - **Always refused**, even with write access (the command still exists and refuses, exit 1; its
256
- `--help` says "always refused"): the whole `auth.*` namespace (login/session β€” use `telegram auth`),
257
- account/session takeover and 2FA/password/phone changes, data export (takeout) and Passport
258
- identity docs, external-site login (url-auth), ownership transfer, money-withdrawal tokens and
259
- paying / Stars-spending, and anything that shares your phone number or location (including
260
- contact/geo media in `SendMedia`). A few `Get*` methods that actually change state (e.g.
261
- `messages.GetMessagesViews`) are treated as writes. Read-only payments (balances, transactions) and
262
- session *listing* (`account.GetAuthorizations`) are allowed. Full table in `docs/api-coverage.md` Β§4.
263
- - Coverage of the full API is tracked in `docs/api-coverage.md` (regenerated by
264
- `scripts/api-coverage.mjs`).
265
-
266
- ### When to use which
267
-
268
- - **Curated command** (`read`, `send`, `search`, `chats`, `members`, …) β€” the default. Friendly,
269
- compact output, pagination, multi-step logic and safety prompts. Always prefer it when one exists.
270
- - **`telegram <ns> <method>`** β€” a method with no curated command, or when you need the exact raw
271
- TL object, from a typed command line.
272
- - **`telegram api <ns.Method> --params`** β€” the same reach, when it is easier to hand it a whole JSON
273
- body (scripts, deeply nested requests).
274
-
275
- ### Examples
276
-
277
- ```bash
278
- telegram help get-config # read, no args (help.* method)
279
- telegram channels get-full-channel --channel @group # read, peer resolved like everywhere
280
- telegram messages get-history --peer @durov --limit 20 # read: paging cursors default to 0
281
- telegram stats get-broadcast-stats --channel @c # a method on a clash namespace
282
- telegram messages delete-messages --id 100,101,102 --revoke # write: vector + true-flag
283
- telegram messages send-reaction --peer @me --msg-id 42 \
284
- --json-params '{"reaction":[{"className":"ReactionEmoji","emoticon":"πŸ‘"}]}' # write, nested
285
- telegram ping --ping-id 1 # root-level method
286
- telegram account delete-account # exists, always refused (exit 1)
287
- echo '{"id":[100,101]}' | telegram messages delete-messages --json-params - # JSON from stdin
288
- ```
289
-
290
- ### Namespace index
291
-
292
- One line per TL namespace (`telegram <ns> --help` lists the methods). Prefer a curated command when
293
- one exists; use these for everything else.
294
-
295
- | Namespace | What it covers |
296
- |---|---|
297
- | `messages` | Chats & dialogs, history, sending, search, reactions, drafts, polls, scheduled, pins |
298
- | `account` | Profile, privacy, active sessions, 2FA, notifications, usernames, business settings |
299
- | `payments` | Stars, gifts, invoices, subscriptions (any paying method is refused) |
300
- | `channels` | Supergroups/channels: members, admin rights, forum topics, invite links, admin log |
301
- | `phone` | Voice/video calls & group calls (no real CLI use) |
302
- | `bots` | Bot management and bot-only methods |
303
- | `stories` | Stories: feeds, views, reactions, posting |
304
- | `auth` | Login/session management β€” refused; use `telegram auth`/`onboard` |
305
- | `contacts` | Contacts, blocked list, top peers, resolve usernames |
306
- | `help` | Client config, app updates, terms, country list |
307
- | `chatlists` | Shareable folder (chat-list) invites |
308
- | `stickers` | Sticker-set creation and editing |
309
- | `communities` | Community management (new in the layer) |
310
- | `ephemeral` | Ephemeral/one-time content (new in the layer) |
311
- | `stats` | Channel/supergroup/message/story statistics |
312
- | `upload` | File upload/download transport (driven by send-file/download) |
313
- | `aicompose` | AI message composing (new in the layer) |
314
- | `smsjobs` | SMS-relay programme |
315
- | `users` | User info / full user |
316
- | `langpack` | Client localisation packs |
317
- | `photos` | Profile photos |
318
- | `premium` | Telegram Premium boosts |
319
- | `updates` | Update state/difference (driven by `watch`) |
320
- | `folders` | Dialog folders (archive) |
321
- | `fragment` | Fragment collectible usernames/numbers |
322
-
323
- Root-level methods (no namespace) are low-level transport/invoke wrappers β€” `telegram ping`,
324
- `telegram invoke-with-layer`, `telegram req-pq`, … β€” rarely needed directly.
325
-
326
- ### Errors
327
-
328
- Methods return raw RPC errors. The common ones: **FLOOD_WAIT_X** β€” wait X seconds and retry (the
329
- number is in the name); `PEER_ID_INVALID` β€” the chat/user couldn't be resolved; `CHAT_ADMIN_REQUIRED`
330
- β€” you lack the needed admin right; `CHANNEL_PRIVATE` β€” you're not a member; `MESSAGE_ID_INVALID` β€” no
331
- such message; `AUTH_KEY_UNREGISTERED`/`SESSION_REVOKED` β€” the session is gone (log in again). A
332
- method's `--help` lists its own "Common errors" when the docs provide them.
333
-
334
- ## MCP server (`telegram mcp`)
335
-
336
- - **Tools:**
337
- - `telegram_help {grep?}`;
338
- - `telegram_read {args}`, marked `readOnlyHint`;
339
- - `telegram_write {args, stdin?}`, marked `destructiveHint`.
340
-
341
- `args` is the CLI argv with the command first, for example `["read","@x","-n","20"]`. `stdin`
342
- fills a `-` text argument.
343
- - **What runs where:**
344
- - Read tool: only the read commands.
345
- - Write tool: everything that changes the account or writes local files (`download`, `sync`,
346
- `avatar`).
347
- - `api` and the generated commands are classified per underlying method: a read goes through the
348
- read tool, a write through the write tool, a refused method never runs β€” `["messages","get-history",…]`
349
- and `["ping"]` like `["api","messages.GetHistory",…]`. On a clash namespace the method form is
350
- classified by its method (`["stats","get-broadcast-stats",…]`) while the curated form keeps its
351
- own class (`["stats","@chat"]` is a read); `["auth","send-code"]` is refused.
352
- - Help is always a read: a bare help request (a command path plus `--help`/`-h`, optionally
353
- `--json`) and `telegram schema …` go through the read tool even for a write or refused method
354
- (`["account","delete-account","--help"]`) β€” help prints, it never executes the method. Add no
355
- other args: with extra args (`["send","@x","--","--help"]`) the call is classified normally.
356
- - Never over MCP: `auth`, `onboard`, `logout`, `transfer-owner`, `update`, `skill`, and changing `write-access`.
357
- Showing its status is allowed (a generated `auth.*` method is refused, not run).
358
- - **Safety:** the read tool runs with `TG_READ_ONLY=1`, which blocks every guarded write even if a
359
- command were misclassified.
360
- - **Execution:** each call is a separate CLI process with no stdin (a worker thread inside Claude
361
- Desktop). Calls run one at a time, time out after 120 s, and output is capped at 100 KB.
362
- `watch` needs `-t` or `-n`.
363
- - **Protocol:** MCP 2025-11-25 with the `initialize` handshake. Newer clients fall back to it.
364
- - **HTTP:** `telegram mcp --http [--host 127.0.0.1] [--port 8787]` serves the same tools on
365
- `POST /mcp` (stateless, JSON responses) for remote hosts such as Grok Bot. Every request needs
366
- `Authorization: Bearer <token>` (`telegram mcp --token`, `--rotate-token`). Requests with an
367
- `Origin` header are refused. `--read-only` drops `telegram_write` (also works over stdio).
368
-
369
- ## Chat identifiers
370
-
371
- `me` / `self` / `saved` / `Saved Messages` / `Π˜Π·Π±Ρ€Π°Π½Π½ΠΎΠ΅` β†’ your Saved Messages. A numeric ID must
372
- exactly match a dialog ID (the `id` from `chats`). `@username` resolves exactly. Anything else
373
- matches titles.
374
-
375
- - **Reads:** an exact title first, then a substring.
376
- - **Writes** (every command gated by write access) accept only an exact, unique title. A substring
377
- or a title shared by several chats is refused with up to 5 candidates (`id type title @username`).
378
- Retry with the ID.
379
-
380
- ## Troubleshooting
381
-
382
- - `Not configured`: run `telegram onboard --json`. It serves a one-shot page on 127.0.0.1 (random
383
- secret path, closes when done, `--timeout` 15 min by default) where the user gets a login key from
384
- better-tg-cli.com (it comes back to the page by itself), or enters their own keys, then scans a QR
385
- code and types their 2FA password. Events: `url`, `waiting_invite`, `waiting_scan`, `need_password`,
386
- `done` (exit 0), `error`, `timeout` (exit 1); `already_logged_in` exits 0 without changes.
387
- `--no-open` only prints the URL. You never get tokens, codes or passwords, and you must not ask
388
- for them or fill in the page. Without a browser on this machine (SSH), the user runs
389
- `telegram auth --qr` (own keys) or `telegram auth --login-key --qr` in their terminal; that is
390
- interactive, so never run it for them. `--qr` logs in by scanning a QR code in the Telegram app instead of
391
- typing a code (`TG_QR_INVERT=1` for light terminals).
392
-
393
- - `command not found: telegram`: the CLI isn't installed. Ask the user first, then install it as the first rule in SKILL.md says (Homebrew, Scoop or npm); other ways are in the README's Install section.
394
- `telegram update` upgrades an existing install (brew, npm or git checkout); `update --check` only reports.
395
- `telegram skill install|status|uninstall [-a <agent>...]` copies this skill into coding agents' global
396
- skills folders; only run it when the user asks.
397
- Never install `@skillhq/telegram` from npm: it is the old GramJS build, and bot replies show
398
- as `(no text)`.
399
- - `Write access is disabled`: the profile is read-only, or a `--for` window expired. Run
400
- `telegram write-access ask`, then ask the user before each write. `on` only when the user asks for
401
- it; they confirm it in a dialog.
402
- - `Approval needed` (exit 3): mode `ask`. Show the action to the user, and after a yes rerun with
403
- `TG_APPROVE=<code>`.
404
- - `FLOOD_WAIT` (rate limit): waits of up to 60 s are retried automatically, and stderr says
405
- `Telegram rate limit on <method>: waiting Ns`. Longer waits fail with the wait in the error
406
- message. `TG_FLOOD_WAIT_MAX=<seconds>` changes the limit: `0` fails fast, a larger value suits
407
- long `sync` runs. Don't retry in a loop, because Telegram extends the ban.
408
- - `NetSocket was closed` or timeouts while connecting: the network blocks Telegram's TCP transport
409
- (common on cloud agent computers that allow only HTTPS). The CLI retries over WebSocket
410
- (`wss://*.web.telegram.org`) by itself and saves `transport: "wss"` for the profile; stderr says
411
- so. Force one with `TG_TRANSPORT=wss` (or `tcp`).
412
- - `CHANNELS_TOO_MUCH` on `join`: the account hit Telegram's channel limit, so leave some first.
413
- - `Could not find the input entity`: the ID is not in your dialogs. Use `@username` or open the
414
- chat first.
415
- - Bot reply shows as `(no text)` with `MessageMediaUnsupported`: the TL layer is behind, so bump
416
- `teleproto`.