-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.py
193 lines (174 loc) · 5.47 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
import asyncio
import logging
import os
from aiohttp import ClientSession
from json import loads
from json.decoder import JSONDecodeError
from telethon import TelegramClient
from telethon.sessions import StringSession
from telethon.errors import RPCError
from telethon.events import NewMessage
from telethon.tl.functions.messages import SendMessageRequest
from telethon.tl.types import User
logging.basicConfig(
level=logging.INFO,
format="[%(asctime)s - %(levelname)s] - %(name)s - %(message)s",
datefmt="%d-%b-%y %H:%M:%S",
)
logger = logging.getLogger(__name__)
def get_config(name: str, d_v=None, should_prompt=False):
""" wrapper for getting the credentials """
""" accepts one mandatory variable
and prompts for the value, if not available """
val = os.environ.get(name, d_v)
if not val and should_prompt:
try:
val = input(f"enter {name}'s value: ")
except EOFError:
val = d_v
print("\n")
return val
API_ID = int(get_config("API_ID", should_prompt=True))
API_HASH = get_config("API_HASH", should_prompt=True)
SESSION = get_config("SESSION", should_prompt=True)
ENDPOINT_API_KEY = get_config("ENDPOINT_API_KEY", "thisismysecret")
GET_ENDPOINT = get_config("GET_ENDPOINT", "http://example.com/getallbots")
UPDATE_ENDPOINT = get_config("UPDATE_ENDPOINT", "http://example.com/updatebotstatus")
OOTU_ENDPOINT = get_config("OOTU_ENDPOINT", "http://example.com/ootumightwork")
CHECK_TIMEOUT = int(get_config("CHECK_TIMEOUT", "25"))
DELAY_TIMEOUT = int(get_config("DELAY_TIMEOUT", "5"))
TG_FLOOD_SLEEP_THRESHOLD = int(get_config("TG_FLOOD_SLEEP_THRESHOLD", "60"))
TG_DEVICE_MODEL = get_config("TG_DEVICE_MODEL")
TG_SYSTEM_VERSION = get_config("TG_SYSTEM_VERSION")
TG_APP_VERSION = get_config("TG_APP_VERSION")
CUST_HEADERS = {
"x-api-key": ENDPOINT_API_KEY
}
usedBots = []
async def get_bots():
async with ClientSession() as session:
one = await session.post(
GET_ENDPOINT,
headers=CUST_HEADERS
)
owt = await one.text()
try:
return loads(owt)
except JSONDecodeError:
return []
async def update_data(username, ping_time, online_status):
update_param_s = {
"username": username,
"ping_time": ping_time,
"online_status": online_status,
}
# logger.info(update_param_s)
async with ClientSession() as session:
one = await session.post(
UPDATE_ENDPOINT,
json=update_param_s,
headers=CUST_HEADERS
)
return await one.text()
async def ootu():
async with ClientSession() as session:
one = await session.post(
OOTU_ENDPOINT,
headers=CUST_HEADERS
)
return await one.text()
async def nme(evt: NewMessage.Event):
# logger.info("updating database")
usernameEntity = (await evt.client.get_entity(
evt.sender_id
))
if not isinstance(usernameEntity, User):
return False
if not usernameEntity.bot:
return False
username = usernameEntity.username
if username:
username = username.lower()
replied = await evt.get_reply_message()
if not replied:
replied = evt
ping_time = round(
evt.date.timestamp() - replied.date.timestamp(),
2
)
await evt.mark_read()
if "off-line" in evt.raw_text:
return False
global usedBots
usedBots.append(username)
return await update_data(
username,
ping_time,
1
)
async def main():
# get the list of bots
bots = await get_bots()
logger.info(
f"Found {len(bots)} Bots"
)
if len(bots) > 0:
# log in as user account,
client = TelegramClient(
StringSession(SESSION),
API_ID,
API_HASH,
flood_sleep_threshold=TG_FLOOD_SLEEP_THRESHOLD,
device_model=TG_DEVICE_MODEL,
system_version=TG_SYSTEM_VERSION,
app_version=TG_APP_VERSION,
)
# register event handler to check bot responses
client.add_event_handler(nme, NewMessage(
incoming=True
))
# start the userbot
await client.start()
cache = await client.get_me()
# send /start to all the bots
reqs = []
for bot in bots:
if len(reqs) > CHECK_TIMEOUT:
try:
await client(reqs)
except RPCError:
pass
reqs = []
await asyncio.sleep(CHECK_TIMEOUT)
reqs.append(
SendMessageRequest(
peer=bot["username"],
message=bot["start_param"],
)
)
if len(reqs) > (
CHECK_TIMEOUT - CHECK_TIMEOUT
):
try:
await client(reqs)
except RPCError:
pass
reqs = []
await asyncio.sleep(CHECK_TIMEOUT)
await asyncio.sleep(DELAY_TIMEOUT)
await client.disconnect()
# update non-responsive bot status
for bot in bots:
botUsername = bot["username"].lower()
if botUsername not in usedBots:
await update_data(
botUsername,
963,
0
)
# finally, do this
txtContent = await ootu()
with open("index.html", "w+") as fod:
fod.write(txtContent)
if __name__ == "__main__":
asyncio.run(main())