import { ClientConfig , Client , middleware , MiddlewareConfig , WebhookEvent , TextMessage , MessageAPIResponseBase } from '@line/bot-sdk' ; import express , { Application , Request , Response } from 'express' ; const clientConfig = { channelAccessToken : process . env . CHANNEL_ACCESS_TOKEN || '' , channelSecret : process . env . CHANNEL_SECRET , } ; const middlewareConfig = { channelAccessToken : process . env . CHANNEL_ACCESS_TOKEN , channelSecret : process . env . CHANNEL_SECRET || '' , } ; const PORT = process . env . PORT || 3000 ; const client = new Client ( clientConfig ) ; const app = express ( ) ; const textEventHandler = async ( event ) : Promise < MessageAPIResponseBase | undefined > => { if ( event . type !== 'message' || event . message . type !== 'text' ) { return ; } const { replyToken } = event ; const { text } = event . message ; const response = { type : 'text' , text , } ; await client . replyMessage ( replyToken , response ) ; } ; app . get ( '/' , async ( _ , res ) : Promise < Response > => { return res . status ( 200 ) . json ( { status : 'success' , message : 'Connected successfully!' , } ) ; } ) ; app . post ( '/webhook' , middleware ( middlewareConfig ) , async ( req , res ) : Promise < Response > => { const events = req . body . events ; const results = await Promise . all ( events . map ( async ( event ) => { try { await textEventHandler ( event ) ; } catch ( err ) { if ( err instanceof Error ) { console . error ( err ) ; } return res . status ( 500 ) . json ( { status : 'error' , } ) ; } } ) ) ; return res . status ( 200 ) . json ( { status : 'success' , results , } ) ; } ) ; app . listen ( PORT , ( ) => { console . log ( `Application is live and listening on port ${ PORT }` ) ; } ) ;