はじめに
おはようございます。こんにちは。こんばんは。
Watatakuです。
本日の記事はnode.jsとexpressを用いてLinebotを作って見ましょう。という記事になります。
対象者
- 初学者。
- LineBotを作りたい方または作ったことがない方。
書かないこと
- herokuアカウントの作り方。
- herokuへのデプロイ方法。
※herokuのアカウントが無いまたはherokuへのデプロイ方法がわからない方はこちらをご覧ください。
プログラムを書く前に
Line Developersにアクセスしログインしてください。
その後プロバイダーを作る
名前はなんでもいいです。Botの製作者として出るものです。
その後「Create a new channel」をクリック。
クリック後モーダルが立ち上がるので「Messaging API」をクリック。
必要事項を入力し「Create」し、チャネルを作成する。
Channel access tokenの発行
後で使うのですが発行しておきます。
作成したチャネルの「Messaging API」タブの一番下にあるChannel access token欄の黒ボタンを押して発行します。
ちなみにもう一つ必要なキーがあるのですが、それはBasic settingsタブ内に表示されています。
プログラムを書いていく
環境構築
$ mkdir linebot-sample
$ cd linebot-sample
$ touch index.js
$ npm init
必要パッケージのインストール
$ npm install node-dev express @line/bot-sdk --save
プログラムを書く
"use strict";
const express = require("express");
const line = require("@line/bot-sdk");
const PORT = process.env.PORT || 3000;
const getChannelSeacret = "ご自身のchannel seacret key";
const getChannelAccessToken = "ご自身のchannel accsess token key";
const config = {
channelSecret: getChannelSeacret(),
channelAccessToken: getChannelAccessToken(),
};
const app = express();
app.post("/webhook", line.middleware(config), (req, res) => {
console.log(req.body.events);
Promise.all(req.body.events.map(handleEvent)).then((result) =>
res.json(result)
);
});
const client = new line.Client(config);
async function handleEvent(event) {
if (event.type !== "message" || event.message.type !== "text") {
return Promise.resolve(null);
}
/* -------------------------------------------
------- 返信メッセージの処理の記述ゾーン ---------
------------------------------------------- */
let replyText = "";
replyText = event.message.text; // event.message.textに自分のメッセージが入っている。
/* ------------------------------------------
------------------------------------------
------------------------------------------ */
return client.replyMessage(event.replyToken, {
type: "text",
text: replyText,
});
}
app.listen(PORT);
console.log(`Server running at ${PORT}`);
このサンプルコードでは「オウム返し」のLineBotですが、コメントの「返信メッセージの処理の記述ゾーン」
で返答するメッセージの処理を記述してください。
LineBotとプログラムを連携させる
上のセクションで書いたプログラムコードをherokuにデプロイする。
するとhttps://○○○○○○○○○○.herokuapp.com
が作成されます。
なのでMessaging APIのこの欄の「Edit」をクリックし、
https://○○○○○○○○○○.herokuapp.com/webhook
と入れる
完成。
最後に
以上がLineBotの作成手順です。
是非ご参考にしていただければ幸いです。