LoginSignup
0
1

More than 1 year has passed since last update.

Pythonで処理したデータをLineで通知する

Last updated at Posted at 2021-11-11

前提

こちらは前回の続きになります。
「スクレイピングしたニュースタイトルを形態素解析してwordCloudを作成する」
https://qiita.com/yu_ku/items/d3b1ebda57ab9543eef6

今回やること

前回までで下記のことを行いました。今回は①と②をLineNotifyを使用してLineで通知させたいと思います。
①スクレイピングしたニュースからURLとタイトルを取得
②①を形態素解析してwordcloudを作成

アクセストークンを取得する

まずは下記からLINE Notify APIを登録して使えるようにします。
https://notify-bot.line.me/ja/

以下のページにわかりやすいやり方が書いてあります。
https://qiita.com/iitenkida7/items/576a8226ba6584864d95

notify.pyを作成して、Line通知の処理を記述する

import requests
import settings

LINE_API_KEY = settings.LINE_NOTIFY
MESSAGE_SIZE_LIMIT = 1000

# スクレイピングしたタイトルとURLを通知する(テキスト)
def line_notify_message(message):
  line_notify_token = LINE_API_KEY # 発行したアクセストークン
  line_notify_api = 'https://notify-api.line.me/api/notify'
  payload = {'message': message}
  headers = {'Authorization': 'Bearer ' + line_notify_token}
  message_length = len(message)
  i = 0
  while message_length > 0:
      if i == 0:
          buf = message[:MESSAGE_SIZE_LIMIT]
      else:
          buf = message[MESSAGE_SIZE_LIMIT * i:MESSAGE_SIZE_LIMIT * (i+1)]
      payload = {"message" :  buf}
      i += 1
      message_length -= MESSAGE_SIZE_LIMIT

      r = requests.post(line_notify_api, headers = headers, params = payload)

      if r.status_code != 200 :
            pass # エラー処理

# 作成したwordCloudを通知する(画像)
def line_notify_file(file):
  line_notify_token = LINE_API_KEY # 発行したアクセストークン
  line_notify_api = 'https://notify-api.line.me/api/notify'
  headers = {'Authorization': 'Bearer ' + line_notify_token}
  data = {'message': 'Morphological analysis'}
  files = {'imageFile': open(file,'rb')}
  result = requests.post(line_notify_api, headers = headers, data = data, files = files)

main.pyでnotify.pyを呼び出す

import notify
# Line通知
notify.line_notify_message(cr_hatena[0])
notify.line_notify_message(cr_hacker_news[0])
notify.line_notify_file((wordcloud_path + str(time) + ".png"))

上記を実行すると指定した部屋にLineの通知が来ていると思います。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1