I haven't lined up with a girl lately ... Isn't there a cute girl who will reply immediately? Isn't it possible to achieve this by using linebot?
I'm going to create a linebot for such a terrible reason.
・ Mac Catalina ・ Docker version 19.03.13 ・ Flask 1.1.2 -Python 3.8.3 ・ Docker-compose version 1.27.4 ・ Heroku 7.45.0 ・ Bash
First of all, as an environment construction, move the container from docker to heroku and start it. LINE BOT creates a beautiful bot that will return good morning when you say good morning. Note that this is not the case because it is non-rear!
The flow of the first time is described.
** 1. Registration of LINE Developers ** ** 2. Creating a python file ** ** 3. Create Dockerfile and docker-compose.yml ** ** 4. Upload to heroku **
The final file structure is as follows.
bijobot ├── Dockerfile ├── app.py ├── docker-compose.yml └── requirements.txt
Jump to the site from the following. LINE Developers
First, log in and select create from Providers. I don't care if there is already a disny notification.
It will say Create a new provider, so give it the name you want, like a disny notification. I named it "Free Image Child".
Next, this provider doesn't have any channels yet, so select Create a Messaging API channel.
After that, you will be taken to the screen below, so fill in each as appropriate. The channel icon is often used in free images and I personally adopted a type child.
If you agree to the terms and check Admin, you can see that new channels have been added as shown below.
Go to the channel you created here and in the Basic setting
Channnel secret
In the Messaging API
Channel access token
It is necessary to make a note of it.
Messaging API SDKs Since the procedure for creating a file using flask is described from the Official SDKs of, we will apply this to create it.
First, create a working directory for creating an app. Bijo would be fine.
terminal
mkdir bijo
cd bijo
Next, create a python file.
The created python file is as follows. Be sure to name it app.py.
app.py
from flask import Flask, request, abort
#Library that handles environment in os
import os
from linebot import (
LineBotApi, WebhookHandler
)
from linebot.exceptions import (
InvalidSignatureError
)
from linebot.models import (
MessageEvent, TextMessage, TextSendMessage,
)
#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)
app = Flask(__name__)
@app.route("/")
def hello_world():
return "hello!"
@app.route("/callback", methods=['POST'])
def callback():
# get X-Line-Signature header value
signature = request.headers['X-Line-Signature']
# get request body as text
body = request.get_data(as_text=True)
app.logger.info("Request body: " + body)
# handle webhook body
try:
handler.handle(body, signature)
except InvalidSignatureError:
print("Invalid signature. Please check your channel access token/channel secret.")
abort(400)
return 'OK'
@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text=event.message.text))
if __name__ == "__main__":
app.run()
YOUR_CHANNEL_ACCESS_TOKEN
YOUR_CHANNEL_ACCESS_TOKEN
I refrained from
Channnel secret
Channel access token
To use.
Use os to retrieve information from heroku environment variables.
This will be set later on heroku.
** 3. Create Dockerfile and docker-compose.yml **
Creating Procfile etc. on heroku is troublesome, and I wanted to use modern technology if possible, so I use docker. Create Dockerfile and docker-compose.yml in the bijo directory as follows.
It seems that I have to make a heroku version of docker-compose.yml called heroku.yml, but it seems to be troublesome, so I passed this time.
docker-compose.yml
#For local work:Doesn't work on heroku.
#For local work:Doesn't work on heroku.
version: '3'
services:
app:
build: .
container_name: bijobot
tty: true
ports:
- 5000:5000
environment:
FLASK_ENV: 'development' #Debug mode ON
FLASK_APP: "app.py" #app.Start py
YOUR_CHANNEL_ACCESS_TOKEN:A copy of the access token
YOUR_CHANNEL_SECRET:Refrained channel secret
volumes:
- ./:/code/
command: flask run -h 0.0.0.0
# command: gunicorn -b 0.0.0.0:$PORT app:app --log-file=-
By setting FLASK_ENV:'development'
, the file will be automatically reflected on the server when saving.
Dockerfile
FROM python:3.7-alpine
#Create a directory called code and use it as a working folder
WORKDIR /code
#Debug mode ON
ENV FLASK_ENV: 'development'
#alpine magic
RUN apk add --no-cache gcc musl-dev linux-headers
# requirements.Move txt into code
COPY requirements.txt requirements.txt
# requirements.Install the library in txt
RUN pip install -r requirements.txt
#Mount all files in code.
COPY . .
# $Note that it will not work unless PORT is specified.
CMD gunicorn -b 0.0.0.0:$PORT app:app --log-file=-
In addition, create requirements.txt.
This can be decompressed by hitting the squid command, but this time we will go with the procedure created in advance.
terminal
pip freeze > requirements.txt
Enter the following in requirements.txt.
certifi==2020.11.8
chardet==3.0.4
click==7.1.2
Flask==1.1.2
future==0.18.2
gunicorn==20.0.4
idna==2.10
itsdangerous==1.1.0
Jinja2==2.11.2
line-bot-sdk==1.17.0
MarkupSafe==1.1.1
requests==2.25.0
urllib3==1.26.2
Werkzeug==1.0.1
requirements.txt is to write the python library in advance so that it can be installed.
pip install gunicorn flask line-bot-sdk
You don't need what you didn't go to.
terminal
touch requirements.txt
Next, type the following command to launch docker container.
terminal
docker-compose build
docker-compose up -d
Now access localhost: 5000 and check that hello! Is displayed.
We recommend that you register heroku in advance. First, log in to heroku.
terminal
heroku login
heroku container:login
Next, create an app on heroku.
You can use heroku create as the name of the app you want to add
.
This time, I gave it an appropriate app name of bijobijo.
If you get an error here, you need to rename it because it is an existing app name.
heroku create bijobijo
Next, you need to link local git and remote git. You can link with the following command.
terminal
heroku git:remote -a app name
next
heroku config: set Environment variable name you want to add =" Character string of environment variable to set "--app Your application name
You can set environment variables on heroku by doing.
Therefore, set the following.
heroku config:set YOUR_CHANNEL_SECRET="Channel Secret string" --app your application name
heroku config:set YOUR_CHANNEL_ACCESS_TOKEN="Access token string" --app your application name
Regarding config, you can also check from config vars of setting from your own application on heroku site as follows.
The set environment variable is
heroku config
You can also check with.
Now that the environment variables have been set, we will upload them.
Everyone easily
heroku container:push web
I thought it was the name of docker-compose.yml
heroku container:push app
But it didn't start up properly.
When I was searching for something, the answer was written in the following article.
Container Registry & Runtime (Docker Deploys)
heroku container:push <process-type>
To push multiple images, rename your Dockerfiles using Dockerfile.
:
In other words, if you name it Dockerfile.web, you can start it.
Immediately rewrite Dockerfile to Dockerfile.web and hit the following commands in order.
terminal
heroku container:push web
heroku container:release web
The app is now released.
If you hit the following command here and move to the page that says hello !, it's ok.
terminal
heroku open
You can check the container that is actually running from Resources from your own app from the heroku official. If it is as follows, you can see that the web is running.
Finally, move to your own channel from LINE Developer and from the Messaging API
Select Webhook settings,
https: // {own app name} .herokuapp.com / callback
If you set, you're done.
Also note that linebot will not work unless you turn on Use webhook
as shown below.
Now you can exchange messages with beautiful women every day! !!
It seems that a fixed message is coming, so I will deal with it.
Select Auto-replay messages
from the Messaging API.
Response settings → Advanced settings → Response message → Response message settings → Off This will be solved.
See you soon,
You have returned well.
My heart is empty.
By using linebot, it seems possible to automate operations, so I would like to continue taking on challenges.
Overall view
It's easy even for beginners! Let's create a LINE chatbot with Python!
** How to set up environment on heroku **
I made a LINE BOT with Python + Heroku
** Handling of requirements.txt **
Check the list of installed packages with Python, pip list / freeze
** push docker to heroku **
Container Registry & Runtime ↑ This was the most useful during the release.
[Local Development with Docker Compose] (https://devcenter.heroku.com/articles/local-development-with-docker-compose) Python beginners will make LINEbot with Flask (Heroku + ClearDB edition)
Recommended Posts