Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

とりあえずLINE BOT APIでオウムを作ってみた

More than 3 years have passed since last update.

LINEBOT API公開記念でただ同じ事を返すだけのボットを作ってみた。

アカウントや設定とかは、 https://developers.line.me から適当にやってください。

まず最初にハマるところは、Callback URLです。どうやらポート番号も必要なので、https://example.com:443/callbackなどのように443を指定してください。

LINE_CHANNEL_ID, LINE_CHANNEL_SECRET, LINE_CHANNEL_MIDは適当な物を指定して下記を実行すると「オウム返しBot」の出来上がり。

APIを呼ぶにはWhitelistにIPを登録する必要があるので、Herokuなどで動かす事はできません。

【追記】 LINE BOT をとりあえずタダで Heroku で動かすを見ると、Fixieっていうアドオンを使えばHerokuでも行けるそうです。

CallbackやWhitelistは追加してから反映までちょっと時間が掛かるみたいです。

app.rb
require 'bundler/setup'
require 'sinatra'
require 'json'
require 'httpclient'

post '/linebot/callback' do
  params = JSON.parse(request.body.read)

  params['result'].each do |msg|
    request_content = {
      to: [msg['content']['from']],
      toChannel: 1383378250, # Fixed  value
      eventType: "138311608800106203", # Fixed value
      content: msg['content']
    }

    http_client = HTTPClient.new
    endpoint_uri = 'https://trialbot-api.line.me/v1/events'
    content_json = request_content.to_json
    http_client.post_content(endpoint_uri, content_json,
        'Content-Type' => 'application/json; charset=UTF-8',
        'X-Line-ChannelID' => ENV["LINE_CHANNEL_ID"],
        'X-Line-ChannelSecret' => ENV["LINE_CHANNEL_SECRET"],
        'X-Line-Trusted-User-With-ACL' => ENV["LINE_CHANNEL_MID"]
      )
  end

  "OK"
end
# Gemfile
source "https://rubygems.org"

# gem "rails"
gem 'sinatra'
gem 'httpclient'
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away