I made a LINE BOT with Python and Heroku

I made a LINE BOT that returns parrots as part of Python learning.

Complete image

スクリーンショット 2020-11-23 210818.png Image from iOS.png

Environmental configuration

・ Python ・ Heroku ・ LINE Developers ・ Flask

Development procedure

  1. LINE Developers Registration & Settings
  2. Heroku Registration & Settings
  3. Implemented in Python
  4. LINE Developers settings again
  5. Deploy to Heroku

LINE Developers Registration & Settings

スクリーンショット 2020-11-23 230638.png Create a LINE Developers account, provider, and channel at the link below. https://developers.line.biz/ja/services/messaging-api/

Account creation

You can create an account with your name and email address.

Provider creation

Created with the provider name (your name or company name)

Channel creation

・ Channel type → Messaging API ・ Provider ・ Channel name ・ Channel description ・ Category ・ Subcategory ·e-mail address Create by agreeing to the terms of use.

Register as a friend

Register as a friend with the QR code of the channel basic setting → message API.

Confirmation of required information

Basic settings → Check channel secret Message API settings → Channel access token issuance and confirmation

Heroku Registration & Settings

スクリーンショット 2020-11-23 230824.png Heroku is simply a service that prepares you for publishing your application. What is Heroku

Heroku installation

For the installation settings etc., I referred to the following article. https://uepon.hatenadiary.com/entry/2018/07/27/002843

Heroku settings

Login with GitCMD

GitCMD


heroku login

heroku: Press any key to open up the browser to login or q to exit:
Opening browser to https://cli-auth.heroku.com/auth/browser/XXXX
Logging in... done
Logged in as XXXX@XXXX

Application registration

GitCMD


heroku create your application name(Below app name)

Creating ● App name... done
https://app name.herokuapp.com/ | https://git.heroku.com/app name.git

Setting environment variables → Reference: What are environment variables Set the channel secret and channel access token confirmed in LINE Developers earlier.

GitCMD


heroku config:set YOUR_CHANNEL_SECRET="Channel Secret string" --app app name
heroku config:set YOUR_CHANNEL_ACCESS_TOKEN="Access token string" --app app name

With this setting "YOUR_CHANNEL_SECRET" is a channel secret "YOUR_CHANNEL_ACCESS_TOKEN" is a channel access token Will be available on Heroku as.

Check settings

GitCMD


heroku config --app app name

Implemented in Python

スクリーンショット 2020-11-23 233037.png

Library installation

Enter the following contents in GitCMD.

GitCMD


pip3 install flask
pip3 install line-bot-sdk

-Flask is a Python web application framework suitable for creating simple web applications for small scale. → Reference: What is Flask

-Line-bot-sdk contains the functions required to create a LINE BOT. → Reference: What is line-bot-sdk

For the actual code, I referred to main.py on the following site. https://uepon.hatenadiary.com/entry/2018/07/27/002843 In addition, I referred to the following site to understand what is written. https://www.wantedly.com/companies/casley/post_articles/139107

main.py


#Loading required modules
from flask import Flask, request, abort
import os
from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage,
)

#Assign Flask to the variable app. Instantiation
app = Flask(__name__)

#Get environment variables
YOUR_CHANNEL_ACCESS_TOKEN = os.environ["YOUR_CHANNEL_ACCESS_TOKEN"]
YOUR_CHANNEL_SECRET = os.environ["YOUR_CHANNEL_SECRET"]

line_bot_api = LineBotApi(YOUR_CHANNEL_ACCESS_TOKEN)
handler = WebhookHandler(YOUR_CHANNEL_SECRET)

#Method for Heroku login connection confirmation
#When I log in to Heroku, "hello world" is displayed in the browser
@app.route("/")
def hello_world():
    return "hello world!"

#When a message is sent by the user, this method is called from the LINE Message API.
@app.route("/callback", methods=['POST'])
def callback():
    #Get the value for signature verification from the request header
    signature = request.headers['X-Line-Signature']

    #Get request body
    body = request.get_data(as_text=True)
    app.logger.info("Request body: " + body)

    #Verify the signature, and if there is no problem, call the function defined in handle.
    try:
        handler.handle(body, signature)
    #If signature verification fails, throw an exception.
    except InvalidSignatureError:
        abort(400)
    #OK if you finish processing the handle
    return 'OK'

#When a Message Event (when a normal message is sent) occurs on LINE,
#def Execute the following function.
# reply_event, the first argument of message.reply_token is a token used to respond to an event.
#The second argument is linebot.We are passing the TextSendMessage object for the reply defined in models.
@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    line_bot_api.reply_message(
        event.reply_token,
        TextSendMessage(text=event.message.text))

#Port number setting
if __name__ == "__main__":
#    app.run()
    port = int(os.getenv("PORT"))
    app.run(host="0.0.0.0", port=port)

Webhook settings

Go back to the LINE Message API and set the Heroku connection destination in the Webhook URL of the Webhook. Webhook URL: https: // app name.herokuapp.com/callback * Don't forget to enter the callback method at the end </ font>

Creating and deploying configuration files

See: What is deployment Create files to be installed on Heroku (including the Python source code "main.py" mentioned earlier). Check the version of Python etc. to create the file

GitCMD


python --version

GitCMD


pip freeze

Create a directory to deploy (this time the folder name is linebot) Files in the directory main.py → source code runtime.txt → Describe the Python version requirements.txt → Description of the library to be installed Procfile → Defines how to execute the program

runtime.txt


Python 3.9.0

requirements.txt


Flask==1.1.2
line-bot-sdk==1.17.0

Procfile web: python main.py

  • Procfile is created by entering "echo web: python main.py> Procfile" at the command prompt.

Installed on Heroku using Git

スクリーンショット 2020-11-24 152809.png

GitCMD



cd linebot  
git init
git add .
git commit -am "make it better"
git push heroku master

I moved to the directory created by "cd" and installed it in Heroku with the following 4 lines. See: What is Git

Check if it was deployed

heroku open

If hello World is displayed, it has been successfully deployed.

Log check

heroku logs --tail

You can check the log with the above command.

Where it gets stuck

When copying the channel access token of LINE Message API, I copied and pasted it in the translated state and it was caught in the signature verification and the parrot was not returned, but when I canceled the translation and copied and pasted it, the expected value was returned.

References

https://www.casleyconsulting.co.jp/blog/engineer/3028/ https://www.sejuku.net/blog/7858 https://uepon.hatenadiary.com/entry/2018/07/27/002843 https://www.wantedly.com/companies/casley/post_articles/139107

Recommended Posts

I made a LINE BOT with Python and Heroku
I made a LINE Bot with Serverless Framework!
I made a Mattermost bot with Python (+ Flask)
I made a Nyanko tweet form with Python, Flask and Heroku
[AWS] I made a reminder BOT with LINE WORKS
I made a household account book bot with LINE Bot
I made a fortune with Python.
I made a daemon with Python
[Python] I made a LINE Bot that detects faces and performs mosaic processing.
I made a LINE BOT that returns parrots with Go
I made a Chatbot using LINE Messaging API and Python
[AWS] I made a reminder BOT with LINE WORKS (implementation)
I made a character counter with Python
I made a Hex map with Python
I made a roguelike game with Python
I made a simple blackjack with Python
I made a configuration file with Python
I made a neuron simulator with Python
[Python] I made a Line bot that randomly asks English words.
I made a simple circuit with Python (AND, OR, NOR, etc.)
I made a Chatbot using LINE Messaging API and Python (2) ~ Server ~
I made a competitive programming glossary with Python
I made a weather forecast bot-like with Python.
I made a GUI application with Python + PyQt5
Create a LINE BOT with Minette for Python
I made a Twitter fujoshi blocker with Python ①
[Python] I made a Youtube Downloader with Tkinter.
I made a bin picking game with Python
I made blackjack with python!
I made a python text
I made a discord bot
I made blackjack with Python.
I made wordcloud with Python.
I made a Christmas tree lighting game with Python
I made a net news notification app with Python
I made a Python3 environment on Ubuntu with direnv.
[Super easy] Let's make a LINE BOT with Python.
I made a Line Bot that uses Python to retrieve unread Gmail emails!
[For beginners] I made a motion sensor with Raspberry Pi and notified LINE!
In Python, I made a LINE Bot that sends pollen information from location information.
I made a music bot using discord.py and Google Drive API (tested with Docker → deployed to Heroku)
I made a Line-bot using Python!
I made a wikipedia gacha bot
I played with PyQt5 and Python3
I made a package to filter time series with python
I made a simple book application with python + Flask ~ Introduction ~
Until I return something with a line bot in Django!
I want to send a message from Python to LINE Bot
I made a puzzle game (like) with Tkinter in Python
I made a program to convert images into ASCII art with Python and OpenCV
I made a LINE bot that tells me the type and strength of Pokemon in the Galar region with Heroku + Flask + PostgreSQL (Heroku Postgres)
I made a library to easily read config files with Python
[Python3] I made a decorator that declares undefined functions and methods.
I made a package that can compare morphological analyzers with Python
I want to know the weather with LINE bot feat.Heroku + Python
I made a payroll program in Python!
I drew a heatmap with seaborn [Python]
Creating a LINE bot ~ Creating, deploying, and launching ~
A memo with Python2.7 and Python3 on CentOS
I made a lot of files for RDP connection with Python
[Python] [LINE Bot] Create a parrot return LINE Bot