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,357 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Telethon
4
+ module CLI
5
+ module AccountCommands
6
+ private
7
+
8
+ def login(args)
9
+ _rest, options = parse_for("login", args)
10
+ raise UsageError, "--qr and --bot-token cannot go together" if options["--qr"] && options["--bot-token"]
11
+
12
+ config = with_shared_api(File.exist?(config_path) ? JSON.parse(File.read(config_path, encoding: "UTF-8")) : {})
13
+ if options["--bot-token"]
14
+ token = ENV.fetch("TG_BOT_TOKEN", "").strip
15
+ if token.empty?
16
+ token = tty? ? ask_hidden("Bot token (hidden): ") : @input.gets.to_s.strip
17
+ end
18
+ fail!("No bot token provided (set TG_BOT_TOKEN or pass it on stdin).") if token.empty?
19
+ unless config["api_id"]
20
+ if !ENV.fetch("TG_API_ID", "").empty? && !ENV.fetch("TG_API_HASH", "").empty?
21
+ config["api_id"] = Integer(ENV.fetch("TG_API_ID"), 10)
22
+ config["api_hash"] = ENV.fetch("TG_API_HASH")
23
+ save_config(config)
24
+ else
25
+ fail!("login needs an interactive terminal to enter API id/hash (or set TG_API_ID and TG_API_HASH).") unless tty?
26
+ @out.puts "API id and hash come from https://my.telegram.org, logged in as the account."
27
+ config["api_id"] = Integer(ask("API id: "), 10)
28
+ config["api_hash"] = ask_hidden("API hash (hidden): ")
29
+ save_config(config)
30
+ end
31
+ end
32
+ PrivateFiles.directory(@home)
33
+ client = new_client(config)
34
+ client.connect
35
+ client.sign_in(bot_token: token) unless client.session.exists? && client.authorized?
36
+ else
37
+ fail!("login needs an interactive terminal: ssh -t ...") unless tty?
38
+ unless config["api_id"]
39
+ @out.puts "API id and hash come from https://my.telegram.org, logged in as the account."
40
+ config["api_id"] = Integer(ask("API id: "), 10)
41
+ config["api_hash"] = ask_hidden("API hash (hidden): ")
42
+ save_config(config)
43
+ end
44
+ PrivateFiles.directory(@home)
45
+ client = new_client(config)
46
+ client.connect
47
+ unless client.session.exists? && client.authorized?
48
+ options["--qr"] ? login_with_qr(client) : login_with_code(client)
49
+ end
50
+ end
51
+ me = client.get_me
52
+ config["account"] = me["username"]
53
+ save_config(config)
54
+ if options["--json"]
55
+ @out.puts JSON.generate("ok" => true, "user" => entity_summary(me), "session_path" => client.session.session_path)
56
+ else
57
+ @out.puts "Logged in as @#{me['username']} (#{me['id']}). Session: #{client.session.session_path}"
58
+ end
59
+ ensure
60
+ client&.disconnect
61
+ end
62
+
63
+ def login_with_code(client)
64
+ phone = ask("Phone, international format (+380...): ")
65
+ sent = client.send_code(phone)
66
+ @out.puts "Code sent via #{Client.code_delivery(sent)}."
67
+ code = ask(Commands::CODE_PROMPT)
68
+ if code.empty?
69
+ sent = client.resend_code(phone, sent["phone_code_hash"])
70
+ @out.puts "Resent via #{Client.code_delivery(sent)}."
71
+ code = ask("Code: ")
72
+ end
73
+ begin
74
+ client.sign_in(phone, code, sent["phone_code_hash"])
75
+ rescue RPCError => e
76
+ raise unless e.name == "SESSION_PASSWORD_NEEDED"
77
+
78
+ client.check_password(ask_hidden("2FA password (hidden): "))
79
+ end
80
+ end
81
+
82
+ def login_with_qr(client)
83
+ qr = client.qr_login
84
+ loop do
85
+ @out.print QR.new(qr.url).to_terminal
86
+ @out.puts "Scan with the account's phone: Settings > Devices > Link Desktop Device. Waiting 60s..."
87
+ begin
88
+ return if qr.wait(60)
89
+ rescue RPCError => e
90
+ raise unless e.name == "SESSION_PASSWORD_NEEDED"
91
+
92
+ client.check_password(ask_hidden("2FA password (hidden): "))
93
+ return
94
+ end
95
+ qr.recreate
96
+ end
97
+ end
98
+
99
+ def logout(args)
100
+ _rest, opts = parse_for("logout", args)
101
+ with_client do |client|
102
+ fail!("Log out failed.") unless client.log_out
103
+ if opts["--json"]
104
+ @out.puts JSON.generate("ok" => true)
105
+ else
106
+ @out.puts "Logged out."
107
+ end
108
+ end
109
+ end
110
+
111
+ def two_fa(args)
112
+ rest, opts = parse_for("2fa", args)
113
+ action = rest[0]
114
+ usage_error("2fa", "2fa action must be set or remove") unless %w[set remove].include?(action)
115
+ fail!("2fa needs an interactive terminal: ssh -t ...") unless tty?
116
+
117
+ with_client do |client|
118
+ if action == "set"
119
+ pwd = client.call(TL.make("account.getPassword"))
120
+ current = pwd["has_password"] ? ask_hidden("Current 2FA password (hidden): ") : nil
121
+ new_pw = ask_hidden("New 2FA password (hidden): ")
122
+ fail!("New password cannot be empty.") if new_pw.empty?
123
+ confirm = ask_hidden("Confirm new 2FA password (hidden): ")
124
+ fail!("Passwords do not match.") unless new_pw == confirm
125
+ email = opts["--email"]
126
+ cb = email ? ->(len) { ask("Email verification code (#{len} digits): ") } : nil
127
+ client.edit_2fa(current_password: current, new_password: new_pw, hint: opts["--hint"] || "",
128
+ email: email, email_code_callback: cb)
129
+ if opts["--json"]
130
+ @out.puts JSON.generate("ok" => true, "action" => "set")
131
+ else
132
+ @out.puts "2FA password updated."
133
+ end
134
+ else
135
+ current = ask_hidden("Current 2FA password (hidden): ")
136
+ fail!("Current password cannot be empty.") if current.empty?
137
+ client.edit_2fa(current_password: current)
138
+ if opts["--json"]
139
+ @out.puts JSON.generate("ok" => true, "action" => "remove")
140
+ else
141
+ @out.puts "2FA password removed."
142
+ end
143
+ end
144
+ end
145
+ end
146
+
147
+ def import_session(args)
148
+ rest, opts = parse_for("import-session", args)
149
+ session = Session.new(@home)
150
+ fail!("#{session.session_path} exists already; remove it to import again.") if session.exists?
151
+
152
+ if opts["--string"]
153
+ unless rest.empty?
154
+ raise UsageError, "do not pass the session string as an argument; pass it via TG_SESSION_STRING or stdin"
155
+ end
156
+
157
+ str = ENV.fetch("TG_SESSION_STRING", "").strip
158
+ if str.empty?
159
+ str = tty? ? ask_hidden("Session string (hidden): ") : @input.gets.to_s.strip
160
+ end
161
+ fail!("No session string provided (set TG_SESSION_STRING or pass it on stdin).") if str.empty?
162
+
163
+ imported = begin
164
+ StringSession.new(str)
165
+ rescue ArgumentError => e
166
+ fail!(e.message)
167
+ end
168
+ fail!("Session string has no auth key.") unless imported.auth_key
169
+
170
+ session.set_dc(imported.dc_id, imported.address, imported.port)
171
+ session.auth_key = imported.auth_key
172
+ session.save
173
+ if opts["--json"]
174
+ @out.puts JSON.generate("ok" => true, "dc_id" => session.dc_id, "entities" => 0, "home" => @home)
175
+ else
176
+ @out.puts "Imported data center #{session.dc_id} from session string into #{@home}."
177
+ end
178
+ else
179
+ file = rest[0] || File.join(@home, "manager.session")
180
+ count = SessionImport.run(file, session)
181
+ if opts["--json"]
182
+ @out.puts JSON.generate("ok" => true, "dc_id" => session.dc_id, "entities" => count, "home" => @home)
183
+ else
184
+ @out.puts "Imported data center #{session.dc_id} and #{count} entities from #{file} into #{@home}."
185
+ end
186
+ end
187
+ rescue SessionImport::Error => e
188
+ fail!(e.message)
189
+ end
190
+
191
+ def export_session(args)
192
+ _rest, opts = parse_for("export-session", args)
193
+ session = Session.new(@home)
194
+ unless session.exists? && session.auth_key
195
+ raise NotLoggedIn, "The session is not logged in: run `tg login` in an interactive terminal."
196
+ end
197
+
198
+ @err.puts "WARNING: this session string grants full access to the Telegram account. Keep it secret."
199
+ encoded = StringSession.save(session)
200
+ if opts["--json"]
201
+ @out.puts JSON.generate("session" => encoded)
202
+ else
203
+ @out.puts encoded
204
+ end
205
+ end
206
+
207
+ def whoami(args)
208
+ _rest, opts = parse_for("whoami", args)
209
+ with_client do |client|
210
+ me = client.get_me
211
+ if opts["--json"]
212
+ @out.puts JSON.pretty_generate(entity_summary(me))
213
+ else
214
+ @out.puts "@#{me['username']} (#{me['id']}) #{name_of(me)}".rstrip
215
+ end
216
+ end
217
+ end
218
+
219
+ # The accounts saved under TG_HOME, read from disk only; `accounts rename OLD NEW` renames one.
220
+ def accounts_command(args)
221
+ rest, opts = parse_for("accounts", args)
222
+ return rename_account(rest, opts) if rest[0] == "rename"
223
+ raise UsageError, "unknown accounts action #{rest[0]} (did you mean rename?)" unless rest.empty?
224
+
225
+ items = CLI.accounts(@base_home).map do |item|
226
+ current = item["name"] == "default" ? @account.nil? : @account == item["name"]
227
+ { "name" => item["name"], "username" => item["username"], "id" => item["id"],
228
+ "logged_in" => item["logged_in"], "current" => current }
229
+ end
230
+ if opts["--json"]
231
+ @out.puts JSON.pretty_generate(items)
232
+ elsif items.empty?
233
+ @out.puts "No accounts yet: run `tg login` (or `tg --account NAME login`)."
234
+ else
235
+ items.each do |item|
236
+ mark = item["current"] ? "*" : " "
237
+ user = item["username"] ? "@#{item['username']}" : "-"
238
+ state = item["logged_in"] ? "logged in" : "not logged in"
239
+ @out.puts "#{mark} #{item['name']}\t#{user}\t#{item['id'] || '-'}\t#{state}"
240
+ end
241
+ end
242
+ end
243
+
244
+ # Renames accounts/OLD to accounts/NEW. OLD may be a name, @username or id; the default account,
245
+ # which lives in TG_HOME itself, has no name to change.
246
+ def rename_account(rest, opts)
247
+ usage_error("accounts", "accounts rename needs OLD and NEW") unless rest.size == 3
248
+ old_name = CLI.resolve_account(@base_home, rest[1])
249
+ new_name = rest[2]
250
+ fail!("The default account lives in #{@base_home} itself and has no name to change.") if old_name.nil?
251
+ old_dir = File.join(@base_home, "accounts", old_name)
252
+ fail!("No saved account is #{rest[1]}: see `tg accounts`.") unless File.directory?(old_dir)
253
+ unless new_name.match?(CLI::ACCOUNT_NAME) && new_name != "default" && !new_name.match?(/\A\d+\z/)
254
+ raise UsageError, "bad account name #{new_name.inspect} (letters, digits, _ . -; not default, not only digits)"
255
+ end
256
+ new_dir = File.join(@base_home, "accounts", new_name)
257
+ fail!("An account named #{new_name} exists already.") if File.exist?(new_dir)
258
+
259
+ File.rename(old_dir, new_dir)
260
+ if opts["--json"]
261
+ @out.puts JSON.generate("ok" => true, "from" => old_name, "to" => new_name)
262
+ else
263
+ @out.puts "Renamed account #{old_name} to #{new_name}."
264
+ end
265
+ end
266
+
267
+ def sessions_command(args)
268
+ _rest, opts = parse_for("sessions", args)
269
+ with_client do |client|
270
+ if opts["--terminate"]
271
+ hash = Args.integer(opts["--terminate"], "--terminate")
272
+ unless opts["--yes"]
273
+ fail!("Refusing to terminate a session without a terminal to confirm in; pass --yes.") unless tty?
274
+ fail!("Nothing terminated.") unless ask("Log out session #{hash}? Type yes: ") == "yes"
275
+ end
276
+ client.call(TL.make("account.resetAuthorization", "hash" => hash))
277
+ if opts["--json"]
278
+ @out.puts JSON.generate("ok" => true, "terminated" => hash)
279
+ else
280
+ @out.puts "Terminated session #{hash}."
281
+ end
282
+ else
283
+ res = client.call(TL.make("account.getAuthorizations"))
284
+ auths = res["authorizations"]
285
+ if opts["--json"]
286
+ items = auths.map do |a|
287
+ {
288
+ "hash" => a["hash"], "current" => a["current"] ? true : false,
289
+ "device_model" => a["device_model"], "platform" => a["platform"],
290
+ "app_name" => a["app_name"], "app_version" => a["app_version"],
291
+ "country" => a["country"], "date_created" => CLI.iso_date(a["date_created"]),
292
+ "date_active" => CLI.iso_date(a["date_active"])
293
+ }
294
+ end
295
+ @out.puts JSON.pretty_generate(items)
296
+ else
297
+ auths.each do |a|
298
+ mark = a["current"] ? "*" : " "
299
+ @out.puts "#{a['hash']}\t#{mark}\t#{a['app_name']} #{a['app_version']}\t#{a['device_model']}\t#{a['country']}\t#{CLI.iso_date(a['date_active'])}"
300
+ end
301
+ end
302
+ end
303
+ end
304
+ end
305
+
306
+ def profile_command(args)
307
+ _rest, opts = parse_for("profile", args)
308
+ photo = opts["--photo"]
309
+ fail!("no such file: #{photo}") if photo && !File.file?(photo)
310
+
311
+ changing_profile = opts.key?("--first-name") || opts.key?("--last-name") || opts.key?("--bio")
312
+ changing = changing_profile || opts.key?("--username") || !photo.nil?
313
+
314
+ with_client do |client|
315
+ unless changing
316
+ full = client.call(TL.make("users.getFullUser", "id" => TL.make("inputUserSelf")))
317
+ me = full["users"][0] || client.get_me
318
+ bio = full["full_user"]["about"]
319
+ summary = entity_summary(me).merge("bio" => bio)
320
+ if opts["--json"]
321
+ @out.puts JSON.pretty_generate(summary)
322
+ else
323
+ @out.puts "name: #{summary['name']}"
324
+ @out.puts "username: @#{summary['username']}" if summary["username"]
325
+ @out.puts "bio: #{bio}" if bio && !bio.empty?
326
+ end
327
+ return
328
+ end
329
+
330
+ updated = []
331
+ if changing_profile
332
+ client.call(TL.make("account.updateProfile", "first_name" => opts["--first-name"],
333
+ "last_name" => opts["--last-name"],
334
+ "about" => opts["--bio"]))
335
+ updated << "first_name" if opts.key?("--first-name")
336
+ updated << "last_name" if opts.key?("--last-name")
337
+ updated << "bio" if opts.key?("--bio")
338
+ end
339
+ if opts.key?("--username")
340
+ client.call(TL.make("account.updateUsername", "username" => opts["--username"].delete_prefix("@")))
341
+ updated << "username"
342
+ end
343
+ if photo
344
+ uploaded = client.upload_file(photo)
345
+ client.call(TL.make("photos.uploadProfilePhoto", "file" => uploaded))
346
+ updated << "photo"
347
+ end
348
+ if opts["--json"]
349
+ @out.puts JSON.generate("ok" => true, "updated" => updated)
350
+ else
351
+ @out.puts "Profile updated (#{updated.join(', ')})."
352
+ end
353
+ end
354
+ end
355
+ end
356
+ end
357
+ end
@@ -0,0 +1,91 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Telethon
4
+ module CLI
5
+ module BotsCommands
6
+ private
7
+
8
+ def inline_command(args)
9
+ rest, opts = parse_for("inline", args)
10
+ bot_ref = rest[0]
11
+ query = rest[1..].join(" ")
12
+ pick = opts["--pick"] && Args.integer(opts["--pick"], "--pick")
13
+ raise UsageError, "--pick must be >= 0" if pick && pick.negative?
14
+
15
+ with_client do |client|
16
+ target = opts["--to"] ? client.get_entity(opts["--to"]) : nil
17
+ results = client.inline_query(bot_ref, query, entity: target)
18
+ if pick
19
+ chosen = results[pick]
20
+ fail!("No inline result at index #{pick} (#{results.size} available).") unless chosen
21
+ dest = target || client.get_entity("me")
22
+ sent = chosen.click(dest)
23
+ if opts["--json"]
24
+ @out.puts JSON.generate("id" => sent&.id, "query_id" => results.query_id, "result_id" => chosen.result["id"])
25
+ else
26
+ @out.puts "Sent message #{sent&.id}."
27
+ end
28
+ elsif opts["--json"]
29
+ items = []
30
+ results.each_with_index do |r, i|
31
+ items << { "index" => i, "id" => r.result["id"], "type" => r.type,
32
+ "title" => r.title, "description" => r.description, "url" => r.url }
33
+ end
34
+ @out.puts JSON.pretty_generate(items)
35
+ else
36
+ results.each_with_index do |r, i|
37
+ @out.puts "#{i}\t#{r.type}\t#{r.title}\t#{r.description}".rstrip
38
+ end
39
+ end
40
+ end
41
+ end
42
+
43
+ def click_command(args)
44
+ rest, opts = parse_for("click", args)
45
+ msg_id = Args.positive_int(rest[1], "message id")
46
+ button_spec = rest[2..].join(" ")
47
+ with_client do |client|
48
+ chat = client.get_entity(rest[0])
49
+ msg = client.get_messages(chat, ids: msg_id)
50
+ fail!("Message #{msg_id} not found.") unless msg
51
+ fail!("Message #{msg_id} has no buttons.") if msg.button_count.zero?
52
+
53
+ begin
54
+ result = if button_spec.match?(/\A\d+\z/)
55
+ msg.click(button_spec.to_i)
56
+ else
57
+ buttons = msg.get_buttons || []
58
+ found = buttons.flatten.any? { |b| b.text == button_spec }
59
+ fail!("No button with text #{button_spec.inspect}.") unless found
60
+ msg.click(text: button_spec)
61
+ end
62
+ rescue IndexError => e
63
+ fail!(e.message)
64
+ end
65
+
66
+ if opts["--json"]
67
+ payload = if result.is_a?(TL::Object)
68
+ { "ok" => true, "message" => result["message"], "url" => result["url"],
69
+ "alert" => result["alert"] ? true : false }
70
+ elsif result.is_a?(Message)
71
+ { "ok" => true, "sent_id" => result.id }
72
+ elsif result.is_a?(String)
73
+ { "ok" => true, "url" => result }
74
+ else
75
+ { "ok" => true }
76
+ end
77
+ @out.puts JSON.generate(payload)
78
+ elsif result.is_a?(TL::Object)
79
+ @out.puts result["message"] || result["url"] || "Clicked."
80
+ elsif result.is_a?(Message)
81
+ @out.puts "Sent message #{result.id}."
82
+ elsif result.is_a?(String)
83
+ @out.puts result
84
+ else
85
+ @out.puts "Clicked."
86
+ end
87
+ end
88
+ end
89
+ end
90
+ end
91
+ end