12
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

LINE BOT チュートリアル

Last updated at Posted at 2017-05-16

準備

LINE@アカウント作成

BOT昨日を有効化

「LINE@MANAGER」 => 「アカウント設定」 => 「Bot設定」 => 「APIを利用する」 => 「Webhook送信を利用する」

必要なkeyを取得

Line developersにアクセスして、以下を控えておく。(かタブで開いておく)

  • Channel ID
  • Channel Secret
  • Channel Access Token
  • 後々 Webhook URL の設定が必要

実装

rails new

$ rails new line-bot -d postgresql
$ cd line-bot/
$ rake db:create

line-bot-sdk-rubyをインストール

Gemfileに追記してbundle install

gem 'line-bot-api', github: 'stivan622/line-bot-sdk-ruby'
gem 'dotenv-rails'

コントローラー作成

$ rails g controller linebot

ルーティングを追加

routes.rb

post '/callback' => 'linebot#callback'

linebot_controllerを編集

Usageを参考にアクションを作成

class LinebotController < ApplicationController
  require 'line/bot'
  protect_from_forgery :except => [:callback]

  def callback
    body = request.body.read

    signature = request.env['HTTP_X_LINE_SIGNATURE']
    unless client.validate_signature(body, signature)
      error 400 do 'Bad Request' end
    end

    events = client.parse_events_from(body)
    events.each { |event|
      case event
      when Line::Bot::Event::Message
        case event.type
        when Line::Bot::Event::MessageType::Text
          message = {
            type: 'text',
            text: event.message['text']
          }
          response = client.reply_message(event['replyToken'], message)
          p response
        end
      end
    }
    head :ok
  end

  private
  def client
    @client ||= Line::Bot::Client.new { |config|
      config.channel_secret = ENV["LINE_CHANNEL_SECRET"]
      config.channel_token = ENV["LINE_CHANNEL_TOKEN"]
    }
  end
end

Heroku

$ heroku create
$ git init
$ git add -A
$ git commit -m "first commit"
$ git push heroku master
$ heroku addons:create fixie:tricycle

Proxy URLOutbound IPsを控える

環境変数の設定

heroku config:add FIXIE_URL='Proxy URL'
heroku config:add LINE_CHANNEL_SECRET='LineのChannel Secret'
heroku config:add LINE_CHANNEL_TOKEN='LineのChannel Access Token'

Line developersの設定

Whitelistの設定

タブからServer IP Whitelist => Outbound Ipsを設定

Webhook URL を設定

https://{ご自身のherokuアプリ名}.herokuapp.com/callback

終わり

12
16
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
12
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?