LoginSignup
1
5

More than 3 years have passed since last update.

スクレイピング⇒Google Spreadsheet⇒条件付きでLINE通知

Last updated at Posted at 2019-06-19

背景

欲しいデータを定期でスクレイピングしてローカルのCSVに保存することは結構あるし、がっつり開発するときはBigqueryに入れる。ただスマホから確認できないのは不便な時もあるし、ちょっとしたデータならSpreadSheetに書き込めばいいのかなと思った。
それから定期的に追いかけているデータが大きく変動した時にLineに通知が来ると安心である。

噛み砕いて言うならば理想は
GCEでデータを取得⇒SpreadSheetに書き込み⇒条件によってLine通知
である。

今回はpythonを使ってSpreadsheetに書き込み、Line通知について書く。

GoogleSpreadsheetに接続

この記事を参考に設定した。
https://qiita.com/akabei/items/0eac37cb852ad476c6b9

やったことは、

  • google driveのAPI設定
  • google spread sheetのAPI設定
  • google spread sheetのサービスアカウントの追加(jsonのダウンロード)
  • spreadsheetの編集権限をjsonファイルの中のmailアドレスに付与

コードを書いた


pip install gspread oauth2client
spreadsheet.py
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import time

scope = ['https://spreadsheets.google.com/feeds',
        'https://www.googleapis.com/auth/drive']

credentials = ServiceAccountCredentials.from_json_keyfile_name('jsonのpath', scope)
gc = gspread.authorize(credentials)

workbook = gc.open('SpreadSheetの名前')
sh = workbook.worksheet('シートの名前')
values_list = sh.col_values('1')
i = len(values_list) +1

#カラムA,B,Cに無限にデータを入れていく。
while True:
    sh.update_acell('A'+str(i),データA)
    sh.update_acell('B'+str(i),データB )
    sh.update_acell('C'+str(i),データC)
    i += 1
    time.sleep(10)

特に意味はないコード
カラムAの最後列の番号を取得して、カラムA,B,Cに無限にデータを入れていく。

Line (Line Notify) と接続

下記のリンクからLine Notifyの登録をする。
https://notify-bot.line.me/ja/

アカウント作成後、マイページからAPIを発行
連絡先は1対1で連絡を選択した。

コードを書いた

line_notice.py
import requests

def notice(message):
    line_notify_token = '発行したAPI'
    line_notify_api = 'https://notify-api.line.me/api/notify'


    payload = {'message': message}
    headers = {'Authorization': 'Bearer ' + line_notify_token}  # 発行したトークン
    line_notify = requests.post(line_notify_api, data=payload, headers=headers)

まとめ

spreadsheet.pyの中にif文で条件分岐をして、notice()を呼び出せばいける。

安心感がある。

1
5
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
1
5