index.ts
2.81 KB
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
// Import all dependencies, mostly using destructuring for better view.
import { ClientConfig, Client, middleware, MiddlewareConfig, WebhookEvent, TextMessage, MessageAPIResponseBase } from '@line/bot-sdk';
import express, { Application, Request, Response } from 'express';
// Setup all LINE client and Express configurations.
const clientConfig: ClientConfig = {
channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN || '',
channelSecret: process.env.CHANNEL_SECRET,
};
const middlewareConfig: MiddlewareConfig = {
channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN,
channelSecret: process.env.CHANNEL_SECRET || '',
};
const PORT = process.env.PORT || 3000;
// Create a new LINE SDK client.
const client = new Client(clientConfig);
// Create a new Express application.
const app: Application = express();
// Function handler to receive the text.
const textEventHandler = async (event: WebhookEvent): Promise<MessageAPIResponseBase | undefined> => {
// Process all variables here.
if (event.type !== 'message' || event.message.type !== 'text') {
return;
}
// Process all message related variables here.
const { replyToken } = event;
const { text } = event.message;
// Create a new message.
const response: TextMessage = {
type: 'text',
text,
};
// Reply to the user.
await client.replyMessage(replyToken, response);
};
// Register the LINE middleware.
// As an alternative, you could also pass the middleware in the route handler, which is what is used here.
// app.use(middleware(middlewareConfig));
// Route handler to receive webhook events.
// This route is used to receive connection tests.
app.get(
'/',
async (_: Request, res: Response): Promise<Response> => {
return res.status(200).json({
status: 'success',
message: 'Connected successfully!',
});
}
);
// This route is used for the Webhook.
app.post(
'/webhook',
middleware(middlewareConfig),
async (req: Request, res: Response): Promise<Response> => {
const events: WebhookEvent[] = req.body.events;
// Process all of the received events asynchronously.
const results = await Promise.all(
events.map(async (event: WebhookEvent) => {
try {
await textEventHandler(event);
} catch (err: unknown) {
if (err instanceof Error) {
console.error(err);
}
// Return an error message.
return res.status(500).json({
status: 'error',
});
}
})
);
// Return a successfull message.
return res.status(200).json({
status: 'success',
results,
});
}
);
// Create a server and listen to it.
app.listen(PORT, () => {
console.log(`Application is live and listening on port ${PORT}`);
});