[PYTHON] How to send a message to LINE with curl

Lottery

Trigger

I decided to create an app that automatically sends messages with LINE, so I decided to use the LINE API. I started working thinking that I could send a message with curl. As a result, I was able to send a message with curl using LINE_API + AWS (APIGateway + lambda). I wanted to make a note of the know-how at that time, and I personally didn't get the information that was already there, so I posted it.

Create a LINE account

First, create a LINE account normally. LINE can create an account without registering an "ID" and "password" in the system, but please register an "ID" and "password" to create a LINE account. If you have already created it, this work is unnecessary.

BOT creation and operation check

Next, create a BOT. After all, create an account for development. When you look at the official website, you will see terms such as BOT, provider, and channel. Those who understand the details can clearly distinguish it, but I could only understand it somehow, probably because of my lack of understanding. In conclusion, you can think of all accounts as ≒ (nearly equal) accounts at first.

https://developers.line.biz/ja/docs/messaging-api/overview/

Then add the provider to your provider list. It's okay for you to understand that creating a new LINE account for automatic sending and replying.

https://developers.line.biz/console/channel/1653419974/basic/

20191103_1.jpg

20191103_2.jpg

Once created, make sure you can chat with your development account. There is a QR code at the bottom of the screen, so let's invite to talk with your first account you created.

Get destination ID

After confirming the operation of the BOT, set the URL of the webhook event to send a message to the existing chat room. The reason why this work is necessary is that when sending a message, the user ID and room ID of the destination are required. It was said that these cannot be obtained by normal LINE user operations, and cannot be easily obtained using the LINE app.

20191103_3.jpg

Change the part of the red frame above.

What is a webhook event? It is a function that sends a fixed message to the set URL when a message is received.

This is where AWS API Gateway + lambda comes in. Set the URL of API Gateway in the webhook URL.

The source of lambda should be able to use the sample below as it is. It's python.

lambda_function.py

import json
import traceback

# ==================================================
#The first function to be called on lambda
# ==================================================
def lambda_handler(event, context):
    try:
        #Log output of request contents
        log(event, 'receive request.')
        createResponse()
        
    except:
        #When an unexpected error occurs
        logger.log(traceback.format_exc())
        traceback.print_exc()
        
        return createResponse()

# ==================================================
#Generate a response
# ==================================================
def createResponse():
    return {
            'isBase64Encoded': False,
            'statusCode': 200,
            'headers': {},
            'body': {}
        }

# ==================================================
#Log output
# ==================================================
def log(event, msg):
    print('EVENT >> ' + str(event))
    print('LOG >> ' + str(msg))

API Gateway settings look like this

20191103_5.jpg

The log is output to cloudwatch. UserId and roomId should be output in this. You can specify these as destinations.

20191103_6.jpg

Image diagram for understanding

Various things have come out. I tried to make it easy to understand. Strictly speaking, there are many different points, but I think it's easy to understand if I think this way based on my own judgment and prejudice, so I created it.

20191103_4.jpg

① http telegram is sent from the mobile phone (= message is sent by LINE) ② The server sends the received message to the mobile phone / BOT in the room. ③ POST telegram is sent to the URL registered as the destination URL of the webhook in BOT.

Send a message with curl

Finally, I will send a message with curl. Sending a message on LINE is called push, and since the API is open to the public, send it according to this. https://developers.line.biz/ja/reference/messaging-api/#send-push-message

By the way, I used a chrome extension called ASR. Anything that can send an http telegram will do.

Method POST URL https://api.line.me/v2/bot/message/push Content-Type application/json Authorization Bearer Issued authorization Token

{
  "to":Obtained ID,
  "messages":[
        {
            "type":"text",
            "text":"You can send it automatically like this."
        }
    ]
}

Recommended Posts

How to send a message to LINE with curl
How to install NPI + send a message to line with python
Send a message to LINE with Python (LINE Notify)
[Python] How to draw a line graph with Matplotlib
I want to send a message from Python to LINE Bot
How to add a package with PyCharm
Send a message from Python to Slack
How to send a request to the DMM (FANZA) API with python
Send a message from Slack to a Python server
How to read a CSV file with Python 2/3
How to draw a 2-axis graph with pyplot
How to develop a cart app with Django
How to make a dictionary with a hierarchical structure.
How to draw a vertical line on a heatmap drawn with Python seaborn
How to create a Kivy 1-line input box
How to create a multi-platform app with kivy
[LINE Messaging API] I want to send a message from the program to everyone's LINE
How to convert / restore a string with [] in python
How to create a submenu with the [Blender] plugin
How to get a logged-in user with Django's forms.py
How to convert a class object to a dictionary with SQLAlchemy
How to do zero-padding in one line with OpenCV
How to make a shooting game with toio (Part 1)
[Python] How to create a 2D histogram with Matplotlib
[Python] How to draw a scatter plot with Matplotlib
How to call a function
Send a signal to subprocess
How to update with SQLAlchemy?
How to cast with Theano
How to hack a terminal
How to Alter with SQLAlchemy?
How to separate strings with','
How to RDP with Fedora31
How to Delete with SQLAlchemy?
Send a push message to the LINE Bot when the LTE-M Button is pressed [SORACOM]
How to deploy a web app made with Flask to Heroku
How to make a Cisco Webex Teams BOT with Flask
How to embed multiple embeds in one message with Discord.py
How to put a hyperlink to "file: // hogehoge" with sphinx-> pdf
How to kill a process instantly with Python's Process Pool Executor
How to convert an array to a dictionary with Python [Application]
How to output a document in pdf format with Sphinx
How to create a flow mesh around a cylinder with snappyHexMesh
How to print characters as a table with Python's print function
How to make a simple Flappy Bird game with pygame
Post a message to Google Hangouts Chat with a thread (Python)
How to display a list of installable versions with pyenv
How to extract other than a specific index with Numpy
A story about how to deal with the CORS problem
How to build a python2.7 series development environment with Vagrant
Create a message corresponding to localization with python translation string
How to cancel RT with tweepy
How to make a Japanese-English translation
How to write a Python class
Python: How to use async with
How to put a symbolic link
How to use virtualenv with PowerShell
How to deal with imbalanced data
How to install python-pip with ubuntu20.04LTS
How to make a slack bot
How to create a Conda package