line-bot-sdk-nodejs を typescript で使う
npm install --save express
npm install --save typescript
npm install --save @line/bot-sdk
npm install --save @types/express
npm install --save @types/node
npm install --save-dev ts-node
npm install --save-dev ts-node-dev
npx tsc --init
mkdir src
touch src/index.ts
npx ts-node src/index.ts
とかでセットアップして
npx ts-node-dev --respawn src/index.ts
で起動。
コードはこんな感じ(typescript 慣れてないから怪しい)。
import line = require('@line/bot-sdk');
import express = require('express');
const config: line.Config = {
channelAccessToken: process.env.LINE_CHANNEL_ACCESS_TOKEN!,
channelSecret: process.env.LINE_CHANNEL_SECRET!,
};
// create LINE SDK client
const client = new line.Client(<line.ClientConfig>config);
// create Express app
// about Express itself: https://expressjs.com/
const app = express();
// register a webhook handler with middleware
// about the middleware, please refer to doc
app.post('/callback', line.middleware(<line.MiddlewareConfig>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
function handleEvent(event: line.WebhookEvent) {
if (event.type !== 'message' || event.message.type !== 'text') {
// ignore non-text-message event
return Promise.resolve(null);
}
console.log(`Received message: ${event.message.text}`);
// create a echoing text message
const echo: line.TextMessage = { type: 'text', text: event.message.text };
// use reply API
return client.replyMessage(event.replyToken, echo);
}
// listen on port
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`listening on ${port}`);
});
Published: 2019-05-07(Tue) 17:35