forked from pradeepgangwar/On-D-Go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
456 lines (408 loc) · 24.2 KB
/
index.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
'use strict'
const express = require('express')
const bodyParser = require('body-parser')
const request = require('request')
const app = express()
var pg = require("pg");
var path = require("path");
app.set('port', (process.env.PORT || 5000))
// Process application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
extended: false
}))
// Process application/json
app.use(bodyParser.json())
//DB
var conString = process.env.DATABASE_URL;
var client = new pg.Client(conString);
client.connect();
client.query("CREATE TABLE IF NOT EXISTS PNR(UserID varchar(100), firstname varchar(100), pnr varchar(100))");
const token = process.env.FB_PAGE_ACCESS_TOKEN
// Index route
app.get('/', function(req, res) {
res.send('Hello world, I am a chat bot')
})
app.get('/privacy-policy', function(req, res) {
res.sendFile(path.join(__dirname + '/privacy-policy.html'))
})
// for Facebook verification
app.get('/webhook/', function(req, res) {
if (req.query['hub.verify_token'] === process.env.VERIFY_TOKEN) {
res.send(req.query['hub.challenge'])
}
res.send('Error, wrong token')
})
app.post('/webhook/', function(req, res) {
let messaging_events = req.body.entry[0].messaging
for (let i = 0; i < messaging_events.length; i++) {
let event = req.body.entry[0].messaging[i]
let sender = event.sender.id
request({
url: "https://graph.facebook.com/v2.6/" + sender,
qs: {
access_token: token,
fields: "first_name"
},
method: "GET",
}, function(error, response, body) {
if (error) {
console.log("error getting username")
} else {
var bodyObj = JSON.parse(body)
let name = bodyObj.first_name
if (event.message && event.message.text) {
let text = event.message.text
console.log("Sender ID: " + sender + " " + name);
var line = text.toLowerCase();
if (line.match(/hi/g) || line.match(/hello/g) || line.match(/hey/g) || line.match(/get/g)) {
sendTextMessage(sender, "Hey " + name + "!");
// setTimeout(function() {
// sendTextMessage(sender, "I can help you keep track of your daily routine and make sure they're done in time!");
// }, 200);
setTimeout(function() {
sendTextMessage(sender, "Enter SERVICES to see all the serivces we provide! :)");
}, 300);
} else if (line.split(" ")[0].match(/services/g)) {
sendTextMessage(sender, "1. For live status of train say: status <train_no> <date-in DD-MM-YYYY>");
setTimeout(function() {
sendTextMessage(sender, "2. To get list of trains departuring at a window of given hours from given station (max 4 hrs): arriving <station_code> <hours_window>");
}, 200);
setTimeout(function() {
sendTextMessage(sender, "3. Check pnr status say : pnr <10-digit-pnr>");
}, 300);
// setTimeout(function() {
// sendTextMessage(sender, "4. Find trains between two stations say: trains from <source station code> to <destination station code> on <dd-mm-yyyy>");
// }, 400);
setTimeout(function() {
sendTextMessage(sender, "OR");
}, 500);
setTimeout(function() {
sendTextMessage(sender, "4. Simply Save your PNR for no further hassle : save pnr <10-digit-pnr>");
}, 600);
} else if (line.split(" ")[0].match(/status/g)) {
request({
url: "https://api.railwayapi.com/v2/live/train/" + line.split(" ")[1] + "/date/" + line.split(" ")[2] + "/apikey/a32b7zrczw/",
qs: {
fields: "position"
},
method: "GET",
}, function(error, response, body) {
if (error) {
console.log(error)
} else {
var bodyObj = JSON.parse(body)
let name = bodyObj.position
if (name == null) {
sendTextMessage(sender, "Sorry there is some error. Try again with valid train no.");
} else {
sendTextMessage(sender, name);
}
}
})
} else if (line.match(/arriv/g)) {
request({
url: "https://api.railwayapi.com/v2/arrivals/station/" + line.split(" ")[1] + "/hours/" + line.split(" ")[2] + "/apikey/a32b7zrczw/",
method: "GET",
}, function(error, response, body) {
if (error) {
console.log(error)
} else {
var bodyObj = JSON.parse(body)
var times;
if (bodyObj.total == 0) {
sendTextMessage(sender, "No trains to show")
} else {
if (bodyObj.trains.length > 3) {
times = 3;
} else {
times = bodyObj.trains.length;
}
for (var i = 0; i < times; i++) {
if (bodyObj.trains[i].actarr === "Source") {
if (bodyObj.trains[i].delayarr === "RIGHT TIME") {
sendTextMessage(sender, bodyObj.trains[i].name + " at " + bodyObj.trains[i].schdep + " No Delay")
} else {
sendTextMessage(sender, bodyObj.trains[i].name + " at " + bodyObj.trains[i].schdep + " delayed by: " + bodyObj.trains[i].delayarr)
}
} else {
if (bodyObj.trains[i].delayarr === "RIGHT TIME") {
sendTextMessage(sender, bodyObj.trains[i].name + " at " + bodyObj.trains[i].actarr + " No Delay")
} else {
sendTextMessage(sender, bodyObj.trains[i].name + " at " + bodyObj.trains[i].actarr + " was delayed by: " + bodyObj.trains[i].delayarr)
}
}
}
console.log(bodyObj.trains[i].name)
}
}
})
} else if (line.split(" ")[0].match(/pnr/g)) {
request({
url: "https://api.railwayapi.com/v2/pnr-status/pnr/" + line.split(" ")[1] + "/apikey/a32b7zrczw/",
method: "GET",
}, function(error, response, body) {
if (error) {
console.log(error)
} else {
var bodyObj = JSON.parse(body)
var times;
if (bodyObj.response_code == 404) {
sendTextMessage(sender, "This is not a valid pnr")
} else {
//setTimeout(function() {
sendTextMessage(sender, "Train: " + bodyObj.train.name + " - " + bodyObj.train.number)
//},100);
//setTimeout(function() {
sendTextMessage(sender, "DOJ: " + bodyObj.doj)
//},200);
//setTimeout(function() {
if (bodyObj.chart_prepared == true)
sendTextMessage(sender, "CHART PREPARED")
else
sendTextMessage(sender, "CHART NOT PREPARED")
//},300);
var j = 0;
for (var i = 0; i < bodyObj.total_passengers; i++) {
j++;
//setTimeout(function() {
if (bodyObj.passengers[i].current_status)
sendTextMessage(sender, "Passenger " + j + ": " + bodyObj.passengers[i].current_status)
//},200);
}
}
}
})
} else if (line.split(" ")[0].match(/save/g) && line.split(" ")[1].match(/pnr/g)) {
var pnrNumber = line.split(" ")[2];
if (name != null) {
client.query("SELECT * FROM pnr WHERE firstname='" + name + "'", function(err, result) {
if (result.rows.length > 0) {
sendTextMessage(sender, "You already have a pnr saved")
} else {
var query = client.query("INSERT INTO pnr(UserID, firstname, pnr) values($1, $2, $3)", [sender, name, pnrNumber]);
sendTextMessage(sender, "PNR SAVED :)");
sendTextMessage(sender, "To see all your ticket info : my ticket status");
sendTextMessage(sender, "To Check the status of your train : my train status");
sendTextMessage(sender, "While you are in train check time to your next station : my next station")
}
})
}
} else if (line.split(" ")[0].match(/my/g) && line.split(" ")[1].match(/ticket/g) && line.split(" ")[2].match(/status/g)) {
client.query("SELECT pnr FROM PNR WHERE firstname='" + name + "'", function(err, result) {
if (result.rows.length > 0) {
console.log(result);
sendTextMessage(sender, "Your pnr is : " + result.rows[0].pnr)
request({
url: "https://api.railwayapi.com/v2/pnr-status/pnr/" + result.rows[0].pnr + "/apikey/a32b7zrczw/",
method: "GET",
}, function(error, response, body) {
if (error) {
console.log(error)
} else {
var bodyObj = JSON.parse(body)
var times;
if (bodyObj.response_code == 404) {
sendTextMessage(sender, "This is not a valid pnr")
} else {
sendTextMessage(sender, "Train: " + bodyObj.train.name + " - " + bodyObj.train.number)
sendTextMessage(sender, "DOJ: " + bodyObj.doj)
//},200);
//setTimeout(function() {
if (bodyObj.chart_prepared == true)
sendTextMessage(sender, "CHART PREPARED")
else
sendTextMessage(sender, "CHART NOT PREPARED")
//},300);
var j = 0;
for (var i = 0; i < bodyObj.total_passengers; i++) {
j++;
//setTimeout(function() {
if (bodyObj.passengers[i].current_status)
sendTextMessage(sender, "Passenger " + j + ": " + bodyObj.passengers[i].current_status)
//},200);
}
}
}
})
} else {
sendTextMessage(sender, "You haven't saved any pnr, save one by entering as follows - save pnr <pnr-number>")
}
})
} else if (line.split(" ")[0].match(/update/g) && line.split(" ")[1].match(/pnr/g)) {
var pnrNumber = line.split(" ")[2];
client.query("SELECT * FROM pnr WHERE firstname='" + name + "'", function(err, result) {
if (result.rows.length > 0) {
client.query("UPDATE PNR SET pnr='" + pnrNumber + "' WHERE firstname='" + name + "'", function(err, result) {
if (err) {
console.log(err)
} else {
sendTextMessage(sender, "Update your pnr with " + pnrNumber);
}
})
} else {
sendTextMessage(sender, "You don't any existing entry for pnr. Add your first pnr by: save pnr <pnr_number>. And we will remember your pnr.")
}
})
} else if (line.split(" ")[0].match(/my/g) && line.split(" ")[1].match(/train/g) && line.split(" ")[2].match(/status/g)) {
client.query("SELECT pnr FROM PNR WHERE firstname='" + name + "'", function(err, result) {
if (result.rows.length > 0) {
console.log(result);
sendTextMessage(sender, "Your pnr is : " + result.rows[0].pnr)
request({
url: "https://api.railwayapi.com/v2/pnr-status/pnr/" + result.rows[0].pnr + "/apikey/a32b7zrczw/",
method: "GET",
}, function(error, response, body) {
if (error) {
console.log(error)
} else {
var bodyObj = JSON.parse(body)
var times;
if (bodyObj.response_code == 404) {
sendTextMessage(sender, "This is not a valid pnr")
} else {
var TrainNumber = bodyObj.train.number;
var doj = bodyObj.doj;
var StationCode = bodyObj.reservation_upto.code;
request({
url: "https://api.railwayapi.com/v2/live/train/" + TrainNumber + "/date/" + doj + "/apikey/a32b7zrczw/",
method: "GET",
}, function(error, response, body) {
if (error) {
console.log(error)
} else {
var bodyObj = JSON.parse(body)
let name = bodyObj.position
var ArrivalTime;
for (var i = 0; i < bodyObj.route.length; i++) {
if (bodyObj.route[i].station.code == StationCode) {
ArrivalTime = bodyObj.route[i].actarr;
}
}
if (name == null) {
sendTextMessage(sender, "Make sure you're train is in the next 24-48 hrs for accurate times :)");
} else {
sendTextMessage(sender, name);
sendTextMessage(sender, "Arriving at " + ArrivalTime);
}
}
})
}
}
})
} else {
sendTextMessage(sender, "You haven't saved any pnr, save one by entering as follows - save pnr <pnr-number>")
}
})
} else if (line.split(" ")[0].match(/my/g) && line.split(" ")[1].match(/next/g) && line.split(" ")[2].match(/station/g)) {
client.query("SELECT pnr FROM PNR WHERE firstname='" + name + "'", function(err, result) {
if (result.rows.length > 0) {
console.log(result);
sendTextMessage(sender, "Your pnr is : " + result.rows[0].pnr)
request({
url: "https://api.railwayapi.com/v2/pnr-status/pnr/" + result.rows[0].pnr + "/apikey/a32b7zrczw/",
method: "GET",
}, function(error, response, body) {
if (error) {
console.log(error)
} else {
var bodyObj = JSON.parse(body)
var times;
if (bodyObj.response_code == 404) {
sendTextMessage(sender, "This is not a valid pnr")
} else {
var TrainNumber = bodyObj.train.number;
var doj = bodyObj.doj;
var StationCode = bodyObj.reservation_upto.code;
request({
url: "https://api.railwayapi.com/v2/live/train/" + TrainNumber + "/date/" + doj + "/apikey/a32b7zrczw/",
method: "GET",
}, function(error, response, body) {
if (error) {
console.log(error)
} else {
var bodyObj = JSON.parse(body)
let name = bodyObj.position
var ArrivalTime, nextStation;
for (var i = 0; i < bodyObj.route.length; i++) {
if (bodyObj.route[i].has_arrived == false) {
ArrivalTime = bodyObj.route[i].actarr;
nextStation = bodyObj.route[i].station.code;
}
}
if (name == null) {
sendTextMessage(sender, "You need to be in the train while you check for the next station :P");
} else {
//sendTextMessage(sender, name);
sendTextMessage(sender, "Arriving next Station " + nextStation + " at " + ArrivalTime);
}
}
})
}
}
})
} else {
sendTextMessage(sender, "You haven't saved any pnr, save one by entering as follows - save pnr <pnr-number>")
}
})
}
// else if(line.match(/from/g) && line.match(/to/g) && line.match(/on/g))
// {
// request({
// url: "https://api.railwayapi.com/v2/between/source/"+line.split(" ")[2]+"/dest/"+line.split(" ")[4]+"/date/"+line.split(" ")[6]+"/apikey/a32b7zrczw/",
// method: "GET",
// }, function (error, response, body) {
// if (error) {
// console.log(error)
// }
// else {
// var bodyObj = JSON.parse(body)
// var times;
// if(bodyObj.response_code == 404) {
// sendTextMessage(sender, "This is not a valid pnr")
// }
// else {
// for(var i=0;i<bodyObj.trains.length;i++)
// {
// sendTextMessage(sender, "Train: "+bodyObj.trains[i].name+"/"+bodyObj.trains[i].number+" Arrival-time: "+bodyObj.trains[i].dest_arrival_time+" Departure-time: "+bodyObj.trains[i].src_departure_time)
// }
// }
// }
// })
// }
else {
sendTextMessage(sender, "I don't seem to understand your query ... :/ Please Try Again");
}
}
}
})
}
res.sendStatus(200)
})
function sendTextMessage(sender, text) {
let messageData = {
text: text
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {
access_token: token
},
method: 'POST',
json: {
recipient: {
id: sender
},
message: messageData,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending messages: ', error)
} else if (response.body.error) {
console.log('Error: ', response.body.error)
}
})
}
// Spin up the server
app.listen(app.get('port'), function() {
console.log('running on port', app.get('port'))
})