1
0

More than 3 years have passed since last update.

node.js + express + herokuを使って LineBotを作ろう。

Last updated at Posted at 2021-08-10

はじめに

おはようございます。こんにちは。こんばんは。
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欄の黒ボタンを押して発行します。
LINE_Developers.png

ちなみにもう一つ必要なキーがあるのですが、それはBasic settingsタブ内に表示されています。

プログラムを書いていく

環境構築

$ mkdir linebot-sample
$ cd linebot-sample
$ touch index.js
$ npm init

必要パッケージのインストール

$ npm install node-dev express @line/bot-sdk --save

プログラムを書く

実際のコード。

index.js
"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と入れる
LINE_Developers-2.png

完成。

最後に

以上がLineBotの作成手順です。
是非ご参考にしていただければ幸いです。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0