LoginSignup
2

More than 3 years have passed since last update.

位置情報をもらうとスタンプを返すLINE Bot

Last updated at Posted at 2019-04-29

はじめに

ある記事の影響を受けてLINE Botを作ってみました。環境構築やらの手順は今更なので省略します。

やったこと

タイトルの通り位置情報を受け取るとスタンプを返します。特に意味がないです。練習のために作りました。上記記事のコードを以下のようにいじりました。

index.js
'use strict';

const functions = require('firebase-functions');
const express = require('express');
const line = require('@line/bot-sdk');

const config = {
    channelSecret: 'hogehoge',
    channelAccessToken: 'hugahuga'
};

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.message.type === 'location') {
    return client.replyMessage(event.replyToken, {
      type: 'sticker',
      packageId: 11538,
      stickerId: 51626496
    });
  }

  if (event.type !== 'message' || event.message.type !== 'location') {
    return Promise.resolve(null);
  }

}

exports.app = functions.https.onRequest(app);

一応解説

特に解説の必要ないかと思いますが、自分の学習のために書きます。上記のコードでevent.message.typeとあるのがLINEユーザから送られてきたメッセージがtextなのかlocationなのかimageなのかを判断する箇所です(linebotのSDKがJsonを勝手にパースしてくれるので楽ですね)。今回は位置情報を受け取ったときの判断をしたいので、if (event.message.type === 'location'){...}としてブロック内に処理を書きます。
次にclient.replyMessage()でメッセージを返します。このとき第1引数にevent.replyTokenを置き、第2引数に返すメッセージのボディを構築します。今回は以下のように構築しました。

{
   type: 'sticker'
   packageId: 11538,
   stickerId: 51626496
}

type:stickerとすることでスタンプを返します。packageIdstickerIdが返すスタンプを選択できる箇所です。このリストを参考に適当に選びました。packageIDは各ページの左上に、stickerIDは各スタンプの絵の下に示している番号で参照が可能です。

動作の様子

こんな感じになりました。
LINE.jpg
まあ、特に意味はないですね。はい。

おわりに

位置情報を使ったサービスとかを実装できたらいいなと思います。あと、LINE Thingsもせっかく触ったので連携してみたいですね。

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
2