telethon 0.1.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 +7 -0
- data/CHANGELOG.md +30 -0
- data/LICENSE +48 -0
- data/README.md +84 -0
- data/data/api.tl +3336 -0
- data/data/mtproto.tl +116 -0
- data/exe/tg +6 -0
- data/lib/telethon/assertions.rb +30 -0
- data/lib/telethon/cli/args.rb +74 -0
- data/lib/telethon/cli/commands.rb +339 -0
- data/lib/telethon/cli.rb +114 -0
- data/lib/telethon/client/auth.rb +149 -0
- data/lib/telethon/client/entities.rb +153 -0
- data/lib/telethon/client/files.rb +236 -0
- data/lib/telethon/client/messages.rb +154 -0
- data/lib/telethon/client.rb +174 -0
- data/lib/telethon/crypto/aes.rb +105 -0
- data/lib/telethon/crypto/hashes.rb +45 -0
- data/lib/telethon/crypto/native.rb +44 -0
- data/lib/telethon/crypto/num.rb +189 -0
- data/lib/telethon/crypto/rsa.rb +39 -0
- data/lib/telethon/crypto/srp.rb +99 -0
- data/lib/telethon/errors.rb +52 -0
- data/lib/telethon/network/auth_key.rb +21 -0
- data/lib/telethon/network/authenticator.rb +133 -0
- data/lib/telethon/network/sender.rb +168 -0
- data/lib/telethon/network/state.rb +103 -0
- data/lib/telethon/network/transport.rb +94 -0
- data/lib/telethon/private_files.rb +25 -0
- data/lib/telethon/qr.rb +356 -0
- data/lib/telethon/session.rb +153 -0
- data/lib/telethon/tl/binary.rb +124 -0
- data/lib/telethon/tl/codec.rb +194 -0
- data/lib/telethon/tl/object.rb +47 -0
- data/lib/telethon/tl/schema.rb +128 -0
- data/lib/telethon/tl/schema_data.rb +2709 -0
- data/lib/telethon/version.rb +7 -0
- data/lib/telethon.rb +35 -0
- data/telethon.gemspec +33 -0
- metadata +102 -0
data/data/mtproto.tl
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
// Core types (no need to gen)
|
|
2
|
+
|
|
3
|
+
//vector#1cb5c415 {t:Type} # [ t ] = Vector t;
|
|
4
|
+
|
|
5
|
+
///////////////////////////////
|
|
6
|
+
/// Authorization key creation
|
|
7
|
+
///////////////////////////////
|
|
8
|
+
|
|
9
|
+
resPQ#05162463 nonce:int128 server_nonce:int128 pq:string server_public_key_fingerprints:Vector<long> = ResPQ;
|
|
10
|
+
|
|
11
|
+
p_q_inner_data#83c95aec pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 = P_Q_inner_data;
|
|
12
|
+
p_q_inner_data_dc#a9f55f95 pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 dc:int = P_Q_inner_data;
|
|
13
|
+
p_q_inner_data_temp#3c6a84d4 pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 expires_in:int = P_Q_inner_data;
|
|
14
|
+
p_q_inner_data_temp_dc#56fddf88 pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 dc:int expires_in:int = P_Q_inner_data;
|
|
15
|
+
|
|
16
|
+
bind_auth_key_inner#75a3f765 nonce:long temp_auth_key_id:long perm_auth_key_id:long temp_session_id:long expires_at:int = BindAuthKeyInner;
|
|
17
|
+
|
|
18
|
+
server_DH_params_fail#79cb045d nonce:int128 server_nonce:int128 new_nonce_hash:int128 = Server_DH_Params;
|
|
19
|
+
server_DH_params_ok#d0e8075c nonce:int128 server_nonce:int128 encrypted_answer:string = Server_DH_Params;
|
|
20
|
+
|
|
21
|
+
server_DH_inner_data#b5890dba nonce:int128 server_nonce:int128 g:int dh_prime:string g_a:string server_time:int = Server_DH_inner_data;
|
|
22
|
+
|
|
23
|
+
client_DH_inner_data#6643b654 nonce:int128 server_nonce:int128 retry_id:long g_b:string = Client_DH_Inner_Data;
|
|
24
|
+
|
|
25
|
+
dh_gen_ok#3bcbf734 nonce:int128 server_nonce:int128 new_nonce_hash1:int128 = Set_client_DH_params_answer;
|
|
26
|
+
dh_gen_retry#46dc1fb9 nonce:int128 server_nonce:int128 new_nonce_hash2:int128 = Set_client_DH_params_answer;
|
|
27
|
+
dh_gen_fail#a69dae02 nonce:int128 server_nonce:int128 new_nonce_hash3:int128 = Set_client_DH_params_answer;
|
|
28
|
+
|
|
29
|
+
destroy_auth_key_ok#f660e1d4 = DestroyAuthKeyRes;
|
|
30
|
+
destroy_auth_key_none#0a9f2259 = DestroyAuthKeyRes;
|
|
31
|
+
destroy_auth_key_fail#ea109b13 = DestroyAuthKeyRes;
|
|
32
|
+
|
|
33
|
+
---functions---
|
|
34
|
+
|
|
35
|
+
req_pq#60469778 nonce:int128 = ResPQ;
|
|
36
|
+
req_pq_multi#be7e8ef1 nonce:int128 = ResPQ;
|
|
37
|
+
|
|
38
|
+
req_DH_params#d712e4be nonce:int128 server_nonce:int128 p:string q:string public_key_fingerprint:long encrypted_data:string = Server_DH_Params;
|
|
39
|
+
|
|
40
|
+
set_client_DH_params#f5045f1f nonce:int128 server_nonce:int128 encrypted_data:string = Set_client_DH_params_answer;
|
|
41
|
+
|
|
42
|
+
destroy_auth_key#d1435160 = DestroyAuthKeyRes;
|
|
43
|
+
|
|
44
|
+
///////////////////////////////
|
|
45
|
+
////////////// System messages
|
|
46
|
+
///////////////////////////////
|
|
47
|
+
|
|
48
|
+
---types---
|
|
49
|
+
|
|
50
|
+
msgs_ack#62d6b459 msg_ids:Vector<long> = MsgsAck;
|
|
51
|
+
|
|
52
|
+
bad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int error_code:int = BadMsgNotification;
|
|
53
|
+
bad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int error_code:int new_server_salt:long = BadMsgNotification;
|
|
54
|
+
|
|
55
|
+
msgs_state_req#da69fb52 msg_ids:Vector<long> = MsgsStateReq;
|
|
56
|
+
msgs_state_info#04deb57d req_msg_id:long info:string = MsgsStateInfo;
|
|
57
|
+
msgs_all_info#8cc0d131 msg_ids:Vector<long> info:string = MsgsAllInfo;
|
|
58
|
+
|
|
59
|
+
msg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long bytes:int status:int = MsgDetailedInfo;
|
|
60
|
+
msg_new_detailed_info#809db6df answer_msg_id:long bytes:int status:int = MsgDetailedInfo;
|
|
61
|
+
|
|
62
|
+
msg_resend_req#7d861a08 msg_ids:Vector<long> = MsgResendReq;
|
|
63
|
+
|
|
64
|
+
//rpc_result#f35c6d01 req_msg_id:long result:Object = RpcResult; // parsed manually
|
|
65
|
+
|
|
66
|
+
rpc_error#2144ca19 error_code:int error_message:string = RpcError;
|
|
67
|
+
|
|
68
|
+
rpc_answer_unknown#5e2ad36e = RpcDropAnswer;
|
|
69
|
+
rpc_answer_dropped_running#cd78e586 = RpcDropAnswer;
|
|
70
|
+
rpc_answer_dropped#a43ad8b7 msg_id:long seq_no:int bytes:int = RpcDropAnswer;
|
|
71
|
+
|
|
72
|
+
future_salt#0949d9dc valid_since:int valid_until:int salt:long = FutureSalt;
|
|
73
|
+
future_salts#ae500895 req_msg_id:long now:int salts:vector<future_salt> = FutureSalts;
|
|
74
|
+
|
|
75
|
+
pong#347773c5 msg_id:long ping_id:long = Pong;
|
|
76
|
+
|
|
77
|
+
destroy_session_ok#e22045fc session_id:long = DestroySessionRes;
|
|
78
|
+
destroy_session_none#62d350c9 session_id:long = DestroySessionRes;
|
|
79
|
+
|
|
80
|
+
new_session_created#9ec20908 first_msg_id:long unique_id:long server_salt:long = NewSession;
|
|
81
|
+
|
|
82
|
+
//message msg_id:long seqno:int bytes:int body:Object = Message; // parsed manually
|
|
83
|
+
//msg_container#73f1f8dc messages:vector<message> = MessageContainer; // parsed manually
|
|
84
|
+
//msg_copy#e06046b2 orig_message:Message = MessageCopy; // parsed manually, not used - use msg_container
|
|
85
|
+
//gzip_packed#3072cfa1 packed_data:string = Object; // parsed manually
|
|
86
|
+
|
|
87
|
+
http_wait#9299359f max_delay:int wait_after:int max_wait:int = HttpWait;
|
|
88
|
+
|
|
89
|
+
//ipPort ipv4:int port:int = IpPort;
|
|
90
|
+
//help.configSimple#d997c3c5 date:int expires:int dc_id:int ip_port_list:Vector<ipPort> = help.ConfigSimple;
|
|
91
|
+
|
|
92
|
+
ipPort#d433ad73 ipv4:int port:int = IpPort;
|
|
93
|
+
ipPortSecret#37982646 ipv4:int port:int secret:bytes = IpPort;
|
|
94
|
+
accessPointRule#4679b65f phone_prefix_rules:string dc_id:int ips:vector<IpPort> = AccessPointRule;
|
|
95
|
+
help.configSimple#5a592a6c date:int expires:int rules:vector<AccessPointRule> = help.ConfigSimple;
|
|
96
|
+
|
|
97
|
+
tlsClientHello blocks:vector<TlsBlock> = TlsClientHello;
|
|
98
|
+
|
|
99
|
+
tlsBlockString data:string = TlsBlock;
|
|
100
|
+
tlsBlockRandom length:int = TlsBlock;
|
|
101
|
+
tlsBlockZero length:int = TlsBlock;
|
|
102
|
+
tlsBlockDomain = TlsBlock;
|
|
103
|
+
tlsBlockGrease seed:int = TlsBlock;
|
|
104
|
+
tlsBlockPublicKey = TlsBlock;
|
|
105
|
+
tlsBlockScope entries:Vector<TlsBlock> = TlsBlock;
|
|
106
|
+
|
|
107
|
+
---functions---
|
|
108
|
+
|
|
109
|
+
rpc_drop_answer#58e4a740 req_msg_id:long = RpcDropAnswer;
|
|
110
|
+
|
|
111
|
+
get_future_salts#b921bd04 num:int = FutureSalts;
|
|
112
|
+
|
|
113
|
+
ping#7abe77ec ping_id:long = Pong;
|
|
114
|
+
ping_delay_disconnect#f3427b8c ping_id:long disconnect_delay:int = Pong;
|
|
115
|
+
|
|
116
|
+
destroy_session#e7512126 session_id:long = DestroySessionRes;
|
data/exe/tg
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Telethon
|
|
4
|
+
# A dependency-free test helper. Each test runs as its file loads and raises on its first failed
|
|
5
|
+
# assertion, so a non-zero exit fails both `spin test` and plain ruby. It lives in the package rather
|
|
6
|
+
# than in test/, because spin treats every test/*.rb as a program of its own.
|
|
7
|
+
module Assertions
|
|
8
|
+
class Failure < StandardError
|
|
9
|
+
end
|
|
10
|
+
|
|
11
|
+
module_function
|
|
12
|
+
|
|
13
|
+
def test(name)
|
|
14
|
+
yield
|
|
15
|
+
puts "ok - #{name}"
|
|
16
|
+
rescue StandardError => e
|
|
17
|
+
raise Failure, "#{name}: #{e.class}: #{e.message}"
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
def assert(value, message = "expected a truthy value")
|
|
21
|
+
raise Failure, message unless value
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
def assert_equal(expected, actual)
|
|
25
|
+
return if expected == actual
|
|
26
|
+
|
|
27
|
+
raise Failure, "expected #{expected.inspect}, got #{actual.inspect}"
|
|
28
|
+
end
|
|
29
|
+
end
|
|
30
|
+
end
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Telethon
|
|
4
|
+
module CLI
|
|
5
|
+
# A wrong command line: exit status 2, as argparse gives.
|
|
6
|
+
class UsageError < StandardError
|
|
7
|
+
end
|
|
8
|
+
|
|
9
|
+
# The command line of one command. spec names each option and what it takes: :flag (nothing),
|
|
10
|
+
# :value (one value) or :list (one value, repeatable). Anything else is positional, negative numbers
|
|
11
|
+
# included, since chat ids are negative (Spinel's optparse also does not compile into this program).
|
|
12
|
+
module Args
|
|
13
|
+
module_function
|
|
14
|
+
|
|
15
|
+
def parse(args, usage, positional, spec)
|
|
16
|
+
options = {}
|
|
17
|
+
rest = []
|
|
18
|
+
i = 0
|
|
19
|
+
while i < args.size
|
|
20
|
+
arg = args[i]
|
|
21
|
+
if arg == "--"
|
|
22
|
+
rest.concat(args[(i + 1)..])
|
|
23
|
+
break
|
|
24
|
+
end
|
|
25
|
+
if arg.start_with?("--")
|
|
26
|
+
name, inline = arg.split("=", 2)
|
|
27
|
+
kind = spec[name]
|
|
28
|
+
raise UsageError, "unrecognized option #{name}\nusage: tg #{usage}" unless kind
|
|
29
|
+
|
|
30
|
+
if kind == :flag
|
|
31
|
+
raise UsageError, "#{name} takes no value\nusage: tg #{usage}" if inline
|
|
32
|
+
|
|
33
|
+
options[name] = true
|
|
34
|
+
else
|
|
35
|
+
value = inline
|
|
36
|
+
if value.nil?
|
|
37
|
+
i += 1
|
|
38
|
+
raise UsageError, "#{name} needs a value\nusage: tg #{usage}" if i >= args.size
|
|
39
|
+
|
|
40
|
+
value = args[i]
|
|
41
|
+
end
|
|
42
|
+
if kind == :list
|
|
43
|
+
options[name] = (options[name] || []) + [value]
|
|
44
|
+
else
|
|
45
|
+
options[name] = value
|
|
46
|
+
end
|
|
47
|
+
end
|
|
48
|
+
else
|
|
49
|
+
rest << arg
|
|
50
|
+
end
|
|
51
|
+
i += 1
|
|
52
|
+
end
|
|
53
|
+
if rest.size < positional.size
|
|
54
|
+
raise UsageError, "missing #{positional[rest.size..].join(' ')}\nusage: tg #{usage}"
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
[rest, options]
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def positive_int(value, what = "value")
|
|
61
|
+
number = integer(value, what)
|
|
62
|
+
raise UsageError, "#{what} must be a positive integer: #{value}" unless number.positive?
|
|
63
|
+
|
|
64
|
+
number
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
def integer(value, what = "value")
|
|
68
|
+
raise UsageError, "#{what} must be an integer: #{value}" unless value.to_s.match?(/\A-?\d+\z/)
|
|
69
|
+
|
|
70
|
+
value.to_i
|
|
71
|
+
end
|
|
72
|
+
end
|
|
73
|
+
end
|
|
74
|
+
end
|
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Telethon
|
|
4
|
+
module CLI
|
|
5
|
+
# One run of a command. Holds the streams and the config directory.
|
|
6
|
+
class Commands
|
|
7
|
+
CODE_PROMPT = "Code (or empty to resend): "
|
|
8
|
+
|
|
9
|
+
def initialize(home, client_factory, input, out, err)
|
|
10
|
+
@home = home
|
|
11
|
+
@client_factory = client_factory
|
|
12
|
+
@input = input
|
|
13
|
+
@out = out
|
|
14
|
+
@err = err
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
def dispatch(command, args)
|
|
18
|
+
case command
|
|
19
|
+
when "login" then login(args)
|
|
20
|
+
when "import-session" then import_session(args)
|
|
21
|
+
when "whoami" then whoami(args)
|
|
22
|
+
when "topics" then topics(args)
|
|
23
|
+
when "export" then export(args)
|
|
24
|
+
when "download" then download(args)
|
|
25
|
+
when "delete" then delete(args)
|
|
26
|
+
when "send" then send_command(args)
|
|
27
|
+
when "edit" then edit(args)
|
|
28
|
+
when "forward" then forward(args)
|
|
29
|
+
else raise Failure, "tg: unknown command #{command} (see tg --help)"
|
|
30
|
+
end
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
private
|
|
34
|
+
|
|
35
|
+
def fail!(message)
|
|
36
|
+
raise Failure, message
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
def config_path
|
|
40
|
+
File.join(@home, "config.json")
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
def load_config
|
|
44
|
+
fail!("Not set up: run `tg login` first (#{config_path} is missing).") unless File.exist?(config_path)
|
|
45
|
+
JSON.parse(File.read(config_path, encoding: "UTF-8"))
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
def save_config(config)
|
|
49
|
+
PrivateFiles.directory(@home)
|
|
50
|
+
PrivateFiles.write(config_path, JSON.pretty_generate(config))
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
def new_client(config)
|
|
54
|
+
return @client_factory.call(config) if @client_factory
|
|
55
|
+
|
|
56
|
+
Client.new(Session.new(@home), api_id: config["api_id"].to_i, api_hash: config["api_hash"].to_s)
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
# A connected, logged-in client, or a failure: nothing here may prompt.
|
|
60
|
+
def connected
|
|
61
|
+
client = new_client(load_config)
|
|
62
|
+
fail!("The session is not logged in: run `tg login` in an interactive terminal.") unless client.session.exists?
|
|
63
|
+
client.connect
|
|
64
|
+
unless client.authorized?
|
|
65
|
+
client.disconnect
|
|
66
|
+
fail!("The session is not logged in: run `tg login` in an interactive terminal.")
|
|
67
|
+
end
|
|
68
|
+
client
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
def with_client
|
|
72
|
+
client = connected
|
|
73
|
+
yield client
|
|
74
|
+
ensure
|
|
75
|
+
client&.disconnect
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
def parse(args, usage, positional, spec = {})
|
|
79
|
+
Args.parse(args, usage, positional, spec)
|
|
80
|
+
end
|
|
81
|
+
def tty?
|
|
82
|
+
@input.respond_to?(:tty?) && @input.tty?
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
def ask(prompt)
|
|
86
|
+
@out.print prompt
|
|
87
|
+
@out.flush
|
|
88
|
+
line = @input.gets
|
|
89
|
+
fail!("No answer given.") if line.nil?
|
|
90
|
+
line.strip
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
def ask_hidden(prompt)
|
|
94
|
+
@out.print prompt
|
|
95
|
+
@out.flush
|
|
96
|
+
line = @input.respond_to?(:noecho) && tty? ? @input.noecho(&:gets) : @input.gets
|
|
97
|
+
@out.puts
|
|
98
|
+
fail!("No answer given.") if line.nil?
|
|
99
|
+
line.strip
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
def name_of(entity)
|
|
103
|
+
Client.display_name(entity)
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
# ---- login ----
|
|
107
|
+
|
|
108
|
+
def login(args)
|
|
109
|
+
_rest, options = parse(args, "login [--qr]", [], "--qr" => :flag)
|
|
110
|
+
fail!("login needs an interactive terminal: ssh -t ...") unless tty?
|
|
111
|
+
config = File.exist?(config_path) ? JSON.parse(File.read(config_path, encoding: "UTF-8")) : {}
|
|
112
|
+
unless config["api_id"]
|
|
113
|
+
@out.puts "API id and hash come from https://my.telegram.org, logged in as the account."
|
|
114
|
+
config["api_id"] = Integer(ask("API id: "), 10)
|
|
115
|
+
config["api_hash"] = ask_hidden("API hash (hidden): ")
|
|
116
|
+
save_config(config)
|
|
117
|
+
end
|
|
118
|
+
PrivateFiles.directory(@home)
|
|
119
|
+
client = new_client(config)
|
|
120
|
+
client.connect
|
|
121
|
+
unless client.session.exists? && client.authorized?
|
|
122
|
+
options["--qr"] ? login_with_qr(client) : login_with_code(client)
|
|
123
|
+
end
|
|
124
|
+
me = client.get_me
|
|
125
|
+
config["account"] = me["username"]
|
|
126
|
+
save_config(config)
|
|
127
|
+
@out.puts "Logged in as @#{me['username']} (#{me['id']}). Session: #{client.session.session_path}"
|
|
128
|
+
ensure
|
|
129
|
+
client&.disconnect
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
def login_with_code(client)
|
|
133
|
+
phone = ask("Phone, international format (+380...): ")
|
|
134
|
+
sent = client.send_code(phone)
|
|
135
|
+
@out.puts "Code sent via #{Client.code_delivery(sent)}."
|
|
136
|
+
code = ask(CODE_PROMPT)
|
|
137
|
+
if code.empty?
|
|
138
|
+
sent = client.resend_code(phone, sent["phone_code_hash"])
|
|
139
|
+
@out.puts "Resent via #{Client.code_delivery(sent)}."
|
|
140
|
+
code = ask("Code: ")
|
|
141
|
+
end
|
|
142
|
+
begin
|
|
143
|
+
client.sign_in(phone, code, sent["phone_code_hash"])
|
|
144
|
+
rescue RPCError => e
|
|
145
|
+
raise unless e.name == "SESSION_PASSWORD_NEEDED"
|
|
146
|
+
|
|
147
|
+
client.check_password(ask_hidden("2FA password (hidden): "))
|
|
148
|
+
end
|
|
149
|
+
end
|
|
150
|
+
|
|
151
|
+
def login_with_qr(client)
|
|
152
|
+
qr = client.qr_login
|
|
153
|
+
loop do
|
|
154
|
+
@out.print QR.new(qr.url).to_terminal
|
|
155
|
+
@out.puts "Scan with the account's phone: Settings > Devices > Link Desktop Device. Waiting 60s..."
|
|
156
|
+
begin
|
|
157
|
+
return if qr.wait(60)
|
|
158
|
+
rescue RPCError => e
|
|
159
|
+
raise unless e.name == "SESSION_PASSWORD_NEEDED"
|
|
160
|
+
|
|
161
|
+
client.check_password(ask_hidden("2FA password (hidden): "))
|
|
162
|
+
return
|
|
163
|
+
end
|
|
164
|
+
qr.recreate
|
|
165
|
+
end
|
|
166
|
+
end
|
|
167
|
+
|
|
168
|
+
def import_session(args)
|
|
169
|
+
rest, = parse(args, "import-session [FILE]", [])
|
|
170
|
+
file = rest[0] || File.join(@home, "manager.session")
|
|
171
|
+
session = Session.new(@home)
|
|
172
|
+
fail!("#{session.session_path} exists already; remove it to import again.") if session.exists?
|
|
173
|
+
count = SessionImport.run(file, session)
|
|
174
|
+
@out.puts "Imported data center #{session.dc_id} and #{count} entities from #{file} into #{@home}."
|
|
175
|
+
rescue SessionImport::Error => e
|
|
176
|
+
fail!(e.message)
|
|
177
|
+
end
|
|
178
|
+
|
|
179
|
+
def whoami(args)
|
|
180
|
+
parse(args, "whoami", [])
|
|
181
|
+
with_client do |client|
|
|
182
|
+
me = client.get_me
|
|
183
|
+
@out.puts "@#{me['username']} (#{me['id']}) #{name_of(me)}".rstrip
|
|
184
|
+
end
|
|
185
|
+
end
|
|
186
|
+
|
|
187
|
+
def topics(args)
|
|
188
|
+
rest, = parse(args, "topics CHAT", ["CHAT"])
|
|
189
|
+
with_client do |client|
|
|
190
|
+
chat = client.get_entity(rest[0])
|
|
191
|
+
client.forum_topics(chat).each { |topic| @out.puts "#{topic['id']}\t#{topic['title']}" }
|
|
192
|
+
end
|
|
193
|
+
end
|
|
194
|
+
|
|
195
|
+
def export(args)
|
|
196
|
+
rest, opts = parse(args, "export CHAT [--topic ID] [--limit N | --all] [--before ID] [--out FILE]", ["CHAT"],
|
|
197
|
+
"--topic" => :value, "--limit" => :value, "--all" => :flag, "--before" => :value,
|
|
198
|
+
"--out" => :value)
|
|
199
|
+
raise UsageError, "--limit and --all cannot go together" if opts["--limit"] && opts["--all"]
|
|
200
|
+
|
|
201
|
+
options = { topic: opts["--topic"] && Args.integer(opts["--topic"], "--topic"),
|
|
202
|
+
limit: opts["--all"] ? nil : Args.positive_int(opts["--limit"] || "100", "--limit"),
|
|
203
|
+
before: opts["--before"] ? Args.positive_int(opts["--before"], "--before") : 0,
|
|
204
|
+
out: opts["--out"] }
|
|
205
|
+
with_client do |client|
|
|
206
|
+
chat = client.get_entity(rest[0])
|
|
207
|
+
messages = []
|
|
208
|
+
last_id = nil
|
|
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"]
|
|
212
|
+
fetched += 1
|
|
213
|
+
@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
|
+
|
|
216
|
+
topic = CLI.message_topic(chat, m, options[:topic])
|
|
217
|
+
messages << {
|
|
218
|
+
"id" => m["id"], "date" => CLI.iso_date(m["date"]), "from_id" => Client.sender_id(m),
|
|
219
|
+
"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"])
|
|
222
|
+
}
|
|
223
|
+
end
|
|
224
|
+
export = { "chat_id" => Client.peer_id(chat), "chat_title" => chat["title"], "topic_id" => options[:topic],
|
|
225
|
+
"messages" => messages, "next_before" => last_id, "fetched" => fetched,
|
|
226
|
+
"complete" => options[:limit].nil? || fetched < options[:limit] }
|
|
227
|
+
payload = JSON.pretty_generate(export)
|
|
228
|
+
if options[:out]
|
|
229
|
+
PrivateFiles.write(options[:out], payload)
|
|
230
|
+
@err.puts "#{messages.size} messages -> #{options[:out]}"
|
|
231
|
+
else
|
|
232
|
+
@out.puts payload
|
|
233
|
+
end
|
|
234
|
+
end
|
|
235
|
+
end
|
|
236
|
+
|
|
237
|
+
def message_ids(values)
|
|
238
|
+
values.map { |v| Args.positive_int(v, "message id") }
|
|
239
|
+
end
|
|
240
|
+
|
|
241
|
+
def download(args)
|
|
242
|
+
rest, opts = parse(args, "download CHAT ID... [--out DIR]", %w[CHAT ID], "--out" => :value)
|
|
243
|
+
options = { out: opts["--out"] || "." }
|
|
244
|
+
ids = message_ids(rest[1..])
|
|
245
|
+
saved = 0
|
|
246
|
+
with_client do |client|
|
|
247
|
+
chat = client.get_entity(rest[0])
|
|
248
|
+
target = private_target(options[:out])
|
|
249
|
+
found = client.get_messages(chat, ids)
|
|
250
|
+
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'}"
|
|
254
|
+
next
|
|
255
|
+
end
|
|
256
|
+
path = client.download_media(pair[0], target)
|
|
257
|
+
unless path
|
|
258
|
+
@err.puts "#{id}\tno media"
|
|
259
|
+
next
|
|
260
|
+
end
|
|
261
|
+
saved += 1
|
|
262
|
+
@out.puts "#{id}\t#{path}"
|
|
263
|
+
end
|
|
264
|
+
end
|
|
265
|
+
fail!("Nothing downloaded.") if saved.zero?
|
|
266
|
+
end
|
|
267
|
+
|
|
268
|
+
def private_target(directory)
|
|
269
|
+
FileUtils.mkdir_p(directory, mode: 0o700) unless Dir.exist?(directory)
|
|
270
|
+
directory
|
|
271
|
+
end
|
|
272
|
+
|
|
273
|
+
def delete(args)
|
|
274
|
+
rest, opts = parse(args, "delete CHAT ID... [--yes]", %w[CHAT ID], "--yes" => :flag)
|
|
275
|
+
options = { yes: opts["--yes"] }
|
|
276
|
+
ids = rest[1..].map { |v| Args.integer(v, "message id") }
|
|
277
|
+
with_client do |client|
|
|
278
|
+
chat = client.get_entity(rest[0])
|
|
279
|
+
found = client.get_messages(chat, ids).compact
|
|
280
|
+
fail!("None of those messages exist.") if found.empty?
|
|
281
|
+
found.each do |message, sender|
|
|
282
|
+
text = message["message"].to_s
|
|
283
|
+
preview = (text.empty? ? "<media>" : text).tr("\n", " ")[0, 80]
|
|
284
|
+
@out.puts "#{message['id']}\t#{name_of(sender)}\t#{preview}"
|
|
285
|
+
end
|
|
286
|
+
unless options[:yes]
|
|
287
|
+
fail!("Refusing to delete without a terminal to confirm in; pass --yes to skip the prompt.") unless tty?
|
|
288
|
+
answer = ask("Delete these #{found.size} messages for everyone? Type yes: ")
|
|
289
|
+
fail!("Nothing deleted.") unless answer == "yes"
|
|
290
|
+
end
|
|
291
|
+
client.delete_messages(chat, found.map { |m, _| m["id"] }, revoke: true)
|
|
292
|
+
@out.puts "Deleted #{found.size} messages."
|
|
293
|
+
end
|
|
294
|
+
end
|
|
295
|
+
|
|
296
|
+
def send_command(args)
|
|
297
|
+
rest, opts = parse(args, "send CHAT TEXT [--topic ID] [--file PATH]...", %w[CHAT TEXT],
|
|
298
|
+
"--topic" => :value, "--file" => :list)
|
|
299
|
+
options = { topic: opts["--topic"] && Args.integer(opts["--topic"], "--topic") }
|
|
300
|
+
files = opts["--file"] || []
|
|
301
|
+
files.each { |path| fail!("no such file: #{path}") unless File.file?(path) }
|
|
302
|
+
with_client do |client|
|
|
303
|
+
chat = client.get_entity(rest[0])
|
|
304
|
+
if files.empty?
|
|
305
|
+
@out.puts "Sent message #{client.send_message(chat, rest[1], reply_to: options[:topic])}."
|
|
306
|
+
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(', ')}."
|
|
309
|
+
end
|
|
310
|
+
end
|
|
311
|
+
end
|
|
312
|
+
|
|
313
|
+
def edit(args)
|
|
314
|
+
rest, = parse(args, "edit CHAT ID TEXT", %w[CHAT ID TEXT])
|
|
315
|
+
id = Args.positive_int(rest[1], "message id")
|
|
316
|
+
with_client do |client|
|
|
317
|
+
@out.puts "Edited message #{client.edit_message(client.get_entity(rest[0]), id, rest[2])}."
|
|
318
|
+
end
|
|
319
|
+
end
|
|
320
|
+
|
|
321
|
+
def forward(args)
|
|
322
|
+
rest, opts = parse(args, "forward CHAT ID... [--from CHAT] [--delete-source]", %w[CHAT ID],
|
|
323
|
+
"--from" => :value, "--delete-source" => :flag)
|
|
324
|
+
options = { from: opts["--from"] || "me", delete_source: opts["--delete-source"] }
|
|
325
|
+
ids = message_ids(rest[1..])
|
|
326
|
+
with_client do |client|
|
|
327
|
+
source = client.get_entity(options[:from])
|
|
328
|
+
target = client.get_entity(rest[0])
|
|
329
|
+
sent = client.forward_messages(target, ids, source, drop_author: true)
|
|
330
|
+
@out.puts "Forwarded as message #{sent.join(', ')}."
|
|
331
|
+
if options[:delete_source]
|
|
332
|
+
client.delete_messages(source, ids)
|
|
333
|
+
@out.puts "Deleted #{ids.size} source messages."
|
|
334
|
+
end
|
|
335
|
+
end
|
|
336
|
+
end
|
|
337
|
+
end
|
|
338
|
+
end
|
|
339
|
+
end
|
data/lib/telethon/cli.rb
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require "io/console"
|
|
5
|
+
require "fileutils"
|
|
6
|
+
|
|
7
|
+
module Telethon
|
|
8
|
+
# The tg command: a Telegram user account from the command line. A port of tg.py, the Telethon
|
|
9
|
+
# script it replaces, with the same commands, output and refusals.
|
|
10
|
+
#
|
|
11
|
+
# tg login [--qr] once, interactively: phone + code + 2FA, or a QR scan
|
|
12
|
+
# tg import-session [FILE] once: take over a Telethon .session instead of logging in
|
|
13
|
+
# tg whoami
|
|
14
|
+
# tg topics CHAT
|
|
15
|
+
# tg export CHAT [--topic ID] [--limit 100 | --all] [--before ID] [--out FILE]
|
|
16
|
+
# tg download CHAT ID [ID ...] [--out DIR]
|
|
17
|
+
# tg delete CHAT ID [ID ...] [--yes]
|
|
18
|
+
# tg send CHAT TEXT [--topic ID] [--file PATH ...]
|
|
19
|
+
# tg edit CHAT ID TEXT
|
|
20
|
+
# tg forward CHAT ID [ID ...] [--from CHAT] [--delete-source]
|
|
21
|
+
#
|
|
22
|
+
# CHAT is a numeric id (-1001874396477), a @username, or "me". The session is the whole account, so
|
|
23
|
+
# it is kept readable by its owner only, in $TG_HOME (else $DOJO_TG_HOME, else ~/.config/tg). Every
|
|
24
|
+
# command but login refuses to prompt, so it can run over a non-interactive ssh.
|
|
25
|
+
module CLI
|
|
26
|
+
class Failure < StandardError
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
USAGE = <<~TEXT
|
|
30
|
+
usage: tg COMMAND [ARGS]
|
|
31
|
+
|
|
32
|
+
commands:
|
|
33
|
+
login [--qr] log in once, interactively
|
|
34
|
+
import-session [FILE] take over a Telethon .session (default: $TG_HOME/manager.session)
|
|
35
|
+
whoami show the logged-in account
|
|
36
|
+
topics CHAT list a forum's topics
|
|
37
|
+
export CHAT [--topic ID] [--limit N | --all] [--before ID] [--out FILE]
|
|
38
|
+
newest messages as JSON
|
|
39
|
+
download CHAT ID... [--out DIR] save messages' attachments (owner-only files)
|
|
40
|
+
delete CHAT ID... [--yes] delete messages for everyone
|
|
41
|
+
send CHAT TEXT [--topic ID] [--file PATH]...
|
|
42
|
+
send a message; with --file, documents with TEXT as caption
|
|
43
|
+
edit CHAT ID TEXT replace the text (or caption) of a message you sent
|
|
44
|
+
forward CHAT ID... [--from CHAT] [--delete-source]
|
|
45
|
+
forward without the "Forwarded from" header (default from: me)
|
|
46
|
+
--version
|
|
47
|
+
TEXT
|
|
48
|
+
|
|
49
|
+
module_function
|
|
50
|
+
|
|
51
|
+
def home
|
|
52
|
+
dir = ENV.fetch("TG_HOME", "")
|
|
53
|
+
dir = ENV.fetch("DOJO_TG_HOME", "") if dir.empty?
|
|
54
|
+
dir = File.join(Dir.home, ".config", "tg") if dir.empty?
|
|
55
|
+
dir
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
# Answers the exit status. client_factory makes the connected client from the config; tests replace it.
|
|
59
|
+
def run(argv, client_factory: nil, input: $stdin, out: $stdout, err: $stderr)
|
|
60
|
+
args = argv.dup
|
|
61
|
+
command = args.shift
|
|
62
|
+
if command.nil? || %w[-h --help help].include?(command)
|
|
63
|
+
out.print USAGE
|
|
64
|
+
return command.nil? ? 2 : 0
|
|
65
|
+
end
|
|
66
|
+
if %w[--version -v].include?(command)
|
|
67
|
+
out.puts "tg #{VERSION} (telethon.rb, a port of #{UPSTREAM}, layer #{TL::LAYER})"
|
|
68
|
+
return 0
|
|
69
|
+
end
|
|
70
|
+
begin
|
|
71
|
+
Commands.new(home, client_factory, input, out, err).dispatch(command, args)
|
|
72
|
+
ensure
|
|
73
|
+
out.flush # what a command printed comes before its failure on stderr, even when piped
|
|
74
|
+
end
|
|
75
|
+
0
|
|
76
|
+
rescue Failure => e
|
|
77
|
+
err.puts e.message
|
|
78
|
+
1
|
|
79
|
+
rescue UsageError => e
|
|
80
|
+
err.puts "tg: #{e.message}"
|
|
81
|
+
2
|
|
82
|
+
rescue RPCError => e
|
|
83
|
+
err.puts "Telegram refused: #{e.message}"
|
|
84
|
+
1
|
|
85
|
+
rescue TransportError => e
|
|
86
|
+
err.puts "Connection failed: #{e.message}"
|
|
87
|
+
1
|
|
88
|
+
rescue Error => e
|
|
89
|
+
err.puts e.message
|
|
90
|
+
1
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
# The pure parts of export, as in tg.py, so that tests can reach them.
|
|
94
|
+
def message_topic(chat, message, requested_topic)
|
|
95
|
+
return requested_topic if requested_topic
|
|
96
|
+
return nil unless chat["forum"]
|
|
97
|
+
|
|
98
|
+
reply = message["reply_to"]
|
|
99
|
+
return reply["reply_to_top_id"] || reply["reply_to_msg_id"] if reply && reply["forum_topic"]
|
|
100
|
+
|
|
101
|
+
1 # General
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
def link_for(chat, topic, message_id)
|
|
105
|
+
internal = chat["id"]
|
|
106
|
+
topic ? "https://t.me/c/#{internal}/#{topic}/#{message_id}" : "https://t.me/c/#{internal}/#{message_id}"
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
def iso_date(unix)
|
|
110
|
+
Time.at(unix).utc.strftime("%Y-%m-%dT%H:%M:%S+00:00")
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
end
|
|
114
|
+
end
|