telegram-cli-local 0.3.0__tar.gz → 0.4.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.
Files changed (30) hide show
  1. {telegram_cli_local-0.3.0 → telegram_cli_local-0.4.0}/.agents/skills/telegram-cli/SKILL.md +39 -4
  2. {telegram_cli_local-0.3.0 → telegram_cli_local-0.4.0}/.claude/skills/telegram-cli/SKILL.md +39 -4
  3. {telegram_cli_local-0.3.0 → telegram_cli_local-0.4.0}/CHANGELOG.md +13 -0
  4. {telegram_cli_local-0.3.0 → telegram_cli_local-0.4.0}/PKG-INFO +93 -8
  5. telegram_cli_local-0.3.0/telegram_cli_local.egg-info/PKG-INFO → telegram_cli_local-0.4.0/README.md +89 -28
  6. {telegram_cli_local-0.3.0 → telegram_cli_local-0.4.0}/README.ru.md +91 -6
  7. {telegram_cli_local-0.3.0 → telegram_cli_local-0.4.0}/RELEASING.md +2 -2
  8. {telegram_cli_local-0.3.0 → telegram_cli_local-0.4.0}/pyproject.toml +4 -1
  9. telegram_cli_local-0.4.0/scripts/benchmark_crypto.py +34 -0
  10. {telegram_cli_local-0.3.0 → telegram_cli_local-0.4.0}/scripts/check_distribution.py +1 -0
  11. {telegram_cli_local-0.3.0 → telegram_cli_local-0.4.0}/tcli_skills/SKILL.md +39 -4
  12. {telegram_cli_local-0.3.0 → telegram_cli_local-0.4.0}/tcli_skills/__init__.py +1 -1
  13. telegram_cli_local-0.3.0/README.md → telegram_cli_local-0.4.0/telegram_cli_local.egg-info/PKG-INFO +113 -6
  14. {telegram_cli_local-0.3.0 → telegram_cli_local-0.4.0}/telegram_cli_local.egg-info/SOURCES.txt +1 -0
  15. telegram_cli_local-0.4.0/telegram_cli_local.egg-info/requires.txt +4 -0
  16. {telegram_cli_local-0.3.0 → telegram_cli_local-0.4.0}/tests/test_tg.py +173 -5
  17. {telegram_cli_local-0.3.0 → telegram_cli_local-0.4.0}/tg.py +121 -19
  18. telegram_cli_local-0.3.0/telegram_cli_local.egg-info/requires.txt +0 -1
  19. {telegram_cli_local-0.3.0 → telegram_cli_local-0.4.0}/AGENTS.md +0 -0
  20. {telegram_cli_local-0.3.0 → telegram_cli_local-0.4.0}/CLAUDE.md +0 -0
  21. {telegram_cli_local-0.3.0 → telegram_cli_local-0.4.0}/LICENSE +0 -0
  22. {telegram_cli_local-0.3.0 → telegram_cli_local-0.4.0}/MANIFEST.in +0 -0
  23. {telegram_cli_local-0.3.0 → telegram_cli_local-0.4.0}/requirements.txt +0 -0
  24. {telegram_cli_local-0.3.0 → telegram_cli_local-0.4.0}/scripts/check_docs.py +0 -0
  25. {telegram_cli_local-0.3.0 → telegram_cli_local-0.4.0}/setup.cfg +0 -0
  26. {telegram_cli_local-0.3.0 → telegram_cli_local-0.4.0}/telegram_cli_local.egg-info/dependency_links.txt +0 -0
  27. {telegram_cli_local-0.3.0 → telegram_cli_local-0.4.0}/telegram_cli_local.egg-info/entry_points.txt +0 -0
  28. {telegram_cli_local-0.3.0 → telegram_cli_local-0.4.0}/telegram_cli_local.egg-info/top_level.txt +0 -0
  29. {telegram_cli_local-0.3.0 → telegram_cli_local-0.4.0}/tests/test_docs.py +0 -0
  30. {telegram_cli_local-0.3.0 → telegram_cli_local-0.4.0}/tests/test_features.py +0 -0
@@ -1,12 +1,12 @@
1
1
  ---
2
2
  name: telegram-cli
3
- description: Use the personal-account Telegram CLI (tcli) for chat discovery, filtered history, topics, reply chains, exports, messages and attachments, scheduling, live updates, JSON automation, and account diagnostics.
3
+ description: Use Telegram CLI (tcli) with named user or bot sessions for messages, attachments, deletion, history, live updates, JSON automation and diagnostics.
4
4
  ---
5
5
 
6
6
  # Telegram CLI
7
7
 
8
- Use the installed `tcli` command from any directory. It acts as the user's personal Telegram account,
9
- not a bot. Respond in the user's language; CLI output and these instructions are English.
8
+ Use the installed `tcli` command from any directory with a user or bot account.
9
+ Respond in the user's language; CLI output and these instructions are English.
10
10
  Do not infer a repository path from the skill's installation directory.
11
11
 
12
12
  ## Choose the command
@@ -34,6 +34,10 @@ If unavailable, inspect `tcli help`; do not assume newer commands exist based on
34
34
  | Observe future messages and edits | `tcli watch "Chat" --edits --json` |
35
35
  | Send literal text | `tcli send me "Text" --json` |
36
36
  | Edit outgoing text or an attachment caption | `tcli edit me 123 "Corrected text" --json` |
37
+ | Delete specific messages for everyone | `tcli delete me 123 124 --json` |
38
+ | List local session files offline | `tcli sessions --json` |
39
+ | Sign in to a named user session | `tcli --session work login` |
40
+ | Sign in to a separate bot session | `tcli --session assistant login --bot` |
37
41
  | Forward with attribution | `tcli forward "Source" 123 "Destination" --json` |
38
42
  | Inspect pending scheduled messages | `tcli scheduled me --json` |
39
43
  | Cancel specific scheduled messages | `tcli scheduled me --cancel 123 124 --json` |
@@ -48,10 +52,39 @@ All example names, IDs, links and paths are placeholders. Resolve actual targets
48
52
  Use `read` for one-time requests; start `watch` only for ongoing observation.
49
53
  Use `thread` for the parent chain and `--around` for chronological neighbors; these are different views.
50
54
 
55
+ ## Sessions, bots and deletion
56
+
57
+ Select the authorized account with `--session NAME` before or after the command; default is `default`.
58
+ Do not assume a different named session belongs to the same person or bot. `sessions --json` lists
59
+ local file presence only, without checking identity or authorization; `doctor --connect` shows user/bot type.
60
+ Names use 1-32 lowercase ASCII letters/digits, underscores or hyphens, starting with letter/digit.
61
+ The default keeps the old account.session; others use sessions/NAME/account.session in the data directory.
62
+ API configuration is shared. Logout affects only the selected session. Do not copy or delete session files.
63
+
64
+ `login --bot` prompts locally with hidden input or reads TG_BOT_TOKEN. API_ID/API_HASH are still required.
65
+ Never collect bot tokens in chat or put them in command arguments. Existing login is reused;
66
+ changing account/type requires another session name. Never log out an unrelated account to switch.
67
+ Bots use MTProto, not HTTP Bot API. Bot capabilities in this CLI:
68
+
69
+ - Send text/files/albums, forward, edit outgoing messages and delete specified IDs within Telegram permissions.
70
+ - Read known IDs (`read --id`), follow `thread`, single download/resume and info, subject to access.
71
+ - Watch live new/edit events only; no history polling or replay guarantee. Privacy mode affects group events.
72
+ - No chats list, title selection, Saved Messages (`me`), history/search/export, pinned/topics/scheduled commands,
73
+ send --schedule, album/batch download. These modes fail with bot_unsupported.
74
+ - Use a known numeric chat ID or @username. A raw ID without a cached entity/access hash may fail.
75
+ Bots cannot initiate arbitrary private conversations; users must contact/add the bot first.
76
+
77
+ `delete CHAT ID [ID ...]` is irreversible, deletes for everyone and has no extra prompt.
78
+ Execute only for the user's explicitly authorized session, chat and IDs. The CLI checks every ID
79
+ belongs to the selected chat before deleting; missing or mismatched IDs abort without deletion.
80
+ `{ok:true,requested_ids:[...]}` means the server accepted the request, not proof for each ID.
81
+ Large requests can partially succeed; after uncertain failure inspect accessible IDs before retrying.
82
+ Use scheduled --cancel for pending scheduled IDs, not delete.
83
+
51
84
  ## Authorization and private data
52
85
 
53
86
  - Read only the chats and history needed for the user's request. A request to read or develop the CLI
54
- does not authorize sends, forwards, edits, scheduling or cancellation, including in Saved Messages.
87
+ does not authorize sends, forwards, edits, deletes, scheduling or cancellation, including in Saved Messages.
55
88
  - For a write, use the user's authorized recipient, content and message ID where applicable. Existing
56
89
  unambiguous authorization remains valid; do not ask for the same permission again. Clarify a genuinely
57
90
  ambiguous recipient, time or action before executing that part.
@@ -270,6 +303,8 @@ JSON contains resulting plain text, not formatting entities or the original Mark
270
303
  | `download` | {ok:true,files:[...]} |
271
304
  | `export` | {ok:true,path,count} |
272
305
  | `scheduled --cancel` | {ok:true,cancelled_ids:[...]} |
306
+ | `delete` | {ok:true,requested_ids:[...]} |
307
+ | `sessions` | Array of {name,path}; file presence only |
273
308
 
274
309
  Download file records contain message_id, chat_id, absolute path, text (caption), grouped_id.
275
310
  Errors with `--json` or `read --jsonl` go to stderr as {ok:false,error:{code,message,retry_after,...}}.
@@ -1,12 +1,12 @@
1
1
  ---
2
2
  name: telegram-cli
3
- description: Use the personal-account Telegram CLI (tcli) for chat discovery, filtered history, topics, reply chains, exports, messages and attachments, scheduling, live updates, JSON automation, and account diagnostics.
3
+ description: Use Telegram CLI (tcli) with named user or bot sessions for messages, attachments, deletion, history, live updates, JSON automation and diagnostics.
4
4
  ---
5
5
 
6
6
  # Telegram CLI
7
7
 
8
- Use the installed `tcli` command from any directory. It acts as the user's personal Telegram account,
9
- not a bot. Respond in the user's language; CLI output and these instructions are English.
8
+ Use the installed `tcli` command from any directory with a user or bot account.
9
+ Respond in the user's language; CLI output and these instructions are English.
10
10
  Do not infer a repository path from the skill's installation directory.
11
11
 
12
12
  ## Choose the command
@@ -34,6 +34,10 @@ If unavailable, inspect `tcli help`; do not assume newer commands exist based on
34
34
  | Observe future messages and edits | `tcli watch "Chat" --edits --json` |
35
35
  | Send literal text | `tcli send me "Text" --json` |
36
36
  | Edit outgoing text or an attachment caption | `tcli edit me 123 "Corrected text" --json` |
37
+ | Delete specific messages for everyone | `tcli delete me 123 124 --json` |
38
+ | List local session files offline | `tcli sessions --json` |
39
+ | Sign in to a named user session | `tcli --session work login` |
40
+ | Sign in to a separate bot session | `tcli --session assistant login --bot` |
37
41
  | Forward with attribution | `tcli forward "Source" 123 "Destination" --json` |
38
42
  | Inspect pending scheduled messages | `tcli scheduled me --json` |
39
43
  | Cancel specific scheduled messages | `tcli scheduled me --cancel 123 124 --json` |
@@ -48,10 +52,39 @@ All example names, IDs, links and paths are placeholders. Resolve actual targets
48
52
  Use `read` for one-time requests; start `watch` only for ongoing observation.
49
53
  Use `thread` for the parent chain and `--around` for chronological neighbors; these are different views.
50
54
 
55
+ ## Sessions, bots and deletion
56
+
57
+ Select the authorized account with `--session NAME` before or after the command; default is `default`.
58
+ Do not assume a different named session belongs to the same person or bot. `sessions --json` lists
59
+ local file presence only, without checking identity or authorization; `doctor --connect` shows user/bot type.
60
+ Names use 1-32 lowercase ASCII letters/digits, underscores or hyphens, starting with letter/digit.
61
+ The default keeps the old account.session; others use sessions/NAME/account.session in the data directory.
62
+ API configuration is shared. Logout affects only the selected session. Do not copy or delete session files.
63
+
64
+ `login --bot` prompts locally with hidden input or reads TG_BOT_TOKEN. API_ID/API_HASH are still required.
65
+ Never collect bot tokens in chat or put them in command arguments. Existing login is reused;
66
+ changing account/type requires another session name. Never log out an unrelated account to switch.
67
+ Bots use MTProto, not HTTP Bot API. Bot capabilities in this CLI:
68
+
69
+ - Send text/files/albums, forward, edit outgoing messages and delete specified IDs within Telegram permissions.
70
+ - Read known IDs (`read --id`), follow `thread`, single download/resume and info, subject to access.
71
+ - Watch live new/edit events only; no history polling or replay guarantee. Privacy mode affects group events.
72
+ - No chats list, title selection, Saved Messages (`me`), history/search/export, pinned/topics/scheduled commands,
73
+ send --schedule, album/batch download. These modes fail with bot_unsupported.
74
+ - Use a known numeric chat ID or @username. A raw ID without a cached entity/access hash may fail.
75
+ Bots cannot initiate arbitrary private conversations; users must contact/add the bot first.
76
+
77
+ `delete CHAT ID [ID ...]` is irreversible, deletes for everyone and has no extra prompt.
78
+ Execute only for the user's explicitly authorized session, chat and IDs. The CLI checks every ID
79
+ belongs to the selected chat before deleting; missing or mismatched IDs abort without deletion.
80
+ `{ok:true,requested_ids:[...]}` means the server accepted the request, not proof for each ID.
81
+ Large requests can partially succeed; after uncertain failure inspect accessible IDs before retrying.
82
+ Use scheduled --cancel for pending scheduled IDs, not delete.
83
+
51
84
  ## Authorization and private data
52
85
 
53
86
  - Read only the chats and history needed for the user's request. A request to read or develop the CLI
54
- does not authorize sends, forwards, edits, scheduling or cancellation, including in Saved Messages.
87
+ does not authorize sends, forwards, edits, deletes, scheduling or cancellation, including in Saved Messages.
55
88
  - For a write, use the user's authorized recipient, content and message ID where applicable. Existing
56
89
  unambiguous authorization remains valid; do not ask for the same permission again. Clarify a genuinely
57
90
  ambiguous recipient, time or action before executing that part.
@@ -270,6 +303,8 @@ JSON contains resulting plain text, not formatting entities or the original Mark
270
303
  | `download` | {ok:true,files:[...]} |
271
304
  | `export` | {ok:true,path,count} |
272
305
  | `scheduled --cancel` | {ok:true,cancelled_ids:[...]} |
306
+ | `delete` | {ok:true,requested_ids:[...]} |
307
+ | `sessions` | Array of {name,path}; file presence only |
273
308
 
274
309
  Download file records contain message_id, chat_id, absolute path, text (caption), grouped_id.
275
310
  Errors with `--json` or `read --jsonl` go to stderr as {ok:false,error:{code,message,retry_after,...}}.
@@ -7,6 +7,19 @@ move them into a versioned section when publishing a release.
7
7
 
8
8
  No unreleased changes.
9
9
 
10
+ ## 0.4.0 - 2026-10-25
11
+
12
+ ### Added
13
+
14
+ - Add `delete CHAT ID...` with full chat-membership preflight and revoke-for-everyone semantics.
15
+ - Add named `--session` selection and offline `sessions` listing, preserving the existing default session.
16
+ - Support hidden-token bot login, direct bot peer resolution and live event-based bot watch;
17
+ reject unsupported bot modes with actionable errors and document capabilities and restrictions.
18
+ - Add a percentage bar that redraws in terminals for uploads, albums and downloads, keeping
19
+ redirected output line-based and JSON progress unchanged. End interrupted bars before errors.
20
+ - Add the optional `fast` extra with native cryptg encryption and an offline correctness/speed
21
+ benchmark, plus workflow performance guidance in both READMEs.
22
+
10
23
  ## 0.3.0 - 2026-10-19
11
24
 
12
25
  ### Changed
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: telegram-cli-local
3
- Version: 0.3.0
4
- Summary: Telegram CLI for a personal account
3
+ Version: 0.4.0
4
+ Summary: Telegram CLI for user and bot accounts with named sessions
5
5
  Author: BYxarek
6
6
  License-Expression: Apache-2.0
7
7
  Project-URL: Repository, https://github.com/BYxarek/telegram-cli
@@ -18,6 +18,8 @@ Requires-Python: >=3.10
18
18
  Description-Content-Type: text/markdown
19
19
  License-File: LICENSE
20
20
  Requires-Dist: Telethon==1.45.0
21
+ Provides-Extra: fast
22
+ Requires-Dist: cryptg<0.7,>=0.5.2; extra == "fast"
21
23
  Dynamic: license-file
22
24
 
23
25
  <div align="center">
@@ -50,8 +52,8 @@ tcli watch "Work chat" # Follow new messages
50
52
  ```
51
53
 
52
54
  `tcli` is a local Python CLI built with [Telethon](https://docs.telethon.dev/).
53
- It uses the Telegram API and acts as your personal account. You need your own
54
- `API_ID` and `API_HASH`; no bot token is used.
55
+ It uses Telegram's MTProto API with a personal account or a bot. Both modes require your own
56
+ `API_ID` and `API_HASH`; bot login additionally requires a BotFather token.
55
57
 
56
58
  ## Features
57
59
 
@@ -71,8 +73,63 @@ are removed from displayed messages.
71
73
 
72
74
  ### Current scope
73
75
 
74
- One local account session, text and attachments, human-readable output, and optional JSON.
75
- Message deletion and a full-screen interface are not available.
76
+ Named local user/bot sessions, text and attachments, message deletion, human-readable output,
77
+ and optional JSON. A full-screen interface is not available.
78
+
79
+ ## Sessions, bots and deletion
80
+
81
+ ```console
82
+ tcli config
83
+ tcli --session work login
84
+ tcli --session assistant login --bot
85
+ tcli sessions --json
86
+ tcli --session work delete me 123 124 --json
87
+ tcli --session assistant send @example_channel "Status update"
88
+ tcli --session assistant watch @example_channel --edits --json
89
+ ```
90
+
91
+ Examples are placeholders; do not execute sends or deletes without explicit authorization.
92
+ `--session NAME` can precede or follow the command. Names contain 1-32 lowercase ASCII
93
+ letters/digits, underscores or hyphens, starting with a letter/digit; Windows device names
94
+ are rejected. `default` keeps the existing `account.session`. Other sessions live under
95
+ `sessions/NAME/account.session` in the same local data directory. API configuration is shared;
96
+ `config` updates it for all sessions. `sessions` lists local file presence offline, not account
97
+ identity or authorization. `doctor --connect` shows the selected account type. `logout` revokes
98
+ only the selected session. Use different session names for different accounts, and avoid
99
+ concurrent processes on the same session. Choosing a new name does not copy existing authorization.
100
+
101
+ `login --bot` reads a token via hidden input or `TG_BOT_TOKEN`, only during login. It does not
102
+ store the token in config or accept it as a command-line argument. Existing authorized sessions
103
+ are reused; login never switches accounts in place. A different account type requires another
104
+ session name. Tokens and session files grant account access; never commit or share them.
105
+
106
+ | Operation | Bot session |
107
+ | --- | --- |
108
+ | Send text/files/albums, forward, edit outgoing messages | Supported, subject to Telegram access and posting permissions |
109
+ | Delete specific IDs | Supported within Telegram permissions; deleting others' messages may require admin rights |
110
+ | `read --id`, `thread`, single `download` including `--resume`, `info` | Supported for accessible known messages/chats; Telegram may reject requests |
111
+ | `watch`, `watch --edits` | Live MTProto events only; no history polling or replay guarantee after downtime |
112
+ | `chats`, history reads/search/export, `pinned`, `topics`, `scheduled`, `send --schedule`, album/batch download | Rejected with `bot_unsupported` in this CLI |
113
+ | Chat selectors | Known numeric ID or `@username`; titles and `me` are rejected |
114
+
115
+ A bot has no Saved Messages and cannot initiate private conversations with arbitrary users:
116
+ the user must first contact it or add it to a group. Groups/channels must grant the necessary
117
+ rights. Group privacy mode affects incoming updates. A numeric peer must already be known to
118
+ the selected session, usually from an update; a raw ID alone does not supply an access hash.
119
+ This uses Telethon/MTProto, not the HTTP Bot API; HTTP Bot API file-size limits are not CLI limits.
120
+ See [Telegram's bot FAQ](https://core.telegram.org/bots/faq),
121
+ [history restriction](https://core.telegram.org/method/messages.getHistory), and
122
+ [known-message retrieval](https://core.telegram.org/method/messages.getMessages).
123
+
124
+ `delete CHAT ID [ID ...]` deletes for everyone (`revoke=True`), without an extra prompt.
125
+ All requested messages are fetched and checked against the selected chat before any deletion;
126
+ a missing ID or a different chat aborts the operation. Duplicate IDs are removed. This check
127
+ is necessary because [Telethon does not validate the chat for deletion](https://docs.telethon.dev/en/stable/modules/client.html#telethon.client.messages.MessageMethods.delete_messages).
128
+ JSON success is `{ok:true,requested_ids:[...]}`: Telegram accepted the request, but does not
129
+ provide per-ID proof of deletion. Telegram determines permissions and message restrictions.
130
+ Large sets may use several server requests and partially succeed before a failure; an uncertain
131
+ network result is not proof that nothing was deleted. Deletion cannot be undone. Scheduled
132
+ messages still use `scheduled --cancel`, not `delete`.
76
133
 
77
134
  ## Extended history and automation
78
135
 
@@ -331,7 +388,9 @@ the CLI displays metadata. Deletion and inline media playback are not supported.
331
388
  | Command | Purpose |
332
389
  | --- | --- |
333
390
  | `tcli config` | Save or replace API credentials |
334
- | `tcli login` | Sign in to your personal account |
391
+ | `tcli login` | Sign in to a user account; add `--bot` for a bot |
392
+ | `tcli sessions --json` | List local named session files offline |
393
+ | `tcli delete CHAT ID [ID ...]` | Delete the selected messages for everyone |
335
394
  | `tcli chats --limit 100` | List up to 100 chats; default: 50 |
336
395
  | `tcli read "Chat" --limit 20` | Read recent messages; default: 20 |
337
396
  | `tcli send "Chat" "Text"` | Send one plain-text message |
@@ -483,12 +542,37 @@ Upload/download progress is enabled automatically when stderr is a terminal. `--
483
542
  it when redirected; `--no-progress` disables it. These flags apply to attachment sends and downloads.
484
543
  Progress includes transferred/total bytes, percentage, and average bytes per second; album upload
485
544
  progress is weighted by local file sizes. Updates are throttled to twice per second, plus completion.
545
+ Human output includes a bar such as `[##########----------] 50.0%`. In a terminal it redraws
546
+ in place; redirected output uses separate lines. Unknown sizes have an empty bar without a percentage.
486
547
  With `--json`, stderr receives JSONL events with `event="transfer_progress"`, `operation`, `file`,
487
548
  `transferred_bytes`, `total_bytes`, `percent` (null for unknown/zero size), and `bytes_per_second`.
488
549
  Errors are still JSON objects on stderr; distinguish them from progress by `ok=false`.
489
550
  Stdout contains only the final result. Progress measures transfer work, not confirmed delivery;
490
551
  cached uploads may produce no progress events.
491
552
 
553
+ ### Performance
554
+
555
+ Install the optional native encryption accelerator from a source checkout:
556
+
557
+ ```console
558
+ python -m pip install -e ".[fast]"
559
+ python scripts/benchmark_crypto.py
560
+ ```
561
+
562
+ Telethon automatically uses `cryptg` when installed, reducing encryption/decryption CPU work
563
+ without changing message handling. The offline benchmark compares the existing fallback with
564
+ cryptg on synthetic data and checks identical ciphertext and successful decryption; its speedup
565
+ is for AES only, not end-to-end Telegram throughput. The base installation remains usable without it.
566
+ See [Telethon's transfer FAQ](https://docs.telethon.dev/en/stable/quick-references/faq.html#file-download-is-slow-or-sending-files-takes-too-long).
567
+
568
+ For faster workflows, forward existing Telegram attachments instead of downloading and uploading
569
+ them again, use `--jsonl` for large history reads, and apply server-side date/sender/media filters
570
+ before filename matching. Keep filename scan bounds as small as the task allows. Disable progress
571
+ with `--no-progress` when measuring transfer speed. Avoid concurrent CLI processes on one session.
572
+ Parallel transfers need separate measurement and careful FloodWait handling; they are not enabled.
573
+ Resumable downloads already use Telethon's maximum default request size (512 KiB).
574
+ Plain text has no byte-transfer callback: the CLI reports the confirmed message ID after sending.
575
+
492
576
  ### Text formatting
493
577
 
494
578
  ```console
@@ -655,7 +739,8 @@ Increase `--limit` if your chat is not in the first page.
655
739
  **Telegram asks you to wait?** Wait for the reported FloodWait period.
656
740
  After a connection failure, check recent history before retrying a send to avoid duplicates.
657
741
 
658
- **Can I use a bot?** This CLI supports personal accounts only.
742
+ **Can I use a bot?** Yes: use a separate `--session NAME` and `login --bot`. See the capabilities
743
+ and restrictions under [Sessions, bots and deletion](#sessions-bots-and-deletion).
659
744
 
660
745
  **Can I still run the Python file?** Yes: `python tg.py ...` from the project root
661
746
  with dependencies installed uses the same commands.
@@ -1,25 +1,3 @@
1
- Metadata-Version: 2.4
2
- Name: telegram-cli-local
3
- Version: 0.3.0
4
- Summary: Telegram CLI for a personal account
5
- Author: BYxarek
6
- License-Expression: Apache-2.0
7
- Project-URL: Repository, https://github.com/BYxarek/telegram-cli
8
- Project-URL: Issues, https://github.com/BYxarek/telegram-cli/issues
9
- Keywords: telegram,cli,telethon,agent-skills
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: Programming Language :: Python :: 3 :: Only
16
- Classifier: Topic :: Communications :: Chat
17
- Requires-Python: >=3.10
18
- Description-Content-Type: text/markdown
19
- License-File: LICENSE
20
- Requires-Dist: Telethon==1.45.0
21
- Dynamic: license-file
22
-
23
1
  <div align="center">
24
2
 
25
3
  # tcli · Telegram in your terminal
@@ -50,8 +28,8 @@ tcli watch "Work chat" # Follow new messages
50
28
  ```
51
29
 
52
30
  `tcli` is a local Python CLI built with [Telethon](https://docs.telethon.dev/).
53
- It uses the Telegram API and acts as your personal account. You need your own
54
- `API_ID` and `API_HASH`; no bot token is used.
31
+ It uses Telegram's MTProto API with a personal account or a bot. Both modes require your own
32
+ `API_ID` and `API_HASH`; bot login additionally requires a BotFather token.
55
33
 
56
34
  ## Features
57
35
 
@@ -71,8 +49,63 @@ are removed from displayed messages.
71
49
 
72
50
  ### Current scope
73
51
 
74
- One local account session, text and attachments, human-readable output, and optional JSON.
75
- Message deletion and a full-screen interface are not available.
52
+ Named local user/bot sessions, text and attachments, message deletion, human-readable output,
53
+ and optional JSON. A full-screen interface is not available.
54
+
55
+ ## Sessions, bots and deletion
56
+
57
+ ```console
58
+ tcli config
59
+ tcli --session work login
60
+ tcli --session assistant login --bot
61
+ tcli sessions --json
62
+ tcli --session work delete me 123 124 --json
63
+ tcli --session assistant send @example_channel "Status update"
64
+ tcli --session assistant watch @example_channel --edits --json
65
+ ```
66
+
67
+ Examples are placeholders; do not execute sends or deletes without explicit authorization.
68
+ `--session NAME` can precede or follow the command. Names contain 1-32 lowercase ASCII
69
+ letters/digits, underscores or hyphens, starting with a letter/digit; Windows device names
70
+ are rejected. `default` keeps the existing `account.session`. Other sessions live under
71
+ `sessions/NAME/account.session` in the same local data directory. API configuration is shared;
72
+ `config` updates it for all sessions. `sessions` lists local file presence offline, not account
73
+ identity or authorization. `doctor --connect` shows the selected account type. `logout` revokes
74
+ only the selected session. Use different session names for different accounts, and avoid
75
+ concurrent processes on the same session. Choosing a new name does not copy existing authorization.
76
+
77
+ `login --bot` reads a token via hidden input or `TG_BOT_TOKEN`, only during login. It does not
78
+ store the token in config or accept it as a command-line argument. Existing authorized sessions
79
+ are reused; login never switches accounts in place. A different account type requires another
80
+ session name. Tokens and session files grant account access; never commit or share them.
81
+
82
+ | Operation | Bot session |
83
+ | --- | --- |
84
+ | Send text/files/albums, forward, edit outgoing messages | Supported, subject to Telegram access and posting permissions |
85
+ | Delete specific IDs | Supported within Telegram permissions; deleting others' messages may require admin rights |
86
+ | `read --id`, `thread`, single `download` including `--resume`, `info` | Supported for accessible known messages/chats; Telegram may reject requests |
87
+ | `watch`, `watch --edits` | Live MTProto events only; no history polling or replay guarantee after downtime |
88
+ | `chats`, history reads/search/export, `pinned`, `topics`, `scheduled`, `send --schedule`, album/batch download | Rejected with `bot_unsupported` in this CLI |
89
+ | Chat selectors | Known numeric ID or `@username`; titles and `me` are rejected |
90
+
91
+ A bot has no Saved Messages and cannot initiate private conversations with arbitrary users:
92
+ the user must first contact it or add it to a group. Groups/channels must grant the necessary
93
+ rights. Group privacy mode affects incoming updates. A numeric peer must already be known to
94
+ the selected session, usually from an update; a raw ID alone does not supply an access hash.
95
+ This uses Telethon/MTProto, not the HTTP Bot API; HTTP Bot API file-size limits are not CLI limits.
96
+ See [Telegram's bot FAQ](https://core.telegram.org/bots/faq),
97
+ [history restriction](https://core.telegram.org/method/messages.getHistory), and
98
+ [known-message retrieval](https://core.telegram.org/method/messages.getMessages).
99
+
100
+ `delete CHAT ID [ID ...]` deletes for everyone (`revoke=True`), without an extra prompt.
101
+ All requested messages are fetched and checked against the selected chat before any deletion;
102
+ a missing ID or a different chat aborts the operation. Duplicate IDs are removed. This check
103
+ is necessary because [Telethon does not validate the chat for deletion](https://docs.telethon.dev/en/stable/modules/client.html#telethon.client.messages.MessageMethods.delete_messages).
104
+ JSON success is `{ok:true,requested_ids:[...]}`: Telegram accepted the request, but does not
105
+ provide per-ID proof of deletion. Telegram determines permissions and message restrictions.
106
+ Large sets may use several server requests and partially succeed before a failure; an uncertain
107
+ network result is not proof that nothing was deleted. Deletion cannot be undone. Scheduled
108
+ messages still use `scheduled --cancel`, not `delete`.
76
109
 
77
110
  ## Extended history and automation
78
111
 
@@ -331,7 +364,9 @@ the CLI displays metadata. Deletion and inline media playback are not supported.
331
364
  | Command | Purpose |
332
365
  | --- | --- |
333
366
  | `tcli config` | Save or replace API credentials |
334
- | `tcli login` | Sign in to your personal account |
367
+ | `tcli login` | Sign in to a user account; add `--bot` for a bot |
368
+ | `tcli sessions --json` | List local named session files offline |
369
+ | `tcli delete CHAT ID [ID ...]` | Delete the selected messages for everyone |
335
370
  | `tcli chats --limit 100` | List up to 100 chats; default: 50 |
336
371
  | `tcli read "Chat" --limit 20` | Read recent messages; default: 20 |
337
372
  | `tcli send "Chat" "Text"` | Send one plain-text message |
@@ -483,12 +518,37 @@ Upload/download progress is enabled automatically when stderr is a terminal. `--
483
518
  it when redirected; `--no-progress` disables it. These flags apply to attachment sends and downloads.
484
519
  Progress includes transferred/total bytes, percentage, and average bytes per second; album upload
485
520
  progress is weighted by local file sizes. Updates are throttled to twice per second, plus completion.
521
+ Human output includes a bar such as `[##########----------] 50.0%`. In a terminal it redraws
522
+ in place; redirected output uses separate lines. Unknown sizes have an empty bar without a percentage.
486
523
  With `--json`, stderr receives JSONL events with `event="transfer_progress"`, `operation`, `file`,
487
524
  `transferred_bytes`, `total_bytes`, `percent` (null for unknown/zero size), and `bytes_per_second`.
488
525
  Errors are still JSON objects on stderr; distinguish them from progress by `ok=false`.
489
526
  Stdout contains only the final result. Progress measures transfer work, not confirmed delivery;
490
527
  cached uploads may produce no progress events.
491
528
 
529
+ ### Performance
530
+
531
+ Install the optional native encryption accelerator from a source checkout:
532
+
533
+ ```console
534
+ python -m pip install -e ".[fast]"
535
+ python scripts/benchmark_crypto.py
536
+ ```
537
+
538
+ Telethon automatically uses `cryptg` when installed, reducing encryption/decryption CPU work
539
+ without changing message handling. The offline benchmark compares the existing fallback with
540
+ cryptg on synthetic data and checks identical ciphertext and successful decryption; its speedup
541
+ is for AES only, not end-to-end Telegram throughput. The base installation remains usable without it.
542
+ See [Telethon's transfer FAQ](https://docs.telethon.dev/en/stable/quick-references/faq.html#file-download-is-slow-or-sending-files-takes-too-long).
543
+
544
+ For faster workflows, forward existing Telegram attachments instead of downloading and uploading
545
+ them again, use `--jsonl` for large history reads, and apply server-side date/sender/media filters
546
+ before filename matching. Keep filename scan bounds as small as the task allows. Disable progress
547
+ with `--no-progress` when measuring transfer speed. Avoid concurrent CLI processes on one session.
548
+ Parallel transfers need separate measurement and careful FloodWait handling; they are not enabled.
549
+ Resumable downloads already use Telethon's maximum default request size (512 KiB).
550
+ Plain text has no byte-transfer callback: the CLI reports the confirmed message ID after sending.
551
+
492
552
  ### Text formatting
493
553
 
494
554
  ```console
@@ -655,7 +715,8 @@ Increase `--limit` if your chat is not in the first page.
655
715
  **Telegram asks you to wait?** Wait for the reported FloodWait period.
656
716
  After a connection failure, check recent history before retrying a send to avoid duplicates.
657
717
 
658
- **Can I use a bot?** This CLI supports personal accounts only.
718
+ **Can I use a bot?** Yes: use a separate `--session NAME` and `login --bot`. See the capabilities
719
+ and restrictions under [Sessions, bots and deletion](#sessions-bots-and-deletion).
659
720
 
660
721
  **Can I still run the Python file?** Yes: `python tg.py ...` from the project root
661
722
  with dependencies installed uses the same commands.
@@ -27,8 +27,8 @@ tcli watch 'Рабочий чат'
27
27
  ```
28
28
 
29
29
  `tcli` — небольшой локальный клиент на Python и [Telethon](https://docs.telethon.dev/).
30
- Он использует Telegram API и действует от вашего имени. Для работы нужны личный
31
- Telegram-аккаунт и собственные `API_ID` / `API_HASH`.
30
+ Он использует Telegram MTProto API с личным аккаунтом или ботом. В обоих режимах нужны
31
+ собственные `API_ID` / `API_HASH`; для входа ботом также требуется токен BotFather.
32
32
 
33
33
  ## Возможности
34
34
 
@@ -48,8 +48,64 @@ Telegram-аккаунт и собственные `API_ID` / `API_HASH`.
48
48
 
49
49
  ### Текущие ограничения
50
50
 
51
- Поддерживаются текст, вложения и одна локальная сессия аккаунта.
52
- Нет удаления сообщений и полноэкранного интерфейса.
51
+ Поддерживаются текст, вложения, удаление сообщений и именованные сессии пользователей и ботов.
52
+ Полноэкранного интерфейса нет.
53
+
54
+ ## Сессии, боты и удаление сообщений
55
+
56
+ ```console
57
+ tcli config
58
+ tcli --session work login
59
+ tcli --session assistant login --bot
60
+ tcli sessions --json
61
+ tcli --session work delete me 123 124 --json
62
+ tcli --session assistant send @example_channel "Обновление статуса"
63
+ tcli --session assistant watch @example_channel --edits --json
64
+ ```
65
+
66
+ Получатели и ID в примерах условные. Отправка и удаление требуют явного поручения пользователя.
67
+ `--session ИМЯ` можно ставить перед командой или после неё. Имя: 1-32 строчные латинские буквы,
68
+ цифры, `_` или `-`, первый символ — буква или цифра; зарезервированные имена Windows запрещены.
69
+ Сессия `default` сохраняет прежний `account.session`. Остальные хранятся в
70
+ `sessions/ИМЯ/account.session` внутри каталога данных CLI. API-настройки общие: `config` меняет
71
+ их для всех сессий. `sessions` без сети показывает наличие файлов, а не личность или авторизацию.
72
+ `doctor --connect` показывает тип аккаунта. `logout` отзывает только выбранную сессию.
73
+ Для разных аккаунтов выбирайте разные имена; не запускайте одновременно несколько процессов
74
+ с одной сессией. Новое имя не копирует авторизацию старой сессии.
75
+
76
+ `login --bot` принимает токен скрытым вводом или из `TG_BOT_TOKEN` только при входе.
77
+ Токен не записывается в config и не передаётся аргументом командной строки. Для бота по-прежнему
78
+ нужны `API_ID` и `API_HASH`. Уже авторизованная сессия используется повторно; вход не заменяет
79
+ аккаунт внутри неё. При другом типе аккаунта требуется отдельное имя сессии.
80
+ Токены и файлы сессий дают доступ к аккаунту: не публикуйте и не коммитьте их.
81
+
82
+ | Операция | Работа через бота |
83
+ | --- | --- |
84
+ | Отправка текста, файлов и альбомов, пересылка, правка исходящих | Поддерживается с учётом доступа и права отправки |
85
+ | Удаление по ID | В пределах прав Telegram; для чужих сообщений могут требоваться права администратора |
86
+ | `read --id`, `thread`, одиночный `download`, включая `--resume`, `info` | Для доступных известных сообщений и чатов; сервер может отказать |
87
+ | `watch`, `watch --edits` | Только события MTProto, без опроса истории и гарантированного восстановления после простоя |
88
+ | `chats`, чтение/поиск/экспорт истории, `pinned`, `topics`, `scheduled`, `send --schedule`, скачивание альбомом/пакетом | В этом CLI отклоняются с `bot_unsupported` |
89
+ | Выбор чата | Известный числовой ID или `@username`; названия и `me` недоступны |
90
+
91
+ У бота нет Избранного. Он не может первым писать произвольному пользователю: пользователь должен
92
+ сначала обратиться к боту или добавить его в группу. В группах и каналах нужны соответствующие
93
+ права; privacy mode влияет на входящие события в группах. Числовой ID должен быть уже известен
94
+ выбранной сессии, например из события: сам ID не содержит access hash.
95
+ Используется Telethon/MTProto, а не HTTP Bot API; лимиты размера файлов HTTP Bot API не являются
96
+ лимитами CLI. Источники: [FAQ Telegram](https://core.telegram.org/bots/faq),
97
+ [ограничение истории](https://core.telegram.org/method/messages.getHistory),
98
+ [получение известных сообщений](https://core.telegram.org/method/messages.getMessages).
99
+
100
+ `delete ЧАТ ID [ID ...]` удаляет сообщения для всех (`revoke=True`) без дополнительного вопроса.
101
+ До удаления CLI получает все указанные сообщения и проверяет принадлежность выбранному чату.
102
+ Отсутствующий ID или другой чат прерывает операцию; повторы ID исключаются. Такая проверка нужна,
103
+ поскольку [Telethon сам не проверяет чат при удалении](https://docs.telethon.dev/en/stable/modules/client.html#telethon.client.messages.MessageMethods.delete_messages).
104
+ JSON-ответ `{ok:true,requested_ids:[...]}` означает принятие запроса сервером, а не отдельное
105
+ подтверждение каждого удалённого ID. Права и ограничения сообщений проверяет Telegram.
106
+ Большой список может обрабатываться несколькими запросами и частично выполниться до ошибки;
107
+ сетевой сбой не доказывает, что ничего не удалено. Отменить удаление нельзя.
108
+ Для отложенных сообщений используйте `scheduled --cancel`.
53
109
  Доступны ответы на сообщения и JSON-вывод для автоматизации.
54
110
 
55
111
  ## Расширенная история и автоматизация
@@ -309,7 +365,9 @@ tcli download me 123 --output photo.jpg
309
365
  | `tcli` / `tcli help` | Показывает общую справку, первые шаги и примеры |
310
366
  | `tcli help send` | Показывает справку по конкретной команде |
311
367
  | `tcli config` | Сохраняет или заменяет API-данные |
312
- | `tcli login` | Выполняет вход в личный аккаунт |
368
+ | `tcli login` | Вход в аккаунт пользователя; `--bot` для бота |
369
+ | `tcli sessions --json` | Список локальных именованных сессий без сети |
370
+ | `tcli delete CHAT ID [ID ...]` | Удаление выбранных сообщений для всех |
313
371
  | `tcli chats --limit 100` | Показывает до 100 чатов; по умолчанию — 50 |
314
372
  | `tcli read 'Чат' --limit 20` | Читает последние сообщения; по умолчанию — 20 |
315
373
  | `tcli send 'Чат' 'Текст'` | Отправляет текстовое сообщение |
@@ -464,6 +522,8 @@ tcli download me 123 --output archive.zip --progress --json
464
522
 
465
523
  Прогресс загрузки и скачивания включён автоматически, когда stderr подключён к терминалу.
466
524
  `--progress` включает его при перенаправлении, `--no-progress` отключает.
525
+ Текстовый вывод содержит полосу `[##########----------] 50.0%`: в терминале она обновляется
526
+ на месте, при перенаправлении — отдельными строками. При неизвестном размере процент не выводится.
467
527
  Флаги доступны для отправки вложений и скачивания. Выводятся переданные/общие байты,
468
528
  процент и средняя скорость в байтах в секунду. Прогресс отправки альбома учитывает размеры файлов.
469
529
  Обновления ограничены двумя в секунду, кроме завершения. С `--json` в stderr идут JSONL-события:
@@ -473,6 +533,30 @@ tcli download me 123 --output archive.zip --progress --json
473
533
  В stdout остаётся только итоговый результат. Прогресс передачи не подтверждает доставку;
474
534
  при использовании кэша события могут отсутствовать.
475
535
 
536
+ ### Производительность
537
+
538
+ Установка из исходников с нативным ускорителем шифрования:
539
+
540
+ ```console
541
+ python -m pip install -e ".[fast]"
542
+ python scripts/benchmark_crypto.py
543
+ ```
544
+
545
+ Telethon автоматически использует установленный `cryptg`, снижая нагрузку на процессор при
546
+ шифровании и расшифровке. Локальный бенчмарк сравнивает прежний механизм с cryptg на искусственных
547
+ данных, проверяет совпадение шифротекста и расшифровку. Коэффициент ускорения относится только
548
+ к AES, а не к скорости передачи через Telegram. Базовая установка работает и без ускорителя.
549
+ См. [рекомендации Telethon](https://docs.telethon.dev/en/stable/quick-references/faq.html#file-download-is-slow-or-sending-files-takes-too-long).
550
+
551
+ Для ускорения работы пересылайте существующие вложения через `forward`, используйте `--jsonl`
552
+ для большой истории и серверные фильтры даты, отправителя и типа медиа перед поиском по имени файла.
553
+ Ограничивайте объём сканирования необходимым минимумом. Для замера скорости отключайте вывод
554
+ через `--no-progress`. Избегайте одновременных процессов CLI с одной сессией.
555
+ Параллельные передачи требуют отдельных замеров и обработки FloodWait; они не включены.
556
+ Докачивание уже использует максимальный стандартный размер запроса Telethon — 512 КиБ.
557
+ У обычного текста нет callback с количеством переданных байтов: после отправки CLI показывает
558
+ подтверждённый ID сообщения.
559
+
476
560
  ### Оформление текста
477
561
 
478
562
  ```console
@@ -638,7 +722,8 @@ tests/ Проверки без реального аккаунт
638
722
  Если виртуальное окружение ссылается на удалённую установку, пересоздайте его и установите проект заново.
639
723
  Не скрывайте stderr: там также выводятся настоящие ошибки CLI.
640
724
 
641
- **Можно ли использовать бота?** Этот CLI предназначен для личного аккаунта. Вход ботом не поддерживается.
725
+ **Можно ли использовать бота?** Да: отдельная `--session ИМЯ` и `login --bot`.
726
+ Возможности и ограничения перечислены в разделе «Сессии, боты и удаление сообщений».
642
727
 
643
728
  **Почему чат не найден?** Используйте точное название, `@username` или ID из `tcli chats`.
644
729
  Если нужного диалога нет в списке, увеличьте `--limit`.