telethon 0.4.0 → 1.0.0

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: d08904d1aac89e8d7633511695c406ed1a7d8b1b758d151c554c6ca52cb8b01a
4
- data.tar.gz: e7315b01846877bc25438c51ae6c4e07578f3efa696e676596bce2009e372b9b
3
+ metadata.gz: 2f131aedb880401c8fa7958fd0802a2e9b51595bf64f1eca1e43ea17f4046a0f
4
+ data.tar.gz: c593f31d90ad9297182d2483a504072988e189165ce682306b4ffcfd6cdf4102
5
5
  SHA512:
6
- metadata.gz: 2520f8e02cbf18e124873f890f7272e63f2c81e0ccc097bc3ac41a847dabf78b525bd4f5f42414885dc3a5f93b8f721002a096b071bb028086984ec173ff0002
7
- data.tar.gz: 2fc45fd477f4a3a9199c1c2aff317b24d218af7a11021925b6c6b92598ecf327c940c395a17c70b4fce361d209dcdf3b3e88b3312443362bd7a8ed30c1a59442
6
+ metadata.gz: 58c033a56e4042b3a1278017cb9b07ddc1c3babae3a5a486c344c285ddc5ccdd0b7fcf9bc09df8c5c9c042dd4d2c81474e4ec5e2724d39fda128924fe5030cd2
7
+ data.tar.gz: e54ff6e8db9cc831c05c236702a40a1e03c45026d625cfc5d51624615788abc14c7acc097ed9bd6f4c005db1d90f84d5ba8f1e56c45ebf65975c8b6ff0b6a670
data/CHANGELOG.md CHANGED
@@ -7,6 +7,42 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.0.0] — 2026-12-02
11
+
12
+ The 1.0 release: milestones M7 and M8 of [the roadmap](docs/ROADMAP.md). The library has every public
13
+ Telethon client method, event and custom class (`rake parity`: 87 of 87), and its public API is now frozen
14
+ under Semantic Versioning (see [the library guide](docs/library.md)). `tg` covers what Telethon can do.
15
+
16
+ ### Added
17
+
18
+ - A complete `tg`: one command table (`lib/telethon/cli/table.rb`) drives option parsing, grouped
19
+ `tg --help`, `tg help COMMAND`, shell completion and the generated [docs/cli.md](docs/cli.md).
20
+ - Reading: `tg chats`, `info`, `listen`.
21
+ - Writing: `reply`, `pin`, `unpin`, `mark-read`, `react`, `draft`, `typing`, and `send` with
22
+ `--at`, `--album`, `--voice`, `--video-note` and `--media`.
23
+ - Chats: `members`, `admin`, `ban`, `kick`, `unban`, `permissions`, `admin-log`, `stats`, `join`,
24
+ `leave`, `archive`, `unarchive`, `delete-chat`, `profile-photos`.
25
+ - Account: `sessions` (and `--terminate`), `profile`.
26
+ - `tg call METHOD [JSON]` for any raw TL function, and `tg completion bash|zsh|fish`.
27
+ - `--json` on every command.
28
+ - Several accounts side by side: `tg --account NAME` (or `TG_ACCOUNT`) keeps each account in
29
+ `TG_HOME/accounts/NAME`; the account in `TG_HOME` itself stays the default. `--account` also takes an
30
+ account's `@username` or numeric id. `tg accounts` lists them; `tg accounts rename OLD NEW` renames one.
31
+ A new account reuses the default account's API id and hash.
32
+ - `TG_CONNECTION` picks `tg`'s transport (`tcp_full`, `tcp_abridged`, `tcp_intermediate`,
33
+ `tcp_obfuscated`, `tcp_obfuscated_intermediate`, `http`).
34
+ - Documentation in `docs/`: install, getting started, the CLI reference, the library guide (with
35
+ example tests), differences from Telethon, and troubleshooting.
36
+
37
+ ### Fixed
38
+
39
+ - The HTTP transport no longer hangs waiting for a result that Telegram sends in the answer to a later
40
+ request: it polls with `http_wait`.
41
+ - `tg send --file` sends files as documents again, as before 0.4.0's CLI work; `--media` sends photos
42
+ and videos as media.
43
+ - `tg sessions --terminate` asks before logging a session out, unless `--yes`.
44
+ - `tg` writes an account's directory, and any missing parent, readable only by its owner.
45
+
10
46
  ## [0.4.0] — 2026-12-01
11
47
 
12
48
  Milestones M3 to M6 of [the roadmap](docs/ROADMAP.md): `rake parity` now finds every public Telethon
data/README.md CHANGED
@@ -1,90 +1,62 @@
1
1
  # telethon.rb
2
2
 
3
- A Ruby port of [Telethon](https://codeberg.org/Lonami/Telethon), the Python MTProto client by Lonami,
4
- with a `tg` command line. It runs as a Telegram **user account**, so it can read history and delete
5
- messages of any age, which the Bot API can't.
6
-
7
- - Zero runtime dependencies; compiles to a standalone native binary with
8
- [Spinel](https://github.com/matz/spinel).
9
- - 100% of Telethon v1's client methods, events, and custom classes (`rake parity`), oracle-checked
10
- against Telethon itself — including bots (buttons, callbacks, inline queries, Bot API file ids),
11
- transports and proxies (SOCKS5, HTTP CONNECT, MTProxy), `MemorySession`/`StringSession`, takeout,
12
- auto-reconnect, and typed RPC errors.
13
- - API layer 234 (Telethon v1.46).
3
+ A Ruby port of [Telethon](https://codeberg.org/Lonami/Telethon) (v1.46, layer 234) with a complete `tg` CLI. It runs as a Telegram **user account** (or bot), so it can read history, manage chats, and delete messages of any age — things the Bot API cannot do.
4
+
5
+ - **Zero runtime dependencies:** ships as the `telethon` Ruby gem and as a standalone native `tg` binary compiled with [Spinel](https://github.com/matz/spinel).
6
+ - **100% Telethon v1 API surface (`rake parity`):** 64/64 client methods, 10/10 events, 13/13 custom classes, oracle-checked against Telethon itself.
7
+ - **Constant-memory file transfers:** streams 2 GB uploads and downloads under 192 MB peak RSS in both CRuby and native builds.
14
8
 
15
9
  ## Install
16
10
 
17
- The `tg` binary needs no Ruby. On macOS (Apple Silicon) and Linux (amd64 or arm64, any distro):
11
+ Install the standalone `tg` binary (macOS arm64, Linux amd64/arm64 static musl — no Ruby required):
18
12
 
19
13
  ```sh
20
14
  curl -fsSL https://raw.githubusercontent.com/shogi-dojo/telethon.rb/main/install.sh | sh
21
15
  ```
22
16
 
23
- It checks the download against the release's `SHA256SUMS` and puts `tg` in `~/.local/bin`
24
- (`sh -s -- --dir DIR` for elsewhere, `--version V` for an older release). The Linux binaries are
25
- static, so they run on Debian, Ubuntu, RHEL, Alpine and the like. The archives are also on the
26
- [releases page](https://github.com/shogi-dojo/telethon.rb/releases).
27
-
28
- The library is a gem:
17
+ Or install the Ruby gem (Ruby 3.2+):
29
18
 
30
19
  ```sh
31
20
  gem install telethon
32
21
  ```
33
22
 
34
- ## The `tg` command
35
-
36
- | Command | What it does |
37
- |---|---|
38
- | `tg login [--qr \| --bot-token]` | Log in: API id/hash, then phone + code, QR, or bot token |
39
- | `tg logout [--json]` | Log out and remove the saved session |
40
- | `tg 2fa set\|remove [--hint H] [--json]` | Set, change, or remove the 2FA password |
41
- | `tg import-session [FILE \| --string]` | Take over a Telethon `.session` or `StringSession` (via `TG_SESSION_STRING`/stdin) |
42
- | `tg export-session` | Print the current session as a Telethon `StringSession` (stdout only) |
43
- | `tg whoami` | The logged-in account |
44
- | `tg topics CHAT` | A forum's topics |
45
- | `tg read CHAT [--limit N] [--topic ID] [--json]` | Human-readable history |
46
- | `tg search [CHAT] QUERY [--from USER] [--filter KIND] [--limit N] [--json]` | Search messages in a chat or globally |
47
- | `tg export CHAT [--topic ID] [--limit N \| --all] [--before ID] [--out FILE]` | History as JSON |
48
- | `tg download CHAT ID... [--out DIR]` | Save those messages' attachments |
49
- | `tg delete CHAT ID... [--yes]` | Delete for everyone |
50
- | `tg send CHAT TEXT [--topic ID] [--file PATH ...]` | Post as the account |
51
- | `tg edit CHAT ID TEXT` | Replace a message's text |
52
- | `tg forward CHAT ID... [--from CHAT] [--delete-source]` | Forward without the "Forwarded from" header |
53
- | `tg inline BOT QUERY [--pick N] [--to CHAT] [--json]` | Query an inline bot (and optionally send result N) |
54
- | `tg click CHAT ID BUTTON [--json]` | Click a message's button by index or text |
55
-
56
- `CHAT` is a numeric id, a `@username`, or `me`. Only `login` and `2fa` prompt, so everything else works over
57
- `ssh`. The session lives in `$TG_HOME` (default `~/.config/tg`), owner-only: whoever can read it owns
58
- the account. Set `TG_PROXY` (`socks5://[user:pass@]host:port`, `http://...`, or `mtproxy://secret@host:port`)
59
- to connect through a proxy. Get an API id and hash at <https://my.telegram.org>.
60
-
61
- Exit codes: `0` ok, `1` failure, `2` usage error, `3` not logged in, `4` Telegram refused (RPC error), `5` connection failed.
62
-
63
- ## As a library
23
+ See [docs/install.md](docs/install.md) for installer flags, manual SHA-256 verification, and shell completion.
24
+
25
+ ## Quick start: `tg` CLI
26
+
27
+ ```sh
28
+ tg login --qr # log in once (stored owner-only in ~/.config/tg)
29
+ tg chats --limit 10 # list recent chats
30
+ tg read me --limit 5 # read Saved Messages
31
+ tg send me "hello from tg" --at +10m # send (or schedule) a message
32
+ tg call help.getNearestDc '{}' # call any raw layer 234 TL method as JSON
33
+ ```
34
+
35
+ Every command supports `--json` for scripts; `tg help COMMAND` prints full usage.
36
+
37
+ ## Quick start: Ruby library
64
38
 
65
39
  ```ruby
66
40
  require "telethon"
67
41
 
68
- session = Telethon::Session.new(File.expand_path("~/.config/tg"))
69
- client = Telethon::Client.new(session, api_id: 12345, api_hash: "...")
42
+ client = Telethon::Client.new(File.expand_path("~/.config/tg"), api_id: 12345, api_hash: "0123456789abcdef0123456789abcdef")
70
43
  client.connect
71
-
72
- client.iter_messages("@telegram", limit: 10) { |m| puts "#{m.sender_id}: #{m.text}" }
44
+ client.iter_messages("@example_channel", limit: 10) { |m| puts "#{m.id}: #{m.text}" }
73
45
  client.send_message("me", "**bold** and __italic__")
74
- client.send_file("me", ["a.jpg", "b.jpg"], caption: ["first", "second"])
75
-
76
- client.on(Telethon::Events::NewMessage.new(pattern: /\A\/start/)) { |e| e.reply("hello") }
46
+ client.on(Telethon::Events::NewMessage.new(pattern: /\A\/ping\b/)) { |e| e.reply("pong") }
77
47
  client.run_until_disconnected
78
48
  ```
79
49
 
80
- The API follows Telethon's names and arguments, so its [docs](https://docs.telethon.dev) apply.
81
- Where the port differs, [DEVELOPING.md](DEVELOPING.md) says so. Any layer function can be called
82
- with `client.call(Telethon::TL.make("messages.getHistory", ...))`.
83
-
84
- ## Development
50
+ ## Documentation
85
51
 
86
- `rake test` runs the tests under CRuby, `spin test` natively; `rake oracle` regenerates the fixtures
87
- from Telethon itself. See [DEVELOPING.md](DEVELOPING.md).
52
+ - [Documentation Index](docs/README.md)
53
+ - [Installation](docs/install.md)
54
+ - [Getting Started](docs/getting-started.md)
55
+ - [`tg` CLI Reference](docs/cli.md) (45 commands, generated from the command table)
56
+ - [Ruby Library Guide](docs/library.md) (with frozen 1.0 API surface)
57
+ - [Differences from Python Telethon](docs/telethon-differences.md)
58
+ - [Troubleshooting](docs/troubleshooting.md)
59
+ - [Roadmap](docs/ROADMAP.md) and [Developing](DEVELOPING.md)
88
60
 
89
61
  ## License
90
62
 
@@ -69,6 +69,39 @@ module Telethon
69
69
 
70
70
  value.to_i
71
71
  end
72
+
73
+ # Parses a Unix timestamp, relative offset (+30s, +10m, +2h, +1d), or ISO-8601 date/time.
74
+ def parse_time(value, what = "time")
75
+ raw = value.to_s.strip
76
+ return raw.to_i if raw.match?(/\A\d+\z/)
77
+
78
+ if (m = raw.match(/\A\+(\d+)([smhd])\z/i))
79
+ mult = case m[2].downcase
80
+ when "s" then 1
81
+ when "m" then 60
82
+ when "h" then 3600
83
+ else 86_400
84
+ end
85
+ return Time.now.to_i + (m[1].to_i * mult)
86
+ end
87
+
88
+ if (m = raw.match(/\A(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2}))?)?(Z|[+-]\d{2}:?\d{2})?\z/))
89
+ offset = 0
90
+ tz = m[7]
91
+ if tz && tz != "Z"
92
+ sign = tz.start_with?("-") ? -1 : 1
93
+ digits = tz[1..].delete(":")
94
+ offset = sign * ((digits[0, 2].to_i * 3600) + (digits[2, 2].to_i * 60))
95
+ end
96
+ begin
97
+ return Time.utc(m[1].to_i, m[2].to_i, m[3].to_i, m[4].to_i, m[5].to_i, m[6].to_i).to_i - offset
98
+ rescue ArgumentError
99
+ # fall through to UsageError
100
+ end
101
+ end
102
+
103
+ raise UsageError, "invalid #{what}: #{value} (use ISO-8601, Unix timestamp, or +10m/+2h/+1d)"
104
+ end
72
105
  end
73
106
  end
74
107
  end
@@ -0,0 +1,182 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Telethon
4
+ module CLI
5
+ # Builds any TL layer function call from JSON arguments (resolving peer strings and decoding base64 bytes)
6
+ # and converts TL responses back into plain JSON-compatible Ruby values.
7
+ module Call
8
+ BASE64_RE = %r{\A[A-Za-z0-9+/=_-]*\z}
9
+
10
+ module_function
11
+
12
+ def build_request(method_name, json_text, client)
13
+ ctor = TL.schema.named(method_name)
14
+ unless ctor && ctor.function
15
+ raise UsageError, "unknown TL method #{method_name.inspect} in layer #{TL::LAYER}"
16
+ end
17
+
18
+ raw = parse_json_object(json_text)
19
+ build_object(ctor, raw, client)
20
+ end
21
+
22
+ def parse_json_object(json_text)
23
+ text = json_text.nil? || json_text.empty? ? "{}" : json_text
24
+ parsed = begin
25
+ JSON.parse(text)
26
+ rescue JSON::ParserError => e
27
+ raise UsageError, "invalid JSON arguments: #{e.message}"
28
+ end
29
+ raise UsageError, "JSON arguments must be an object ({...})" unless parsed.is_a?(Hash)
30
+
31
+ parsed
32
+ end
33
+
34
+ def build_object(ctor, hash, client)
35
+ param_map = {}
36
+ ctor.params.each { |p| param_map[p.name] = p unless p.flags? }
37
+
38
+ hash.each_key do |key|
39
+ raise UsageError, "unknown field #{key.inspect} for #{ctor.name}" unless param_map.key?(key)
40
+ end
41
+
42
+ fields = {}
43
+ ctor.params.each do |param|
44
+ next if param.flags?
45
+
46
+ where = "#{ctor.name}.#{param.name}"
47
+ if hash.key?(param.name) && !hash[param.name].nil?
48
+ fields[param.name] = coerce(param.type, hash[param.name], where, client)
49
+ elsif !param.optional? && param.type != "true"
50
+ fields[param.name] = default_value(param, where, client)
51
+ end
52
+ end
53
+ TL.make(ctor.name, fields)
54
+ end
55
+
56
+ def default_value(param, where, client)
57
+ case param.type
58
+ when "int" then 0
59
+ when "long" then param.name == "random_id" ? client.random_id : 0
60
+ when "double" then 0.0
61
+ when "Bool" then false
62
+ when "string" then ""
63
+ when "bytes" then "".b
64
+ else
65
+ if param.type.start_with?("Vector<") || param.type.start_with?("vector<")
66
+ []
67
+ else
68
+ raise UsageError, "missing required field #{where} (#{param.type})"
69
+ end
70
+ end
71
+ end
72
+
73
+ def coerce(type, value, where, client)
74
+ case type
75
+ when "int", "long"
76
+ raise UsageError, "#{where} must be an integer" unless value.is_a?(Integer)
77
+
78
+ value
79
+ when "double"
80
+ raise UsageError, "#{where} must be a number" unless value.is_a?(Integer) || value.is_a?(Float)
81
+
82
+ value.to_f
83
+ when "Bool", "true"
84
+ value ? true : false
85
+ when "string"
86
+ value.to_s
87
+ when "bytes", "int128", "int256"
88
+ bytes = decode_base64(value, where)
89
+ if type == "int128" && bytes.bytesize != 16
90
+ raise UsageError, "#{where} must decode to 16 bytes"
91
+ elsif type == "int256" && bytes.bytesize != 32
92
+ raise UsageError, "#{where} must decode to 32 bytes"
93
+ end
94
+ bytes
95
+ when "InputPeer"
96
+ return client.get_input_entity(value) if value.is_a?(String) || value.is_a?(Integer)
97
+
98
+ coerce_object(value, type, where, client)
99
+ when "InputChannel"
100
+ if value.is_a?(String) || value.is_a?(Integer)
101
+ peer = client.get_input_entity(value)
102
+ unless Client.entity_type(peer) == :channel
103
+ raise UsageError, "#{where}: #{value.inspect} is not a channel"
104
+ end
105
+ return TL.make("inputChannel", "channel_id" => peer["channel_id"], "access_hash" => peer["access_hash"])
106
+ end
107
+ coerce_object(value, type, where, client)
108
+ when "InputUser"
109
+ if value.is_a?(String) || value.is_a?(Integer)
110
+ peer = client.get_input_entity(value)
111
+ begin
112
+ return Client.input_user(peer)
113
+ rescue Error => e
114
+ raise UsageError, "#{where}: #{e.message}"
115
+ end
116
+ end
117
+ coerce_object(value, type, where, client)
118
+ else
119
+ if type.start_with?("Vector<") || type.start_with?("vector<")
120
+ raise UsageError, "#{where} must be a JSON array" unless value.is_a?(Array)
121
+
122
+ inner = type[7, type.size - 8]
123
+ value.map { |item| coerce(inner, item, where, client) }
124
+ else
125
+ coerce_object(value, type, where, client)
126
+ end
127
+ end
128
+ end
129
+
130
+ def coerce_object(value, expected_type, where, client)
131
+ if value.is_a?(String)
132
+ ctor = TL.schema.named(value)
133
+ raise UsageError, "#{where}: unknown TL constructor #{value.inspect}" unless ctor && !ctor.function
134
+
135
+ return build_object(ctor, {}, client)
136
+ end
137
+ raise UsageError, "#{where} must be a JSON object with \"_\" constructor name" unless value.is_a?(Hash)
138
+
139
+ name = value["_"] || (TL.bare?(expected_type) ? expected_type : nil)
140
+ raise UsageError, "#{where} is missing \"_\" constructor name" unless name.is_a?(String)
141
+
142
+ ctor = TL.schema.named(name)
143
+ raise UsageError, "#{where}: unknown TL constructor #{name.inspect}" unless ctor
144
+
145
+ fields = {}
146
+ value.each { |k, v| fields[k] = v unless k == "_" }
147
+ build_object(ctor, fields, client)
148
+ end
149
+
150
+ def decode_base64(value, where)
151
+ raise UsageError, "#{where} must be a base64 string" unless value.is_a?(String)
152
+
153
+ cleaned = value.delete(" \t\r\n")
154
+ raise UsageError, "#{where} is not valid base64" unless cleaned.match?(BASE64_RE)
155
+
156
+ std = cleaned.tr("-_", "+/")
157
+ pad = (4 - (std.bytesize % 4)) % 4
158
+ std = "#{std}#{'=' * pad}" if pad.positive?
159
+ std.unpack1("m0")
160
+ end
161
+
162
+ def to_json_value(value)
163
+ case value
164
+ when TL::Object
165
+ out = { "_" => value.name }
166
+ value.fields.each { |k, v| out[k] = to_json_value(v) }
167
+ out
168
+ when Array
169
+ value.map { |v| to_json_value(v) }
170
+ when String
171
+ if value.encoding == Encoding::BINARY || !value.valid_encoding?
172
+ [value].pack("m0")
173
+ else
174
+ value
175
+ end
176
+ else
177
+ value
178
+ end
179
+ end
180
+ end
181
+ end
182
+ end