UNPKG

2.82 kBJavaScriptView Raw
1import express from 'express';
2import session from 'express-session';
3import connectMongo from 'connect-mongo';
4import bodyParser from 'body-parser';
5import twilio from 'twilio';
6import superscript from 'superscript';
7
8const app = express();
9const MongoStore = connectMongo(session);
10
11// Twilio Configuration
12// Number format should be "+19876543210", with "+1" the country code
13const twilioConfig = {
14 account: '[YOUR_TWILIO_SID]',
15 token: '[YOUR_TWILIO_TOKEN]',
16 number: '[YOUR_TWILIO_NUMBER]',
17};
18
19const accountSid = process.env.TWILIO_SID || twilioConfig.account;
20const authToken = process.env.TWILIO_AUTH || twilioConfig.token;
21const twilioNum = process.env.NUM || twilioConfig.number;
22
23twilio.client = twilio(accountSid, authToken);
24twilio.handler = twilio;
25twilio.authToken = authToken;
26twilio.num = twilioNum;
27
28// Send Twilio text message
29const 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
47const dataHandle = function dataHandle(data, phoneNumber, twilioNumber, bot) {
48 // Format message
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// TWILIO
59// In your Twilio account, set up Twilio Messaging "Request URL" as HTTP POST
60// If running locally and using ngrok, should look something like: http://b2053b5e.ngrok.io/api/messages
61const 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// Main entry point
73const options = {
74 factSystem: {
75 clean: true,
76 },
77 importFile: './data.json',
78};
79
80superscript.setup(options, (err, bot) => {
81 // Middleware
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 // PORT
92 const port = process.env.PORT || 3000;
93
94 // START SERVER
95 app.listen(port, () => {
96 console.log(`Listening on port: ${port}`);
97 });
98
99 botHandle(null, bot);
100});