[Python] [LINE Bot] Create a parrot return LINE Bot

It's a long time ago, but I suddenly decided to create a LINE Bot, I just made a LINE Bot that returns parrots. スクリーンショット 2020-05-12 20.39.28.png

1. Create a Line Messaging API channel

Create a channel with LINE Developers

Basically, you should be able to register without any problems according to the official page below. [To use Messaging API | LINE Developers](https://developers.line.biz/ja/docs/messaging-api/getting-started/#%E3%83%81%E3%83%A3%E3 % 83% 8D% E3% 83% AB% E3% 81% AE% E4% BD% 9C% E6% 88% 90)

![Screenshot 2020-05-12 20.48.49.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/130414/83b70611-c51f-d7f0-ca71 -6389eac33f13.png)

If the channel can be registered safely, it will be in a state like ↓ スクリーンショット 2020-05-12 20.58.26.png

Check the following two as you will need it later ・ Channel secret ← Located in the Basic Setting tab ・ Channel access token (long-lived) ← Located in the Messaging API tab

2.Heroku

Create an account

Basically, you should be able to register without any problems according to the official page below. Heroku Dev Center

![Screenshot 2020-05-12 21.14.40.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/130414/add1067e-c321-8ba2-a348 -3dcf648916be.png)

Download Heroku CLI

Download and install the Heroku CLI from the following page The Heroku CLI | Heroku Dev Center

![Screenshot 2020-05-12 21.21.03.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/130414/a3ee0f63-8bb9-a06e-418e -27c04e72a1b5.png)

After a successful installation, you should be able to use the heroku command in your terminal. スクリーンショット 2020-05-12 21.24.23.png

3. Create a file to deploy

File structure

Create a file with the following configuration スクリーンショット 2020-05-12 21.29.07.png

main.py The main part of the program

main.py


# -*- coding: utf-8 -*-
#  Licensed under the Apache License, Version 2.0 (the "License"); you may
#  not use this file except in compliance with the License. You may obtain
#  a copy of the License at
#
#       https://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#  License for the specific language governing permissions and limitations
#  under the License.

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__)

# get channel_secret and channel_access_token from your environment variable
channel_secret = os.getenv('LINE_CHANNEL_SECRET', None)
channel_access_token = os.getenv('LINE_CHANNEL_ACCESS_TOKEN', None)
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)

line_bot_api = LineBotApi(channel_access_token)
handler = WebhookHandler(channel_secret)


@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:
        abort(400)

    return 'OK'


@handler.add(MessageEvent, message=TextMessage)
def message_text(event):
    line_bot_api.reply_message(
        event.reply_token,
        TextSendMessage(text=event.message.text)
    )


if __name__ == "__main__":
    port = int(os.getenv("PORT", 5000))
    app.run(host="0.0.0.0", port=port)

Procfile How to run the program

web: python main.py

requirements.txt Module to use

Flask==0.12.2
line-bot-sdk==1.8.0

runtime.txt Listed python version

python-3.6.6

4. Deploy to Heroku

Create a git repository and commit

Execute the following command from a terminal etc.

$ cd line-bot
$ git init
$ git config user.name "name"
$ git config user.email email address
$ git add .
$ git commit -m "comment"

$ cd line-bot: Move to root directory $ git init: Initialize git repository $ git config user.name "name": config config $ git config user.email email address: config settings $ git add.: Add $ git commit -m "comment": commit

Log in to Heroku

Execute the following command to log in to Heroku

$ heroku login

When you execute it, it will be in the following state, so if you press any key, the login screen will be displayed on the browser, so Click the Log In button to log in スクリーンショット 2020-05-12 21.46.31.png スクリーンショット 2020-05-12 21.46.39.png

Create and deploy application

Execute the following command to create and deploy an application on Heroku

$heroku create application name
$ heroku config:set LINE_CHANNEL_SECRET="Channel Secret" --app application name
$ heroku config:set LINE_CHANNEL_ACCESS_TOKEN="Access token" --app application name
$ git push heroku master

The application name is arbitrary Set the "Channel Secret" and "Access Token" that you confirmed when you created the channel with LINE Developers.

build pack settings

Deployment may fail if the build pack is not set. In that case, execute the following command and set the build pack

$ heroku buildpacks:set heroku/python

5. Webhook settings on the LINE Bot side

Set the webhook settings for the channel created from the Line Developers console Use Webhook and specify the following URL as the webhook URL

https://Application name.herokuapp.com/callback

Complete

When the work up to this point is completed, the bot that returns the parrot is completed! I was a beginner who had never used Heroku, Git, or Messaging API, but it was surprisingly easy to create. I wish I could make something based on this in the future スクリーンショット 2020-05-12 22.16.00.png

Recommended Posts

[Python] [LINE Bot] Create a parrot return LINE Bot
[LINE Messaging API] Create parrot return BOT with Python
Create a LINE BOT with Minette for Python
Parrot return LINE BOT creation
Make a parrot return LINE Bot on AWS Cloud9
Create a LINE Bot in Django
[LINE Messaging API] Create a BOT that connects with someone with Python
Create a Python module
Create a Python environment
Create a slack bot
Steps to create a Twitter bot with python
Create a data collection bot in Python using Selenium
Create a dictionary in Python
[LINE Messaging API] Create a rich menu in Python
Make a LINE BOT (chat)
I made a LINE BOT with Python and Heroku
[For play] Let's make Yubaba a LINE Bot (Python)
Create a python numpy array
Create a directory with python
[Super easy] Let's make a LINE BOT with Python.
Create a machine learning app with ABEJA Platform + LINE Bot
Create a Mastodon bot with a function to automatically reply with Python
Until I return something with a line bot in Django!
Create a Twitter BOT with the GoogleAppEngine SDK for Python
I want to send a message from Python to LINE Bot
Create a python GUI using tkinter
Create a DI Container in Python
Create a virtual environment with Python!
Create a binary file in Python
Create a python environment on centos
Create a Python general-purpose decorator framework
Create a Kubernetes Operator in Python
[Python] return A [or / and] B
[LINE bot] I'm a ranger! Part 2
5 Ways to Create a Python Chatbot
Create a random string in Python
[Python] I made a Line bot that randomly asks English words.
Create a command line tool to convert dollars to yen using Python
Create a Python function decorator with Class
Create a bot to retweet coronavirus information
Create a new Python numerical calculation project
Build a blockchain with Python ① Create a class
Create a dummy image with Python + PIL.
Create a python environment on your Mac
Create a simple GUI app in Python
Let's create a virtual environment for Python
[Python] Create a virtual environment with Anaconda
Creating a LINE bot ~ Creating, deploying, and launching ~
Let's create a free group with Python
Create a JSON object mapper in Python
[Python] Create a Batch environment using AWS-CDK
Create a word frequency counter with Python 3.4
Create a deb file from a python package
[Python] Create a LineBot that runs regularly
[GPS] Create a kml file in Python
Create a bot that boosts Twitter trends
Let's make a Twitter Bot with Python!
The story of making a university 100 yen breakfast LINE bot with Python
I made a stamp substitute bot with line
Create a frame with transparent background with tkinter [Python]
[Python] List Comprehension Various ways to create a list