--I want to send individual messages to users who have registered as friends. --I want to do it programmatically.
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.
――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.
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.
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.
It looks like this when illustrated. If you look at the figure, you can see why you need a server.
It is not the "LINE official account" that sends messages to each user. It's a "channel".
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.
Let's proceed on the premise that "LINE official account" and "provider" have already been created.
Once you have created a channel and registered as a friend, you can talk on https://manager.line.biz/ at this point.
Get the "Channel Secret" and "Access Token" from the channel preferences.
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.
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()
# 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
.
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.
I found that the upload was successful.
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 ....
There is a QR code at the bottom of the channel preferences page, from which you can register this channel as a friend.
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.
In my_flask_script.py, ʻapp.logger.infooutputs the information sent to this script. You can check it with
heroku 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
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!'))
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