LoginSignup
6
5

More than 5 years have passed since last update.

今更ながらLINE BOTのEchoサーバをRails4で簡易的に書いてみる

Last updated at Posted at 2016-04-13

今までのは前段でした、的な投稿

http://qiita.com/kskomori/items/ba84ae0bb6a3b5bf6305
http://qiita.com/kskomori/items/07b93b46e5b12ee22685

参考にしたページ

環境

Rails:4.2.0
Ruby:2.1.3p242(with rbenv)
Gem:faraday

Railsコード(コントローラのみで完結させてます)

require 'faraday'

class Linebots::BotController < ApplicationController

  protect_from_forgery except: :callback


  def callback
    if request.method != 'POST'
      render text: 'NG', status: 500
    end

    post_text(params[:result][0][:content][:from], params[:result][0][:content][:text])

    render text: ''
  end


private

  def post_text(to, text)
    content = {
      contentType: 1,
      toType: 1,
      text: text
    }

    post_event(to, content)
  end

  def post_event(to, content)
    msg = {
      to: [ to ],
      toChannel: '1383378250',        # 固定値
      eventType: 138311608800106203,  # 固定値
      content: content
    }

    conn = Faraday::Connection.new(url: 'https://trialbot-api.line.me') do |builder|
      builder.request :url_encoded
      builder.response :logger
      builder.adapter Faraday.default_adapter
    end

    res = conn.post '/v1/events' do |req|
      req.headers['Content-type'] = 'application/json; charset=UTF-8'
      req.headers['X-Line-ChannelID'] = 'xxxxxxxxxxxxx'
      req.headers['X-Line-ChannelSecret'] =  'yyyyyyyyyyyyyyyyyyy'
      req.headers['X-Line-Trusted-User-With-ACL'] =  'zzzzzzzzzzzzzzzzzzzzzzzzzzzz'

      req.body = msg.to_json
    end
  end

end

注意

  • テキストのみ対応です
  • エラー処理入れてません
6
5
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
6
5