-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
392 lines (369 loc) · 23.7 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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
import httpx
import asyncio
import json
import time
import sys
import os
import aioconsole
from pydantic import ValidationError
from config import BOT_API_TOKEN, MAIN_CHANNEL_CHAT_ID
from model import TelegramgetMeResponse, TelegramMessage, TelegramPhoto, TelegramPoll, TelegramDocument, TelegramAudio, \
TelegramVideo
from tele import send_photo, send_message, send_document, send_poll, get_me, send_audio, send_video
print()
print('###################################################')
print('Telegram Bot System')
print('Made by Muhammad Nizamuddin Aulia')
print('###################################################')
print()
# TELEGRAM
URL = 'https://api.telegram.org/bot' + str(BOT_API_TOKEN)
# Main channel is used for receiving bot status, such as ON or OFF status.
main_channel_chat_id = MAIN_CHANNEL_CHAT_ID
'''Add your telegram bot into your channel. Do not forget to make your bot as admin that has access to read and post messages'''
# TELEGRAM UPDATES READER
async def get_updates(offset):
async with httpx.AsyncClient(http2=True) as tele:
url = f"{URL}/getUpdates?offset={offset}"
# url = URL + "/getUpdates?offset={}".format(offset)
r = await tele.post(url)
return r.json()
async def get_update_id(updates):
num_updates = len(updates['result'])
last_update = num_updates - 1
update_id = updates['result'][last_update]['update_id']
return update_id
async def update_id_and_offset():
try:
with open('update_id.txt', encoding="utf8") as u:
update_id = str(u.read())
except FileNotFoundError:
update_id = '0'
try:
with open('offset.txt', encoding="utf8") as o:
offset = str(o.read())
except FileNotFoundError:
offset = 0
return update_id, offset
async def get_poll_answer(poll_id):
while True:
try:
answer = answered
return answer
except NameError:
await asyncio.sleep(1)
try:
with open(str(poll_id) + '_answered.txt', encoding="utf8") as op:
answered = str(op.read())
os.remove(str(poll_id) + '_answered.txt')
except FileNotFoundError:
pass
async def welcome(chat_id):
if not os.path.exists('Data/' + str(chat_id)):
os.makedirs('Data/' + str(chat_id))
await send_message(bot_api_token=BOT_API_TOKEN,
message=TelegramMessage(chat_id=chat_id, text="<b>Welcome to YG Information System</b>",
parse_mode="HTML"))
async def restart(chat_id):
choice = await get_poll_answer(await send_poll(bot_api_token=BOT_API_TOKEN,
poll=TelegramPoll(chat_id=chat_id, question="Are you sure?",
options=json.dumps(["Yes", "No"]))))
if choice == 'Yes':
await send_message(bot_api_token=BOT_API_TOKEN,
message=TelegramMessage(chat_id=chat_id, text="Restarting bot..", parse_mode="HTML"))
os.execv(sys.executable, ['python3'] + sys.argv)
else:
pass
async def text_handler(chat_id: int, text: str):
try:
if text == '/start':
asyncio.ensure_future(welcome(chat_id))
elif text == '/restart':
asyncio.ensure_future(restart(chat_id))
elif text == '/chatid':
asyncio.ensure_future(
send_message(bot_api_token=BOT_API_TOKEN, message=TelegramMessage(chat_id=chat_id, text=str(chat_id),
parse_mode="HTML")))
elif text == '/sendmessage':
asyncio.ensure_future(send_message(bot_api_token=BOT_API_TOKEN,
message=TelegramMessage(chat_id=chat_id, text="This is message",
parse_mode="HTML")))
elif text == '/sendphoto':
asyncio.ensure_future(send_photo(bot_api_token=BOT_API_TOKEN,
photo=TelegramPhoto(chat_id=chat_id, photo='example-resources/bear.png',
caption="This is photocaption"), is_local=True))
elif text == '/senddocument':
asyncio.ensure_future(send_document(bot_api_token=BOT_API_TOKEN, document=TelegramDocument(chat_id=chat_id,
document='example-resources/bear.png',
caption="This is document caption"),
is_local=True))
elif text == '/sendaudio':
asyncio.ensure_future(send_audio(bot_api_token=BOT_API_TOKEN, audio=TelegramAudio(chat_id=chat_id,
audio='example-resources/bensound-cute.mp3',
caption="This is audio caption"),
is_local=True))
elif text == '/sendvideo':
asyncio.ensure_future(send_video(bot_api_token=BOT_API_TOKEN,
video=TelegramVideo(chat_id=chat_id,
video='example-resources/tailwind.mp4',
caption="This is video caption"), is_local=True))
else:
pass
except (ValueError, IndexError, AssertionError, KeyError):
await aioconsole.aprint('TEXT HANDLING ERROR:', text)
exc_type, exc_obj, exc_tb = sys.exc_info()
await aioconsole.aprint(exc_type, exc_tb.tb_lineno)
async def poll_answer_handler(poll_id: int, answer: str):
if os.path.exists('Poll/' + str(poll_id) + '_answer.txt'):
with open('Poll/' + str(poll_id) + '_answered.txt', 'w') as sa:
sa.write(str(answer))
os.remove('Poll/' + str(poll_id) + '_answer.txt')
else:
await aioconsole.aprint('Poll is already answered:', poll_id)
async def main():
await aioconsole.aprint()
await aioconsole.aprint('\33[95mTelegram System STARTED\33[0m')
try:
bot = TelegramgetMeResponse.model_validate(await get_me(BOT_API_TOKEN))
await aioconsole.aprint("BOT INFORMATION")
await aioconsole.aprint(f"ID : {bot.result.id}")
await aioconsole.aprint(f"Name : {bot.result.first_name}")
await aioconsole.aprint(f"Username: {bot.result.username}")
except ValidationError:
await aioconsole.aprint("Bot Configuration Error")
sys.exit()
await aioconsole.aprint()
await send_message(bot_api_token=BOT_API_TOKEN, message=TelegramMessage(chat_id=MAIN_CHANNEL_CHAT_ID,
text=f"Telegram System ON\n{time.ctime(time.time())}",
parse_mode="HTML"))
# INITIAL CONDITIONS
latest_update_id, offset = await update_id_and_offset()
# TELEGRAM UPDATES LOOP
while True:
try:
while True:
try:
updates = await get_updates(offset)
offset = await get_update_id(updates)
i = len(updates['result']) - 1
update_id = updates['result'][i]['update_id']
break
except (KeyError, IndexError):
await asyncio.sleep(1)
# Only process new updates
if update_id != latest_update_id:
latest_update_id = update_id
with open("update_id.txt", 'w') as u:
u.write(str(latest_update_id))
with open("offset.txt", 'w') as o:
o.write(str(offset))
try:
# MESSAGE
if updates['result'][i]['message']:
chat_id = updates['result'][i]['message']['chat']['id']
chat_type = updates['result'][i]['message']['chat']['type']
if not os.path.exists('Data/' + str(chat_id)):
os.makedirs('Data/' + str(chat_id))
try:
# TEXT
if updates['result'][i]['message']['text']:
text = updates['result'][i]['message']['text']
await aioconsole.aprint('Text', chat_id, chat_type, text)
asyncio.ensure_future(text_handler(chat_id, text))
except KeyError:
try:
# DOCUMENT
if updates['result'][i]['message']['document']:
file_date = updates['result'][i]['message']['date']
file_id = updates['result'][i]['message']['document']['file_id']
mime_type = updates['result'][i]['message']['document']['mime_type']
file_name = updates['result'][i]['message']['document']['file_name']
try:
# W/ CAPTION
caption = updates['result'][i]['message']['caption']
await aioconsole.aprint('Document', file_name, mime_type, file_id, caption,
file_date)
except KeyError:
# W/O CAPTION
await aioconsole.aprint('Document', file_name, mime_type, file_id, file_date)
except KeyError:
try:
# POLL
if updates['result'][i]['message']['poll']:
poll_id = updates['result'][i]['message']['poll']['id']
question = updates['result'][i]['message']['poll']['question']
options = updates['result'][i]['message']['poll']['options']
await aioconsole.aprint('Poll', poll_id, question, options)
except KeyError:
try:
# PHOTO
if updates['result'][i]['message']['photo']:
files = updates['result'][i]['message']['photo'][
len(updates['result'][i]['message']['photo']) - 1]
file_id = files['file_id']
width = files['width']
height = files['height']
try:
# W/ CAPTION
caption = updates['result'][i]['message']['caption']
await aioconsole.aprint('Photo', file_id, width, height, caption)
except KeyError:
# W/O CAPTION
await aioconsole.aprint('Photo', file_id, width, height)
except KeyError:
try:
# AUDIO
if updates['result'][i]['message']['audio']:
file_name = updates['result'][i]['message']['audio']['file_name']
mime_type = updates['result'][i]['message']['audio']['mime_type']
title = updates['result'][i]['message']['audio']['title']
file_id = updates['result'][i]['message']['audio']['file_id']
try:
# W/ CAPTION
caption = updates['result'][i]['message']['caption']
await aioconsole.aprint('Audio', file_name, mime_type, title,
file_id, caption)
except KeyError:
# W/O CAPTION
await aioconsole.aprint('Audio', file_name, mime_type, title,
file_id)
except KeyError:
try:
# LOCATION
if updates['result'][i]['message']['location']:
latitude = updates['result'][i]['message']['location']['latitude']
longitude = updates['result'][i]['message']['location']['longitude']
await aioconsole.aprint('Location', latitude, longitude)
except KeyError:
try:
# CONTACT
if updates['result'][i]['message']['contact']:
phone_number = updates['result'][i]['message']['contact'][
'phone_number']
first_name = updates['result'][i]['message']['contact'][
'first_name']
await aioconsole.aprint('Contact', phone_number, first_name)
except KeyError:
await aioconsole.aprint('Unknown message type')
await aioconsole.aprint(updates)
except KeyError:
try:
# CHANNEL POST
if updates['result'][i]['channel_post']:
chat_id = updates['result'][i]['channel_post']['chat']['id']
chat_type = updates['result'][i]['channel_post']['chat']['type']
try:
# TEXT
if updates['result'][i]['channel_post']['text']:
text = updates['result'][i]['channel_post']['text']
await aioconsole.aprint('Text', chat_id, chat_type, text)
asyncio.ensure_future(text_handler(chat_id, text))
except KeyError:
try:
# DOCUMENT
if updates['result'][i]['channel_post']['document']:
file_date = updates['result'][i]['channel_post']['date']
file_id = updates['result'][i]['channel_post']['document']['file_id']
mime_type = updates['result'][i]['channel_post']['document']['mime_type']
file_name = updates['result'][i]['channel_post']['document']['file_name']
try:
# W/ CAPTION
caption = updates['result'][i]['channel_post']['caption']
await aioconsole.aprint('File', file_name, mime_type, file_date, caption,
file_id)
except KeyError:
# W/O CAPTION
await aioconsole.aprint('File', file_name,
mime_type, file_date)
except KeyError:
try:
# POLL
if updates['result'][i]['channel_post']['poll']:
poll_id = updates['result'][i]['channel_post']['poll']['id']
question = updates['result'][i]['channel_post']['poll']['question']
options = updates['result'][i]['channel_post']['poll']['options']
await aioconsole.aprint('Poll', poll_id, question, options)
except KeyError:
try:
# PHOTO
if updates['result'][i]['channel_post']['photo']:
files = updates['result'][i]['channel_post']['photo'][
len(updates['result'][i]['channel_post']['photo']) - 1]
file_id = files['file_id']
width = files['width']
height = files['height']
try:
# W/ CAPTION
caption = updates['result'][i]['channel_post']['caption']
await aioconsole.aprint('Photo', file_id, width, height, caption)
except KeyError:
# W/O CAPTION
await aioconsole.aprint('Photo', file_id, width, height)
except KeyError:
try:
# AUDIO
if updates['result'][i]['channel_post']['audio']:
file_name = updates['result'][i]['channel_post']['audio'][
'file_name']
mime_type = updates['result'][i]['channel_post']['audio'][
'mime_type']
title = updates['result'][i]['channel_post']['audio']['title']
file_id = updates['result'][i]['channel_post']['audio']['file_id']
try:
# W/ CAPTION
caption = updates['result'][i]['channel_post']['caption']
await aioconsole.aprint('Audio', file_name, mime_type, title,
file_id, caption)
except KeyError:
# W/O CAPTION
await aioconsole.aprint('Audio', file_name, mime_type, title,
file_id)
except KeyError:
try:
if updates['result'][i]['channel_post']['location']:
latitude = updates['result'][i]['channel_post']['location'][
'latitude']
longitude = updates['result'][i]['channel_post']['location'][
'longitude']
await aioconsole.aprint('Location', latitude, longitude)
except KeyError:
try:
if updates['result'][i]['channel_post']['contact']:
phone_number = \
updates['result'][i]['channel_post']['contact'][
'phone_number']
first_name = \
updates['result'][i]['channel_post']['contact'][
'first_name']
await aioconsole.aprint('Contact', phone_number, first_name)
except KeyError:
await aioconsole.aprint('Unknown message type')
await aioconsole.aprint(updates)
except KeyError:
try:
# POLL ANSWER
if updates['result'][i]['poll']['id']:
poll_id = updates['result'][i]['poll']['id']
for option in updates['result'][i]['poll']['options']:
if option['voter_count'] == 1:
answer = option['text']
await aioconsole.aprint('Poll Answer', poll_id, answer)
asyncio.ensure_future(poll_answer_handler(poll_id, answer))
except KeyError:
await aioconsole.aprint('Unknown update_type')
await aioconsole.aprint(updates)
else:
pass
except httpx.HTTPError as exc:
await aioconsole.aprint(f"HTTP Exception for {exc.request.url} - {exc}")
exc_type, exc_obj, exc_tb = sys.exc_info()
await aioconsole.aprint(exc_type, exc_tb.tb_lineno)
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
print()
print('Telegram System SHUTDOWN')
asyncio.run(send_message(bot_api_token=BOT_API_TOKEN, message=TelegramMessage(chat_id=MAIN_CHANNEL_CHAT_ID,
text=f"YG System OFF\n{time.ctime(time.time())}",
parse_mode="HTML")))