We developed LINE Bot to learn Web API. This time we will create an echoBot that returns a simple sent text as it is. Develop with Rails and even deploy to Heroku.
・ Ruby 2.6.5 ・ Rails 6.0.3.2 ・ PostgreSQL ・ Heroku
・ Create a channel with LINE Developers -Create a program for the bot itself (Ruby / Rails) -Deploy to Heroku
First, register as a LINE developer. Then create a provider and channel to get the API key you need. https://developers.line.biz/ja/docs/messaging-api/getting-started/
Create a channel for Bot by referring to the formula (above). If you itemize the work easily,
-Log in to the LINE Developers console -Create a developer account by entering your name and email address ・ Create provider and channel, specify Messaging API at this time ・ Issue an access token ・ Turn off response messages and turn on Webhock
A Channel secret and a Channel access token are required for bot development, so make a note here!
The DB uses PostgreSQL because it will be deployed on Heroku.
$rails new app name-d postgresql
$cd app name
$ git init
Use a gem called line-bot-api.
Gemfile
gem 'line-bot-api'
$ bundule install
config/routes.rb
Rails.application.routes.draw do
post '/callback' => 'linebot#callback'
end
$ rails g controller linebot
The description to the controller was (copied) with reference to RUBY of the official line SDK. https://github.com/line/line-bot-sdk-ruby/blob/master/examples/echobot/app.rb
python
class LinebotController < ApplicationController
require 'line/bot' # gem 'line-bot-api'
def client
@client ||= Line::Bot::Client.new { |config|
config.channel_secret = ENV["LINE_CHANNEL_SECRET"]
config.channel_token = ENV["LINE_CHANNEL_TOKEN"]
}
end
post '/callback' do
body = request.body.read
signature = request.env['HTTP_X_LINE_SIGNATURE']
unless client.validate_signature(body, signature)
halt 400, {'Content-Type' => 'text/plain'}, 'Bad Request'
end
events = client.parse_events_from(body)
events.each do |event|
case event
when Line::Bot::Event::Message
case event.type
when Line::Bot::Event::MessageType::Text
message = {
type: 'text',
text: event.message['text']
}
client.reply_message(event['replyToken'], message)
end
end
end
"OK"
end
end
First, log in to Heroku, create an app on Heroku, and deploy it.
$ heroku config:set LINE_CHANNEL_SECRET=Paste the Channel Secret you noted earlier here
$ heroku config:set LINE_CHANNEL_TOKEN=Paste the access token you noted earlier here
Set the URL with / callback at the end of the deployed address in the webhook.
This completes the echo-bot. Sending the text will return the same text.
Currently, after changing the code, it will not be reflected unless it is deployed, so Next time, I will use ngrok to run it in a local environment. https://qiita.com/shizu9d/items/42b2cb209b2e23a9af6d
I referred to the following article. https://qiita.com/noriya1217/items/00d6461e9f54900377a3
Recommended Posts