telethon 0.1.0 → 0.2.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.
Files changed (44) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +96 -0
  3. data/README.md +103 -8
  4. data/lib/telethon/cli/commands.rb +25 -20
  5. data/lib/telethon/client/auth.rb +22 -1
  6. data/lib/telethon/client/chats.rb +577 -0
  7. data/lib/telethon/client/dialogs.rb +211 -0
  8. data/lib/telethon/client/downloads.rb +659 -0
  9. data/lib/telethon/client/entities.rb +50 -2
  10. data/lib/telethon/client/files.rb +341 -192
  11. data/lib/telethon/client/messages.rb +264 -40
  12. data/lib/telethon/client/updates.rb +407 -0
  13. data/lib/telethon/client.rb +119 -31
  14. data/lib/telethon/crypto/rsa.rb +81 -5
  15. data/lib/telethon/custom/admin_log_event.rb +133 -0
  16. data/lib/telethon/custom/conversation.rb +358 -0
  17. data/lib/telethon/custom/dialog.rb +144 -0
  18. data/lib/telethon/custom/file.rb +130 -0
  19. data/lib/telethon/custom/forward.rb +63 -0
  20. data/lib/telethon/custom/getters.rb +152 -0
  21. data/lib/telethon/custom/participant_permissions.rb +100 -0
  22. data/lib/telethon/errors.rb +12 -0
  23. data/lib/telethon/events/album.rb +108 -0
  24. data/lib/telethon/events/chat_action.rb +212 -0
  25. data/lib/telethon/events/common.rb +173 -0
  26. data/lib/telethon/events/message_deleted.rb +119 -0
  27. data/lib/telethon/events/new_message.rb +176 -0
  28. data/lib/telethon/events/raw.rb +35 -0
  29. data/lib/telethon/events/user_update.rb +129 -0
  30. data/lib/telethon/extensions/html.rb +373 -0
  31. data/lib/telethon/extensions/markdown.rb +116 -0
  32. data/lib/telethon/extensions/text.rb +171 -0
  33. data/lib/telethon/message.rb +423 -0
  34. data/lib/telethon/mime.rb +1930 -0
  35. data/lib/telethon/mime_guess.rb +54 -0
  36. data/lib/telethon/network/authenticator.rb +5 -4
  37. data/lib/telethon/network/sender.rb +7 -0
  38. data/lib/telethon/private_files.rb +25 -0
  39. data/lib/telethon/session.rb +18 -0
  40. data/lib/telethon/tl/object.rb +4 -0
  41. data/lib/telethon/updates/message_box.rb +481 -0
  42. data/lib/telethon/version.rb +1 -1
  43. data/lib/telethon.rb +25 -0
  44. metadata +26 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 5607a36bd3fbc7d666e096d87c2e4b27afd11a6094dd7b0543b08f34f3f21b33
4
- data.tar.gz: 6112f30ab2b1828057dcf93bb4fda8795da297e0024fe9a6301d7d0ae3246aca
3
+ metadata.gz: d52c2f704368e359d11abd5fafa5e1ff7385a94322c6c837f530955813954f38
4
+ data.tar.gz: 8af90ee3b7073ea948d0bf682882dbb3a1d09b8fff4847183de1c32123c51751
5
5
  SHA512:
6
- metadata.gz: 605c58ae8407a5f20d65d9025ed27329280f4893db0f5320a9ca89ce4333161419ab65b3cc58a5c487a939e51964fd1f6e4626e7940f163f0601723d58f3a848
7
- data.tar.gz: 88ba8e5a1977c16267e18a8ab593e316fe2acd28fdf2d4db4e285d8be1e19ef3d0e1ad885e0657a82ec1a4aaeefa015298596a310dc428582d5ee3a2556ab052
6
+ metadata.gz: cbcb552233be4e1c1f6b27cd1cdcfc9246987c3ad6abfdcb23cc7ba94a363fa379d4f402fffcc1933b4955c95ee9efd07c128640f4bb0fcde79500c2f6ec6ee6
7
+ data.tar.gz: d26af10ffd68fd176a3fcf4b1839a85ebbc5f2963a2dfee6ad4db81248814c4b8642efd5616bfdf4a7b8cba26d2b7842c0e69c4b31ad295ce3c09a086ffe784b
data/CHANGELOG.md CHANGED
@@ -7,6 +7,102 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.2.0] — 2026-11-30
11
+
12
+ ### Fixed
13
+
14
+ - A stripped thumbnail downloads as a JPEG (Telethon's header and footer around it), not as the raw
15
+ stripped bytes.
16
+
17
+ ### Added
18
+
19
+ - Updates and events. `Telethon::Updates::MessageBox` is Telethon's: pts, qts and seq per account and
20
+ channel, possible gaps, `updates.getDifference` and `updates.getChannelDifference`, with the state
21
+ saved in `session.json`. `Client#on`, `add_event_handler`, `remove_event_handler`,
22
+ `list_event_handlers`, `catch_up`, `run_until_disconnected` and `step_updates` run handlers in one
23
+ thread, one update at a time, with a ping and a save once a minute. The events are `Raw`,
24
+ `NewMessage`, `MessageEdited`, `MessageDeleted`, `MessageRead`, `ChatAction`, `UserUpdate` and
25
+ `Album`, with Telethon's filters (`chats`, `blacklist_chats`, `incoming`, `outgoing`, `from_users`,
26
+ `forwards`, `pattern`, `func`) and `StopPropagation`.
27
+ - `Telethon::Message`: a message with its client, and `respond`, `reply`, `edit`, `delete`, `forward_to`
28
+ and `get_reply_message`.
29
+ - Client methods take a marked chat id as well as an entity.
30
+ - Telethon's parse modes: `Telethon::Markdown` and `Telethon::HTML`, both ways, with entity offsets in
31
+ UTF-16 units. `send_message`, `edit_message` and `send_file` captions read markdown by default, as
32
+ Telethon does (and so `tg send` and `tg edit` do again, as `tg.py` did); `Client.new(parse_mode:)`
33
+ and `client.parse_mode=` take `"markdown"`, `"html"` or `nil`, and each call takes `parse_mode:` and
34
+ `formatting_entities:`. Mentions written as `tg://user?id=N` links become mention entities.
35
+ - Telethon's custom objects: `Message` with all of Telethon's properties (`text` in the parse mode,
36
+ `file`, `photo`, `document`, `audio`, `voice`, `video`, `gif`, `sticker`, `geo`, `poll`, `forward`,
37
+ `reply_to_chat`, `action_entities`, `get_entities_text`, ...) and actions (`download_media`,
38
+ `mark_read`, `pin`, `unpin`); `FileInfo` (Telethon's `File`), `Forward`, `Dialog` and `Draft`.
39
+ - `get_input_entity`, `pin_message`, `unpin_message` and `send_read_acknowledge`.
40
+ - Dialogs: `iter_dialogs` and `get_dialogs` (paged, with `offset_date`, `folder`, `archived`,
41
+ `ignore_pinned`, `ignore_migrated`), `iter_drafts` and `get_drafts`, `edit_folder`, `delete_dialog`,
42
+ and `conversation` (`Telethon::Conversation`: `send_message`, `send_file`, `get_response`,
43
+ `get_reply`, `get_edit`, `wait_read`, `wait_event`, `mark_read`, `cancel`).
44
+ - Chats: `iter_participants` and `get_participants` (search, filters, each user's `participant`),
45
+ `iter_admin_log` and `get_admin_log` (`Telethon::AdminLogEvent`), `iter_profile_photos` and
46
+ `get_profile_photos`, `action` (typing and the other chat actions, `Telethon::ChatAction`),
47
+ `edit_admin`, `edit_permissions`, `kick_participant`, `get_permissions`
48
+ (`Telethon::ParticipantPermissions`), `get_stats` (on the data center that keeps them) and `is_bot`.
49
+ - `get_*` answer a `Telethon::TotalList`: the results, and `total`, how many there are in all.
50
+ - Files, as Telethon has them. `download_media` saves into a directory, a path, an IO or `:bytes`,
51
+ takes `thumb:` (an index, a size type or a size) and `progress_callback:`, saves contacts as vCards,
52
+ link previews' documents and photos and a chat photo change's photo, refreshes an expired file
53
+ reference from its message, follows `FILE_MIGRATE` and retries a timeout once. New:
54
+ `download_file`, `iter_download` (offset, stride, limit, chunk and request sizes),
55
+ `download_profile_photo` and `Client.stripped_photo_to_jpg`. `upload_file` takes `part_size_kb`,
56
+ `file_name`, `progress_callback`, `key` and `iv`, and IO objects. `send_file` sends http(s) URLs, IO,
57
+ uploaded files and media sent before; adds video, round-video and voice attributes, `attributes`,
58
+ `mime_type`, `thumb`, `ttl`, `silent`, `background`, `schedule`, `clear_draft`, `formatting_entities`,
59
+ `send_as` and `message_effect_id`; and sends a list as albums of ten, a caption per file.
60
+ - CDN downloads, as https://core.telegram.org/cdn specifies them: an auth key of its own on the CDN
61
+ (with the CDN's RSA keys), AES-256-CTR, every part checked against the file's hashes, and reuploads.
62
+ - `client.random_source=`, for tests that need the same random ids every run.
63
+ - Layer 234's communities are addressed as channels, as Telethon does.
64
+ - `rake oracle` also writes `test/fixtures/telethon_files.rb` (each file method's requests, answers,
65
+ written files and progress, by Telethon), which `test/files_parity_test.rb` replays, and
66
+ `lib/telethon/mime.rb` (Python's mimetypes tables with Telethon's own types).
67
+ - `rake oracle` also writes `test/fixtures/telethon_chats.rb` (each dialog and chat method's requests
68
+ and answers, by Telethon, for scripted Telegram answers), which `test/chats_parity_test.rb` replays.
69
+ - `rake oracle` also writes `test/fixtures/telethon_objects.rb` (the parse modes, custom objects and
70
+ client calls, by Telethon), which `test/objects_parity_test.rb` replays.
71
+ - `rake oracle` also writes `test/fixtures/telethon_updates.rb`, the trace of Telethon's own message
72
+ box and event builders on fixed inputs, which `test/updates_parity_test.rb` replays.
73
+
74
+ ### Changed
75
+
76
+ - `send_file(entity, file)` takes one file as Telethon does, and a list as albums (one file in a list
77
+ is an album of one); it answers a `Message`, or the `Message`s for a list. Uploads go in Telethon's
78
+ part sizes (128 KB below 100 MB, not 512 KB).
79
+ - `download_media(message, file = nil, thumb:, progress_callback:)` and `Message#download_media` take
80
+ Telethon's arguments; a path that is a file is overwritten, as in Telethon. Downloads name files
81
+ as Telethon does: only audio and voice notes have a kind of their own (videos and stickers are
82
+ `document_...`), and an audio file is named "performer - title" only when it has both.
83
+ - Mime types and extensions come from Python's mimetypes tables with Telethon's additions, which
84
+ `Message#file.ext` uses too (`.tgs`, `audio/m4a`, `video/avi`... were missing).
85
+
86
+ - `iter_messages` yields `Message`s (the sender is `message.sender`), and `get_messages` answers them.
87
+ `send_message`, `edit_message`, `forward_messages`, `send_file` and `pin_message` answer the sent
88
+ `Message`s, not their ids. `Message#[]` still reads the TL fields.
89
+ - `get_me` stores the account's id in the session when it lacks one (an imported Telethon session),
90
+ and whether the account is a bot.
91
+ - `get_entity` takes an entity or an input peer as well, and asks Telegram for it, as Telethon does.
92
+ - A `Message` that no client was given has no `text`, as in Telethon.
93
+ - One call or read on the connection at a time, so a chat action's thread can call while the program
94
+ does.
95
+
96
+ ### Fixed (compared with Telethon)
97
+
98
+ - A difference's `other_updates` reach the handlers. Telethon drops every one with a pts, so an edit or
99
+ deletion that only `catch_up` brings never reached a handler.
100
+ - The no-updates deadlines reset when updates arrive, and a channel's deletions move the channel's pts.
101
+ - `edit_admin` in a basic group without `is_admin` works (Telethon's raises on Python 3.13+), a basic
102
+ group's participants stop at `limit`, and `Conversation#wait_read` resolves when the message is read.
103
+
104
+ ## [0.1.0] — 2026-11-29
105
+
10
106
  ### Added
11
107
 
12
108
  - MTProto crypto: AES-256-IGE and CTR, SHA-512 and PBKDF2-HMAC-SHA512, big-integer math on byte
data/README.md CHANGED
@@ -4,15 +4,19 @@ A Ruby port of [Telethon](https://codeberg.org/Lonami/Telethon), the Python MTPr
4
4
  Lonami, with a `tg` command line. It logs in as a Telegram **user account** (not a bot), so it can
5
5
  read chat history and delete messages of any age, which the Bot API can't.
6
6
 
7
- It is a port of the parts of Telethon a user-account CLI needs, not all of it. The original, and its
8
- full documentation, is at <https://codeberg.org/Lonami/Telethon> (docs: <https://docs.telethon.dev>).
7
+ It ports most of Telethon v1 (about 82% of its code, 49 of its 58 client methods): everything but bots
8
+ (buttons, inline queries, callback queries), the other transports and proxies, SQLite and string
9
+ sessions, takeout, `log_out` and `edit_2fa`. The original, and its full documentation, is at
10
+ <https://codeberg.org/Lonami/Telethon> (docs: <https://docs.telethon.dev>).
9
11
 
10
12
  - Pure Ruby, zero runtime dependencies (the standard library's `openssl`, `socket`, `zlib`, `json`).
11
13
  - Also compiles to a standalone native binary with [Spinel](https://github.com/matz/spinel), matz's
12
14
  Ruby AOT compiler. The binary links nothing but the system C library.
13
15
  - API layer 234, the schema of Telethon v1.46.
14
16
 
15
- Status: 0.1.0, unreleased. Checked byte for byte against Telethon (see "Tested against Telethon").
17
+ Status: 0.2.0 is on [RubyGems](https://rubygems.org/gems/telethon), and `tg` binaries for macOS and
18
+ Linux are on the [releases page](https://github.com/shogi-dojo/telethon.rb/releases). Checked against
19
+ Telethon itself (see "Tested against Telethon").
16
20
 
17
21
  ## The `tg` command
18
22
 
@@ -49,20 +53,96 @@ session = Telethon::Session.new(File.expand_path("~/.config/tg"))
49
53
  client = Telethon::Client.new(session, api_id: 12345, api_hash: "...")
50
54
  client.connect
51
55
  chat = client.get_entity("@telegram")
52
- client.iter_messages(chat, limit: 10) { |message, sender| puts message["message"] }
56
+ client.iter_messages(chat, limit: 10) { |message| puts "#{message.sender_id}: #{message.text}" }
57
+ client.send_message("me", "**bold** and __italic__, [a link](https://example.com)")
53
58
  client.disconnect
54
59
  ```
55
60
 
56
- TL objects are `Telethon::TL::Object`s: a schema name and its fields by their schema names
57
- (`message["reply_to"]["reply_to_top_id"]`). Any function of the layer can be called with
58
- `client.call(Telethon::TL.make("messages.getHistory", ...))`.
61
+ Messages are Telethon's custom `Message`: `text` (in the parse mode), `raw_text`, `sender`, `chat`,
62
+ `file` (name, size, mime type, dimensions), `photo`, `document`, `voice`, `forward`, `reply_to_msg_id`
63
+ and the rest, and `reply`, `respond`, `edit`, `delete`, `forward_to`, `download_media`, `mark_read`,
64
+ `pin` and `unpin`. Text is markdown by default, as in Telethon: `client.parse_mode = "html"` (or
65
+ `nil`) changes that, and so does `parse_mode:` on a call. `Telethon::Markdown` and `Telethon::HTML`
66
+ parse and unparse text and TL entities themselves.
67
+
68
+ The rest are `Telethon::TL::Object`s: a schema name and its fields by their schema names
69
+ (`message["reply_to"]["reply_to_top_id"]` works on a `Message` too). Any function of the layer can be
70
+ called with `client.call(Telethon::TL.make("messages.getHistory", ...))`.
71
+
72
+ ### Dialogs and chats
73
+
74
+ ```ruby
75
+ client.get_dialogs(limit: 20).each { |d| puts "#{d.name}: #{d.unread_count} unread" }
76
+ admins = client.get_participants(group, filter: "channelParticipantsAdmins")
77
+ admins.each { |user| puts "#{user['first_name']} (#{user.participant.name})" }
78
+ client.get_admin_log(group, limit: 50, ban: true).each { |e| puts "#{e.user_id} #{e.kind}" }
79
+ client.action(chat, "typing") { sleep 2 } # shows "typing" while the block runs
80
+
81
+ client.conversation("@SomeBot") do |conv|
82
+ conv.send_message("/start")
83
+ puts conv.get_response.raw_text
84
+ end
85
+ ```
86
+
87
+ `get_*` answer a `Telethon::TotalList`, with `total`, how many there are in all; `iter_*` yield one at a
88
+ time and answer the total. Also `get_drafts`, `edit_folder`, `delete_dialog`, `get_profile_photos`,
89
+ `edit_admin`, `edit_permissions`, `kick_participant`, `get_permissions` (a
90
+ `Telethon::ParticipantPermissions`), `get_stats` and `is_bot`. A conversation waits by running the
91
+ update loop, so use it from the thread that runs updates (or with none running).
92
+
93
+ ### Files
94
+
95
+ ```ruby
96
+ client.send_file("me", "report.pdf", caption: "**Q3**")
97
+ client.send_file("me", ["a.jpg", "b.jpg"], caption: ["first", "second"]) # an album
98
+ client.send_file(chat, "voice.ogg", voice_note: true, progress_callback: ->(done, total) { puts done })
99
+
100
+ Dir.mkdir("downloads") unless Dir.exist?("downloads")
101
+ client.iter_messages(chat, limit: 20) do |message|
102
+ path = message.download_media("downloads") # the file's own name, or kind_date.ext
103
+ thumb = message.download_media(:bytes, thumb: 0) if message.photo
104
+ end
105
+ client.download_profile_photo("@telegram", :bytes)
106
+ client.iter_download(document, request_size: 128 * 1024) { |chunk| io.write(chunk) }
107
+ ```
108
+
109
+ A file target is an existing directory, a path, an IO or `:bytes` (nil is the current directory). Downloads are written owner-only. Files on
110
+ Telegram's CDNs download as Telegram specifies: decrypted, and checked against the file's hashes.
111
+
112
+ ### Events
113
+
114
+ Handlers get updates as Telethon's events. They run one at a time, in the thread that runs the loop:
115
+
116
+ ```ruby
117
+ E = Telethon::Events
118
+
119
+ client.on(E::NewMessage.new(incoming: true, pattern: /\A\/start/)) do |event|
120
+ event.reply("hello, #{event.sender&.[]("first_name")}")
121
+ end
122
+ client.on(E::MessageDeleted.new) { |event| puts "deleted #{event.deleted_ids}" }
123
+ client.on { |update| p update.name } # Events::Raw: every update as a TL object
124
+
125
+ client.run_until_disconnected # until a handler calls client.disconnect, or Ctrl-C
126
+ ```
127
+
128
+ `NewMessage`, `MessageEdited`, `MessageDeleted`, `MessageRead`, `ChatAction`, `UserUpdate`, `Album` and
129
+ `Raw` take Telethon's filters (`chats:`, `blacklist_chats:`, `incoming:`, `outgoing:`, `from_users:`,
130
+ `forwards:`, `pattern:`, `func:`). Raise `Telethon::Events::StopPropagation` in a handler to keep the
131
+ later ones from the update. `Client.new(..., catch_up: true)` starts from the state saved last time
132
+ and fetches what was missed; `client.step_updates(max_wait)` is one turn of the loop, for a program
133
+ with a loop of its own. As in Telethon v1, the messages this client sends are not events.
59
134
 
60
135
  ## Tested against Telethon
61
136
 
62
137
  `rake oracle` runs Telethon itself (the commit the schema comes from) and Python's `qrcode` on fixed
63
138
  inputs, and `test/telethon_parity_test.rb` checks the port against what they produced: the bytes of
64
139
  every request the client sends, a decoded message, the auth-key exchange, RSA, MTProto 2.0 encryption,
65
- the SRP 2FA check and the login QR code. `spin test` runs every test natively as well and compares it
140
+ the SRP 2FA check and the login QR code. `test/updates_parity_test.rb` replays fixed scenarios
141
+ through Telethon's own message box (gaps, differences, channels) and event builders and must print
142
+ the same trace, `test/objects_parity_test.rb` checks the parse modes, `Message`, `Dialog` and
143
+ `send_message` against Telethon's, and `test/chats_parity_test.rb` gives the dialog and chat methods the
144
+ answers Telethon got and must send the requests it sent, and `test/files_parity_test.rb` does the same
145
+ for downloads and uploads (with the files they write and the progress they report). Where the port departs from Telethon, DEVELOPING.md says so. `spin test` runs every test natively as well and compares it
66
146
  with CRuby.
67
147
 
68
148
  ## Install
@@ -71,6 +151,21 @@ with CRuby.
71
151
  gem install telethon
72
152
  ```
73
153
 
154
+ Or download the `tg` binary for your system from the
155
+ [releases page](https://github.com/shogi-dojo/telethon.rb/releases): it needs no Ruby.
156
+
157
+ ```sh
158
+ # macOS on Apple silicon
159
+ curl -LO https://github.com/shogi-dojo/telethon.rb/releases/latest/download/tg-macos-arm64.tar.gz
160
+ # Linux x86_64 (glibc 2.41 or later: Debian 13, Ubuntu 25.04 and newer)
161
+ curl -LO https://github.com/shogi-dojo/telethon.rb/releases/latest/download/tg-linux-amd64.tar.gz
162
+
163
+ tar xzf tg-*.tar.gz && ./tg --version
164
+ shasum -a 256 -c SHA256SUMS --ignore-missing # with SHA256SUMS from the same release
165
+ ```
166
+
167
+ The macOS binary is not signed: if macOS refuses to open it, run `xattr -d com.apple.quarantine tg`.
168
+
74
169
  Or build the native binary from a checkout (needs Spinel, see [DEVELOPING.md](DEVELOPING.md)):
75
170
 
76
171
  ```sh
@@ -207,18 +207,19 @@ module Telethon
207
207
  messages = []
208
208
  last_id = nil
209
209
  fetched = 0
210
- client.iter_messages(chat, limit: options[:limit], reply_to: options[:topic], offset_id: options[:before]) do |m, sender|
211
- last_id = m["id"]
210
+ client.iter_messages(chat, limit: options[:limit], reply_to: options[:topic], offset_id: options[:before]) do |m|
211
+ sender = m.sender
212
+ last_id = m.id
212
213
  fetched += 1
213
214
  @err.puts "Read #{fetched} messages, oldest id so far: #{last_id}" if (fetched % 1000).zero?
214
- next if m.is?("messageService") # joins, pins, topic edits
215
+ next if m.service? # joins, pins, topic edits
215
216
 
216
- topic = CLI.message_topic(chat, m, options[:topic])
217
+ topic = CLI.message_topic(chat, m.raw, options[:topic])
217
218
  messages << {
218
- "id" => m["id"], "date" => CLI.iso_date(m["date"]), "from_id" => Client.sender_id(m),
219
+ "id" => m.id, "date" => CLI.iso_date(m.date), "from_id" => m.sender_id,
219
220
  "from_username" => sender && sender["username"], "from_name" => name_of(sender),
220
- "text" => m["message"] || "", "media" => !m["media"].nil?, "file_name" => Client.file_name(m),
221
- "topic_id" => topic, "link" => CLI.link_for(chat, topic, m["id"])
221
+ "text" => m.raw_text || "", "media" => !m.media.nil?, "file_name" => m.file_name,
222
+ "topic_id" => topic, "link" => CLI.link_for(chat, topic, m.id)
222
223
  }
223
224
  end
224
225
  export = { "chat_id" => Client.peer_id(chat), "chat_title" => chat["title"], "topic_id" => options[:topic],
@@ -248,12 +249,12 @@ module Telethon
248
249
  target = private_target(options[:out])
249
250
  found = client.get_messages(chat, ids)
250
251
  ids.each_with_index do |id, i|
251
- pair = found[i]
252
- unless pair && pair[0]["media"]
253
- @err.puts "#{id}\t#{pair ? 'no media' : 'no such message'}"
252
+ message = found[i]
253
+ unless message && message.media
254
+ @err.puts "#{id}\t#{message ? 'no media' : 'no such message'}"
254
255
  next
255
256
  end
256
- path = client.download_media(pair[0], target)
257
+ path = client.download_media(message.raw, target)
257
258
  unless path
258
259
  @err.puts "#{id}\tno media"
259
260
  next
@@ -278,17 +279,17 @@ module Telethon
278
279
  chat = client.get_entity(rest[0])
279
280
  found = client.get_messages(chat, ids).compact
280
281
  fail!("None of those messages exist.") if found.empty?
281
- found.each do |message, sender|
282
- text = message["message"].to_s
282
+ found.each do |message|
283
+ text = message.raw_text.to_s
283
284
  preview = (text.empty? ? "<media>" : text).tr("\n", " ")[0, 80]
284
- @out.puts "#{message['id']}\t#{name_of(sender)}\t#{preview}"
285
+ @out.puts "#{message.id}\t#{name_of(message.sender)}\t#{preview}"
285
286
  end
286
287
  unless options[:yes]
287
288
  fail!("Refusing to delete without a terminal to confirm in; pass --yes to skip the prompt.") unless tty?
288
289
  answer = ask("Delete these #{found.size} messages for everyone? Type yes: ")
289
290
  fail!("Nothing deleted.") unless answer == "yes"
290
291
  end
291
- client.delete_messages(chat, found.map { |m, _| m["id"] }, revoke: true)
292
+ client.delete_messages(chat, found.map(&:id), revoke: true)
292
293
  @out.puts "Deleted #{found.size} messages."
293
294
  end
294
295
  end
@@ -302,10 +303,13 @@ module Telethon
302
303
  with_client do |client|
303
304
  chat = client.get_entity(rest[0])
304
305
  if files.empty?
305
- @out.puts "Sent message #{client.send_message(chat, rest[1], reply_to: options[:topic])}."
306
+ @out.puts "Sent message #{client.send_message(chat, rest[1], reply_to: options[:topic])&.id}."
306
307
  else
307
- ids = client.send_file(chat, files, caption: rest[1], reply_to: options[:topic], force_document: true)
308
- @out.puts "Sent message #{ids.join(', ')}."
308
+ # One file goes as one message, several as albums, as Telethon sends a file and a list.
309
+ sent = client.send_file(chat, files.size == 1 ? files[0] : files, caption: rest[1],
310
+ reply_to: options[:topic], force_document: true)
311
+ sent = [sent] unless sent.is_a?(Array)
312
+ @out.puts "Sent message #{sent.map { |m| m&.id }.join(', ')}."
309
313
  end
310
314
  end
311
315
  end
@@ -314,7 +318,8 @@ module Telethon
314
318
  rest, = parse(args, "edit CHAT ID TEXT", %w[CHAT ID TEXT])
315
319
  id = Args.positive_int(rest[1], "message id")
316
320
  with_client do |client|
317
- @out.puts "Edited message #{client.edit_message(client.get_entity(rest[0]), id, rest[2])}."
321
+ edited = client.edit_message(client.get_entity(rest[0]), id, rest[2])
322
+ @out.puts "Edited message #{edited ? edited.id : id}."
318
323
  end
319
324
  end
320
325
 
@@ -327,7 +332,7 @@ module Telethon
327
332
  source = client.get_entity(options[:from])
328
333
  target = client.get_entity(rest[0])
329
334
  sent = client.forward_messages(target, ids, source, drop_author: true)
330
- @out.puts "Forwarded as message #{sent.join(', ')}."
335
+ @out.puts "Forwarded as message #{sent.map { |m| m&.id }.join(', ')}."
331
336
  if options[:delete_source]
332
337
  client.delete_messages(source, ids)
333
338
  @out.puts "Deleted #{ids.size} source messages."
@@ -57,8 +57,29 @@ module Telethon
57
57
  QRLogin.new(self, except_ids).recreate
58
58
  end
59
59
 
60
+ # The logged-in user. Remembers its id in the session when it did not have it (an imported
61
+ # Telethon session does not), as Telethon keeps its own: Message#out? and events need it.
60
62
  def get_me
61
- call(TL.make("users.getUsers", "id" => [TL.make("inputUserSelf")]))[0]
63
+ user = call(TL.make("users.getUsers", "id" => [TL.make("inputUserSelf")]))[0]
64
+ if user && user.is?("user")
65
+ bot = user["bot"] ? true : false
66
+ if @session.user_id != user["id"] || @session.bot != bot
67
+ @session.user_id = user["id"]
68
+ @session.bot = bot
69
+ @session.save
70
+ end
71
+ end
72
+ user
73
+ end
74
+
75
+ # Whether the account is a bot, from the session, else asked once with get_me.
76
+ def is_bot
77
+ get_me if @session.bot.nil?
78
+ @session.bot ? true : false
79
+ end
80
+
81
+ def bot?
82
+ is_bot
62
83
  end
63
84
 
64
85
  # An auth.authorization, as signIn, checkPassword and a QR login answer: remembers the user.