forked from xaviablaza/xavai
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
67 lines (55 loc) · 1.62 KB
/
app.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
import * as line from '@line/bot-sdk'
import express from 'express'
// create LINE SDK config from env variables
const config = {
channelSecret: process.env.LINE_CHANNEL_SECRET,
};
// create LINE SDK client
const client = new line.messagingApi.MessagingApiClient({
channelAccessToken: process.env.LINE_CHANNEL_ACCESS_TOKEN
});
const app = express();
app.get('/', (_req, res) => {
res.send('hello friend.');
});
app.get('/up', (_req, res) => {
res.status(200).end();
});
// register a webhook handler with middleware
// about the middleware, please refer to doc
app.post('/line/webhook', line.middleware(config), (req, res) => {
Promise
.all(req.body.events.map(handleEvent))
.then((result) => res.json(result))
.catch((err) => {
console.error(err);
res.status(500).end();
});
});
// event handler
async function handleEvent(event) {
if (event.type !== 'message' || event.message.type !== 'text') {
// ignore non-text-message event
return Promise.resolve(null);
}
// Get bot info to check its display name
const botInfo = await client.getBotInfo();
const botName = `@${botInfo.displayName}`;
// Only reply if message mentions the bot by display name
if (!event.message.text.includes(botName)) {
return Promise.resolve(null);
}
// create an echoing text message
const echo = { type: 'text', text: event.message.text };
console.log(echo);
// use reply API
return client.replyMessage({
replyToken: event.replyToken,
messages: [echo],
});
}
// listen on port
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`listening on ${port}`);
});