-
Notifications
You must be signed in to change notification settings - Fork 1
/
bot.js
529 lines (383 loc) · 15.6 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
const { Client, Message } = require('discord.js');
const client = new Client({ partials: ['MESSAGE', 'REACTION'] });
const PREFIX = "!";
require("dotenv").config();
var Dis;
var Age;
var Id;
var userArray;
var ua;
const axios = require('axios');
const bodyParser = require('body-parser');
const cron = require('node-cron');
var distArray = [{ "district_id": 301, "district_name": "Alappuzha" }, { "district_id": 307, "district_name": "Ernakulam" }, { "district_id": 306, "district_name": "Idukki" }, { "district_id": 297, "district_name": "Kannur" },
{ "district_id": 295, "district_name": "Kasaragod" }, { "district_id": 298, "district_name": "Kollam" }, { "district_id": 304, "district_name": "Kottayam" }, { "district_id": 305, "district_name": "Kozhikode" },
{ "district_id": 302, "district_name": "Malappuram" }, { "district_id": 308, "district_name": "Palakkad" }, { "district_id": 300, "district_name": "Pathanamthitta" }, { "district_id": 296, "district_name": "Thiruvananthapuram" },
{ "district_id": 303, "district_name": "Thrissur" }, { "district_id": 299, "district_name": "Wayanad" }, { "district_id": 225, "district_name": "Baramulla" }, { "district_id": 237, "district_name": "Rajouri" }
];
let resultsObjectArray = new Array();
console.log("updating data cache")
for (var i = 0; i < distArray.length; i++) {
// console.log(distArray[i])
flow(distArray[i]);
// console.log("data update")
// resultsObjectArray.push(r);
}
cron.schedule('0 5,15,25,35,45,55 * * * *', () => {
console.log("updating data cache")
for (var i = 0; i < distArray.length; i++) {
// console.log(distArray[i])
flow(distArray[i]);
// console.log("data update")
// resultsObjectArray.push(r);
}
// console.log(resultsObjectArray)
})
cron.schedule('0 0 * * * *', () => {
sendUser();
})
client.login(process.env.DISCORDJS_BOT_TOKEN);
client.on('ready', () => {
console.log(`${client.user.tag} has logged in.`);
});
const mongoose = require('mongoose')
const { Schema } = mongoose;
const dotenv = require('dotenv');
dotenv.config();
mongoose.connect(process.env.atlasURI, { useNewUrlParser: true, useUnifiedTopology: true })
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("connection successful")
});
//Questions Start Here - Main part
const userSchema = new Schema({
discordID: String, // String is shorthand for {type: String}
choice: [{
disID: Number,
ageGp: Number
}]
});
const user = mongoose.model("user", userSchema)
client.on('message', (message) => {
if (message.author.bot) return;
if (message.guild === null) return; {
if (message.content === '!help' || message.content === '!HELP') //|| message.content === 'Help'
{
message.reply('Hello! I sense that you have asked for help', { files: ["https://ik.imagekit.io/nik/newhelp-myvac_jse93D0f3.png"] });
}
if (message.content.startsWith(PREFIX)) {
const [CMD_NAME, ...args] = message.content.trim().substring(PREFIX.length).split(/\s+/);
if (CMD_NAME === 'vaccine' || CMD_NAME === 'check' || CMD_NAME === 'VACCINE' || CMD_NAME === 'CHECK') {
let userCMD = CMD_NAME
// console.log(userCMD)
message.react('💉')
Id = message.author.id;
// console.log(Id);
//message.reply('Enter your District'); --- Asking Question PART
let filter = m => m.author.id === message.author.id
message.channel.send('<@' + Id + `> Enter your District ID`, { files: ["https://ik.imagekit.io/nik/districts-myvac_RrklJ79ZX.png"] }).then(() => {
message.channel.awaitMessages(filter, {
max: 1,
time: 30000,
errors: ['time']
})
.then(message => {
message = message.first()
if (message.author.id == Id) {
if (message.content == '301' || message.content == '307' || message.content == '306' || message.content == '297' || message.content == '295' || message.content == '298' || message.content == '304' || message.content == '305' || message.content == '302' || message.content == '300' || message.content == '308' || message.content == '303' || message.content == '296' || message.content == '299') {
Dis = message.content;
message.react('👍');
// console.log(Dis);
message.channel.send('<@' + Id + '> Ok.Now Enter your Age Category (18+ or 45+)');
message.channel.awaitMessages(filter, {
max: 1,
time: 30000,
errors: ['time']
})
.then(message => {
message = message.first()
if (message.author.id == Id) {
if (message.content == '18' || message.content == '45' || message.content == '18+' || message.content == '45+') {
if (message.content == '18+') {
Age = 18
} else if (message.content == '45+') {
Age = 45
} else {
Age = message.content
}
message.react('👍');
// console.log(Age);
userArray = [{
discordID: Id,
choice: [{
disID: Dis,
ageGp: Age,
}]
}]
// console.log(userCMD)
if (userCMD === 'vaccine' || userCMD === 'VACCINE') {
// console.log("in1")
message.channel.send('Thankyou ' + '<@' + Id + '> We will fetch the details for you soon\n' + 'Be ready to get vaccinated!', { files: ["https://ik.imagekit.io/nik/thanks-myvac_R0-60xlpN.png"] })
.then(() => {
// console.log(userArray[0])
userInput = new user(userArray[0])
userInput.save()
.then(() => {
client.users.fetch(Id).then((user) => {
resultDM = sendDM(userArray[0])
user.send('Hello ' + '<@' + Id + '>' + ' Your selected choices are:\n' + 'Age Category: ' + Age + '\nDistrict ID: ' + Dis);
user.send(resultDM)
// console.log(distArray)
});
})
.catch('error', () => {
console.log(error)
})
})
} else if (userCMD === 'check' || userCMD === 'CHECK') {
// console.log("in1")
message.channel.send('Thankyou ' + '<@' + Id + '> Check your DM for latest slot update. You can type ``!vaccine`` to register for hourly updates')
.then(() => {
client.users.fetch(Id).then((user) => {
resultDM = sendDM(userArray[0])
user.send(resultDM)
});
})
}
} else {
message.channel.send('Wrong Category');
setTimeout(function() {
message.channel.send('Type ``!vaccine`` and try again');
}, 2000);
}
}
})
.catch(collected => {
message.channel.send('Timeout!');
})
} else {
message.channel.send('Wrong District ID');
setTimeout(function() {
message.channel.send('Type ``!vaccine`` and try again');
}, 2000);
}
}
})
.catch(collected => {
message.channel.send('Timeout!');
})
})
} else if (CMD_NAME === 'unsubscribe') {
message.react('👋')
Id = message.member.id;
Model.deleteMany({ discordID: Id })
.then(message.channel.send('<@' + Id + '> Hope you enjoyed my services. You will no longer recieve slot notifications. You can type ``!vaccine`` anytime to add a new district and start recieving alerts... 😊'))
}
};
}
}
)
function flow(districtArray) {
district = districtArray.district_id
let date_ob = new Date();
// current date
// adjust 0 before single digit date
let date = ("0" + date_ob.getDate()).slice(-2);
// current month
let month = ("0" + (date_ob.getMonth() + 1)).slice(-2);
// current year
let year = date_ob.getFullYear();
var formattedDate = date + "-" + month + "-" + year;
// let hours = date_ob.getHours();
// // current minutes
// let minutes = date_ob.getMinutes();
// // console.log(formattedDate + " [" + hours + ":" + minutes + "]");
var array45 = new Array();
var array18 = new Array();
// centersArray.push(formattedDate + " [" + hours + ":" + minutes + "]");
var result18 = ""
var result45 = ""
var cap45 = 0
var cap18 = 0
url = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByDistrict?district_id=" + district + "&date=" + formattedDate
// url = "https://gist.githubusercontent.com/nikiljos/28f37128f9a21632d3c21b04da175e07/raw/4c2d65287faa1368a3cd6a012cc0503231b0a3e2/cowin-sample.json";
axios.get(url, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36',
},
}, )
.then((response) => {
dName = districtArray.district_name
district = districtArray.district_id
cowinData = response.data
function length(cowinData) {
return Object.keys(cowinData).length;
}
// dName = cowinData.centers[0].district_name;
// x = length(cowinData.centres);
x = length(cowinData.centers)
// console.log(x)
array45.push("\n**" + dName + "**")
array18.push("\n**" + dName + "**")
var availableCap = 0;
for (m = 0; m < x; m++) {
// console.log(url);
y = length(cowinData.centers[m].sessions)
// console.log(y)
for (n = 0; n < y; n++) {
// console.log()
var cap = cowinData.centers[m].sessions[n].available_capacity;
var d1Cap = cowinData.centers[m].sessions[n].available_capacity_dose1
var d2Cap = cowinData.centers[m].sessions[n].available_capacity_dose2
var minAge = cowinData.centers[m].sessions[n].min_age_limit
cap45 = cap45 + cap
var cName = cowinData.centers[m].name
var vName = cowinData.centers[m].sessions[n].vaccine
var vDate = cowinData.centers[m].sessions[n].date
if (cap > 0) {
array45.push("```" + cName + " - " + cap + " - " + vName + " - " + vDate + " - " + minAge + "+\n1st Dose - " + d1Cap + " slots | 2nd Dose - " + d2Cap + " slots```")
}
if (minAge == 18) {
cap18 = cap18 + cap
if (cap > 0) {
array18.push("```" + cName + " - " + cap + " - " + vName + " - " + vDate + " - " + minAge + "+\n1st Dose - " + d1Cap + " slots | 2nd Dose - " + d2Cap + " slots```")
}
}
}
}
array45.push("\nAvailble slots for 45+ category: " + cap45)
array45.push("Total centres listed: " + x)
array45.push("Book your slots on https://selfregistration.cowin.gov.in/")
array18.push("\nAvailble slots for 18+ category: " + cap18)
array18.push("Total centres listed: " + x)
array18.push("Book your slots on https://selfregistration.cowin.gov.in/")
// Here array.values() function is called.
var iterator = array45.values();
// Here all the elements of the array is being appended.
for (let elements of iterator) {
result45 = result45.concat(elements + "\n");
}
var iterator2 = array18.values();
for (let elements of iterator2) {
result18 = result18.concat(elements + "\n");
ar = ({
districtID: district,
districtName: dName,
cap18: cap18,
cap45: cap45,
result18: result18,
result45: result45
})
log(ar)
// console.log(ar)
// console.log(resultsObjectArray)
// return resultsObjectArray;
}
})
.catch(function(error) {
// handle error
console.log(error);
// console.log("error in cowin response")
})
// return aR
// function ss() {
// console.log("test", distArray)
// console.log()
// }
}
function sendDM(userArray) {
// console.log("in", resultsObjectArray[0].districtID)
for (var x = 0; x < 16; x++) {
// console.log("in56", resultsObjectArray[x].districtID)
if (userArray.choice[0].disID == resultsObjectArray[x].districtID) {
if (userArray.choice[0].ageGp == 18) {
// console.log("in1", userArray.choice[0])
mess = resultsObjectArray[x].result18.slice(0, 2000)
return mess
} else if (userArray.choice[0].ageGp == 45) {
// console.log("in2")
mess = resultsObjectArray[x].result45.slice(0, 2000)
return mess
}
}
}
}
function log(ar) {
switch (ar.districtID) {
case 301:
resultsObjectArray[0] = ar;
break;
case 307:
resultsObjectArray[1] = ar;
break;
case 306:
resultsObjectArray[2] = ar;
break;
case 297:
resultsObjectArray[3] = ar;
break;
case 295:
resultsObjectArray[4] = ar;
break;
case 298:
resultsObjectArray[5] = ar;
break;
case 304:
resultsObjectArray[6] = ar;
break;
case 305:
resultsObjectArray[7] = ar;
break;
case 302:
resultsObjectArray[8] = ar;
break;
case 308:
resultsObjectArray[9] = ar;
break;
case 300:
resultsObjectArray[10] = ar;
break;
case 296:
resultsObjectArray[11] = ar;
break;
case 303:
resultsObjectArray[12] = ar;
break;
case 299:
resultsObjectArray[13] = ar;
break;
case 225:
resultsObjectArray[14] = ar;
break;
case 237:
resultsObjectArray[15] = ar;
break;
}
// console.log("done")
}
const Model = mongoose.model('users', userSchema);
function sendUser() {
Model.find(async(err, data) => {
if (err) {
console.log(err)
} else {
let sendArray = []
for (var nx = 0; nx < data.length; nx++) {
let dataToSend = sendDM(data[nx])
let userToSend = data[nx].discordID
sendArray.push({
userToSend,
dataToSend
})
}
await Promise.all(sendArray.map(({
userToSend,
dataToSend
}) => (client.users.fetch(userToSend, false).then((user) => {
// console.log(nx, dataToSend, userToSend)
user.send(dataToSend)
}))))
}
})
}