[PYTHON] [LINE Messaging API] I want to send a message from the program to everyone's LINE

Overview

--I want to send individual messages to users who have registered as friends. --I want to do it programmatically.

line18.jpg

A page with similar content is already on the net. However, I think it would be nice to have a page that answers the following questions that I have, and I will write an article so that someone with similar questions will be stabbed.

Question

――I searched for "Send a message from the LINE program", but I'm not sure because LINE Notify, LINE official account, and LINE @ came out. ――I just want to send it, but when I look at the article on the net, the server suddenly appears and I'm confused.

A rough and simple answer ...

――The LINE Messaging API that can be used after obtaining an official LINE account is used. ――You can "send" from your own location (without a server), but you need the ID of the destination user to specify the destination. You'll need a server to get it. But it's okay because you can do it for free on Heroku.

Why LINE Messaging API

We will respond to "I don't know if LINE Notify, LINE official account, LINE @, etc. will come out."

So, first create an official LINE account and then use the LINE Messaging API.

Fee

You can find it in What is a LINE official account? Introducing charges. Maybe you can use as many automatic replies as you like for free, and you can use the push function (active sending, the goal of what you want to do this time) up to 1,000 per month for free.

Organize what you are going to make

It looks like this when illustrated. If you look at the figure, you can see why you need a server.

line17.png

Create channel

It is not the "LINE official account" that sends messages to each user. It's a "channel".

line15.jpg

On the left side of this, the conversation partner is not an official account but a channel. So, first create a "LINE official account", create a "provider" for that child element, and then create a "channel" for that child element.

-** LINE Official Account ** -Please go to https://developers.line.biz/. -** Provider ** ――The "provider" that suddenly appeared is the organization that provides the application, and it seems that you enter your name or company name. However, my name is tied to the LINE official account, and I feel uncomfortable using my name here .... -** Channel ** ――Give the name you want to display on LINE.

Until new channel creation

Let's proceed on the premise that "LINE official account" and "provider" have already been created.

line01.jpg

line02.jpg

line03.jpg

line04.jpg

line05.jpg

line06.jpg

line07.jpg

line08.jpg

Once you have created a channel and registered as a friend, you can talk on https://manager.line.biz/ at this point.

Acquisition of tokens

Get the "Channel Secret" and "Access Token" from the channel preferences.

line09.jpg

line10.jpg

Prepare a server

As mentioned above, you need that user's ID to automatically send a message to someone.

The user's ID can be obtained from the Json that the user sends a message to the channel once, and then the channel sends it to his server. Next, create a web app in Python to deploy on the server.

Create a python script

In my case, I use pipenv, so I prepare the environment like this.

pipenv install flask line-bot-sdk gunicorn

I named the Python script my_flask_script.py. I got the base code from the line-bot-sdk documentation and modified it.

my_flask_script.py


from flask import Flask, request, abort

from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage,
)

#To get environment variables.
import os

#To output the log.
import logging
import sys

app = Flask(__name__)

#Log to standard output. heroku logs--This is to check with tail.
# app.logger.Since it is output by info, set the level to INFO.
app.logger.addHandler(logging.StreamHandler(sys.stdout))
app.logger.setLevel(logging.INFO)

#Get important information from environment variables.
CHANNEL_ACCESS_TOKEN = os.environ['CHANNEL_ACCESS_TOKEN']
CHANNEL_SECRET = os.environ['CHANNEL_SECRET']

line_bot_api = LineBotApi(CHANNEL_ACCESS_TOKEN)
handler = WebhookHandler(CHANNEL_SECRET)


#Although it is not required, I will add a top page to check when it comes up to the server.
@app.route('/')
def top_page():
    return 'Here is root page.'


#This URL is accessed when the user sends a message.
@app.route('/callback', methods=['POST'])
def callback_post():
    # 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 reply_message(event):
    #Test of reply.
    line_bot_api.reply_message(
        event.reply_token,
        TextSendMessage(text='This will be sent from the callback process:'+event.message.text))


if __name__ == '__main__':
    app.run()

Create file for Heroku

# runtime.txt:Described the Python version.
echo python-3.7.4 > runtime.txt

# requirements.txt:Description of dependent libraries.
pip freeze > requirements.txt

# Procfile:Describes how to execute the program.
echo web: gunicorn my_flask_script:app --log-file - > Procfile

Procfile didn't work for some reason in web: python my_flask_script.py. The Procfile --log-file is an option to spit out logs. - points to stdout. By setting this, you can check the logs later with heroku logs --tail.

Up to Heroku

We'll assume you already have a Heroku account.

#Create Git repository.
git init
#As a personal hobby, first create an empty commit.
git commit --allow-empty -m "Initial Commit"
#Commit all files.
git add --all
git commit -m "Add all files"

#The app name this time is line-messaging-py-py-Try to make it py.
heroku create line-messaging-py-py-py

#Set environment variables.
heroku config:set CHANNEL_ACCESS_TOKEN="Copy the access token from the channel preferences page" --app line-messaging-py-py-py
heroku config:set CHANNEL_SECRET="Copy the Channel Secret from the Channel Preferences page" --app line-messaging-py-py-py

#Uploaded to Heroku repository.
git push heroku master

#If something goes wrong on the way, delete it with destroy and start over with create.
# heroku apps:destroy --app line-messaging-py-py-py

I have also created a method for the top page, so I will open it.

line11.jpg

I found that the upload was successful.

Subscribe to the Heroku URL

Register the webhook URL on the channel preferences page to enable webhook sending. In the Python script above, the URL that accepts callbacks is / callback, so this time the Webhook URL is https://line-messaging-py-py-py.herokuapp.com/callback.

I'm not sure about this, but when I do a "connection check", red letters appear, which makes us uneasy. However, there was no problem if I proceeded as it was ....

line12.jpg

Try using reply_message

There is a QR code at the bottom of the channel preferences page, from which you can register this channel as a friend.

line13.jpg

line14.jpg

line15.jpg

You can see that the message was returned after going through a callback process written in Python. Right now, the channel setting is the default, so various automatic replies are sent, but I hope you can edit it later.

Contents of event and userId

In my_flask_script.py, ʻapp.logger.infooutputs the information sent to this script. You can check it withheroku logs --tail`.

{
    "events": [
        {
            "type": "message",
            "replyToken": "********************************",
            "source": {
                "userId": "*********************************",
                "type": "user"
            },
            "timestamp": 1572247838104,
            "message": {
                "type": "text",
                "id": "**************",
                "text": "foo bar baz"
            }
        }
    ],
    "destination": "*********************************"
}

Make a note of ʻuserId` in this because you want to use it for push_message later. If you want to get it in the code, get it as follows.

event.source.user_id

Try using push_message

This is the goal. You can actively send messages by using the "access token" and "userId" that you wrote down above. Of course this doesn't have to be uploaded to Heroku, you can try it locally.

push_message.py


from linebot import LineBotApi
from linebot.models import TextSendMessage

CHANNEL_ACCESS_TOKEN = 'CHANNEL used above_ACCESS_Same as TOKEN'
USER_ID = 'The value of userId noted above'

line_bot_api = LineBotApi(CHANNEL_ACCESS_TOKEN)

line_bot_api.push_message(
    USER_ID,
    TextSendMessage(text='This is Pushumesseji. Hi!'))

line16.jpg

As you can see, you can always send a message by keeping ʻuser_id`, which is unique to each user. end. It's been a long article ...

Recommended Posts

[LINE Messaging API] I want to send a message from the program to everyone's LINE
I want to send a message from Python to LINE Bot
I want to send a signal only from the sub thread to the main thread
I created a Python library to call the LINE WORKS API
Send a message from Python to Slack
Send a message from the server to your Chrome extension using Google Cloud Messaging for Chrome
How to send a message to LINE with curl
[Free] Hit the Clash Royale API from lambda and send it to LINE
I want to see the file name from DataLoader
I want to send a business start email automatically
How to post a ticket from the Shogun API
[Python] I made a system to introduce "recipes I really want" from the recipe site!
Send a push message to the LINE Bot when the LTE-M Button is pressed [SORACOM]
How to install NPI + send a message to line with python
I want to save the photos sent by LINE to S3
I want to start a lot of processes from python
I want to calculate the allowable downtime from the operating rate
I want to install a package from requirements.txt with poetry
I tried to get various information from the codeforces API
I made a Chatbot using LINE Messaging API and Python
I want to create a Dockerfile for the time being.
I didn't want to write the AWS key in the program
A script that makes it easy to create rich menus with the LINE Messaging API
I want to find the intersection of a Bezier curve and a straight line (Bezier Clipping method)
I made a program to solve (hint) Saizeriya's spot the difference
I want to record the execution time and keep a log.
I want to automatically find high-quality parts from the videos I shot
I want to know the weather with LINE bot feat.Heroku + Python
I want to create a system to prevent forgetting to tighten the key 1
How to extract the desired character string from a line 4 commands
I want to make a parameter list from CloudFormation code (yaml)
I want to make the second line the column name in pandas
I tried to cut out a still image from the video
I made a Chatbot using LINE Messaging API and Python (2) ~ Server ~
How to send a request to the DMM (FANZA) API with python
I want to get information from fstab at the ssh connection destination and execute a command
[Python] I tried to make a simple program that works on the command line using argparse.
I want to improve efficiency with Python even in the experimental system (5) I want to send a notification at the end of the experiment with the slack API
I want to pin Spyder to the taskbar
I want to output to the console coolly
I want to be healed by Mia Nanasawa's image. In such a case, hit the Twitter API ♪
I want to print in a comprehension
I want to handle the rhyme part1
[Python memo] I want to get a 2-digit hexadecimal number from a decimal number
I want to handle the rhyme part3
I want to use jar from python
I want to build a Python environment
I tried to make "Sakurai-san" a LINE BOT with API Gateway + Lambda
I want to sort a list in the order of other lists
I made a program to notify you by LINE when switches arrive
I tried to touch the COTOHA API
I want to display the progress bar
I want to identify the alert email. --Is that x a wildcard? ---
I tried to send a registration completion email from Gmail with django.
I want to make an automation program!
I tried to make a Web API
I made a program to check the size of a file in Python
Python: I want to measure the processing time of a function neatly
I want to handle the rhyme part2
I want to handle the rhyme part5
I want to handle the rhyme part4