Skip to content

Commit a964ebd

Browse files
committed
feat: add example echo bot
1 parent 62fe090 commit a964ebd

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

examples/echo-bot-ts/index.ts

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
// Import all dependencies, mostly using destructuring for better view.
2+
import { ClientConfig, Client, middleware, MiddlewareConfig, WebhookEvent, TextMessage, MessageAPIResponseBase } from '@line/bot-sdk';
3+
import express, { Application, Request, Response } from 'express';
4+
5+
// Setup all LINE client and Express configurations.
6+
const clientConfig: ClientConfig = {
7+
channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN || '',
8+
channelSecret: process.env.CHANNEL_SECRET,
9+
};
10+
11+
const middlewareConfig: MiddlewareConfig = {
12+
channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN,
13+
channelSecret: process.env.CHANNEL_SECRET || '',
14+
};
15+
16+
const PORT = process.env.PORT || 3000;
17+
18+
// Create a new LINE SDK client.
19+
const client = new Client(clientConfig);
20+
21+
// Create a new Express application.
22+
const app: Application = express();
23+
24+
// Function handler to receive the text.
25+
const textEventHandler = async (event: WebhookEvent): Promise<MessageAPIResponseBase | undefined> => {
26+
// Process all variables here.
27+
if (event.type !== 'message' || event.message.type !== 'text') {
28+
return;
29+
}
30+
31+
// Process all message related variables here.
32+
const { replyToken } = event;
33+
const { text } = event.message;
34+
35+
// Create a new message.
36+
const response: TextMessage = {
37+
type: 'text',
38+
text,
39+
};
40+
41+
// Reply to the user.
42+
return client.replyMessage(replyToken, response);
43+
};
44+
45+
// Register the LINE middleware.
46+
// As an alternative, you could also pass the middleware in the route handler.
47+
app.use(middleware(middlewareConfig));
48+
49+
// Route handler to receive webhook events.
50+
app.post(
51+
'/webhook',
52+
async (req: Request, res: Response): Promise<Response> => {
53+
const events: WebhookEvent[] = req.body.events;
54+
55+
// Process all of the received events asynchronously.
56+
const results = events.map((event: WebhookEvent) => {
57+
try {
58+
textEventHandler(event);
59+
} catch (err: unknown) {
60+
if (err instanceof Error) {
61+
console.error(err);
62+
}
63+
64+
// Return an error message.
65+
return res.status(500).json({
66+
status: 'error',
67+
});
68+
}
69+
});
70+
71+
// Return a successfull message.
72+
return res.status(200).json({
73+
status: 'success',
74+
results,
75+
});
76+
}
77+
);
78+
79+
// Create a server and listen to it.
80+
app.listen(PORT, () => {
81+
console.log(`Application is live and listening on port ${PORT}`);
82+
});

0 commit comments

Comments
 (0)