Easy Code Share > Python > Scraping > 3 Steps Line Notify API Inform Group Member by Token

3 Steps Line Notify API Inform Group Member by Token


Line Notify API with an authorized token allows web applications to occasionally fire information to registered people. If web applications act as services, these services are no longer passive. Services can actively pass messages to users on conditional events or by scheduled jobs. We use Python scripts to implement Line Notify in the post.

Line notify API makes auto notifications possible, and behaved like a bot. It is so important that we list 3 steps helping developers to implement Line notify with less efforts. You will learn the way to become a friend of Line Notify, generate access tokens, and use Python scripts to pass messages manually or automatically.

All codes here are not complicated, so you can easily understand even though you are still students in school. To benefit your learning, we will provide you download link to a zip file thus you can get all source codes for future usage.

Estimated reading time: 6 minutes

 

 

BONUS
Source Code Download

We have released it under the MIT license, so feel free to use it in your own project or your school homework.

 

Download Guideline

  • Prepare Python environment for Windows by clicking Python Downloads, or search a Python setup pack for Linux.
  • The pack of Windows version also contains pip install for you to obtain more Python libraries in the future.
 DOWNLOAD SOURCE

 

STEP 1
Line Notify Friend

To use Line Notify API, being a friend of Line Notify is the first step. Then invite your new friend to the target group. Members of this group will receive notifications from Line.

 

Login Line Notify

When you login the Line Notify website, you will be a friend of Line Notify. You should have a email linking to your phone number in Line app. If forgot, check Line settings in your mobile phone.

Login and Verification Before Using Line Notify API

There is a verification to be taken. Once done, Line Notify is your new friend.

 

Invite Line Notify to The Group

Remember to invite your new friend to the group you have joined. And then people in the group can receive real-time notifications from Line Notify.

 

STEP 2
Generate Token

Line Notify allow you to generate a token as the key to authorization. You can apply more than one token for variant purposes. Moreover, you can remove not used tokens.

 

Generate Access Token

Through the friend Line Notify, when you would like to fire a message to group members, you should have an access token associated with the group. Click the generate token button in “my page” and search for your group which has the friend Line Notify.

Alternatively, you can choose the default 1-on-1 chat group. Then notifications can be sent to only yourself.

Line Notify Select Group and Generate Token

When you submit and see the token, copy it to a secure place because of the notice “If you leave this page, you will not be able to view your newly generated token again. Please copy the token before leaving this page.”

 

Line Notify Token Complete

When generating token successfully, the Line Notify friend gives you some notices to welcome your participation.

Token Ready Notice

You can apply more than one token, or remove tokens. To remove tokens, click disconnect button on the website.

Token Removal

 

STEP 3
Web-Crawled Notice

Our example presents that web-crawled information upon preset conditions trigger event messages sending. We use Python scripts to crawl and send notifications manually. Once scheduled on Linux servers, it will be automatic.

 

Crawling Websites

We use the library Python requests to scrape the Yahoo stock website. Once getting data, BeautifulSoup parses them to find the price of Tesla, Inc. You can get more practices about BeautifulSoup in our previous article.

notify.py
 # Python Scraping using BeautifulSoup
import requests
from bs4 import BeautifulSoup
def get_span(id) :
    return info.find("span", attrs={"data-reactid": id}).string
the_url = "https://finance.yahoo.com/quote/TSLA/"
r = requests.get(the_url)
if r.status_code != 200:
    print('Download Err: '+r.url)
    exit()
soup = BeautifulSoup(r.text, "html.parser")
info = soup.find("div", attrs={"id": "quote-header-info"})
items = list()
items.append(info.find("h1").string)
items.append(get_span("9"))
items.append("{} {}".format(get_span("32"), get_span("33")))
items.append(get_span("35"))
notification = "\n".join(items)
print(notification)

The crawled result are as below.

$ python notify.py

Tesla, Inc. (TSLA)
NasdaqGS - NasdaqGS Real Time Price. Currency in USD
872.79 +32.98 (+3.93%)
At close: 4:00PM EST
{'status': 200, 'message': 'OK'}

 

Manual Notifications

With the secure token, request Line Notify API to send messages if conditions are satisfied in our Python codes. For example, if Telsa stock price is larger than 850, the crawled stuff are sent out. Each token determines a target group.

notify.py
token = "HUkpcDV6KJ2KMVmypDp3iVhcojmuuPbQn7bZbcJl9S1"
stock_price = float(get_span("32"))
if stock_price > 850:
    headers = {
        "Authorization": "Bearer " + token,
        "Content-Type": "application/x-www-form-urlencoded"
    }
    params = { "message": notification }
    r = requests.post("https://notify-api.line.me/api/notify", headers=headers, params=params)
    print(r.json())

The possible failed results are shown.

{'status': 401, 'message': 'Invalid access token'}

Check your mobile phone to find notifications.

Python Send Crawled Data to Line Notify

 

Auto Notifications

In Linux, you can schedule the command line, python notify.py daily at the time of 10 minutes after stock market closed. Thus auto system is running to report specified stock prices.

 # m h  dom mon dow   command

# Hourly check deamons
10 16 * * * python notify.py

 

Removing Token

The alternative Line Notify API revoke can remove your token if no longer necessary. It is simply shown below.

revoke.py
 # Line Notify Revoke
import requests
token = "HUkpcDV6KJ2KMVmypDp3iVhcojmuuPbQn7bZbcJl9S1"
headers = {
    "Authorization": "Bearer " + token,
    "Content-Type": "application/x-www-form-urlencoded"
}
params = { "message": "" }
r = requests.post("https://notify-api.line.me/api/revoke", headers=headers, params=params)
print(r.json())

Issue the command line to disconnect or remove the token.

$ python revoke.py

{'status': 200, 'message': 'OK'}

 

Line Notify in PHP

Alternatively, the PHP codes for Line Notify are as below. There is just a dummy message to send.

notify.php
<?php
line_notify('This is a dummy test');
function line_notify($msg) {
    $curl = curl_init();
    $token = "HUkpcDV6KJ2KMVmypDp3iVhcojmuuPbQn7bZbcJl9S1";
    curl_setopt_array($curl, array(
      CURLOPT_URL => 'https://notify-api.line.me/api/notify',
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => '',
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => 'POST',
      CURLOPT_POSTFIELDS => [ "message"=>$msg ],
      CURLOPT_HTTPHEADER => array(
        "Authorization: Bearer $token",
        "Content-Type: multipart/form-data"
      ),
    ));
    $str = curl_exec($curl);
    echo $str;
}
?>
$ php notify.php

{'status': 200, 'message': 'OK'}

 

FINAL
Conclusion

Line Notify API is secured by the authorized token. Through tokens, Python scripts send crawled information to the members of target group. You can find more in the official material, Line Notify API document.

Thank you for reading, and we have suggested more helpful articles here. If you want to share anything, please feel free to comment below. Good luck and happy coding!

 

Suggested Reading

Leave a Comment