1 | import express from 'express';
|
2 | import session from 'express-session';
|
3 | import connectMongo from 'connect-mongo';
|
4 | import bodyParser from 'body-parser';
|
5 | import twilio from 'twilio';
|
6 | import superscript from 'superscript';
|
7 |
|
8 | const app = express();
|
9 | const MongoStore = connectMongo(session);
|
10 |
|
11 |
|
12 |
|
13 | const twilioConfig = {
|
14 | account: '[YOUR_TWILIO_SID]',
|
15 | token: '[YOUR_TWILIO_TOKEN]',
|
16 | number: '[YOUR_TWILIO_NUMBER]',
|
17 | };
|
18 |
|
19 | const accountSid = process.env.TWILIO_SID || twilioConfig.account;
|
20 | const authToken = process.env.TWILIO_AUTH || twilioConfig.token;
|
21 | const twilioNum = process.env.NUM || twilioConfig.number;
|
22 |
|
23 | twilio.client = twilio(accountSid, authToken);
|
24 | twilio.handler = twilio;
|
25 | twilio.authToken = authToken;
|
26 | twilio.num = twilioNum;
|
27 |
|
28 |
|
29 | const sendSMS = function sendSMS(recipient, sender, message) {
|
30 | twilio.client.messages.create({
|
31 | to: recipient,
|
32 | from: sender,
|
33 | body: message,
|
34 | }, (err, result) => {
|
35 | if (!err) {
|
36 | console.log('Reply sent! The SID for this message is: ');
|
37 | console.log(result.sid);
|
38 | console.log('Message sent on');
|
39 | console.log(result.dateCreated);
|
40 | } else {
|
41 | console.log('Error sending message');
|
42 | console.log(err);
|
43 | }
|
44 | });
|
45 | };
|
46 |
|
47 | const dataHandle = function dataHandle(data, phoneNumber, twilioNumber, bot) {
|
48 |
|
49 | let message = `${data}`;
|
50 |
|
51 | message = message.replace(/[\x0D\x0A]/g, '');
|
52 |
|
53 | bot.reply(message.trim(), (err, reply) => {
|
54 | sendSMS(phoneNumber, twilioNumber, reply.string);
|
55 | });
|
56 | };
|
57 |
|
58 |
|
59 |
|
60 |
|
61 | const botHandle = function (err, bot) {
|
62 | app.post('/api/messages', (req, res) => {
|
63 | if (twilio.handler.validateExpressRequest(req, twilio.authToken)) {
|
64 | console.log(`Twilio Message Received: ${req.body.Body}`);
|
65 | dataHandle(req.body.Body, req.body.From, twilio.num, bot);
|
66 | } else {
|
67 | res.set('Content-Type', 'text/xml').status(403).send('Error handling text messsage. Check your request params');
|
68 | }
|
69 | });
|
70 | };
|
71 |
|
72 |
|
73 | const options = {
|
74 | factSystem: {
|
75 | clean: true,
|
76 | },
|
77 | importFile: './data.json',
|
78 | };
|
79 |
|
80 | superscript.setup(options, (err, bot) => {
|
81 |
|
82 | app.use(bodyParser.json());
|
83 | app.use(bodyParser.urlencoded({ extended: true }));
|
84 | app.use(session({
|
85 | secret: 'cellar door',
|
86 | resave: true,
|
87 | saveUninitialized: false,
|
88 | store: new MongoStore({ mongooseConnection: bot.db }),
|
89 | }));
|
90 |
|
91 |
|
92 | const port = process.env.PORT || 3000;
|
93 |
|
94 |
|
95 | app.listen(port, () => {
|
96 | console.log(`Listening on port: ${port}`);
|
97 | });
|
98 |
|
99 | botHandle(null, bot);
|
100 | });
|