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.
@@ -0,0 +1,279 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Telethon
4
+ module CLI
5
+ module ChatsCommands
6
+ INVITE_LINK = %r{\A(?:https?://)?t\.me/(?:\+|joinchat/)([A-Za-z0-9_-]+)\z}
7
+
8
+ private
9
+
10
+ def members_command(args)
11
+ rest, opts = parse_for("members", args)
12
+ limit = opts["--limit"] && Args.positive_int(opts["--limit"], "--limit")
13
+ filter = opts["--admins"] ? "channelParticipantsAdmins" : nil
14
+ with_client do |client|
15
+ chat = client.get_entity(rest[0])
16
+ users = []
17
+ client.iter_participants(chat, limit: limit, search: opts["--search"] || "", filter: filter) { |u| users << u }
18
+ if opts["--json"]
19
+ items = users.map do |u|
20
+ entity_summary(u).merge("role" => u.participant && u.participant.name)
21
+ end
22
+ @out.puts JSON.pretty_generate(items)
23
+ else
24
+ users.each do |u|
25
+ handle = u["username"] ? "@#{u['username']}" : "-"
26
+ @out.puts "#{u['id']}\t#{handle}\t#{name_of(u)}"
27
+ end
28
+ end
29
+ end
30
+ end
31
+
32
+ def admin_command(args)
33
+ rest, opts = parse_for("admin", args)
34
+ revoke = opts["--revoke"] ? true : false
35
+ right_flags = %w[--change-info --post-messages --edit-messages --delete-messages --ban-users
36
+ --invite-users --pin-messages --add-admins --manage-call --anonymous]
37
+ explicit = right_flags.any? { |f| opts[f] }
38
+ is_admin = revoke ? false : !explicit
39
+ with_client do |client|
40
+ client.edit_admin(
41
+ rest[0], rest[1],
42
+ change_info: opts["--change-info"], post_messages: opts["--post-messages"],
43
+ edit_messages: opts["--edit-messages"], delete_messages: opts["--delete-messages"],
44
+ ban_users: opts["--ban-users"], invite_users: opts["--invite-users"],
45
+ pin_messages: opts["--pin-messages"], add_admins: opts["--add-admins"],
46
+ manage_call: opts["--manage-call"], anonymous: opts["--anonymous"],
47
+ is_admin: is_admin, title: opts["--title"]
48
+ )
49
+ if opts["--json"]
50
+ @out.puts JSON.generate("ok" => true, "admin" => !revoke)
51
+ else
52
+ @out.puts revoke ? "Revoked admin rights." : "Updated admin rights."
53
+ end
54
+ end
55
+ end
56
+
57
+ def ban_command(args)
58
+ rest, opts = parse_for("ban", args)
59
+ until_date = opts["--until"] && Args.parse_time(opts["--until"], "--until")
60
+ with_client do |client|
61
+ client.edit_permissions(rest[0], rest[1], until_date, view_messages: false)
62
+ if opts["--json"]
63
+ @out.puts JSON.generate("ok" => true, "until_date" => until_date)
64
+ else
65
+ @out.puts "Banned user."
66
+ end
67
+ end
68
+ end
69
+
70
+ def kick_command(args)
71
+ rest, opts = parse_for("kick", args)
72
+ with_client do |client|
73
+ client.kick_participant(rest[0], rest[1])
74
+ if opts["--json"]
75
+ @out.puts JSON.generate("ok" => true)
76
+ else
77
+ @out.puts "Kicked user."
78
+ end
79
+ end
80
+ end
81
+
82
+ def unban_command(args)
83
+ rest, opts = parse_for("unban", args)
84
+ with_client do |client|
85
+ client.edit_permissions(rest[0], rest[1], view_messages: true)
86
+ if opts["--json"]
87
+ @out.puts JSON.generate("ok" => true)
88
+ else
89
+ @out.puts "Unbanned user."
90
+ end
91
+ end
92
+ end
93
+
94
+ def permissions_command(args)
95
+ rest, opts = parse_for("permissions", args)
96
+ user_ref = rest[1]
97
+ with_client do |client|
98
+ perms = client.get_permissions(rest[0], user_ref)
99
+ if perms.is_a?(ParticipantPermissions)
100
+ data = {
101
+ "admin" => perms.admin?, "creator" => perms.creator?, "banned" => perms.banned?,
102
+ "left" => perms.has_left?, "default_permissions" => perms.has_default_permissions?,
103
+ "add_admins" => perms.add_admins?, "ban_users" => perms.ban_users?,
104
+ "pin_messages" => perms.pin_messages?, "invite_users" => perms.invite_users?,
105
+ "delete_messages" => perms.delete_messages?, "edit_messages" => perms.edit_messages?,
106
+ "post_messages" => perms.post_messages?, "change_info" => perms.change_info?,
107
+ "anonymous" => perms.anonymous?, "manage_call" => perms.manage_call?
108
+ }
109
+ if opts["--json"]
110
+ @out.puts JSON.pretty_generate(data)
111
+ else
112
+ data.each { |k, v| @out.puts "#{k}: #{v}" }
113
+ end
114
+ elsif perms.is_a?(TL::Object)
115
+ data = tl_to_json(perms)
116
+ if opts["--json"]
117
+ @out.puts JSON.pretty_generate(data)
118
+ else
119
+ perms.fields.each { |k, v| @out.puts "#{k}: #{v}" }
120
+ end
121
+ elsif opts["--json"]
122
+ @out.puts JSON.generate(nil)
123
+ else
124
+ @out.puts "none"
125
+ end
126
+ end
127
+ end
128
+
129
+ def admin_log_command(args)
130
+ rest, opts = parse_for("admin-log", args)
131
+ limit = Args.positive_int(opts["--limit"] || "20", "--limit")
132
+ with_client do |client|
133
+ events = []
134
+ client.iter_admin_log(rest[0], limit: limit, search: opts["--search"]) { |ev| events << ev }
135
+ if opts["--json"]
136
+ items = events.map do |ev|
137
+ { "id" => ev.id, "date" => CLI.iso_date(ev.date), "user_id" => ev.user_id,
138
+ "action" => ev.action && ev.action.name }
139
+ end
140
+ @out.puts JSON.pretty_generate(items)
141
+ else
142
+ events.each do |ev|
143
+ @out.puts "#{ev.id}\t#{CLI.iso_date(ev.date)}\t#{ev.user_id}\t#{ev.action && ev.action.name}"
144
+ end
145
+ end
146
+ end
147
+ end
148
+
149
+ def stats_command(args)
150
+ rest, opts = parse_for("stats", args)
151
+ msg_id = rest[1] ? Args.positive_int(rest[1], "message id") : nil
152
+ with_client do |client|
153
+ res = client.get_stats(rest[0], msg_id)
154
+ if opts["--json"]
155
+ @out.puts JSON.pretty_generate(tl_to_json(res))
156
+ else
157
+ @out.puts "type: #{res.name}"
158
+ res.fields.each do |k, v|
159
+ if v.is_a?(TL::Object) && v.is?("statsAbsValueAndPrev")
160
+ @out.puts "#{k}: #{v['current']} (prev: #{v['previous']})"
161
+ elsif v.is_a?(Integer) || v.is_a?(Float) || v.is_a?(String)
162
+ @out.puts "#{k}: #{v}"
163
+ end
164
+ end
165
+ end
166
+ end
167
+ end
168
+
169
+ def join_command(args)
170
+ rest, opts = parse_for("join", args)
171
+ target = rest[0]
172
+ with_client do |client|
173
+ if (m = target.match(INVITE_LINK))
174
+ client.call(TL.make("messages.importChatInvite", "hash" => m[1]))
175
+ else
176
+ peer = client.get_input_entity(target)
177
+ fail!("#{target} is not a channel or supergroup.") unless Client.entity_type(peer) == :channel
178
+ channel = TL.make("inputChannel", "channel_id" => peer["channel_id"], "access_hash" => peer["access_hash"])
179
+ client.call(TL.make("channels.joinChannel", "channel" => channel))
180
+ end
181
+ if opts["--json"]
182
+ @out.puts JSON.generate("ok" => true, "target" => target)
183
+ else
184
+ @out.puts "Joined #{target}."
185
+ end
186
+ end
187
+ end
188
+
189
+ def leave_command(args)
190
+ rest, opts = parse_for("leave", args)
191
+ target = rest[0]
192
+ with_client do |client|
193
+ peer = client.get_input_entity(target)
194
+ case Client.entity_type(peer)
195
+ when :channel
196
+ channel = TL.make("inputChannel", "channel_id" => peer["channel_id"], "access_hash" => peer["access_hash"])
197
+ client.call(TL.make("channels.leaveChannel", "channel" => channel))
198
+ when :chat
199
+ client.call(TL.make("messages.deleteChatUser", "chat_id" => peer["chat_id"],
200
+ "user_id" => TL.make("inputUserSelf")))
201
+ else
202
+ fail!("Cannot leave a private chat; use `tg delete-chat` instead.")
203
+ end
204
+ if opts["--json"]
205
+ @out.puts JSON.generate("ok" => true, "chat" => target)
206
+ else
207
+ @out.puts "Left #{target}."
208
+ end
209
+ end
210
+ end
211
+
212
+ def archive_command(args)
213
+ rest, opts = parse_for("archive", args)
214
+ with_client do |client|
215
+ client.edit_folder(rest, 1)
216
+ if opts["--json"]
217
+ @out.puts JSON.generate("ok" => true, "folder" => 1, "count" => rest.size)
218
+ else
219
+ @out.puts "Archived #{rest.size} chat(s)."
220
+ end
221
+ end
222
+ end
223
+
224
+ def unarchive_command(args)
225
+ rest, opts = parse_for("unarchive", args)
226
+ with_client do |client|
227
+ client.edit_folder(rest, 0)
228
+ if opts["--json"]
229
+ @out.puts JSON.generate("ok" => true, "folder" => 0, "count" => rest.size)
230
+ else
231
+ @out.puts "Unarchived #{rest.size} chat(s)."
232
+ end
233
+ end
234
+ end
235
+
236
+ def delete_chat_command(args)
237
+ rest, opts = parse_for("delete-chat", args)
238
+ target = rest[0]
239
+ revoke = opts["--revoke"] ? true : false
240
+ unless opts["--yes"]
241
+ fail!("Refusing to delete chat without a terminal to confirm in; pass --yes to skip the prompt.") unless tty?
242
+ answer = ask("Delete chat #{target}? Type yes: ")
243
+ fail!("Nothing deleted.") unless answer == "yes"
244
+ end
245
+ with_client do |client|
246
+ client.delete_dialog(target, revoke: revoke)
247
+ if opts["--json"]
248
+ @out.puts JSON.generate("ok" => true, "chat" => target, "revoke" => revoke)
249
+ else
250
+ @out.puts "Deleted chat #{target}."
251
+ end
252
+ end
253
+ end
254
+
255
+ def profile_photos_command(args)
256
+ rest, opts = parse_for("profile-photos", args)
257
+ limit = opts["--limit"] && Args.positive_int(opts["--limit"], "--limit")
258
+ out_dir = opts["--out"]
259
+ with_client do |client|
260
+ target = out_dir ? private_target(out_dir) : nil
261
+ items = []
262
+ client.iter_profile_photos(rest[0], limit: limit) do |photo|
263
+ path = target ? client.download_media(photo, target) : nil
264
+ items << { "id" => photo["id"], "date" => photo["date"] && CLI.iso_date(photo["date"]), "path" => path }
265
+ end
266
+ if opts["--json"]
267
+ @out.puts JSON.pretty_generate(items)
268
+ else
269
+ items.each do |item|
270
+ line = "#{item['id']}\t#{item['date']}"
271
+ line = "#{line}\t#{item['path']}" if item["path"]
272
+ @out.puts line
273
+ end
274
+ end
275
+ end
276
+ end
277
+ end
278
+ end
279
+ end
@@ -0,0 +1,203 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Telethon
4
+ module CLI
5
+ module ReadingCommands
6
+ private
7
+
8
+ def chats_command(args)
9
+ _rest, opts = parse_for("chats", args)
10
+ raise UsageError, "--archived and --folder cannot go together" if opts["--archived"] && opts["--folder"]
11
+
12
+ limit = opts["--limit"] && Args.positive_int(opts["--limit"], "--limit")
13
+ folder = opts["--folder"] && Args.integer(opts["--folder"], "--folder")
14
+ archived = opts["--archived"] ? true : nil
15
+ with_client do |client|
16
+ dialogs = []
17
+ client.iter_dialogs(limit: limit, folder: folder, archived: archived) { |d| dialogs << d }
18
+ if opts["--json"]
19
+ @out.puts JSON.pretty_generate(dialogs.map { |d| dialog_summary(d) })
20
+ else
21
+ dialogs.each do |d|
22
+ @out.puts "#{d.id}\t#{entity_kind(d.entity)}\t#{d.name}\t#{d.unread_count}"
23
+ end
24
+ end
25
+ end
26
+ end
27
+
28
+ def info_command(args)
29
+ rest, opts = parse_for("info", args)
30
+ with_client do |client|
31
+ entity = client.get_entity(rest[0])
32
+ summary = entity_summary(entity)
33
+ if opts["--json"]
34
+ @out.puts JSON.pretty_generate(summary)
35
+ else
36
+ @out.puts "id: #{summary['id']}"
37
+ @out.puts "kind: #{summary['kind']}"
38
+ @out.puts "name: #{summary['name']}" if summary["name"] && !summary["name"].empty?
39
+ @out.puts "username: @#{summary['username']}" if summary["username"]
40
+ @out.puts "bot: true" if summary["bot"]
41
+ @out.puts "forum: true" if summary["forum"]
42
+ end
43
+ end
44
+ end
45
+
46
+ def listen_command(args)
47
+ rest, opts = parse_for("listen", args)
48
+ json = opts["--json"] ? true : false
49
+ with_client do |client|
50
+ chats = rest.empty? ? nil : rest.map { |ref| client.get_entity(ref) }
51
+ out = @out
52
+ client.on(Events::NewMessage.new(chats: chats)) do |event|
53
+ emit_listen_message("new", event.message, json, out)
54
+ end
55
+ client.on(Events::MessageEdited.new(chats: chats)) do |event|
56
+ emit_listen_message("edit", event.message, json, out)
57
+ end
58
+ client.on(Events::MessageDeleted.new(chats: chats)) do |event|
59
+ if json
60
+ out.puts JSON.generate("event" => "delete", "chat_id" => event.chat_id, "deleted_ids" => event.deleted_ids)
61
+ else
62
+ out.puts "delete\t#{event.chat_id}\t#{event.deleted_ids.join(',')}"
63
+ end
64
+ out.flush
65
+ end
66
+ client.run_until_disconnected
67
+ end
68
+ end
69
+
70
+ def emit_listen_message(kind, msg, json, out)
71
+ if json
72
+ payload = { "event" => kind }.merge(message_summary(msg))
73
+ out.puts JSON.generate(payload)
74
+ else
75
+ out.puts "#{kind}\t#{msg.chat_id}\t#{format_message_line(msg)}"
76
+ end
77
+ out.flush
78
+ end
79
+
80
+ def topics(args)
81
+ rest, opts = parse_for("topics", args)
82
+ with_client do |client|
83
+ chat = client.get_entity(rest[0])
84
+ list = client.forum_topics(chat)
85
+ if opts["--json"]
86
+ @out.puts JSON.pretty_generate(list.map { |t| { "id" => t["id"], "title" => t["title"] } })
87
+ else
88
+ list.each { |topic| @out.puts "#{topic['id']}\t#{topic['title']}" }
89
+ end
90
+ end
91
+ end
92
+
93
+ def read_command(args)
94
+ rest, opts = parse_for("read", args)
95
+ limit = Args.positive_int(opts["--limit"] || "20", "--limit")
96
+ topic = opts["--topic"] && Args.integer(opts["--topic"], "--topic")
97
+ with_client do |client|
98
+ chat = client.get_entity(rest[0])
99
+ messages = []
100
+ client.iter_messages(chat, limit: limit, reply_to: topic) { |m| messages << m unless m.service? }
101
+ messages.reverse!
102
+ if opts["--json"]
103
+ @out.puts JSON.pretty_generate(messages.map { |m| message_summary(m) })
104
+ else
105
+ messages.each { |m| @out.puts format_message_line(m) }
106
+ end
107
+ end
108
+ end
109
+
110
+ def search_command(args)
111
+ rest, opts = parse_for("search", args)
112
+ usage_error("search", "missing QUERY") if rest.empty? && opts["--filter"].nil? && opts["--from"].nil?
113
+ limit = Args.positive_int(opts["--limit"] || "20", "--limit")
114
+ chat_ref, query = if rest.size >= 2
115
+ [rest[0], rest[1..].join(" ")]
116
+ else
117
+ [nil, rest[0]]
118
+ end
119
+ with_client do |client|
120
+ chat = chat_ref ? client.get_entity(chat_ref) : nil
121
+ from_user = opts["--from"] ? client.get_entity(opts["--from"]) : nil
122
+ messages = []
123
+ client.iter_messages(chat, limit: limit, search: query, filter: opts["--filter"],
124
+ from_user: from_user) { |m| messages << m unless m.service? }
125
+ if opts["--json"]
126
+ @out.puts JSON.pretty_generate(messages.map { |m| message_summary(m) })
127
+ else
128
+ messages.each { |m| @out.puts format_message_line(m) }
129
+ end
130
+ end
131
+ end
132
+
133
+ def export(args)
134
+ rest, opts = parse_for("export", args)
135
+ raise UsageError, "--limit and --all cannot go together" if opts["--limit"] && opts["--all"]
136
+
137
+ options = { topic: opts["--topic"] && Args.integer(opts["--topic"], "--topic"),
138
+ limit: opts["--all"] ? nil : Args.positive_int(opts["--limit"] || "100", "--limit"),
139
+ before: opts["--before"] ? Args.positive_int(opts["--before"], "--before") : 0,
140
+ out: opts["--out"] }
141
+ with_client do |client|
142
+ chat = client.get_entity(rest[0])
143
+ messages = []
144
+ last_id = nil
145
+ fetched = 0
146
+ client.iter_messages(chat, limit: options[:limit], reply_to: options[:topic], offset_id: options[:before]) do |m|
147
+ sender = m.sender
148
+ last_id = m.id
149
+ fetched += 1
150
+ @err.puts "Read #{fetched} messages, oldest id so far: #{last_id}" if (fetched % 1000).zero?
151
+ next if m.service? # joins, pins, topic edits
152
+
153
+ topic = CLI.message_topic(chat, m.raw, options[:topic])
154
+ messages << {
155
+ "id" => m.id, "date" => CLI.iso_date(m.date), "from_id" => m.sender_id,
156
+ "from_username" => sender && sender["username"], "from_name" => name_of(sender),
157
+ "text" => m.raw_text || "", "media" => !m.media.nil?, "file_name" => m.file_name,
158
+ "topic_id" => topic, "link" => CLI.link_for(chat, topic, m.id)
159
+ }
160
+ end
161
+ export = { "chat_id" => Client.peer_id(chat), "chat_title" => chat["title"], "topic_id" => options[:topic],
162
+ "messages" => messages, "next_before" => last_id, "fetched" => fetched,
163
+ "complete" => options[:limit].nil? || fetched < options[:limit] }
164
+ payload = JSON.pretty_generate(export)
165
+ if options[:out]
166
+ PrivateFiles.write(options[:out], payload)
167
+ @err.puts "#{messages.size} messages -> #{options[:out]}"
168
+ else
169
+ @out.puts payload
170
+ end
171
+ end
172
+ end
173
+
174
+ def download(args)
175
+ rest, opts = parse_for("download", args)
176
+ options = { out: opts["--out"] || "." }
177
+ ids = message_ids(rest[1..])
178
+ saved = []
179
+ with_client do |client|
180
+ chat = client.get_entity(rest[0])
181
+ target = private_target(options[:out])
182
+ found = client.get_messages(chat, ids)
183
+ ids.each_with_index do |id, i|
184
+ message = found[i]
185
+ unless message && message.media
186
+ @err.puts "#{id}\t#{message ? 'no media' : 'no such message'}"
187
+ next
188
+ end
189
+ path = client.download_media(message.raw, target)
190
+ unless path
191
+ @err.puts "#{id}\tno media"
192
+ next
193
+ end
194
+ saved << { "id" => id, "path" => path }
195
+ @out.puts "#{id}\t#{path}" unless opts["--json"]
196
+ end
197
+ end
198
+ fail!("Nothing downloaded.") if saved.empty?
199
+ @out.puts JSON.pretty_generate(saved) if opts["--json"]
200
+ end
201
+ end
202
+ end
203
+ end