LoginSignup
1
1

More than 3 years have passed since last update.

目次

  • はじめに
  • サンプルコード
  • サンプル画像と使用例
  • おわりに
  • 参考にしたサイト

はじめに

今回は、LINE BOTでFizzBuzzをやってみた。
なお、当LINE BOTを作成する際に、この記事をベースにした。

サンプルコード

'use strict';

// 使用パッケージ群
const express = require('express'); // Node.jsで利用できるWebアプリケーションフレームワーク
const line = require('@line/bot-sdk'); // ボットサーバへのリクエストが当LineBOTからきたものかどうかを検証してくれる(要は署名検証)
const PORT = process.env.PORT || 3000;  //Node.jsアプリケーションを使用するポートを設定
// LineBOT用定数群
const config = {
    channelSecret: 'YourChannelSecret',
    channelAccessToken: 'YourChannelAccessToken'
};

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 client.replyMessage(event.replyToken, {
            type: 'text',
            text: "数字を入力してください。"
        });
    } else
    {
        if ((event.message.text % 3 === 0) && (event.message.text % 5 === 0))
        {
            // LineBOTに返信されるメッセージを設定
            return client.replyMessage(event.replyToken, {
                type: 'text',
                text: 'FizzBuzz' // LineBOTに返信されるメッセージ
            });
        } else if (event.message.text % 3 === 0)
        {
            return client.replyMessage(event.replyToken, {
                type: 'text',
                text: 'Fizz'
            });
        } else if (event.message.text % 5 === 0)
        {
            return client.replyMessage(event.replyToken, {
                type: 'text',
                text: 'Buzz'
            });
        } else
        {
            return client.replyMessage(event.replyToken, {
                type: 'text',
                text: event.message.text
            });
        }
    }
};

app.listen(PORT);
console.log(`Server running at ${PORT}`);

サンプル画像と使用例

こんな感じになります。
コメント 2020-06-01 131340.png

おわりに

次は、VercelでLINE BOTを動かす 2020年5月版を参考に、Vercelを介してLINE BOTを動かしてみようと思う。

参考にしたサイト

  • 使用したパッケージ群について

Node.jsのフレームワーク「Express」とは【初心者向け】
LINE BOTをHeroku + Node.jsでやるまで

  • webhook について

Webhookって何?を子どもでもわかるように描いてみた

1
1
1

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
1