-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
85 lines (71 loc) · 2 KB
/
server.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
const Koa = require('koa');
const Router = require('koa-router');
const Nexmo = require('nexmo');
const bodyParser = require('koa-bodyparser');
const PORT = process.env.PORT || 3000;
const jokes = require('./src/jokes');
const app = new Koa();
const router = new Router();
app.use(bodyParser());
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config();
}
const nexmo = new Nexmo({
apiKey: process.env.NEXMO_API_KEY,
apiSecret: process.env.NEXMO_API_SECRET,
applicationId: process.env.NEXMO_APPLICATION_ID,
privateKey: process.env.NEXMO_APPLICATION_PRIVATE_KEY
});
const reply = async (number, text) => {
const lowerText = text.toLowerCase();
const joke = () => {
let rand = Math.floor(Math.random() * jokes.length);
return jokes[rand].line;
};
const selectReplyNumber = number => {
return number.charAt(0) === '1'
? process.env.NEXMO_FROM_NUMBER_US
: process.env.NEXMO_FROM_NUMBER;
};
return new Promise((resolve, reject) => {
if (lowerText === 'awkward' || lowerText === 'more') {
nexmo.channel.send(
{ type: 'sms', number: number },
{ type: 'sms', number: selectReplyNumber(number) },
{
content: {
type: 'text',
text: 'Quick, say this: ' + joke()
}
},
(error, data) => {
if (data) {
resolve({ sent: true, detail: data });
} else {
reject({ sent: false, detail: error });
}
}
);
} else {
reject({ sent: false, detail: 'Keyword unknown' });
}
});
};
router.post('/inbound', async ctx => {
const { msisdn, text } = await ctx.request.body;
reply(msisdn, text)
.then(res => {
console.log(res);
ctx.status = 200;
})
.catch(err => {
console.log(err);
ctx.status = 200;
});
ctx.status = 200;
});
router.post('/status', async ctx => {
ctx.status = 200;
});
app.use(router.routes());
app.listen(PORT, () => console.log(`Server listening on port ${PORT}`));