-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
93 lines (80 loc) · 2.5 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
from bottle import request, route, run, template
from telethon import TelegramClient
from telethon.errors import SessionPasswordNeededError
import time
from settings import *
from multiprocessing import Process
count_msgs = 0
last_msg_text = ''
proc = 0
session = 'inactive'
def start_forwarding(client):
print("-> Starting forwarder...")
chnl = client.get_entity(from_channel_link)
target = client.get_entity(to_user)
last_msg_id = 0
print("-> Forwarding messages...")
session = 'active'
while True:
msgs = client.get_messages(chnl)
new_msg = msgs[0]
if new_msg.id != last_msg_id:
last_msg_id = new_msg.id
client.forward_messages(target, new_msg)
print('New channel message forwarded:')
print(new_msg.message)
last_msg_text = new_msg.message
count_msgs += 1
time.sleep(poll_interval)
def spawn_forwarding_process(client):
global proc
if __name__ == '__main__':
if proc == 0 or not proc.is_alive():
print("-> spawning forwarding process...")
proc = Process(target=start_forwarding, args=(client,))
proc.daemon = True
proc.start()
else:
print("-> forwarding process already running.")
def start_server(client):
print("-> Starting server...")
@route('/')
def login():
print("-> Serving /")
if not client.is_user_authorized():
try:
client.send_code_request(phone)
return '''
<h2>Telegram sign in</h2>
<form action="/" method="post">
Sign in code: <input name="sign_in_code" type="text" />
<input value="Submit" type="submit" />
</form>
'''
except:
return '''
<h2>Telegram sign in</h2>
<p>Error while trying to login. (Most probably FloodError - wait 24 hours)...</p>
'''
else:
spawn_forwarding_process(client)
return template('<h2>Telegram session {{session_status}}</h2><p>Messages forwarded: {{count}}</p><p>Last message: {{msg}}</p>', count=count_msgs, msg=last_msg_text, session_status=session)
@route('/', method='POST')
def do_login():
print("-> Got POST form")
# try to login using the code from the user
sign_in_code = request.forms.get('sign_in_code')
client.sign_in(phone, sign_in_code)
if client.is_user_authorized():
spawn_forwarding_process(client)
return "<p>Signed in successfully.</p>"
else:
return "<p>Incorrect code - please retry.</p>"
# run(host='localhost', port=8080)
run(host='0.0.0.0', port=int(os.getenv("PORT")))
def start():
print("-> trying Telegram login...")
client = TelegramClient(username, api_id, api_hash)
client.connect()
start_server(client)
start()