Procedure for creating a LineBot made with Python

Preface

Many articles have written about how to create a linebot, but as a beginner I had a stumbling block, so I made up for it and made it easy for me to understand. Since this is an article I made for myself, there are many points that are difficult to understand, but please do your best while referring to other articles.

Premise: LineBot has been created

スクリーンショット 2020-02-01 11.10.20.png #### Get channel secret ![スクリーンショット 2020-05-06 17.13.47.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/517291/204af3f7-9656-3ddb-d799-e9ff025776b4.png)

Get a channel access token

Premise: Heroku account created & credit registered

  1. Start the terminal 2、
$mkdir lineBotTest

$cd lineBotTest

Enter 3. Launch TextEdit in your application 4, select the format in the top bar, select standard text, copy and paste the following No need to change such as'LINE_CHANNEL_SECRET' Copy as it is

import os
import sys
from argparse import ArgumentParser
from flask import Flask, request, abort
from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage,
)

app = Flask(__name__)

"""
heroku config:set LINE_CHANNEL_SECRET="Channel secret" --app app name
Is typed into the terminal, so the channel secret is automatically entered in the following code every time.
The access token is the same, so there is no need to change it.
"""
channel_secret = os.getenv('LINE_CHANNEL_SECRET', None)
channel_access_token = os.getenv('LINE_CHANNEL_ACCESS_TOKEN', None)

"""
Null channel secret or access token(nothing)Processing in case of
"""
if channel_secret is None:
    print('Specify LINE_CHANNEL_SECRET as environment variable.')
    sys.exit(1)
if channel_access_token is None:
    print('Specify LINE_CHANNEL_ACCESS_TOKEN as environment variable.')
    sys.exit(1)
    
"""
Get tokens etc. from Heroku variables
"""
line_bot_api = LineBotApi(channel_access_token)
handler = WebhookHandler(channel_secret)

"""
Webhook from LINE
Basic functions that do not change
"""
@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)

    #Validate the signature and call the function defined in handle if there is no problem
    try:
        handler.handle(body, signature)
    except InvalidSignatureError:#Returns 400 when an error occurs
        abort(400)
    return 'OK'

"""
Massage Event on LINE(When a text message is sent)Called when
line_bot_api.reply_event as the first argument of message.reply_token is used to respond to events
The second argument is linebot.Pass the TextSendMessage object for reply defined in models
"""
@handler.add(MessageEvent, message=TextMessage)
def message_text(event):
    #What you entered(event.message.text)Reply according to
    line_bot_api.reply_message(
        event.reply_token,
        TextSendMessage(text=event.message.text)
    )

if __name__ == "__main__":#Identify if it is running with the correct file extension
    port = int(os.getenv("PORT", 5000))
    app.run(host="0.0.0.0", port=port)
  1. Name it main.py. Also, save it in lineBotTest at this point スクリーンショット 2020-02-01 11.32.48.png It should be like this.

  2. Confirm that it is lineBotTest user $ in the terminal, and enter the following command

$brew tap heroku/brew && brew install heroku

$heroku login
//Login starts when you press a button other than q

$heroku create app name
//Use an app name created by another person and a unique name that does not cover
//heroku create linetest0000 Use linetest0000 this time

$heroku addons:create fixie:tricycle --app linetest0000
//Addition of "Fixie" add-on

$pipenv install flask
$pipenv install line-bot-sdk
//"Pipfile" and "Pipfile" in the folder."lock" is generated.

/*
Enter when doing web scraping
$pipenv install bs4
$pipenv install requests
*/

$heroku config:set LINE_CHANNEL_SECRET="Channel secret" --app linetest0000
//Enter the first acquired channel secret

$heroku config:set LINE_CHANNEL_ACCESS_TOKEN="Access token (long term)" --app linetest0000
//Enter the access token you got first

$echo web: python main.py > Procfile
//Profile creation

$heroku git:remote --app linetest0000

$git init

$git add -A

$git commit -m "Enter a comment"

$git push heroku master

git add -A The following command is a command to type to reflect when the code is changed

webhook settings
スクリーンショット 2020-02-01 12.53.56.png Enter "https: // app name.herokuapp.com/callback"

Caution

If you use import in your code, use Procfile

$pipenv install library name

Enter Enter Procfile with a command instead of opening it

When it doesn't move

$heroku logs -t

You can see the log at. This usually works.

This completes スクリーンショット 2020-02-01 13.42.47.png

Recommended Posts

Procedure for creating a LineBot made with Python
Commands for creating a python3 environment with virtualenv
Procedure for creating a Python quarantine environment (venv environment)
[GCP] Procedure for creating a web application with Cloud Functions (Python + Flask)
I made a Line-bot using Python!
I made a fortune with Python.
I made a daemon with Python
Installation procedure for Python and Ansible with a specific version
Creating a simple PowerPoint file with Python
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
A textbook for beginners made by Python beginners
I made a neuron simulator with Python
I made a lot of files for RDP connection with Python
I made a python dictionary file for Neocomplete
I made a competitive programming glossary with Python
I made a GUI application with Python + PyQt5
I made a Twitter fujoshi blocker with Python ①
[Python] I made a Youtube Downloader with Tkinter.
A memo when creating a python environment with miniconda
A memo for creating a python environment by a beginner
I made a bin picking game with Python
I made a Mattermost bot with Python (+ Flask)
Procedure for creating an application with Django with Pycharm ~ Preparation ~
I made a Twitter BOT with GAE (python) (with a reference)
I made a Christmas tree lighting game with Python
I made a window for Log output with Tkinter
Build a python environment for each directory with pyenv-virtualenv
I made a net news notification app with Python
I made a VM that runs OpenCV for Python
I made a Python3 environment on Ubuntu with direnv.
Problems when creating a csv-json conversion tool with python
I made a LINE BOT with Python and Heroku
Creating ρ method for elliptic curve cryptography with python
Procedure for building a CDK environment on Windows (Python)
Create a Layer for AWS Lambda Python with Docker
[Python] I made a classifier for irises [Machine learning]
Procedure for creating a Line Bot on AWS Lambda
[Piyopiyokai # 1] Let's play with Lambda: Creating a Python script
Python 3.6 installation procedure [for Windows]
I made blackjack with python!
Creating an egg with python
Make a fortune with Python
I made a python text
Made a command for FizzBuzz
I made blackjack with Python.
Create a directory with python
Othello made with python (GUI-like)
I made wordcloud with Python.
I made a simple typing game with tkinter in Python
kabu Station® API-I made a Python wrapper for REST API
I made a package to filter time series with python
Recommendations for django, wagtail ~ Why develop a website with python ~
[VSCode] I made a user snippet for Python print f-string
Create a child account for connect with Stripe in Python
I made LINE-bot with Python + Flask + ngrok + LINE Messaging API
Experiment to make a self-catering PDF for Kindle with Python
I made a simple book application with python + Flask ~ Introduction ~