|
| 1 | +// Import all dependencies, mostly using destructuring for better view. |
| 2 | +import { |
| 3 | + ClientConfig, |
| 4 | + MessageAPIResponseBase, |
| 5 | + messagingApi, |
| 6 | + middleware, |
| 7 | + MiddlewareConfig, |
| 8 | + webhook, |
| 9 | + HTTPFetchError, |
| 10 | +} from '@line/bot-sdk'; |
| 11 | +import express, {Application, Request, Response} from 'express'; |
| 12 | + |
| 13 | +// Setup all LINE client and Express configurations. |
| 14 | +const clientConfig: ClientConfig = { |
| 15 | + channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN || '', |
| 16 | +}; |
| 17 | + |
| 18 | +const middlewareConfig: MiddlewareConfig = { |
| 19 | + channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN, |
| 20 | + channelSecret: process.env.CHANNEL_SECRET || '', |
| 21 | +}; |
| 22 | + |
| 23 | +const PORT = process.env.PORT || 3000; |
| 24 | + |
| 25 | +// Create a new LINE SDK client. |
| 26 | +const client = new messagingApi.MessagingApiClient(clientConfig); |
| 27 | + |
| 28 | +// Create a new Express application. |
| 29 | +const app: Application = express(); |
| 30 | + |
| 31 | +const isTextEvent = (event: any): event is webhook.MessageEvent & { message: webhook.TextMessageContent } => { |
| 32 | + return event.type === 'message' && event.message && event.message.type === 'text'; |
| 33 | +}; |
| 34 | + |
| 35 | +// Function handler to receive the text. |
| 36 | +const textEventHandler = async (event: webhook.Event): Promise<MessageAPIResponseBase | undefined> => { |
| 37 | + // Process all variables here. |
| 38 | + if (!isTextEvent(event)) { |
| 39 | + return; |
| 40 | + } |
| 41 | + |
| 42 | + // Process all message related variables here. |
| 43 | + // Create a new message. |
| 44 | + // Reply to the user. |
| 45 | + await client.replyMessage({ |
| 46 | + replyToken: event.replyToken as string, |
| 47 | + messages: [{ |
| 48 | + type: 'text', |
| 49 | + text: event.message.text, |
| 50 | + }], |
| 51 | + }); |
| 52 | +}; |
| 53 | + |
| 54 | +// Register the LINE middleware. |
| 55 | +// As an alternative, you could also pass the middleware in the route handler, which is what is used here. |
| 56 | +// app.use(middleware(middlewareConfig)); |
| 57 | + |
| 58 | +// Route handler to receive webhook events. |
| 59 | +// This route is used to receive connection tests. |
| 60 | +app.get( |
| 61 | + '/', |
| 62 | + async (_: Request, res: Response): Promise<Response> => { |
| 63 | + return res.status(200).json({ |
| 64 | + status: 'success', |
| 65 | + message: 'Connected successfully!', |
| 66 | + }); |
| 67 | + } |
| 68 | +); |
| 69 | + |
| 70 | +// This route is used for the Webhook. |
| 71 | +app.post( |
| 72 | + '/callback', |
| 73 | + middleware(middlewareConfig), |
| 74 | + async (req: Request, res: Response): Promise<Response> => { |
| 75 | + const callbackRequest: webhook.CallbackRequest = req.body; |
| 76 | + const events: webhook.Event[] = callbackRequest.events!; |
| 77 | + |
| 78 | + // Process all the received events asynchronously. |
| 79 | + const results = await Promise.all( |
| 80 | + events.map(async (event: webhook.Event) => { |
| 81 | + try { |
| 82 | + await textEventHandler(event); |
| 83 | + } catch (err: unknown) { |
| 84 | + if (err instanceof HTTPFetchError) { |
| 85 | + console.error(err.status); |
| 86 | + console.error(err.headers.get('x-line-request-id')); |
| 87 | + console.error(err.body); |
| 88 | + } else if (err instanceof Error) { |
| 89 | + console.error(err); |
| 90 | + } |
| 91 | + |
| 92 | + // Return an error message. |
| 93 | + return res.status(500).json({ |
| 94 | + status: 'error', |
| 95 | + }); |
| 96 | + } |
| 97 | + }) |
| 98 | + ); |
| 99 | + |
| 100 | + // Return a successful message. |
| 101 | + return res.status(200).json({ |
| 102 | + status: 'success', |
| 103 | + results, |
| 104 | + }); |
| 105 | + } |
| 106 | +); |
| 107 | + |
| 108 | +// Create a server and listen to it. |
| 109 | +app.listen(PORT, () => { |
| 110 | + console.log(`Application is live and listening on port ${PORT}`); |
| 111 | +}); |
0 commit comments