[DOCKER] [Python] Using Line API [1st Creation of Beauty Bot]

motivation

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.

environment

・ 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

What to create this time

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!

flow

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

1. Registration of LINE Developers

Jump to the site from the following. LINE Developers

スクリーンショット 2020-11-15 21.56.14.png

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.

スクリーンショット 2020-11-15 21.59.43.png

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.

スクリーンショット 2020-11-15 22.03.18.png

If you agree to the terms and check Admin, you can see that new channels have been added as shown below.

スクリーンショット 2020-11-15 22.06.36.png

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.

2. Creating a python file

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.

4. Deploy on heroku

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.

スクリーンショット 2020-11-16 0.24.58.png

The set environment variable is

heroku config

You can also check with.

Now that the environment variables have been set, we will upload them.

The place where I got stuck here

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.

スクリーンショット 2020-11-16 1.19.33.png

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. スクリーンショット 2020-11-16 1.28.27.png

Now you can exchange messages with beautiful women every day! !!

S__116711449.jpg

It seems that a fixed message is coming, so I will deal with it.

Select Auto-replay messages from the Messaging API. スクリーンショット 2020-11-16 1.30.34.png

Response settings → Advanced settings → Response message → Response message settings → Off This will be solved.

スクリーンショット 2020-11-16 1.34.52.png

See you soon,

S__116711452.jpg

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.

Reference article

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

[Python] Using Line API [1st Creation of Beauty Bot]
[Question] About API conversion of chat bot using Python
LINE BOT with Python + AWS Lambda + API Gateway
Recent ranking creation using Qiita API with Python
Anonymous upload of images using Imgur API (using Python)
[Python] Summary of table creation method using DataFrame (pandas)
[LINE Messaging API] Create parrot return BOT with Python
Various memorandums when using sdk of LINE Messaging API with Python (2.7.9) + Google App Engine
python: Basics of using scikit-learn ①
Parrot return LINE BOT creation
Broadcast on LINE using python
Run LINE Bot implemented in Python (Flask) "without using Heroku"
[Python] I tried collecting data using the API of wikipedia
Asynchronous processing using LINE BOT: RQ (Redis Queue) in Python
I made a Chatbot using LINE Messaging API and Python
Easy-to-understand demo of Imagemap Message of LINE Messaging API [PHP] [Ruby] [Python]
[Python] Make your own LINE bot
Image capture of firefox using python
Data acquisition using python googlemap api
Removal of haze using Python detailEnhanceFilter
[Python] LINE notification of the latest information using Twitter automatic search
Try using Pleasant's API (python / FastAPI)
[LINE Messaging API] Create a BOT that connects with someone with Python
Implementation of desktop notifications using Python
Try using Python argparse's action API
Excel graph creation using python xlwings
Run Ansible from Python using API
I made a Chatbot using LINE Messaging API and Python (2) ~ Server ~
LINE BOT (Messaging API) development with API Gateway and Lambda (Python) [Part 2]
GUI creation in python using tkinter 2
The story of making a university 100 yen breakfast LINE bot with Python
Python calling Google Cloud Vision API from LINE BOT via AWS Lambda
Development and deployment of REST API in Python using Falcon Web Framework
Get images of great find / 47 sites using Python (1/2: until target list creation)
Python: Basics of image recognition using CNN
Mouse operation using Windows API in Python
[Python] Extension using inheritance of matplotlib (NavigationToolbar2TK)
Automatic collection of stock prices using python
About building GUI using TKinter of Python
Try using the Wunderlist API in Python
GUI creation in python using tkinter part 1
I tried using Twitter api and Line api
(Bad) practice of using this in Python
Try using the Kraken API in Python
Flexible animation creation using animation.FuncAnimation of matplotlib
Python: Application of image recognition using CNN
[Python] [LINE Bot] Create a parrot return LINE Bot
Get Youtube data in Python using Youtube Data API
I tried using UnityCloudBuild API from Python
Develop slack bot in python using chat.postMessage
Creation of negative / positive classifier using BERT
Study on Tokyo Rent Using Python (3-1 of 3)
Creating Google Spreadsheet using Python / Google Data API
Awareness of using Aurora Severless Data API
Meaning of using DI framework in Python
I made a LINE BOT that returns a terrorist image using the Flickr API
Add conversation function to slack bot (made by python) using Recruit's Talk API
Let Python measure the average score of a page using the PageSpeed Insights API
[Python] Automatically totals the total number of articles posted by Qiita using the API
LINE Bot sent me the scraping results of IT trend information [LINE Messaging API]
[Python] A story about making a LINE Bot with a practical manned function on its own without using Salesforce [Messaging API]