-
Notifications
You must be signed in to change notification settings - Fork 5
/
bot.js
1957 lines (1823 loc) · 87 KB
/
bot.js
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const { Telegraf, Scenes, session, TelegramError } = require('telegraf')
const { CoWIN, em } = require('./wrapper')
const mongoose = require('mongoose')
const User = require('./model')
const fs = require('fs')
const Token = require('./token')
const cron = require('node-cron')
const { spawnSync } = require('child_process')
const { Location } = require('./locationModel')
const moment = require('moment-timezone')
mongoose.connect('mongodb://localhost:27017/Cowin', { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, useCreateIndex: true })
.then(() => console.log('Connected to Database!'))
.catch((err) => console.log(err))
const BOT_TOKEN = process.env.BOT_TOKEN
const bot = new Telegraf(BOT_TOKEN)
const SWAPNIL = parseInt(process.env.OWNER_TG_ID)
const MAX_OTP_PER_DAY = 50
// ========CRON=========
cron.schedule('2 0 * * *', async () => {
await bot.telegram.sendMessage(SWAPNIL, 'Cron Task: Resetting OTP Counts and Flushing pm2 logs!')
await User.updateMany({ allowed: true }, { $set: { otpCount: 0 } })
spawnSync('pm2', ['flush'])
spawnSync('mongoexport', ['-d', 'Cowin', '-c', 'users', '--jsonArray', '-o', 'cowin_users.json'])
await bot.telegram.sendDocument(SWAPNIL, { source: fs.createReadStream('cowin_users.json'), filename: 'cowin_users.json' })
fs.unlinkSync('cowin_users.json')
fs.unlinkSync('states.json')
await Location.deleteMany({})
await bot.telegram.sendMessage(SWAPNIL, 'Deleted states.json and cleared Districts db!')
}, { timezone: 'Asia/Kolkata', scheduled: true })
// =====================
/**
* Helper methods
*/
function getDoseCount(beneficiary) {
if(beneficiary.dose1_date) {
return 2
}
return 1
}
function shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
function checkCenterToBook(uCenter, userCenters) {
if (!userCenters.length) {
return true
}
return !!userCenters.includes(uCenter.center_id)
}
function generateMessages(userCenters, userdata) {
const alerts = userCenters.map(uCenter => `✅<b>SLOT AVAILABLE!</b>\n\n<b>Name</b>: ${uCenter.name}\n<b>Pincode</b>: ${uCenter.pincode}\n<b>Age group</b>: ${userdata.age_group}+\n<b>Fee</b>: ${uCenter.fee_type}\n<b>Slots</b>:\n\t${uCenter.sessions.map(s => `<b>Date</b>: ${s.date}\n\t<b>Total Available Slots</b>: ${s.available_capacity}\n\t\t<b>Dose 1 Slots</b>: ${s.available_capacity_dose1}\n\t\t<b>Dose 2 Slots</b>: ${s.available_capacity_dose2}${s.vaccine ? '\n\t<b>Vaccine</b>: ' + s.vaccine : ''}${s?.allow_all_age ? `\n<b><u>Walk-in Available for all Age Groups!</u></b>` : ''}`).join('\n')}\n\n<u>Hurry! Book your slot before someone else does.</u>\nCoWIN Site: https://selfregistration.cowin.gov.in/`)
let chunkSize = 0
const MAX_MSG_SIZE = 4096 - 50 // 50bytes padding for safer side
const messages = []
let msg = ''
for (const alert of alerts) {
chunkSize += alert.length
if (chunkSize < MAX_MSG_SIZE) {
msg += alert + '\n\n'
} else {
messages.push(msg)
msg = ''
msg += alert + '\n\n'
chunkSize = 0
chunkSize += alert.length
}
}
messages.push(msg)
return messages
}
function calculateSleeptime() {
const proxies = fs.readFileSync('proxies.txt').toString().split('\n').filter(line => !!line).map(line => ({ host: line.split(':')[0], port: line.split(':')[1] }))
const ipCount = proxies.length
if (ipCount == 0) {
return 180
}
// deprecated: No proxy usage from now on
const fivMins = 5*60*1000
const reqPerIp = 100
const perIpTime = fivMins/ipCount
const sleeptime = parseInt((perIpTime/reqPerIp) + 25)
console.log('SLEEPTIME:', sleeptime)
return sleeptime
}
var TRACKER_SLEEP_TIME = calculateSleeptime() // for x ips
const MAX_TRACKING_ALLOWED = 4
const SNOOZE_LITERALS = [
{ name: '10min', seconds: 10 * 60 },
{ name: '20min', seconds: 20 * 60 },
{ name: '45min', seconds: 45 * 60 },
{ name: '1hr', seconds: 1 * 60 * 60 },
{ name: '2hr', seconds: 2 * 60 * 60 },
{ name: '4hr', seconds: 4 * 60 * 60 },
{ name: '6hr', seconds: 6 * 60 * 60 },
{ name: '8hr', seconds: 8 * 60 * 60 },
{ name: '10hr', seconds: 10 * 60 * 60 },
{ name: '12hr', seconds: 12 * 60 * 60 },
{ name: '18hr', seconds: 18 * 60 * 60 }
]
/**
* @deprecated no thumbs usage
*/
const THUMBS = {
up: ['👍', '👍🏻', '👍🏼', '👍🏽', '👍🏾', '👍🏿'],
down: ['👎', '👎🏻', '👎🏼', '👎🏽', '👎🏾', '👎🏿']
}
const _isAuth = async (chatId) => {
const { token } = await User.findOne({ chatId })
return Token.isValid(token)
}
const _isInvited = async (chatId) => {
const allowed = await User.findOne({ chatId, allowed: true })
return !!allowed
}
function secondsToHms(d) {
d = Number(d);
let h = Math.floor(d / 3600);
let m = Math.floor(d % 3600 / 60);
let s = Math.floor(d % 3600 % 60);
let hDisplay = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : "";
let mDisplay = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : "";
let sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : "";
return hDisplay + mDisplay + sDisplay;
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(() => resolve(), ms)
})
}
function getFutureDate(appointment) {
const appointmentDate = moment(appointment.date, 'DD-MM-YYYY').tz('Asia/Kolkata')
const today = moment(moment().tz('Asia/Kolkata').format('DD-MM-YYYY'), 'DD-MM-YYYY')
return today <= appointmentDate
}
function checkValidVaccine(center, preferredBenef) {
if (!preferredBenef.vaccine) {
return true
}
const valid = !!center.sessions.find(s => s.vaccine == preferredBenef.vaccine)
return valid
}
function switchChoose (preferredBenef) {
if(!preferredBenef.appointments.length) {
return 'schedule'
}
const hasFuture = !!preferredBenef.appointments.find(getFutureDate)
if (hasFuture) {
return 'reschedule'
} else {
return 'schedule'
}
}
function getFutureAppointment(appointments) {
const appointment = appointments.find(getFutureDate)
return appointment.appointment_id
}
/**
* Middlewares
*/
const authMiddle = async (ctx, next) => {
if (await _isAuth(ctx.chat.id)) {
next()
} else {
try {
return await ctx.reply('Sorry! You\'re not logged in! Please /login first.')
} catch (err) {
if (err instanceof TelegramError) {
await User.deleteOne({ chatId: ctx.chat.id })
}
}
}
}
const switchMiddle = async (ctx, next) => {
const { autobook } = await User.findOne({ chatId: ctx.chat.id, allowed: true })
if (autobook == true) {
return next()
} else {
return authMiddle(ctx, next)
}
}
const pinCheckMiddle = async (ctx, next) => {
const { tracking } = await User.findOne({ chatId: ctx.chat.id })
if (Array.isArray(tracking) && tracking.length > 0) {
next()
} else {
return await ctx.reply('You aren\'t tracking any pincode. Please /track atleast one pincode to activate /autobook')
}
}
const inviteMiddle = async (ctx, next) => {
if(await _isInvited(ctx.chat.id)) {
next()
} else {
try {
return await ctx.reply('Please verify yourself by providing invite code!\nSend /start to invite yourself.')
} catch (err) {
if (err instanceof TelegramError) {
await User.deleteOne({ chatId: ctx.chat.id })
}
}
}
}
const groupDetection = async (ctx, next) => {
try {
if(String(ctx.chat.id).startsWith('-')) {
await ctx.reply('This bot is not operatable in groups!')
return await ctx.leaveChat()
}
next()
} catch (err) { }
}
const benefMiddle = async (ctx, next) => {
try {
const { beneficiaries, preferredBenef } = await User.findOne({ chatId: ctx.chat.id })
if (Array.isArray(beneficiaries) && beneficiaries.length) {
if (preferredBenef && (Object.keys(preferredBenef)).length !== 0) {
return next()
}
return await ctx.reply('Please choose preferred beneficiary for auto slot booking. Send /beneficiaries to choose.')
}
return await ctx.reply('Please search for /beneficiaries and choose your preferred one.')
} catch (error) {}
}
const botUnderMaintain = async (ctx, next) => {
if (ctx.chat.id == SWAPNIL) {
return next()
}
try {
return await ctx.reply('Bot is under maintenance. Please try again after few minutes.')
} catch (err) { }
}
/**
* Wizards
*/
const walkthrough = new Scenes.WizardScene(
'walkthrough',
async (ctx) => {
await ctx.reply('Welcome to the bot! Let\'s get started with a simple walkthrough :)\nFirstly login using the bot.')
return ctx.scene.enter('login')
}
)
const loginWizard = new Scenes.WizardScene(
'login',
async (ctx) => {
try {
const { mobile } = await User.findOne({ chatId: ctx.chat.id }).select('mobile')
let options = {}
if (mobile) {
options = {
reply_markup: {
keyboard: [
[{ text: mobile }]
],
remove_keyboard: true,
one_time_keyboard: true
}
}
}
await ctx.reply('Send your phone number (10 digits only)', options)
return ctx.wizard.next()
} catch (error) {
if (error instanceof TelegramError) {
await User.deleteOne({ chatId: ctx.chat.id })
return ctx.scene.leave()
}
console.log(error)
try {
await ctx.reply('Some error occured please retry!')
} catch (err) { }
return ctx.scene.leave()
}
},
async (ctx) => {
try {
const mobile = ctx.message.text.trim()
ctx.wizard.state.mobile = mobile
if (mobile.length != 10) {
await ctx.reply('Please send 10 digit mobile number!', { reply_markup: { remove_keyboard: true } })
return ctx.scene.reenter()
}
const isnum = /^\d+$/.test(mobile)
if (!isnum) {
await ctx.reply('Please provide numbers only!')
return ctx.scene.reenter()
}
try {
const cowin = new CoWIN(mobile)
ctx.wizard.state.cowin = cowin
const MAX_TIMEOUT_OTP = 180 //sec
const currentTime = parseInt(Date.now() / 1000)
const { lastOtpRequested } = await User.findOneAndUpdate({ chatId: ctx.chat.id }, { $set: { mobile } })
if (currentTime - lastOtpRequested < MAX_TIMEOUT_OTP) {
await ctx.reply(`Please wait ${Math.abs(currentTime - (lastOtpRequested + MAX_TIMEOUT_OTP))} seconds before requesting for new otp.`)
return await ctx.scene.leave()
}
// const hour = moment().tz('Asia/Kolkata').get('hour')
// if (hour >= 16 && hour <= 20) {
// await ctx.reply('Instead bot, You can now login from the bot\'s site. Click on the button below to login. Once you finish the process check back here on bot. :)', {
// reply_markup: {
// inline_keyboard: [
// [{ text: 'Login!', url: `http://20.193.247.116/login?mobile=${mobile}&chatId=${ctx.chat.id}` }]
// ]
// }
// })
// return ctx.scene.leave()
// } else {
await ctx.wizard.state.cowin.sendOtp()
await User.updateOne({ chatId: ctx.chat.id }, {
$set: {
lastOtpRequested: parseInt(Date.now()/1000),
txnId: ctx.wizard.state.cowin.txnId
},
$inc: { otpCount: 1 }
})
// }
} catch (err) {
if (err instanceof TelegramError) {
await User.deleteOne({ chatId: ctx.chat.id })
return ctx.scene.leave()
}
console.log(err)
await ctx.reply('Error while sending OTP!\nPlease try again after some time!')
await ctx.reply('Instead bot, You can now login from the bot\'s site. Click on the button below to login. Once you finish the process check back here on bot. :)', {
reply_markup: {
inline_keyboard: [
[{ text: 'Login!', url: `http://20.193.247.116/login?mobile=${mobile}&chatId=${ctx.chat.id}` }]
]
}
})
return ctx.scene.leave()
}
const { otpCount, walkthrough } = await User.findOne({ chatId: ctx.chat.id }).select('otpCount walkthrough')
if (!walkthrough) {
await ctx.reply(`You\'ve requested OTP for ${otpCount} time${otpCount > 1 ? 's': ''} today. You can check your otp counts by sending /status`)
}
await ctx.reply('Send your OTP')
return ctx.wizard.next()
} catch (error) {
if (error instanceof TelegramError) {
await User.deleteOne({ chatId: ctx.chat.id })
return ctx.scene.leave()
}
console.log(error)
try {
await ctx.reply('Some error occured please retry!')
} catch (err) {}
return ctx.scene.leave()
}
},
async (ctx) => {
try {
const otp = ctx.message.text.trim()
const isnum = /^\d+$/.test(otp)
if (!isnum) {
await ctx.reply('Please provide numbers only!')
return
}
try {
await ctx.wizard.state.cowin.verifyOtp(otp)
await User.updateOne({ chatId: ctx.chat.id }, { $set: { token: ctx.wizard.state.cowin.token } })
await ctx.reply('Login successful!')
await User.updateOne({ chatId: ctx.chat.id }, { $set: { mobile: ctx.wizard.state.mobile, expireCount: 0 } })
const { walkthrough } = await User.findOne({ chatId: ctx.chat.id })
if (!walkthrough) {
await ctx.reply('Send /help to know further commands.')
} else {
await ctx.reply('Alright! Now choose your beneficiary for whom you want to book.')
beneficiaryCommand(ctx)
}
return ctx.scene.leave()
} catch (err) {
if (err instanceof TelegramError) {
await User.deleteOne({ chatId: ctx.chat.id })
return ctx.scene.leave()
}
console.log(err)
await ctx.reply('Invalid OTP!\nYou can try again with /otp <your-OTP>')
return ctx.scene.leave()
}
} catch (error) {
if (error instanceof TelegramError) {
await User.deleteOne({ chatId: ctx.chat.id })
return ctx.scene.leave()
}
console.log(error)
try {
await ctx.reply('Some error occured please retry!')
} catch (err) { }
return ctx.scene.leave()
}
}
)
loginWizard.command('cancel', async (ctx) => {
await ctx.scene.leave()
return await ctx.reply('Operation cancelled!')
})
const slotWizard = new Scenes.WizardScene(
'slot-booking',
async (ctx) => {
try {
await ctx.reply('Send your pincode')
return ctx.wizard.next()
} catch (error) {
console.log(error)
try {
await ctx.reply('Some error occured please retry!')
} catch (err) { }
return ctx.scene.leave()
}
},
async (ctx) => {
try {
const pincode = ctx.message.text.trim()
if (pincode.length !== 6) {
await ctx.reply('Please provide valid pincode!')
return ctx.scene.reenter()
}
const isnum = /^\d+$/.test(pincode)
if (!isnum) {
await ctx.reply('Please provide numbers only!')
return ctx.scene.reenter()
}
ctx.wizard.state.pincode = pincode
await User.updateOne({ chatId: ctx.chat.id }, { $set: { tmpPincode: pincode } })
await ctx.reply('Please choose age group.', { reply_markup:
{
inline_keyboard:[
[
{ text: '15+', callback_data: '15_plus' },
{ text: '18+', callback_data: '18_plus' },
{ text: '45+', callback_data: '45_plus' },
]
]
}
})
return ctx.scene.leave()
} catch(err) {
if (err instanceof TelegramError && err.response.status == 401) {
await ctx.reply('No slots available for this pin!')
return ctx.scene.leave()
}
console.log(err)
try {
await ctx.reply('Some error occured please retry!')
} catch (err) { }
return ctx.scene.leave()
}
}
)
slotWizard.command('cancel', async (ctx) => {
await ctx.scene.leave()
return await ctx.reply('Operation cancelled!')
})
bot.action('15_plus', async (ctx) => {
try {
const chatId = ctx.update.callback_query.from.id
await User.updateOne({ chatId }, { $set: { tmp_age_group: 15 } })
return await ctx.editMessageText('Please choose specific dose you want to track.', { reply_markup: {
inline_keyboard: [
[
{ text: 'Dose 1', callback_data: `dose-selection--${1}` },
{ text: 'Dose 2', callback_data: `dose-selection--${2}` },
{ text: 'Any Dose', callback_data: `dose-selection--${0}` }
]
]
} })
} catch (error) {
if (err instanceof TelegramError) {
await User.deleteOne({ chatId: ctx.chat.id })
}
}
})
bot.action('18_plus', async (ctx) => {
try {
const chatId = ctx.update.callback_query.from.id
await User.updateOne({ chatId }, { $set: { tmp_age_group: 18 } })
return await ctx.editMessageText('Please choose specific dose you want to track.', { reply_markup: {
inline_keyboard: [
[
{ text: 'Dose 1', callback_data: `dose-selection--${1}` },
{ text: 'Dose 2', callback_data: `dose-selection--${2}` },
{ text: 'Any Dose', callback_data: `dose-selection--${0}` }
]
]
} })
} catch (err) {
if (err instanceof TelegramError) {
await User.deleteOne({ chatId: ctx.chat.id })
}
}
// return ctx.scene.enter('track-pt2')
})
bot.action('45_plus', async (ctx) => {
try {
const chatId = ctx.update.callback_query.from.id
await User.updateOne({ chatId }, { $set: { tmp_age_group: 45 } })
return await ctx.editMessageText('Please choose specific dose you want to track.', { reply_markup: {
inline_keyboard: [
[
{ text: 'Dose 1', callback_data: `dose-selection--${1}` },
{ text: 'Dose 2', callback_data: `dose-selection--${2}` },
{ text: 'Any Dose', callback_data: `dose-selection--${0}` }
]
]
} })
} catch (err) {
if (err instanceof TelegramError) {
await User.deleteOne({ chatId: ctx.chat.id })
return ctx.scene.leave()
}
}
// return ctx.scene.enter('track-pt2')
})
bot.action(/dose-selection--.*/, async (ctx) => {
try {
const chatId = ctx.update.callback_query.from.id
const dose = parseInt(ctx.update.callback_query.data.split('dose-selection--')[1])
await User.updateOne({ chatId }, { $set: { tmpDose: dose } })
// return await ctx.editMessageText(`Selected ${dose ? 'Dose ' + dose : 'Any Dose'}\nSend any text to continue...`)
const { tmpPincode, tmp_age_group } = await User.findOne({ chatId: ctx.chat.id })
const userTracking = await User.findOne({ chatId: ctx.chat.id, tracking: { $elemMatch: { pincode: tmpPincode, age_group: tmp_age_group } } }).select('tracking')
if (userTracking) {
return await ctx.editMessageText('You are already tracking this pincode and age group!')
}
return await ctx.editMessageText(`Your provided Information.\n<b>Pincode</b>: ${tmpPincode}\n<b>Age group</b>: ${tmp_age_group}+\n<b>Dose</b>: ${dose === 0 ? 'ANY' : dose}\nIf it is correct then send 👍 else 👎`, { parse_mode: 'HTML', reply_markup: {
inline_keyboard: [
[{ text: '👍', callback_data: `selection-accept` }, { text: '👎', callback_data: `selection-reject` }]
]
} })
} catch (err) {
console.log(err)
if (err instanceof TelegramError) {
await User.deleteOne({ chatId: ctx.chat.id })
return
}
}
})
bot.action('selection-accept', async (ctx) => {
try {
const txt = ctx.update.callback_query.message.text
const entities = ctx.update.callback_query.message.entities
await ctx.editMessageText(txt + '\n\nRequest accepted!', { entities })
const { tmpPincode, tmp_age_group, tmpDose, walkthrough } = await User.findOne({ chatId: ctx.chat.id })
await User.updateOne({ chatId: ctx.chat.id }, { $push:
{
tracking: { pincode: tmpPincode, age_group: tmp_age_group, dose: tmpDose }
}
})
await User.updateOne({ chatId: ctx.chat.id }, { $unset: { tmpPincode: 1, tmp_age_group: 1, tmpDose: 1 } })
await ctx.reply('Now, You\'ll be notified as soon as the vaccine will be available in your desired pincode. Please take a note that this bot is in experimental mode. You may or may not receive messages. So please check the portal by yourself as well. Also if you find some issues then please let me know @SoniSins')
await ctx.reply(`You can track multiple pins. Max tracking pin limit is ${MAX_TRACKING_ALLOWED}\nYou can choose your preferred vaccine and fee type by sending /vaccine\nAlso you can choose your desired center for autobooking using /center`)
if (walkthrough) {
await ctx.reply('Awesome! Now we\'re all set up! Now you can Turn ON <b>Autobook</b> Feature. :)\nJust select \"Turn ON\" button from next Message.', { parse_mode: 'HTML' })
autoBookCommand(ctx)
}
} catch (error) {
console.log(error)
}
})
bot.action('selection-reject', async (ctx) => {
try {
const txt = ctx.update.callback_query.message.text
const entities = ctx.update.callback_query.message.entities
return ctx.editMessageText(txt + '\nRequest Rejected!', { entities })
} catch (error) {
console.log(error)
}
})
const sendToAll = new Scenes.WizardScene(
'send-all',
async (ctx) => {
await ctx.reply('Send the message which you want to convey to all.')
return ctx.wizard.next()
},
async (ctx) => {
const msg = ctx.message.text
const entities = ctx.message.entities
ctx.wizard.state.msg = msg
ctx.wizard.state.entities = entities
await ctx.reply(`Start from?`)
return ctx.wizard.next()
},
async (ctx) => {
try {
const startfrom = parseInt(ctx.message.text.trim()) || 0
ctx.scene.leave()
const { msg, entities } = ctx.wizard.state
const users = (await User.find({})).filter(u => u.allowed && u.chatId)
await ctx.reply(`Broadcasting the message to ${users.length} people.`)
const mesg = await ctx.reply('Status...')
await ctx.scene.leave()
let counter = 0
for (const user of users) {
if (counter < startfrom) {
counter += 1
continue
}
try {
if (user.allowed) {
const announcement = await bot.telegram.sendMessage(user.chatId, msg, { entities })
await bot.telegram.pinChatMessage(user.chatId, announcement.message_id)
await sleep(200)
}
} catch (err) {
console.log("Broadcast error!", err)
if (err instanceof TelegramError) {
if (err.response.error_code == 403) {
await User.deleteOne({ chatId: user.chatId })
const index = users.findIndex(u => u.chatId == user.chatId)
users.splice(index, 1)
}
}
}
counter += 1
await ctx.telegram.editMessageText(SWAPNIL, mesg.message_id, null, `Notified to ${counter}/${users.length} people.`)
}
} catch (err) {
await ctx.reply('Some error occured!')
}
}
)
sendToAll.command('cancel', async (ctx) => {
await ctx.scene.leave()
return await ctx.reply('Operation cancelled!')
})
const districtSelection = new Scenes.WizardScene(
'district',
async (ctx) => {
try {
const states = await CoWIN.getStates()
const markupButton = states.reduce((result, value, index, array) => {
const buttonMap = array.slice(index, index+2)
if (index % 2 === 0)
result.push(buttonMap.map(v => ({ text: v.state_name })))
return result
}, [])
await ctx.reply('Choose your preferred state first. Make sure you choose the state/district whichever\'s pincode you wanna track.', { reply_markup: {
keyboard: markupButton,
remove_keyboard: true,
one_time_keyboard: true
} })
return ctx.wizard.next()
} catch (error) {
console.log(error)
await ctx.reply('Something went wrong! try again.')
if (error instanceof TelegramError) {
await User.deleteOne({ chatId: ctx.chat.id })
return ctx.scene.leave()
}
}
},
async (ctx) => {
try {
const state_nam = ctx.message.text
const states = await CoWIN.getStates()
const { state_id, state_name } = states.find(s => s.state_name.trim() == state_nam.trim())
if (!state_id) {
await ctx.reply('Sorry invalid selection. Try again /district and Please choose valid state.', { reply_markup: { remove_keyboard: true } })
return ctx.scene.leave()
}
await User.updateOne({ chatId: ctx.chat.id }, { $set: { stateId: state_id } })
const districts = await CoWIN.getDistrict(state_id)
ctx.wizard.state.state_id = state_id
const markupButton = districts.reduce((result, value, index, array) => {
const buttonMap = array.slice(index, index+2)
if (index % 2 === 0)
result.push(buttonMap.map(v => ({ text: v.district_name })))
return result
}, [])
await ctx.reply(`You\'ve selected ${state_name}. Please choose your district.`, {
reply_markup: {
keyboard: markupButton,
remove_keyboard: true,
one_time_keyboard: true
}
})
return ctx.wizard.next()
} catch (error) {
console.log(error)
if (error instanceof TelegramError) {
await User.deleteOne({ chatId: ctx.chat.id })
return ctx.scene.leave()
}
}
},
async (ctx) => {
try {
const district_nam = ctx.message.text
const districts = await CoWIN.getDistrict(ctx.wizard.state.state_id)
const { district_id, district_name } = districts.find(d => d.district_name.trim() == district_nam.trim())
if (!district_id) {
await ctx.reply('Sorry invalid selection. Try again /district and Please choose valid district.', { reply_markup: { remove_keyboard: true } })
return ctx.scene.leave()
}
await User.updateOne({ chatId: ctx.chat.id }, { $set: { districtId: district_id, centers: [] } })
const { walkthrough } = await User.findOne({ chatId: ctx.chat.id }).select('walkthrough')
await ctx.reply(`You\'ve selected ${district_name}.`, { reply_markup: { remove_keyboard: true } })
if (walkthrough) {
await ctx.reply('Amazing! One final step...\nNow lets choose the pincodes you wanna track.')
return ctx.scene.enter('slot-booking')
} else {
await ctx.reply('Now you can /track your desired pincode. You can also change your district whenever you want to by sending /district\nAlso your preferred /center list is also cleared')
}
return ctx.scene.leave()
} catch (error) {
console.log(error)
if (error instanceof TelegramError) {
await User.deleteOne({ chatId: ctx.chat.id })
return ctx.scene.leave()
}
}
}
)
const stage = new Scenes.Stage([loginWizard, slotWizard, sendToAll, districtSelection, walkthrough])
// bot.use(botUnderMaintain)
bot.use(session())
bot.use(groupDetection)
bot.use(stage.middleware())
/**
* Commands
*/
bot.help(inviteMiddle, async (ctx) => {
try {
let commands = ``
if (_isAuth(ctx.chat.id)) {
commands += `/logout = logout from the bot/portal\n`
}
commands += `/beneficiaries = to list beneficiaries\n/donate = Please do :)\n/certificate - to download certificate\n/vaccine = To choose your preferred vaccine while tracking\n/snooze = To pause messages for several given time\n/unsnooze = remove message pause and get message on every ~1min interval\n/login = To login with your number!\n/track = to track available slot with given pincode.\n/untrack = untrack your current pincode\n/otp <your-OTP> = during auth if your OTP is wrong then you can try again with /otp command\n/status = check your status\n/district = to set your prefered district for tracking pincodes.\n/locations = Usage: /locations <State Name> -> to get number of users in your state/area who are active on this bot.\n/center - Choose preferred center for autobooking.\n/autobook - for autobooking on tracking pincode with available slots`
if (ctx.chat.id == SWAPNIL) {
commands += `\nAdmin commands:\n/sleeptime | /sleeptime <ms>\n/sendall\n/botstat\n/revokeall\n/captchainfo\n/captchatest`
}
return await ctx.reply(commands)
} catch (err) {
if (err instanceof TelegramError) {
await User.deleteOne({ chatId: ctx.chat.id })
return
}
}
})
bot.command('id', async (ctx) => await ctx.reply(`Your chat id is: ${ctx.chat.id}`))
bot.start(async (ctx) => {
if (!(await User.findOne({ chatId: ctx.chat.id }))) {
await User.create({ chatId: ctx.chat.id, allowed: true, walkthrough: true })
}
const msg = `Hi, This bot can operate on selfregistration.cowin.gov.in.\nYou can send /help to know instructions about how to use this bot.\nDeveloped by <a href="https://github.com/SwapnilSoni1999">Swapnil Soni</a>`
await ctx.reply(msg, { parse_mode: 'HTML' })
await ctx.reply(`Before you proceed further, Make sure you read the following notes:\n\n - <u>You must have atleast one beneficiary on your registered mobile number.</u>\n - <u>You must use login number which you used to register on cowin portal.</u>\n\nRead previous Bot Changelog here: https://telegra.ph/Cowin-Vaccine-Tracker-Bot-Changelog-06-07`, { parse_mode: 'HTML' })
const { walkthrough } = await User.findOne({ chatId: ctx.chat.id }).select('walkthrough')
if (walkthrough) {
return ctx.scene.enter('walkthrough')
}
})
bot.command('login', inviteMiddle, async (ctx) => {
const user = await User.findOne({ chatId: ctx.chat.id })
if (user) {
if (user.token && Token.isValid(user.token)) {
return await ctx.reply('You\'re already logged in! Send /logout to Logout.')
}
}
if (user.otpCount > MAX_OTP_PER_DAY) {
return await ctx.reply(`Sorry! you've reached max OTP request limit for today! Try tomorrow.\nAlso do not login on CoWIN portal else your account will be banned for 24 hours.`)
}
ctx.scene.enter('login')
})
bot.command('otp', inviteMiddle, async (ctx) => {
const user = await User.findOne({ chatId: ctx.chat.id })
if (user.token) {
return await ctx.reply('You\'re already logged in! Send /logout to Logout.')
}
if(!user.txnId) {
return await ctx.reply('You\'ve not initialized login process. Please send /login to continue.')
}
try {
const token = await CoWIN.verifyOtpStatic(ctx.message.text.split(' ')[1], user.txnId)
await User.updateOne({ chatId: ctx.chat.id }, { token: token })
return await ctx.reply('Login successful!')
} catch (err) {
console.log(err)
return await ctx.reply('Wrong OTP! Please try again with /otp <your-OTP>')
}
})
bot.command('logout', inviteMiddle, async (ctx) => {
try {
const user = await User.findOne({ chatId: ctx.chat.id })
if (!user.token) {
return await ctx.reply('You\'re not logged in! Please /login first.')
}
if (user.txnId) {
await User.updateOne({ chatId: ctx.chat.id }, { txnId: null })
}
await User.updateOne({ chatId: ctx.chat.id }, { $set: { token: null, txnId: null, beneficiaries: [], preferredBenef: null } })
return await ctx.reply('Logged out! Send /login to login. Note: You\'re still tracking your current pincode and age group. Check it with /status')
} catch (err) {
if (err.response.status == 403 || err instanceof TelegramError) {
await User.deleteOne({ chatId: ctx.chat.id })
}
}
})
function expandAppointments(appointments) {
console.log('Expanding appointments', appointments)
// seperated by \n at end \t at begining
let msg = `There ${appointments.length > 1 ? 'are' : 'is'} ${appointments.length} appointment${appointments.length > 1 ? 's' : ''} Booked.\n`
const appointmentMap = appointments.map(ap => [
`<b>Center Name</b>: ${ap.name || 'Unavailable'}`,
`${ap.district ? '<b>District</b>: ' + ap.district : ''}`,
`<b>Block</b>: ${ap.block_name}`,
`${ap.state_name ? '<b>State</b>: ' + ap.state_name : ''}`,
`<b>Center Timings</b>\n: ${[
`<u><b>From</b></u>: ${ap.from}`,
`<u><b>To</b></u>: ${ap.to}`,
`<b>Dose</b>: ${ap.dose}`,
`<b>Date</b>: ${ap.date}`,
`<u><b>Your time Slot</b></u>: <u>${ap.slot}</u>`
].join('\n\t\t')}`
].filter(v => !!v).join('\n'))
msg += appointmentMap.join("\n")
return msg
}
const beneficiaryCommand = async (ctx) => {
const { token } = await User.findOne({ chatId: ctx.chat.id })
try {
const ben = await CoWIN.getBeneficiariesStatic(token)
if (!ben.length) {
return await ctx.reply('No beneficiaries. Please add beneficiary first from cowin.gov.in and send /beneficiaries again.')
}
await User.updateOne({ chatId: ctx.chat.id }, { $set: { beneficiaries: ben } })
const txts = ben.map(b => `<b>ID:</b> ${b.beneficiary_reference_id}\n<b>Name</b>: ${b.name}\n<b>Birth Year</b>: ${b.birth_year}\n<b>Gender</b>: ${b.gender}\n<b>Vaccination Status</b>: ${b.vaccination_status}\n<b>Vaccine</b>: ${b.vaccine}\n<b>Dose 1 Date</b>: ${b.dose1_date || 'Not vaccinated'}\n<b>Dose 2 Date</b>: ${b.dose2_date || 'Not vaccinated'}\n\n<b>Appointments</b>: ${b.appointments.length ? expandAppointments(b.appointments) : 'No appointments booked.'}\n\n<u>It is recommended to take both doses of same vaccines. Please do not take different vaccine doeses.</u>`)
for (const txt of txts) {
await ctx.reply(txt, { parse_mode: 'HTML' })
}
const validBenef = ben.filter(b => ((b.dose1_date ? false : true) || (b.dose2_date ? false : true)))
const markupButton = validBenef.map(b => ([{ text: b.name, callback_data: `benef--${b.beneficiary_reference_id}` }]))
await ctx.reply('Please choose preferred beneficiary for auto booking.', { reply_markup: {
inline_keyboard: markupButton
} })
return
} catch (err) {
console.log(err)
await User.updateOne({ chatId: ctx.chat.id }, { token: null, txnId: null })
return await ctx.reply('Token expired! Please /login again. Or maybe you haven\'t added any beneficiary on cowin portal. Please consider adding atleast one from selfregistration.cowin.gov.in')
}
}
bot.command('beneficiaries', inviteMiddle, authMiddle, beneficiaryCommand)
bot.action(/benef--.*/, async (ctx) => {
try {
const benefId = ctx.update.callback_query.data.split('benef--')[1]
const { beneficiaries, walkthrough } = await User.findOne({ chatId: ctx.update.callback_query.from.id }).select('beneficiaries walkthrough')
const matched = beneficiaries.find(b => b.beneficiary_reference_id == benefId)
await User.updateOne({ chatId: ctx.update.callback_query.from.id }, { $set: { preferredBenef: matched } })
await ctx.editMessageText(`<b>ID:</b> ${matched.beneficiary_reference_id}\n<b>Name</b>: ${matched.name}\n<b>Birth Year</b>: ${matched.birth_year}\n<b>Gender</b>: ${matched.gender}\n\n\nNow you can use /autobook feature.`, { parse_mode: 'HTML' })
if (walkthrough) {
if (matched.dose1_date) {
await ctx.reply(`Great! The beneficiary has taken ${matched.vaccine}. So setting default tracking to ${matched.vaccine}. You can change your vaccine tracking by sending /vaccine anytime.`)
await User.updateOne({ chatId: ctx.update.callback_query.from.id }, { $set: { vaccine: matched.vaccine } })
const FEES = [
{ text: 'Free', callback_data: `fee-type--Free` },
{ text: 'Paid', callback_data: `fee-type--Paid` },
{ text: 'Any', callback_data: `fee-type--ANY` }
]
return ctx.reply('Choose vaccine Fee Type.', {
reply_markup: {
inline_keyboard: [
FEES
]
}
})
} else {
await ctx.reply(`It seems like the beneficiary hasn't been vaccinated OR fully vaccinated already. So choose the vaccine type you want to track first.`)
return vaccineCommand(ctx)
}
}
} catch (err) {
if (err instanceof TelegramError) {
await User.deleteOne({ chatId: ctx.chat.id })
return ctx.scene.leave()
}
}
})
const vaccineCommand = async (ctx) => {
try {
const vaccines = ['COVISHIELD', 'COVAXIN', 'SPUTNIK V', 'ANY']
const markupButton = [vaccines.map(v => ({ text: v, callback_data: `vaccine--${v}`}))]
return await ctx.reply(`Choose your preferred vaccine to track.`, { reply_markup: {
inline_keyboard: markupButton
} })
} catch (error) {
if (err instanceof TelegramError) {
await User.deleteOne({ chatId: ctx.chat.id })
return
}
}
}
bot.command('vaccine', inviteMiddle, vaccineCommand)
const vaccineAction = async (ctx) => {
try {
const vaccine = ctx.update.callback_query.data.split('vaccine--')[1]
await User.updateOne({ chatId: ctx.update.callback_query.from.id }, { $set: { vaccine } })
await ctx.editMessageText(`You've chosen: <b>${vaccine}</b>\nYou will be notified only for ${vaccine} slots available only.\nIf you wish to change your preferred vaccine then send /vaccine to change.`, { parse_mode: 'HTML' })
const FEES = [
{ text: 'Free', callback_data: `fee-type--Free` },
{ text: 'Paid', callback_data: `fee-type--Paid` },
{ text: 'Any', callback_data: `fee-type--ANY` }
]
return ctx.reply('Choose vaccine Fee Type.', {
reply_markup: {
inline_keyboard: [
FEES
]
}
})
} catch (err) {
console.log(err)
if (err instanceof TelegramError) {
await User.deleteOne({ chatId: ctx.chat.id })
return
}
}
}
bot.action(/vaccine--.*/, vaccineAction)
bot.action(/fee-type--.*/, async (ctx) => {
try {
const feeType = ctx.update.callback_query.data.split('fee-type--')[1]
await User.updateOne({ chatId: ctx.update.callback_query.from.id }, { $set: { feeType } })
await ctx.editMessageText(`You've chosen fee type: <b>${feeType}</b>\nYou can check your current status by sending /status`, { parse_mode: 'HTML' })
const { walkthrough } = await User.findOne({ chatId: ctx.update.callback_query.from.id }).select('walkthrough')
if (walkthrough) {
await ctx.reply('We\'re almost there! Now lets choose the district!')