I made a LINE BOT that returns parrots as part of Python learning.
・ Python ・ Heroku ・ LINE Developers ・ Flask
Create a LINE Developers account, provider, and channel at the link below. https://developers.line.biz/ja/services/messaging-api/
You can create an account with your name and email address.
Created with the provider name (your name or company name)
・ 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 with the QR code of the channel basic setting → message API.
Basic settings → Check channel secret Message API settings → Channel access token issuance and confirmation
Heroku is simply a service that prepares you for publishing your application. What is Heroku
For the installation settings etc., I referred to the following article. https://uepon.hatenadiary.com/entry/2018/07/27/002843
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
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)
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>
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
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
heroku open
If hello World is displayed, it has been successfully deployed.
heroku logs --tail
You can check the log with the above command.
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.
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