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 +4 -4
- data/CHANGELOG.md +36 -0
- data/README.md +34 -62
- data/lib/telethon/cli/args.rb +33 -0
- data/lib/telethon/cli/call.rb +182 -0
- data/lib/telethon/cli/commands/account.rb +357 -0
- data/lib/telethon/cli/commands/bots.rb +91 -0
- data/lib/telethon/cli/commands/chats.rb +279 -0
- data/lib/telethon/cli/commands/reading.rb +203 -0
- data/lib/telethon/cli/commands/writing.rb +278 -0
- data/lib/telethon/cli/commands.rb +158 -468
- data/lib/telethon/cli/completion.rb +100 -0
- data/lib/telethon/cli/table.rb +805 -0
- data/lib/telethon/cli.rb +108 -45
- data/lib/telethon/client/auth.rb +12 -4
- data/lib/telethon/client/files.rb +11 -5
- data/lib/telethon/client/messages.rb +82 -13
- data/lib/telethon/custom/dialog.rb +5 -0
- data/lib/telethon/network/sender.rb +22 -1
- data/lib/telethon/network/transport.rb +14 -1
- data/lib/telethon/private_files.rb +5 -1
- data/lib/telethon/version.rb +1 -1
- data/lib/telethon.rb +8 -0
- metadata +9 -1
|
@@ -3,11 +3,23 @@
|
|
|
3
3
|
module Telethon
|
|
4
4
|
module CLI
|
|
5
5
|
# One run of a command. Holds the streams and the config directory.
|
|
6
|
+
# Individual command groups live in lib/telethon/cli/commands/*.rb as modules mixed in here.
|
|
6
7
|
class Commands
|
|
8
|
+
# The transports TG_CONNECTION names, as Telethon's connection classes.
|
|
9
|
+
CONNECTIONS = %w[tcp_full tcp_abridged tcp_intermediate tcp_obfuscated tcp_obfuscated_intermediate http].freeze
|
|
10
|
+
|
|
11
|
+
include AccountCommands
|
|
12
|
+
include ReadingCommands
|
|
13
|
+
include WritingCommands
|
|
14
|
+
include ChatsCommands
|
|
15
|
+
include BotsCommands
|
|
16
|
+
|
|
7
17
|
CODE_PROMPT = "Code (or empty to resend): "
|
|
8
18
|
|
|
9
|
-
def initialize(home, client_factory, input, out, err)
|
|
19
|
+
def initialize(home, client_factory, input, out, err, base_home: nil, account: nil)
|
|
10
20
|
@home = home
|
|
21
|
+
@base_home = base_home || home
|
|
22
|
+
@account = account
|
|
11
23
|
@client_factory = client_factory
|
|
12
24
|
@input = input
|
|
13
25
|
@out = out
|
|
@@ -22,6 +34,12 @@ module Telethon
|
|
|
22
34
|
when "import-session" then import_session(args)
|
|
23
35
|
when "export-session" then export_session(args)
|
|
24
36
|
when "whoami" then whoami(args)
|
|
37
|
+
when "accounts" then accounts_command(args)
|
|
38
|
+
when "sessions" then sessions_command(args)
|
|
39
|
+
when "profile" then profile_command(args)
|
|
40
|
+
when "chats" then chats_command(args)
|
|
41
|
+
when "info" then info_command(args)
|
|
42
|
+
when "listen" then listen_command(args)
|
|
25
43
|
when "topics" then topics(args)
|
|
26
44
|
when "read" then read_command(args)
|
|
27
45
|
when "search" then search_command(args)
|
|
@@ -29,10 +47,33 @@ module Telethon
|
|
|
29
47
|
when "download" then download(args)
|
|
30
48
|
when "delete" then delete(args)
|
|
31
49
|
when "send" then send_command(args)
|
|
50
|
+
when "reply" then reply_command(args)
|
|
51
|
+
when "pin" then pin_command(args)
|
|
52
|
+
when "unpin" then unpin_command(args)
|
|
53
|
+
when "mark-read" then mark_read_command(args)
|
|
54
|
+
when "react" then react_command(args)
|
|
55
|
+
when "draft" then draft_command(args)
|
|
56
|
+
when "typing" then typing_command(args)
|
|
32
57
|
when "edit" then edit(args)
|
|
33
58
|
when "forward" then forward(args)
|
|
59
|
+
when "members" then members_command(args)
|
|
60
|
+
when "admin" then admin_command(args)
|
|
61
|
+
when "ban" then ban_command(args)
|
|
62
|
+
when "kick" then kick_command(args)
|
|
63
|
+
when "unban" then unban_command(args)
|
|
64
|
+
when "permissions" then permissions_command(args)
|
|
65
|
+
when "admin-log" then admin_log_command(args)
|
|
66
|
+
when "stats" then stats_command(args)
|
|
67
|
+
when "join" then join_command(args)
|
|
68
|
+
when "leave" then leave_command(args)
|
|
69
|
+
when "archive" then archive_command(args)
|
|
70
|
+
when "unarchive" then unarchive_command(args)
|
|
71
|
+
when "delete-chat" then delete_chat_command(args)
|
|
72
|
+
when "profile-photos" then profile_photos_command(args)
|
|
34
73
|
when "inline" then inline_command(args)
|
|
35
74
|
when "click" then click_command(args)
|
|
75
|
+
when "call" then call_command(args)
|
|
76
|
+
when "completion" then completion_command(args)
|
|
36
77
|
else raise Failure, "tg: unknown command #{command} (see tg --help)"
|
|
37
78
|
end
|
|
38
79
|
end
|
|
@@ -48,9 +89,31 @@ module Telethon
|
|
|
48
89
|
end
|
|
49
90
|
|
|
50
91
|
def load_config
|
|
51
|
-
|
|
92
|
+
if @account && !File.directory?(@home)
|
|
93
|
+
raise NotLoggedIn, "No saved account is #{@account}: see `tg accounts`, or `tg --account #{@account} login`."
|
|
94
|
+
end
|
|
52
95
|
|
|
53
|
-
JSON.parse(File.read(config_path, encoding: "UTF-8"))
|
|
96
|
+
config = File.exist?(config_path) ? JSON.parse(File.read(config_path, encoding: "UTF-8")) : {}
|
|
97
|
+
config = with_shared_api(config)
|
|
98
|
+
raise NotLoggedIn, "Not set up: run `tg login` first (#{config_path} is missing)." unless config["api_id"]
|
|
99
|
+
|
|
100
|
+
config
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
# A named account without its own API id/hash borrows the default account's: they belong to the
|
|
104
|
+
# developer app, not to the Telegram account.
|
|
105
|
+
def with_shared_api(config)
|
|
106
|
+
return config if config["api_id"] || @home == @base_home
|
|
107
|
+
|
|
108
|
+
base = File.join(@base_home, "config.json")
|
|
109
|
+
return config unless File.exist?(base)
|
|
110
|
+
|
|
111
|
+
shared = JSON.parse(File.read(base, encoding: "UTF-8"))
|
|
112
|
+
if shared["api_id"]
|
|
113
|
+
config["api_id"] = shared["api_id"]
|
|
114
|
+
config["api_hash"] = shared["api_hash"]
|
|
115
|
+
end
|
|
116
|
+
config
|
|
54
117
|
end
|
|
55
118
|
|
|
56
119
|
def save_config(config)
|
|
@@ -61,13 +124,29 @@ module Telethon
|
|
|
61
124
|
def new_client(config)
|
|
62
125
|
return @client_factory.call(config) if @client_factory
|
|
63
126
|
|
|
127
|
+
Client.new(Session.new(@home), api_id: config["api_id"].to_i, api_hash: config["api_hash"].to_s,
|
|
128
|
+
connection: env_connection, proxy: env_proxy)
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
# TG_CONNECTION picks the transport (Telethon's connection=): tcp_full, tcp_abridged,
|
|
132
|
+
# tcp_intermediate, tcp_obfuscated, tcp_obfuscated_intermediate (the default) or http.
|
|
133
|
+
def env_connection
|
|
134
|
+
name = ENV.fetch("TG_CONNECTION", "").strip
|
|
135
|
+
return nil if name.empty?
|
|
136
|
+
|
|
137
|
+
Network::Transport.normalize_connection(name)
|
|
138
|
+
rescue ArgumentError
|
|
139
|
+
fail!("TG_CONNECTION: unknown transport #{name.inspect} (use #{CONNECTIONS.join(', ')})")
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def env_proxy
|
|
64
144
|
proxy = ENV.fetch("TG_PROXY", "")
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
end
|
|
145
|
+
return nil if proxy.empty?
|
|
146
|
+
|
|
147
|
+
Network::Proxy.parse(proxy)
|
|
148
|
+
rescue ArgumentError => e
|
|
149
|
+
fail!("TG_PROXY: #{e.message}")
|
|
71
150
|
end
|
|
72
151
|
|
|
73
152
|
# A connected, logged-in client, or a failure: nothing here may prompt.
|
|
@@ -93,6 +172,19 @@ module Telethon
|
|
|
93
172
|
def parse(args, usage, positional, spec = {})
|
|
94
173
|
Args.parse(args, usage, positional, spec)
|
|
95
174
|
end
|
|
175
|
+
|
|
176
|
+
def parse_for(name, args)
|
|
177
|
+
entry = Table.find(name)
|
|
178
|
+
raise Failure, "unknown table entry #{name}" unless entry
|
|
179
|
+
|
|
180
|
+
Args.parse(args, entry[:usage], entry[:positionals], entry[:spec])
|
|
181
|
+
end
|
|
182
|
+
|
|
183
|
+
def usage_error(name, message)
|
|
184
|
+
entry = Table.find(name)
|
|
185
|
+
raise UsageError, "#{message}\nusage: tg #{entry[:usage]}"
|
|
186
|
+
end
|
|
187
|
+
|
|
96
188
|
def tty?
|
|
97
189
|
@input.respond_to?(:tty?) && @input.tty?
|
|
98
190
|
end
|
|
@@ -118,251 +210,55 @@ module Telethon
|
|
|
118
210
|
Client.display_name(entity)
|
|
119
211
|
end
|
|
120
212
|
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
def login(args)
|
|
124
|
-
_rest, options = parse(args, "login [--qr | --bot-token]", [], "--qr" => :flag, "--bot-token" => :flag)
|
|
125
|
-
raise UsageError, "--qr and --bot-token cannot go together" if options["--qr"] && options["--bot-token"]
|
|
126
|
-
|
|
127
|
-
config = File.exist?(config_path) ? JSON.parse(File.read(config_path, encoding: "UTF-8")) : {}
|
|
128
|
-
if options["--bot-token"]
|
|
129
|
-
token = ENV.fetch("TG_BOT_TOKEN", "").strip
|
|
130
|
-
if token.empty?
|
|
131
|
-
token = tty? ? ask_hidden("Bot token (hidden): ") : @input.gets.to_s.strip
|
|
132
|
-
end
|
|
133
|
-
fail!("No bot token provided (set TG_BOT_TOKEN or pass it on stdin).") if token.empty?
|
|
134
|
-
unless config["api_id"]
|
|
135
|
-
if !ENV.fetch("TG_API_ID", "").empty? && !ENV.fetch("TG_API_HASH", "").empty?
|
|
136
|
-
config["api_id"] = Integer(ENV.fetch("TG_API_ID"), 10)
|
|
137
|
-
config["api_hash"] = ENV.fetch("TG_API_HASH")
|
|
138
|
-
save_config(config)
|
|
139
|
-
else
|
|
140
|
-
fail!("login needs an interactive terminal to enter API id/hash (or set TG_API_ID and TG_API_HASH).") unless tty?
|
|
141
|
-
@out.puts "API id and hash come from https://my.telegram.org, logged in as the account."
|
|
142
|
-
config["api_id"] = Integer(ask("API id: "), 10)
|
|
143
|
-
config["api_hash"] = ask_hidden("API hash (hidden): ")
|
|
144
|
-
save_config(config)
|
|
145
|
-
end
|
|
146
|
-
end
|
|
147
|
-
PrivateFiles.directory(@home)
|
|
148
|
-
client = new_client(config)
|
|
149
|
-
client.connect
|
|
150
|
-
client.sign_in(bot_token: token) unless client.session.exists? && client.authorized?
|
|
151
|
-
else
|
|
152
|
-
fail!("login needs an interactive terminal: ssh -t ...") unless tty?
|
|
153
|
-
unless config["api_id"]
|
|
154
|
-
@out.puts "API id and hash come from https://my.telegram.org, logged in as the account."
|
|
155
|
-
config["api_id"] = Integer(ask("API id: "), 10)
|
|
156
|
-
config["api_hash"] = ask_hidden("API hash (hidden): ")
|
|
157
|
-
save_config(config)
|
|
158
|
-
end
|
|
159
|
-
PrivateFiles.directory(@home)
|
|
160
|
-
client = new_client(config)
|
|
161
|
-
client.connect
|
|
162
|
-
unless client.session.exists? && client.authorized?
|
|
163
|
-
options["--qr"] ? login_with_qr(client) : login_with_code(client)
|
|
164
|
-
end
|
|
165
|
-
end
|
|
166
|
-
me = client.get_me
|
|
167
|
-
config["account"] = me["username"]
|
|
168
|
-
save_config(config)
|
|
169
|
-
@out.puts "Logged in as @#{me['username']} (#{me['id']}). Session: #{client.session.session_path}"
|
|
170
|
-
ensure
|
|
171
|
-
client&.disconnect
|
|
172
|
-
end
|
|
173
|
-
|
|
174
|
-
def login_with_code(client)
|
|
175
|
-
phone = ask("Phone, international format (+380...): ")
|
|
176
|
-
sent = client.send_code(phone)
|
|
177
|
-
@out.puts "Code sent via #{Client.code_delivery(sent)}."
|
|
178
|
-
code = ask(CODE_PROMPT)
|
|
179
|
-
if code.empty?
|
|
180
|
-
sent = client.resend_code(phone, sent["phone_code_hash"])
|
|
181
|
-
@out.puts "Resent via #{Client.code_delivery(sent)}."
|
|
182
|
-
code = ask("Code: ")
|
|
183
|
-
end
|
|
184
|
-
begin
|
|
185
|
-
client.sign_in(phone, code, sent["phone_code_hash"])
|
|
186
|
-
rescue RPCError => e
|
|
187
|
-
raise unless e.name == "SESSION_PASSWORD_NEEDED"
|
|
188
|
-
|
|
189
|
-
client.check_password(ask_hidden("2FA password (hidden): "))
|
|
190
|
-
end
|
|
191
|
-
end
|
|
192
|
-
|
|
193
|
-
def login_with_qr(client)
|
|
194
|
-
qr = client.qr_login
|
|
195
|
-
loop do
|
|
196
|
-
@out.print QR.new(qr.url).to_terminal
|
|
197
|
-
@out.puts "Scan with the account's phone: Settings > Devices > Link Desktop Device. Waiting 60s..."
|
|
198
|
-
begin
|
|
199
|
-
return if qr.wait(60)
|
|
200
|
-
rescue RPCError => e
|
|
201
|
-
raise unless e.name == "SESSION_PASSWORD_NEEDED"
|
|
202
|
-
|
|
203
|
-
client.check_password(ask_hidden("2FA password (hidden): "))
|
|
204
|
-
return
|
|
205
|
-
end
|
|
206
|
-
qr.recreate
|
|
207
|
-
end
|
|
208
|
-
end
|
|
209
|
-
|
|
210
|
-
def logout(args)
|
|
211
|
-
_rest, opts = parse(args, "logout [--json]", [], "--json" => :flag)
|
|
212
|
-
with_client do |client|
|
|
213
|
-
fail!("Log out failed.") unless client.log_out
|
|
214
|
-
if opts["--json"]
|
|
215
|
-
@out.puts JSON.generate("ok" => true)
|
|
216
|
-
else
|
|
217
|
-
@out.puts "Logged out."
|
|
218
|
-
end
|
|
219
|
-
end
|
|
220
|
-
end
|
|
221
|
-
|
|
222
|
-
def two_fa(args)
|
|
223
|
-
rest, opts = parse(args, "2fa set|remove [--hint HINT] [--email EMAIL] [--json]", ["ACTION"],
|
|
224
|
-
"--hint" => :value, "--email" => :value, "--json" => :flag)
|
|
225
|
-
action = rest[0]
|
|
226
|
-
unless %w[set remove].include?(action)
|
|
227
|
-
raise UsageError, "2fa action must be set or remove\nusage: tg 2fa set|remove [--hint HINT] [--email EMAIL] [--json]"
|
|
228
|
-
end
|
|
229
|
-
fail!("2fa needs an interactive terminal: ssh -t ...") unless tty?
|
|
230
|
-
|
|
231
|
-
with_client do |client|
|
|
232
|
-
if action == "set"
|
|
233
|
-
pwd = client.call(TL.make("account.getPassword"))
|
|
234
|
-
current = pwd["has_password"] ? ask_hidden("Current 2FA password (hidden): ") : nil
|
|
235
|
-
new_pw = ask_hidden("New 2FA password (hidden): ")
|
|
236
|
-
fail!("New password cannot be empty.") if new_pw.empty?
|
|
237
|
-
confirm = ask_hidden("Confirm new 2FA password (hidden): ")
|
|
238
|
-
fail!("Passwords do not match.") unless new_pw == confirm
|
|
239
|
-
email = opts["--email"]
|
|
240
|
-
cb = email ? ->(len) { ask("Email verification code (#{len} digits): ") } : nil
|
|
241
|
-
client.edit_2fa(current_password: current, new_password: new_pw, hint: opts["--hint"] || "",
|
|
242
|
-
email: email, email_code_callback: cb)
|
|
243
|
-
if opts["--json"]
|
|
244
|
-
@out.puts JSON.generate("ok" => true, "action" => "set")
|
|
245
|
-
else
|
|
246
|
-
@out.puts "2FA password updated."
|
|
247
|
-
end
|
|
248
|
-
else
|
|
249
|
-
current = ask_hidden("Current 2FA password (hidden): ")
|
|
250
|
-
fail!("Current password cannot be empty.") if current.empty?
|
|
251
|
-
client.edit_2fa(current_password: current)
|
|
252
|
-
if opts["--json"]
|
|
253
|
-
@out.puts JSON.generate("ok" => true, "action" => "remove")
|
|
254
|
-
else
|
|
255
|
-
@out.puts "2FA password removed."
|
|
256
|
-
end
|
|
257
|
-
end
|
|
258
|
-
end
|
|
259
|
-
end
|
|
260
|
-
|
|
261
|
-
def import_session(args)
|
|
262
|
-
rest, opts = parse(args, "import-session [FILE | --string]", [], "--string" => :flag)
|
|
263
|
-
session = Session.new(@home)
|
|
264
|
-
fail!("#{session.session_path} exists already; remove it to import again.") if session.exists?
|
|
265
|
-
|
|
266
|
-
if opts["--string"]
|
|
267
|
-
unless rest.empty?
|
|
268
|
-
raise UsageError, "do not pass the session string as an argument; pass it via TG_SESSION_STRING or stdin"
|
|
269
|
-
end
|
|
270
|
-
|
|
271
|
-
str = ENV.fetch("TG_SESSION_STRING", "").strip
|
|
272
|
-
if str.empty?
|
|
273
|
-
str = tty? ? ask_hidden("Session string (hidden): ") : @input.gets.to_s.strip
|
|
274
|
-
end
|
|
275
|
-
fail!("No session string provided (set TG_SESSION_STRING or pass it on stdin).") if str.empty?
|
|
276
|
-
|
|
277
|
-
imported = begin
|
|
278
|
-
StringSession.new(str)
|
|
279
|
-
rescue ArgumentError => e
|
|
280
|
-
fail!(e.message)
|
|
281
|
-
end
|
|
282
|
-
fail!("Session string has no auth key.") unless imported.auth_key
|
|
283
|
-
|
|
284
|
-
session.set_dc(imported.dc_id, imported.address, imported.port)
|
|
285
|
-
session.auth_key = imported.auth_key
|
|
286
|
-
session.save
|
|
287
|
-
@out.puts "Imported data center #{session.dc_id} from session string into #{@home}."
|
|
288
|
-
else
|
|
289
|
-
file = rest[0] || File.join(@home, "manager.session")
|
|
290
|
-
count = SessionImport.run(file, session)
|
|
291
|
-
@out.puts "Imported data center #{session.dc_id} and #{count} entities from #{file} into #{@home}."
|
|
292
|
-
end
|
|
293
|
-
rescue SessionImport::Error => e
|
|
294
|
-
fail!(e.message)
|
|
295
|
-
end
|
|
296
|
-
|
|
297
|
-
def export_session(args)
|
|
298
|
-
parse(args, "export-session", [])
|
|
299
|
-
session = Session.new(@home)
|
|
300
|
-
unless session.exists? && session.auth_key
|
|
301
|
-
raise NotLoggedIn, "The session is not logged in: run `tg login` in an interactive terminal."
|
|
302
|
-
end
|
|
303
|
-
|
|
304
|
-
@err.puts "WARNING: this session string grants full access to the Telegram account. Keep it secret."
|
|
305
|
-
@out.puts StringSession.save(session)
|
|
213
|
+
def message_ids(values)
|
|
214
|
+
values.map { |v| Args.positive_int(v, "message id") }
|
|
306
215
|
end
|
|
307
216
|
|
|
308
|
-
def
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
me = client.get_me
|
|
312
|
-
@out.puts "@#{me['username']} (#{me['id']}) #{name_of(me)}".rstrip
|
|
313
|
-
end
|
|
217
|
+
def private_target(directory)
|
|
218
|
+
FileUtils.mkdir_p(directory, mode: 0o700) unless Dir.exist?(directory)
|
|
219
|
+
directory
|
|
314
220
|
end
|
|
315
221
|
|
|
316
|
-
def
|
|
317
|
-
|
|
318
|
-
with_client do |client|
|
|
319
|
-
chat = client.get_entity(rest[0])
|
|
320
|
-
client.forum_topics(chat).each { |topic| @out.puts "#{topic['id']}\t#{topic['title']}" }
|
|
321
|
-
end
|
|
322
|
-
end
|
|
222
|
+
def entity_kind(entity)
|
|
223
|
+
return "unknown" unless entity.is_a?(TL::Object)
|
|
323
224
|
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
with_client do |client|
|
|
330
|
-
chat = client.get_entity(rest[0])
|
|
331
|
-
messages = []
|
|
332
|
-
client.iter_messages(chat, limit: limit, reply_to: topic) { |m| messages << m unless m.service? }
|
|
333
|
-
messages.reverse!
|
|
334
|
-
if opts["--json"]
|
|
335
|
-
@out.puts JSON.pretty_generate(messages.map { |m| message_summary(m) })
|
|
336
|
-
else
|
|
337
|
-
messages.each { |m| @out.puts format_message_line(m) }
|
|
338
|
-
end
|
|
225
|
+
case entity.name
|
|
226
|
+
when "user", "userEmpty" then "user"
|
|
227
|
+
when "channel", "channelForbidden" then entity["megagroup"] ? "supergroup" : "channel"
|
|
228
|
+
when "chat", "chatForbidden" then "group"
|
|
229
|
+
else entity.name
|
|
339
230
|
end
|
|
340
231
|
end
|
|
341
232
|
|
|
342
|
-
def
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
233
|
+
def entity_summary(entity)
|
|
234
|
+
return nil unless entity.is_a?(TL::Object)
|
|
235
|
+
|
|
236
|
+
{
|
|
237
|
+
"id" => Client.peer_id(entity),
|
|
238
|
+
"kind" => entity_kind(entity),
|
|
239
|
+
"username" => entity["username"],
|
|
240
|
+
"name" => name_of(entity),
|
|
241
|
+
"first_name" => entity["first_name"],
|
|
242
|
+
"last_name" => entity["last_name"],
|
|
243
|
+
"title" => entity["title"],
|
|
244
|
+
"bot" => entity["bot"] ? true : false,
|
|
245
|
+
"forum" => entity["forum"] ? true : false
|
|
246
|
+
}
|
|
247
|
+
end
|
|
248
|
+
|
|
249
|
+
def dialog_summary(d)
|
|
250
|
+
{
|
|
251
|
+
"id" => d.id,
|
|
252
|
+
"kind" => entity_kind(d.entity),
|
|
253
|
+
"name" => d.name,
|
|
254
|
+
"username" => d.entity && d.entity["username"],
|
|
255
|
+
"unread_count" => d.unread_count,
|
|
256
|
+
"pinned" => d.pinned,
|
|
257
|
+
"archived" => d.archived,
|
|
258
|
+
"folder_id" => d.folder_id,
|
|
259
|
+
"date" => d.date && CLI.iso_date(d.date),
|
|
260
|
+
"last_message" => d.message && d.message.raw_text
|
|
261
|
+
}
|
|
366
262
|
end
|
|
367
263
|
|
|
368
264
|
def message_summary(m)
|
|
@@ -379,235 +275,29 @@ module Telethon
|
|
|
379
275
|
"#{m.id}\t#{CLI.iso_date(m.date)}\t#{sender}\t#{body}"
|
|
380
276
|
end
|
|
381
277
|
|
|
382
|
-
def
|
|
383
|
-
|
|
384
|
-
"--topic" => :value, "--limit" => :value, "--all" => :flag, "--before" => :value,
|
|
385
|
-
"--out" => :value)
|
|
386
|
-
raise UsageError, "--limit and --all cannot go together" if opts["--limit"] && opts["--all"]
|
|
387
|
-
|
|
388
|
-
options = { topic: opts["--topic"] && Args.integer(opts["--topic"], "--topic"),
|
|
389
|
-
limit: opts["--all"] ? nil : Args.positive_int(opts["--limit"] || "100", "--limit"),
|
|
390
|
-
before: opts["--before"] ? Args.positive_int(opts["--before"], "--before") : 0,
|
|
391
|
-
out: opts["--out"] }
|
|
392
|
-
with_client do |client|
|
|
393
|
-
chat = client.get_entity(rest[0])
|
|
394
|
-
messages = []
|
|
395
|
-
last_id = nil
|
|
396
|
-
fetched = 0
|
|
397
|
-
client.iter_messages(chat, limit: options[:limit], reply_to: options[:topic], offset_id: options[:before]) do |m|
|
|
398
|
-
sender = m.sender
|
|
399
|
-
last_id = m.id
|
|
400
|
-
fetched += 1
|
|
401
|
-
@err.puts "Read #{fetched} messages, oldest id so far: #{last_id}" if (fetched % 1000).zero?
|
|
402
|
-
next if m.service? # joins, pins, topic edits
|
|
403
|
-
|
|
404
|
-
topic = CLI.message_topic(chat, m.raw, options[:topic])
|
|
405
|
-
messages << {
|
|
406
|
-
"id" => m.id, "date" => CLI.iso_date(m.date), "from_id" => m.sender_id,
|
|
407
|
-
"from_username" => sender && sender["username"], "from_name" => name_of(sender),
|
|
408
|
-
"text" => m.raw_text || "", "media" => !m.media.nil?, "file_name" => m.file_name,
|
|
409
|
-
"topic_id" => topic, "link" => CLI.link_for(chat, topic, m.id)
|
|
410
|
-
}
|
|
411
|
-
end
|
|
412
|
-
export = { "chat_id" => Client.peer_id(chat), "chat_title" => chat["title"], "topic_id" => options[:topic],
|
|
413
|
-
"messages" => messages, "next_before" => last_id, "fetched" => fetched,
|
|
414
|
-
"complete" => options[:limit].nil? || fetched < options[:limit] }
|
|
415
|
-
payload = JSON.pretty_generate(export)
|
|
416
|
-
if options[:out]
|
|
417
|
-
PrivateFiles.write(options[:out], payload)
|
|
418
|
-
@err.puts "#{messages.size} messages -> #{options[:out]}"
|
|
419
|
-
else
|
|
420
|
-
@out.puts payload
|
|
421
|
-
end
|
|
422
|
-
end
|
|
423
|
-
end
|
|
424
|
-
|
|
425
|
-
def message_ids(values)
|
|
426
|
-
values.map { |v| Args.positive_int(v, "message id") }
|
|
427
|
-
end
|
|
428
|
-
|
|
429
|
-
def download(args)
|
|
430
|
-
rest, opts = parse(args, "download CHAT ID... [--out DIR]", %w[CHAT ID], "--out" => :value)
|
|
431
|
-
options = { out: opts["--out"] || "." }
|
|
432
|
-
ids = message_ids(rest[1..])
|
|
433
|
-
saved = 0
|
|
434
|
-
with_client do |client|
|
|
435
|
-
chat = client.get_entity(rest[0])
|
|
436
|
-
target = private_target(options[:out])
|
|
437
|
-
found = client.get_messages(chat, ids)
|
|
438
|
-
ids.each_with_index do |id, i|
|
|
439
|
-
message = found[i]
|
|
440
|
-
unless message && message.media
|
|
441
|
-
@err.puts "#{id}\t#{message ? 'no media' : 'no such message'}"
|
|
442
|
-
next
|
|
443
|
-
end
|
|
444
|
-
path = client.download_media(message.raw, target)
|
|
445
|
-
unless path
|
|
446
|
-
@err.puts "#{id}\tno media"
|
|
447
|
-
next
|
|
448
|
-
end
|
|
449
|
-
saved += 1
|
|
450
|
-
@out.puts "#{id}\t#{path}"
|
|
451
|
-
end
|
|
452
|
-
end
|
|
453
|
-
fail!("Nothing downloaded.") if saved.zero?
|
|
454
|
-
end
|
|
455
|
-
|
|
456
|
-
def private_target(directory)
|
|
457
|
-
FileUtils.mkdir_p(directory, mode: 0o700) unless Dir.exist?(directory)
|
|
458
|
-
directory
|
|
459
|
-
end
|
|
460
|
-
|
|
461
|
-
def delete(args)
|
|
462
|
-
rest, opts = parse(args, "delete CHAT ID... [--yes]", %w[CHAT ID], "--yes" => :flag)
|
|
463
|
-
options = { yes: opts["--yes"] }
|
|
464
|
-
ids = rest[1..].map { |v| Args.integer(v, "message id") }
|
|
465
|
-
with_client do |client|
|
|
466
|
-
chat = client.get_entity(rest[0])
|
|
467
|
-
found = client.get_messages(chat, ids).compact
|
|
468
|
-
fail!("None of those messages exist.") if found.empty?
|
|
469
|
-
found.each do |message|
|
|
470
|
-
text = message.raw_text.to_s
|
|
471
|
-
preview = (text.empty? ? "<media>" : text).tr("\n", " ")[0, 80]
|
|
472
|
-
@out.puts "#{message.id}\t#{name_of(message.sender)}\t#{preview}"
|
|
473
|
-
end
|
|
474
|
-
unless options[:yes]
|
|
475
|
-
fail!("Refusing to delete without a terminal to confirm in; pass --yes to skip the prompt.") unless tty?
|
|
476
|
-
answer = ask("Delete these #{found.size} messages for everyone? Type yes: ")
|
|
477
|
-
fail!("Nothing deleted.") unless answer == "yes"
|
|
478
|
-
end
|
|
479
|
-
client.delete_messages(chat, found.map(&:id), revoke: true)
|
|
480
|
-
@out.puts "Deleted #{found.size} messages."
|
|
481
|
-
end
|
|
482
|
-
end
|
|
483
|
-
|
|
484
|
-
def send_command(args)
|
|
485
|
-
rest, opts = parse(args, "send CHAT TEXT [--topic ID] [--file PATH]...", %w[CHAT TEXT],
|
|
486
|
-
"--topic" => :value, "--file" => :list)
|
|
487
|
-
options = { topic: opts["--topic"] && Args.integer(opts["--topic"], "--topic") }
|
|
488
|
-
files = opts["--file"] || []
|
|
489
|
-
files.each { |path| fail!("no such file: #{path}") unless File.file?(path) }
|
|
490
|
-
with_client do |client|
|
|
491
|
-
chat = client.get_entity(rest[0])
|
|
492
|
-
if files.empty?
|
|
493
|
-
@out.puts "Sent message #{client.send_message(chat, rest[1], reply_to: options[:topic])&.id}."
|
|
494
|
-
else
|
|
495
|
-
# One file goes as one message, several as albums, as Telethon sends a file and a list.
|
|
496
|
-
sent = client.send_file(chat, files.size == 1 ? files[0] : files, caption: rest[1],
|
|
497
|
-
reply_to: options[:topic], force_document: true)
|
|
498
|
-
sent = [sent] unless sent.is_a?(Array)
|
|
499
|
-
@out.puts "Sent message #{sent.map { |m| m&.id }.join(', ')}."
|
|
500
|
-
end
|
|
501
|
-
end
|
|
278
|
+
def tl_to_json(value)
|
|
279
|
+
Call.to_json_value(value)
|
|
502
280
|
end
|
|
503
281
|
|
|
504
|
-
def
|
|
505
|
-
rest, =
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
end
|
|
282
|
+
def call_command(args)
|
|
283
|
+
rest, = parse_for("call", args)
|
|
284
|
+
method_name = rest[0]
|
|
285
|
+
json_text = rest[1] || "{}"
|
|
286
|
+
# Validate method and JSON syntax before connecting so usage errors fail fast with exit 2.
|
|
287
|
+
ctor = TL.schema.named(method_name)
|
|
288
|
+
raise UsageError, "unknown TL method #{method_name.inspect} in layer #{TL::LAYER}" unless ctor && ctor.function
|
|
512
289
|
|
|
513
|
-
|
|
514
|
-
rest, opts = parse(args, "forward CHAT ID... [--from CHAT] [--delete-source]", %w[CHAT ID],
|
|
515
|
-
"--from" => :value, "--delete-source" => :flag)
|
|
516
|
-
options = { from: opts["--from"] || "me", delete_source: opts["--delete-source"] }
|
|
517
|
-
ids = message_ids(rest[1..])
|
|
290
|
+
Call.parse_json_object(json_text)
|
|
518
291
|
with_client do |client|
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
@out.puts "Forwarded as message #{sent.map { |m| m&.id }.join(', ')}."
|
|
523
|
-
if options[:delete_source]
|
|
524
|
-
client.delete_messages(source, ids)
|
|
525
|
-
@out.puts "Deleted #{ids.size} source messages."
|
|
526
|
-
end
|
|
292
|
+
request = Call.build_request(method_name, json_text, client)
|
|
293
|
+
result = client.call(request)
|
|
294
|
+
@out.puts JSON.pretty_generate(Call.to_json_value(result))
|
|
527
295
|
end
|
|
528
296
|
end
|
|
529
297
|
|
|
530
|
-
def
|
|
531
|
-
rest,
|
|
532
|
-
|
|
533
|
-
bot_ref = rest[0]
|
|
534
|
-
query = rest[1..].join(" ")
|
|
535
|
-
pick = opts["--pick"] && Args.integer(opts["--pick"], "--pick")
|
|
536
|
-
raise UsageError, "--pick must be >= 0" if pick && pick.negative?
|
|
537
|
-
|
|
538
|
-
with_client do |client|
|
|
539
|
-
target = opts["--to"] ? client.get_entity(opts["--to"]) : nil
|
|
540
|
-
results = client.inline_query(bot_ref, query, entity: target)
|
|
541
|
-
if pick
|
|
542
|
-
chosen = results[pick]
|
|
543
|
-
fail!("No inline result at index #{pick} (#{results.size} available).") unless chosen
|
|
544
|
-
dest = target || client.get_entity("me")
|
|
545
|
-
sent = chosen.click(dest)
|
|
546
|
-
if opts["--json"]
|
|
547
|
-
@out.puts JSON.generate("id" => sent&.id, "query_id" => results.query_id, "result_id" => chosen.result["id"])
|
|
548
|
-
else
|
|
549
|
-
@out.puts "Sent message #{sent&.id}."
|
|
550
|
-
end
|
|
551
|
-
elsif opts["--json"]
|
|
552
|
-
items = []
|
|
553
|
-
results.each_with_index do |r, i|
|
|
554
|
-
items << { "index" => i, "id" => r.result["id"], "type" => r.type,
|
|
555
|
-
"title" => r.title, "description" => r.description, "url" => r.url }
|
|
556
|
-
end
|
|
557
|
-
@out.puts JSON.pretty_generate(items)
|
|
558
|
-
else
|
|
559
|
-
results.each_with_index do |r, i|
|
|
560
|
-
@out.puts "#{i}\t#{r.type}\t#{r.title}\t#{r.description}".rstrip
|
|
561
|
-
end
|
|
562
|
-
end
|
|
563
|
-
end
|
|
564
|
-
end
|
|
565
|
-
|
|
566
|
-
def click_command(args)
|
|
567
|
-
rest, opts = parse(args, "click CHAT ID BUTTON [--json]", %w[CHAT ID BUTTON], "--json" => :flag)
|
|
568
|
-
msg_id = Args.positive_int(rest[1], "message id")
|
|
569
|
-
button_spec = rest[2..].join(" ")
|
|
570
|
-
with_client do |client|
|
|
571
|
-
chat = client.get_entity(rest[0])
|
|
572
|
-
msg = client.get_messages(chat, ids: msg_id)
|
|
573
|
-
fail!("Message #{msg_id} not found.") unless msg
|
|
574
|
-
fail!("Message #{msg_id} has no buttons.") if msg.button_count.zero?
|
|
575
|
-
|
|
576
|
-
begin
|
|
577
|
-
result = if button_spec.match?(/\A\d+\z/)
|
|
578
|
-
msg.click(button_spec.to_i)
|
|
579
|
-
else
|
|
580
|
-
buttons = msg.get_buttons || []
|
|
581
|
-
found = buttons.flatten.any? { |b| b.text == button_spec }
|
|
582
|
-
fail!("No button with text #{button_spec.inspect}.") unless found
|
|
583
|
-
msg.click(text: button_spec)
|
|
584
|
-
end
|
|
585
|
-
rescue IndexError => e
|
|
586
|
-
fail!(e.message)
|
|
587
|
-
end
|
|
588
|
-
|
|
589
|
-
if opts["--json"]
|
|
590
|
-
payload = if result.is_a?(TL::Object)
|
|
591
|
-
{ "ok" => true, "message" => result["message"], "url" => result["url"],
|
|
592
|
-
"alert" => result["alert"] ? true : false }
|
|
593
|
-
elsif result.is_a?(Message)
|
|
594
|
-
{ "ok" => true, "sent_id" => result.id }
|
|
595
|
-
elsif result.is_a?(String)
|
|
596
|
-
{ "ok" => true, "url" => result }
|
|
597
|
-
else
|
|
598
|
-
{ "ok" => true }
|
|
599
|
-
end
|
|
600
|
-
@out.puts JSON.generate(payload)
|
|
601
|
-
elsif result.is_a?(TL::Object)
|
|
602
|
-
@out.puts result["message"] || result["url"] || "Clicked."
|
|
603
|
-
elsif result.is_a?(Message)
|
|
604
|
-
@out.puts "Sent message #{result.id}."
|
|
605
|
-
elsif result.is_a?(String)
|
|
606
|
-
@out.puts result
|
|
607
|
-
else
|
|
608
|
-
@out.puts "Clicked."
|
|
609
|
-
end
|
|
610
|
-
end
|
|
298
|
+
def completion_command(args)
|
|
299
|
+
rest, = parse_for("completion", args)
|
|
300
|
+
@out.print Completion.generate(rest[0])
|
|
611
301
|
end
|
|
612
302
|
end
|
|
613
303
|
end
|