Hi, all! I am Eishia Konno, a developer from GMO-Research System Department.
Today, we will build together a LINE chatbot. I think chatbot’s importance is emerging more than ever, especially nowadays that almost everything is being switched online. Times have come where offline response or even marketing is crucial for every business to thrive in these trying times. Having this in mind, I started a passion project recently with the use of LINE API, Ruby and Heroku. I chose these tools to learn new technologies and to brush up on my Ruby skills.
Outline
- Setup Line Messaging API
- Setup Heroku
- Write Ruby code
- Deploy code with Heroku Service
- Add your LINE bot as a friend. Test it. Enjoy!
Are you ready? Let’s create the chatbot!
Step 1. LINE Messaging API
In order to do this, you need to sign up for a LINE Developers account. If you already have a LINE account you can easily just login to this site https://developers.line.biz/en/. The LINE Messaging API is able to do push and receives messages. Once you’ve logged in we’re ready.
Create a provider.
Once you have created a provider, you are now able to create a dedicated Messaging API channel for your bot. When prompted to choose a channel type, click Create a Messaging API channel. Take note that the Channel Icon and Name are going to appear in your bot’s LINE profile. Make sure it’s what you want as you may not be able to edit it later.
After creating the channel, issue Channel Secret token, Assertion Signing token in the Basic Settings tab. After that, move to the Messaging API tab and issue the Channel Access Token. Keep them in a note for easier access as we will use them later.
Step 2: Heroku Web App Setup
Register with Heroku if you don’t have an account yet. Once able to login, create a new app. Since Heroku is a service to build and run applications on the cloud, we will later deploy our code to Heroku.
Step 3: Write your code
In the app.rb file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
# app.rb require "sinatra" require "json" require "net/http" require "uri" require "tempfile" require "line/bot" def client @client ||= Line::Bot::Client.new { |config| config.channel_secret = ENV["LINE_CHANNEL_SECRET"] config.channel_token = ENV["LINE_CHANNEL_TOKEN"] } end def chat_bot_replies(a_question, user_name) if a_question.match?(/(Hi|Hey|Konnichiwa|Hi there|Hey there|Hello|Test).*/i) "Hey " + user_name + ", how are you?" elsif a_question.match?(/(Good Morning|Wake up|Morning).*/i) "Good morning" elsif a_question.match?(/(Good night|Sleep|Night|Evening).*/i) ["Sweet dreams, "+ user_name, "Good night!" + user_name].sample elsif a_question.match?(/how\s+.*are\s+.*you.*/i) "I am super!, " + user_name elsif a_question.end_with?('?') "Nice question, " + user_name + "!" else ["Really?!", "Great to hear that.", "Wow."].sample end End post "/callback" do 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 p event user_id = event["source"]["userId"] user_name = "" response = client.get_profile(user_id) case response when Net::HTTPSuccess then contact = JSON.parse(response.body) p contact user_name = contact["displayName"] else p "#{response.code} #{response.body}" end message = { type: "text", text: chat_bot_replies(event.message["text"], user_name) } client.reply_message(event["replyToken"], message) p 'One more message!' p event["replyToken"] p message p client else message = { type: "sticker", packageId: "11537", stickerId: ["52002742", "52002753", "52002745", "52002768"].sample } client.reply_message(event["replyToken"], message) end end } "OK" end |
For a kickstart, I’ve uploaded a package in this link to help you get started.
Of course, you may also use other programming languages such as PHP and Python. Assuming you’d use the programming language of your choice, I did not include any more the steps on how to set up the Ruby environment. But if you are interested in Ruby, check out Ruby’s official documentation to help you get started.
Step 4: Deploy code to Heroku
Hosting your bot with Heroku is pretty straightforward. A deployment tab which has the steps is readily available in the Heroku site.
URL: https://dashboard.heroku.com/apps/{HEROKU_APP_NAME}/deploy/heroku-git
Or, you may also just follow the steps here. There are two deployment methods available but we will choose the Heroku CLI method.
Install the Heroku CLI
Download and install the Heroku CLI.
If you haven’t already, log in to your Heroku account and follow the prompts to create a new SSH public key.
1 |
$ heroku login |
Create a new Git repository
Initialize a git repository in a new or existing directory
1 2 3 |
$ cd gmorbot/ $ git init $ heroku git:remote -a gmorbot |
Set the tokens saved from Step 2 as environment variables on Heroku.
1 2 3 |
$ heroku config:set LINE_CHANNEL_SECRET={YOUR LINE_CHANNEL_SECRET} $ heroku config:set LINE_CHANNEL_TOKEN={YOUR LINE_CHANNEL_TOKEN} |
You may directly input environment variables in your Heroku dashboard.
Deploy your application
Commit your code to the repository and deploy it to Heroku using Git. Every time you make changes just repeat these same steps!
1 2 3 |
$ git add . $ git commit -m "delete...add...edit..i hope it works" $ git push heroku master |
Finally, go back to the LINE Console (Page) and input the webhook URL in the Messaging API tab. The URL must be in the following format:
https://{HEROKU_APP_NAME}.herokuapp.com/callback
Click the Verify button to confirm the webhook works! If it returns SUCCESS then we are good to go.
Step 5: Add your LINE Bot
Finally, add your LINE Bot through the QR code displayed in the Messaging API tab. You may start chatting with your new bot friend. If it sends back a reply, then, congratulations! You’ve just successfully created your simple LINE bot. Continue testing and if you have time, tweak as you like. You may also send stickers and other file types with the API.
For debugging: https://dashboard.heroku.com/apps/{HEROKU_APP_NAME}/logs
Additional Information:
I also integrated IBM’s Watson Visual Recognition Tool in my personal project. When an image gets sent to the bot, the service tries to identify the image sent. Lastly, I believe not everybody is friends with regex. So I would like to share this site which I think is also useful for testing Ruby regular expressions.
Feel free to add GMOR Bot as your LINE friend! Thank you for reading!
References:
https://developers.line.biz/en/docs/messaging-api/building-bot/
https://developers.line.biz/en/docs/messaging-api/building-sample-bot-with-heroku/