LoginSignup
26
24

More than 5 years have passed since last update.

【LINE bot】最寄駅検索bot

Last updated at Posted at 2018-03-23
1 / 17

はじめに

  • Line bot勉強会の資料です。
  • テンプレートってボタン操作を行う
  • 外部APIと連携して、幅を広げる

LINE bot勉強会の流れ

流れ step1 step2 step3
機能 おみくじbot カウントbot 最寄駅検索bot
学ぶこと LINE botの作り方 DB・リッチニュー ボタンアクション・URIスキーマ・外部API

その他TIPS


今回学ぶこと

  • URIスキームを使う
  • APIを使う

ボタンの実装


ボタンについて

  • ボタンはいくつかのアクションを起こすことができます。アクションの動作は次の一覧の通りです。
action type 動作
ポストバック postback dataを返す
メッセージ message ユーザーからメッセージを返す
URI uri 指定したURIへ飛ばす
日時選択 datetimepicker postbackに日付のデータを加える

ドキュメントのボタンテンプレートをコピーします。

app.rb
def template
  {
    "type": "template",
    ...
  }
end

templateメソッドを呼びだす。

  • 駅と打つとtemplateが返ってくるようにします。
app.rb
55 elsif event.message['text'] =~ /駅/
56   client.reply_message(event['replyToken'], template)

実行結果

  • ボタンがついたテンプレートが返ってくる


位置情報を送る


 uriスキーム

  • uriアクションの中にはuriスキームという、カメラを立ち上げたり、マップを立ち上げたりする機能があります。
  • 今回はその中からGPSを送信する。line://nv/locationを利用します。

templateを編集する

  • templateの中を必要最低限の要素だけにします。
app.rb
def template
  {
    "type": "template",
    "altText": "位置検索中",
    "template": {
        "type": "buttons",
        "title": "最寄駅探索探索",
        "text": "現在の位置を送信しますか?",
        "actions": [
            {
              "type": "uri",
              "label": "位置を送る",
              "uri": "line://nv/location"
            }
        ]
    }
  }
end

eventを取得する

GPSのデータを送れるようになったので、次に受け取る処理を書きます。

app.rb
62 when Line::Bot::Event::MessageType::Location
63   p event["message"]["latitude"]
64   p event["message"]["longitude"]
# 65 APIを呼び出す関数です
65   p stations(event["message"]["longitude"], event["message"]["latitude"])
66 end

APIへのリクエストを投げる

app.rb
def stations(longitude, latitude)
  uri = URI("http://express.heartrails.com/api/json")
  uri.query = URI.encode_www_form({
  method: "getStations",
    x: longitude,
    y: latitude
  })
  res = Net::HTTP.get_response(uri)
  JSON.parse(res.body)["response"]["station"]
end

APIの結果をメッセージで表示する

  • APIから返された値を駅名と路線の配列に変更し、改行文字で連結しメッセージとしてbotに返します。
app.rb
66 stations = stations(event["message"]["longitude"], event["message"]["latitude"])
67 message = stations.map{|station|
68   "#{station["name"]}駅 >> #{station["line"]}"
69 }.join("\n")
70 client.reply_message(event['replyToken'],{ type: 'text', text: message })

結果

  • 最寄駅の情報を検索するbot完成


まとめ

  • テンプレートを使ったアクションは便利
  • uriスキームを使うとマップや写真を送りやすくなる。
  • 外部APIを用いると幅が広がる。
26
24
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
26
24