-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
557 lines (460 loc) · 24.5 KB
/
app.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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
'''
vaccine bot to help people get vaccinated.
'''
### Imports ############
import re
import configparser
from flask import Flask, request
import telegram
from telegram import (
ReplyKeyboardMarkup,
KeyboardButton,
InlineKeyboardMarkup,
InlineKeyboardButton,
ReplyKeyboardRemove,
ChatAction
)
import requests
from requests.models import PreparedRequest
from country import Country
import telegramcalender
import pickle
import time
import sqlalchemy
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime,timedelta
scheduler = BackgroundScheduler({'apscheduler.timezone': 'Asia/Calcutta'})
# scheduler.add_jobstore('sqlalchemy', url='sqlite:////tmp/schedule.db')
parser = configparser.ConfigParser()
parser.read('credentials/config.conf')
global bot
global TOKEN
global news_state_api
global news_district_api
### config #########
TOKEN = parser['Telebot']['token']
URL = parser['Telebot']['URL']
BORE = parser['Extapi']['bore']
news_state_api = parser['Extapi']['news_state']
news_district_api = parser['Extapi']['news_district']
slotbyD = parser['Extapi']['slotbyD']
slotbyP = parser['Extapi']['slotbyP']
quote = parser['Extapi']['quote']
## bot init ##########
bot = telegram.Bot(token=TOKEN)
country = Country()
states = country.get_states()
check_states = country.get_check_states()
covid_data_state_dict = {}
covid_data_district_dict = {}
pr_quo_list = []
@scheduler.scheduled_job('interval', minutes=30)
def timed_job():
print('This job is run every thirty minutes.')
subs_rem = {}
with open('user_stat.txt','rb') as f:
User = pickle.load(f)
print(User)
for chat_id in User:
if 'Subcriptions' in User[chat_id]:
subscrib = User[chat_id]['Subcriptions']
subs_rem[chat_id] = []
if subscrib:
if len(subscrib['pin'])>0:
for i in subscrib['pin']:
date = datetime.today()
print(i,date,chat_id)
for c in range(3):
ret = send_slot_data(bot,i,date.strftime("%d-%m-%Y"),'pincode',chat_id,'msg_id',slotbyP)
print(i,date,chat_id,ret)
if ret>0:
subs_rem[chat_id].append(i)
bot.sendMessage(chat_id=callback_query.message.chat.id, text='No sessions found for this date!')
break
date +=timedelta(1)
if len(subscrib['dis'])>0:
for i in subscrib['dis']:
date = datetime.today()
id = country.get_district_id(i)
print(date,id,i,chat_id)
for c in range(3):
ret = send_slot_data(bot,id,date.strftime("%d-%m-%Y"),'district_id',chat_id,'msg_id',slotbyD)
print(date,id,i,chat_id)
if ret>0:
subs_rem[chat_id].append(i)
break
date +=timedelta(1)
for chat_id in subs_rem:
subscrib = read_user(chat_id,'Subcriptions')
if subscrib:
for text in subs_rem[chat_id]:
if text in subscrib['pin']:
subscrib['pin'].remove(text)
bot_text = 'We removed the subscription: '+text
bot.sendMessage(chat_id=chat_id, text=bot_text)
elif text in subscrib['dis']:
subscrib['dis'].remove(text)
bot_text = 'We removed the subscription: '+text
bot.sendMessage(chat_id=chat_id, text=bot_text)
update_user(chat_id,'Subcriptions',subscrib)
@scheduler.scheduled_job('cron', day_of_week='mon-fri', hour=6)
def scheduled_job():
print('This job is run every weekday at 5pm.')
scheduler.start()
app = Flask(__name__)
def update_user(chat_id,param,data):
try:
User = []
with open('user_stat.txt','rb') as f:
User = pickle.load(f)
if chat_id not in User:
User[chat_id] = {}
User[chat_id][param] = data
else:
User[chat_id][param] = data
with open('user_stat.txt','wb') as f:
pickle.dump(User,f,protocol=pickle.HIGHEST_PROTOCOL)
except EOFError:
print('ERROR')
def read_user(chat_id,param):
try:
with open('user_stat.txt','rb') as f:
User = pickle.load(f)
if chat_id in User:
if param in User[chat_id]:
return User[chat_id][param]
return False
except EOFError:
print('ERROR')
def remove_user(chat_id):
try:
User = []
with open('user_stat.txt','rb') as f:
User = pickle.load(f)
if chat_id in User:
del User[chat_id]
with open('user_stat.txt','wb') as f:
pickle.dump(User,f,protocol=pickle.HIGHEST_PROTOCOL)
except EOFError:
print('ERROR')
# def get_object():
# with open('stat.txt','rb') as f:
# status = pickle.load(f)
# return status
def send_slot_data(bot,param1,param2,filter,chat_id,msg_id,url):
params = {filter:param1,'date':param2}
req = PreparedRequest()
req.prepare_url(url, params)
headers = {'user-agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36"}
data = requests.get(req.url,headers=headers)
print(req.url)
data = data.json()
# print(data)
count = 0
text = 'No sessions found for this date!'
if 'centers' in data:
print('good')
if len(data['centers'])>0:
for i in data['centers']:
try:
# print(i)
if next(item for item in i['sessions'] if item["available_capacity"]>0):
print('working')
text = 'Here are the slots we found for you!\nFor state {} in district {} :\nCenter name : {}\nAddress : {}\nFee Type : {}\n'.format(i['state_name'],i['district_name'],i['name'],i['address'],i['fee_type'])
bot.sendMessage(chat_id=chat_id, text=text)
for j in i['sessions']:
if j['available_capacity']>0:
text2 = 'Sessions:\ndate: {}\nAge limit: {}\nvaccine: {}\ndose 1: {}\ndose availablity \ndose 2: {}\nslots: {}\n'.format(j['date'],j['min_age_limit'],j['vaccine'],j['available_capacity_dose1'],j['available_capacity_dose2'],'\nslots: '.join(j['slots']))
bot.sendMessage(chat_id=chat_id, text=text2)
count+=1
except:
print('No sessions found at center {}'.format(i['name']))
return count
District = []
@app.route('/{}'.format(TOKEN), methods=['POST'])
def respond():
try:
# retrieve the message in JSON and then transform it to Telegram object
update = telegram.Update.de_json(request.get_json(force=True), bot)
callback_query = update.callback_query
if callback_query is not None:
if callback_query.data == "state_slot":
bot_text = "Enter the State name:"
reply_markup = ReplyKeyboardMarkup(states,resize_keyboard=True,one_time_keyboard=True)
bot.sendMessage(chat_id=callback_query.message.chat.id,text=bot_text, reply_markup=reply_markup, reply_to_message_id=callback_query.message.message_id)
return 'ok'
elif callback_query.data == "dis_slot":
bot_text = "Enter the State name:"
reply_markup = ReplyKeyboardMarkup(check_states,resize_keyboard=True,one_time_keyboard=True)
bot.sendMessage(chat_id=callback_query.message.chat.id,text=bot_text, reply_markup=reply_markup, reply_to_message_id=callback_query.message.message_id)
if read_user(callback_query.message.chat.id,'status') == 'NEWS':
update_user(callback_query.message.chat.id,'status','NEWS_dis')
elif read_user(callback_query.message.chat.id,'status') == 'CHECK':
update_user(callback_query.message.chat.id,'status','CHECK_dis')
elif read_user(callback_query.message.chat.id,'status') == 'SUBSCRIBE':
update_user(callback_query.message.chat.id,'status','SUBSCRIBE_dis')
return 'ok'
elif callback_query.data == "pin_slot":
bot_text = "Enter the Pincode name:"
bot.sendMessage(chat_id=callback_query.message.chat.id, text=bot_text)
if read_user(callback_query.message.chat.id,'status') == 'CHECK':
update_user(callback_query.message.chat.id,'status','CHECK_pin')
elif read_user(callback_query.message.chat.id,'status') == 'SUBSCRIBE':
update_user(callback_query.message.chat.id,'status','SUBSCRIBE_add_pin')
return 'ok'
elif 'CHECK,' in read_user(callback_query.message.chat.id,'status') or 'CHECKPIN,' in read_user_stat(callback_query.message.chat.id):
try:
call_back,_,_,_ = telegramcalender.separate_callback_data(callback_query.data)
except Exception:
print('Error')
if call_back in ['IGNORE', 'DAY','PREV-MONTH','NEXT-MONTH']:
# print('all good')
selected,date = telegramcalender.process_calendar_selection(bot, update)
if selected:
bot.send_message(chat_id=callback_query.message.chat.id,
text="You selected %s" % (date.strftime("%d-%m-%Y")),
reply_markup=ReplyKeyboardRemove())
bot.send_chat_action(chat_id=callback_query.message.chat.id, action=ChatAction.TYPING)
if 'CHECK,' in read_user(callback_query.message.chat.id,'status'):
_,district = read_user(callback_query.message.chat.id,'status').split(',')
id = country.get_district_id(district)
ret = send_slot_data(bot,id,date.strftime("%d-%m-%Y"),'district_id',callback_query.message.chat.id,callback_query.message.message_id,slotbyD)
if ret == 0:
bot.sendMessage(chat_id=callback_query.message.chat.id, text='No sessions found for this date!')
elif 'CHECKPIN,' in read_user(callback_query.message.chat.id,'status'):
_,pincode = read_user(callback_query.message.chat.id,'status').split(',')
ret = send_slot_data(bot,pincode,date.strftime("%d-%m-%Y"),'pincode',callback_query.message.chat.id,callback_query.message.message_id,slotbyP)
if ret == 0:
bot.sendMessage(chat_id=callback_query.message.chat.id, text='No sessions found for this date!')
update_user(callback_query.message.chat.id,'status','DONE')
return 'ok'
if update.message is None:
return 'BAD Request'
chat_id = update.message.chat.id
msg_id = update.message.message_id
# Telegram understands UTF-8, so encode text for unicode compatibility
text = update.message.text.encode('utf-8').decode()
# for debugging purposes only
print("got text message :", text)
# the welcoming message ####################3
if text == "/start":
# print the welcoming message ######################
bot_welcome = """
I am here to help you find your slot to get Vaccinated, I will also update you on the rising cases in your area!
1. use /start to initialize me
2. use /news to get an update on current covid news on your area
3. use /bore and I will send you jokes to make you laugh
4. use /check_availability for check availability of slots
5. use /add_subcription for get slot alert
6. use /my_subcriptions to view your subcriptions
7. use /remove_subcription to remove subcription
8. use /help to know how I work
9. use /share to share me with family and friends
10. use /delete_all Delete my data stored
Thank you for choosing me. I am glad to help you and others. Share with other people too.
"""
# send the welcoming message
bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id)
elif text == "/help":
bot_welcome = """
I am a telegram bot who can helpyou find your vaccination slots.
I am designed to save your time and efforts you spend on Co-Win.
Vaccination is one way to protect yourself and your family from this deadly virus.
I encourage you to get vaccinated as soon as possible
Use me and share with others too.
Here is the list of commands you can use :
1. use /start to initialize me
2. use /news to get an update on current covid news on your area
3. use /bore and I will send you jokes to make you laugh
4. use /check_availability for check availability of slots
5. use /help to know how I work
6. use /share to share me with family and friends
Thank you for choosing me. I am glad to help you and others. Share with other people too.
"""
# send the welcoming message
bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id)
########### bore #################
elif text == "/bore":
re = requests.get(BORE)
joke = re.json()
punch = joke['setup'] +" " + joke['punchline']
bot.sendMessage(chat_id=chat_id, text=punch, reply_to_message_id=msg_id)
###########share####################
elif text=="/share":
link = """
Getting vaccination is first step to win over this covid-war.
Join me to get slots info, news and more here.
https://t.me/VaccinationslotBot
please share with your family and friends!
"""
bot.sendMessage(chat_id=chat_id, text=link, reply_to_message_id=msg_id)
### /check availability #########################
elif text == "/check_availability":
bot_check_avail = "Hi! Tell me your location"
keys_inline = []
keys_inline.append([InlineKeyboardButton(text='Pincode',callback_data='pin_slot'),InlineKeyboardButton(text='District',callback_data='dis_slot')])
reply_markup = InlineKeyboardMarkup(keys_inline)
bot.sendMessage(chat_id=chat_id, text=bot_check_avail, reply_markup=reply_markup,reply_to_message_id=msg_id)
########### track user ##########
update_user(chat_id,'status','CHECK')
##### news ###############
elif text == "/delete_all":
pass
elif text == "/remove_subcription":
subscrib = read_user(chat_id,'Subcriptions')
if subscrib:
bot_text = 'Select the region you want to remove:'
key_buttons = subscrib['dis'] + subscrib['pin']
reply_markup = ReplyKeyboardMarkup([key_buttons],resize_keyboard=True,one_time_keyboard=True)
bot.sendMessage(chat_id=chat_id,text=bot_text, reply_markup=reply_markup, reply_to_message_id=msg_id)
update_user(chat_id,'status','SUBSCRIBE_rem')
else:
bot_text = 'You have no subcriptions!'
bot.sendMessage(chat_id=chat_id, text=bot_text, reply_to_message_id=msg_id)
elif text == "/my_subcriptions":
subscrib = read_user(chat_id,'Subcriptions')
bot_text = ''
if subscrib:
print(subscrib)
bot_text = 'These are your subcriptions:\n'
bot_text += '{}\n{}'.format('\n'.join(subscrib['dis']),'\n'.join(subscrib['pin']))
else:
bot_text = 'You have no subcription!'
bot.sendMessage(chat_id=chat_id, text=bot_text, reply_to_message_id=msg_id)
elif text == "/add_subcription":
bot_subscribe = "Hi! Let's subscribe your home:"
keys_inline = []
keys_inline.append([InlineKeyboardButton(text='Pincode',callback_data='pin_slot'),InlineKeyboardButton(text='District',callback_data='dis_slot')])
reply_markup = InlineKeyboardMarkup(keys_inline)
bot.sendMessage(chat_id=chat_id, text=bot_subscribe, reply_markup=reply_markup,reply_to_message_id=msg_id)
update_user(chat_id,'status','SUBSCRIBE')
elif text == "/news":
bot_news = "Tell me the place for which you want news!"
keys_inline = []
keys_inline.append([InlineKeyboardButton(text='State',callback_data='state_slot'),InlineKeyboardButton(text='District',callback_data='dis_slot')])
reply_markup = InlineKeyboardMarkup(keys_inline)
bot.sendMessage(chat_id=chat_id, text=bot_news, reply_markup=reply_markup,reply_to_message_id=msg_id)
################## after sending ###########
global covid_data_state_dict
global covid_data_district_dict
global pr_quo_list
########### get covid news state wise ##################
covid_data_state = requests.get(news_state_api)
covid_data_state = covid_data_state.json()
covid_data_state_dict = {}
for i in covid_data_state:
if i['state_name'] == '':
i['state_name'] = 'Unknown'
covid_data_state_dict[i['state_name']] = i
#########Get quote ###################
req = requests.get(quote)
quo = req.json()
pr_quo_list = [i['q'] for i in quo if 'q' in i]
########### user track id #############
update_user(chat_id,'status','NEWS')
########### get covid news district wise ##################
covid_data_district_dict = {}
covid_data_district = requests.get(news_district_api)
covid_data_district = covid_data_district.json()
for s in country.get_flat_states():
if s in covid_data_district:
covid_data_district_dict.update(covid_data_district[s]['districtData'])
else:
##### for debuging ############
# if read_user_stat(chat_id) == 'CHECK_date':
# print(text)
# bot_text = 'Enter the date:'
# reply_markup = telegramcalender.create_calendar()
# bot.sendMessage(chat_id=chat_id, text=bot_text, reply_markup=reply_markup, reply_to_message_id=msg_id)
print(read_user(chat_id,'status'))
if read_user(chat_id,'status') == 'NEWS_dis':
if text in country.get_flat_states():
bot_text = "Enter the district:"
districts = country.get_district(text)
reply_markup = ReplyKeyboardMarkup(districts,resize_keyboard=True,one_time_keyboard=True)
bot.sendMessage(chat_id=chat_id,text=bot_text, reply_markup=reply_markup, reply_to_message_id=msg_id)
update_user(chat_id,'status','NEWS')
elif read_user(chat_id,'status') == 'CHECK_dis':
if text in country.get_flat_check_states():
bot_text = "Enter the district:"
districts = country.get_check_district(text)
reply_markup = ReplyKeyboardMarkup(districts,resize_keyboard=True,one_time_keyboard=True)
bot.sendMessage(chat_id=chat_id,text=bot_text, reply_markup=reply_markup, reply_to_message_id=msg_id)
update_user(chat_id,'status','CHECK_date')
elif read_user(chat_id,'status') == 'SUBSCRIBE_dis':
if text in country.get_flat_check_states():
bot_text = "Enter the district:"
districts = country.get_check_district(text)
reply_markup = ReplyKeyboardMarkup(districts,resize_keyboard=True,one_time_keyboard=True)
bot.sendMessage(chat_id=chat_id,text=bot_text, reply_markup=reply_markup, reply_to_message_id=msg_id)
update_user(chat_id,'status','SUBSCRIBE_add_dis')
elif read_user(chat_id,'status') == 'NEWS':
covid_req = {}
if text in country.get_flat_states():
covid_req = covid_data_state_dict[text]
covid_text = 'Hey! There are {} no. of active cases and {} people recovered from coronavirus in {} state. And only {} no. of deaths reported due to covid. So, Don\'t worry. \nTotal confirmed cases are {}.\nStay home Stay safe!'.format(covid_req['new_active'],covid_req['new_cured'],covid_req['state_name'],covid_req['new_death'],covid_req['new_positive'])
pr_quo= pr_quo_list[0]
bot.sendMessage(chat_id=chat_id, text=covid_text, reply_to_message_id=msg_id)
bot.sendMessage(chat_id=chat_id, text=pr_quo)
elif text in covid_data_district_dict:
covid_req = covid_data_district_dict[text]
covid_text = 'Hey! There are {} no. of active cases and {} recovered from coronavirus in {} District. And only {} no. of deaths reported due to covid. So, Don\'t worry. \nTotal confirmed cases are {}'.format(covid_req['active'],covid_req['recovered'],text,covid_req['deceased'],covid_req['confirmed'])
pr_quo= pr_quo_list[0]
bot.sendMessage(chat_id=chat_id, text=covid_text, reply_to_message_id=msg_id)
bot.sendMessage(chat_id=chat_id, text=pr_quo)
update_user(chat_id,'status','DONE')
elif read_user(chat_id,'status') == 'CHECK_date':
bot_text = 'Enter the date:'
reply_markup = telegramcalender.create_calendar()
update.message.reply_text("Please select a date: ", reply_markup=telegramcalender.create_calendar())
update_user(chat_id,'status','CHECK,'+text)
elif read_user(chat_id,'status') == 'CHECK_pin':
bot_text = 'Enter the pincode:'
reply_markup = telegramcalender.create_calendar()
update.message.reply_text("Please select a date: ", reply_markup=telegramcalender.create_calendar())
update_user(chat_id,'status','CHECKPIN,'+text)
elif read_user(chat_id,'status') == 'SUBSCRIBE_add_dis':
subscrib = read_user(chat_id,'Subcriptions')
if subscrib:
if text not in subscrib['dis']:
subscrib['dis'].append(text)
else:
subscrib = {'dis':[],'pin':[]}
subscrib['dis'].append(text)
update_user(chat_id,'Subcriptions',subscrib)
update_user(chat_id,'status','DONE')
elif read_user(chat_id,'status') == 'SUBSCRIBE_add_pin':
subscrib = read_user(chat_id,'Subcriptions')
if subscrib:
if text not in subscrib['pin']:
subscrib['pin'].append(text)
else:
subscrib = {'dis':[],'pin':[]}
subscrib['pin'].append(text)
update_user(chat_id,'Subcriptions',subscrib)
update_user(chat_id,'status','DONE')
elif read_user(chat_id,'status') == 'SUBSCRIBE_rem':
subscrib = read_user(chat_id,'Subcriptions')
if subscrib:
if text in subscrib['pin']:
subscrib['pin'].remove(text)
elif text in subscrib['dis']:
subscrib['dis'].remove(text)
update_user(chat_id,'Subcriptions',subscrib)
update_user(chat_id,'status','DONE')
except Exception as e:
# if things went wrong
print('error',e)
return 'ok'
@app.route('/set_webhook', methods=['GET', 'POST'])
def set_webhook():
s = bot.setWebhook('{URL}{HOOK}'.format(URL=URL, HOOK=TOKEN))
if s:
return "webhook setup ok"
else:
return "webhook setup failed"
@app.route('/')
def index():
return '.'
if __name__ == '__main__':
app.run(threaded=True)