Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9322

[Node.js][LINE] 毎日 LINE に花粉情報を通知する

$
0
0

概要

に引き続き、LINE Notifyを使って LINE に通知するシリーズです!

花粉 (デス・パウダー)が辛い季節ですね :disappointed_relieved:花粉情報が非常に気になる毎日なので、当日の花粉情報を LINE に通知するようにしました。

方法

バージョン情報

  • Node.js 14.15.5
  • Playwright 1.9.1
  • axios 0.21.1

コード

まず Playwrightを使ってヘッドレス Chrome を操作し、Yahoo! JAPAN の花粉情報のスクリーンショットを撮影します。花粉情報のページの URL は任意の地域のものに書き換えてください。なお、本当は 日本気象協会 tenki.jpの花粉情報を通知したかったのですが、Playwright でのアクセスがタイムアウトになってしまうので諦めました。スクレイピング対策されているのかもしれませんね。

そして axiosを使って LINE Notify の API を叩き、LINE に通知します。LINE Notify はメッセージを送信できるだけでなく、画像を送信することもできます。

~/workspace/death_powder_forcast/main.js
const{chromium}=require('playwright');constfs=require('fs');constaxios=require('axios');constFormData=require('form-data');// Yahoo! JAPAN の福岡市中央区の花粉情報。constPOLLEN_FORCAST_URL='https://weather.yahoo.co.jp/weather/pollen/10/40/40133/';constSCREENSHOT_FILEPATH='./today.png';constLINE_NOTIFY_TOKEN='ここに LINE Notify のトークンを入力する。';// 指定した要素のスクリーンショットを撮影する。consttakeScreenshot=async({url,selector,filepath})=>{// Raspberry Pi では ARM 用の Chromium を使用する必要があるので executablePath を指定する。constbrowser=awaitchromium.launch({executablePath:'/usr/bin/chromium-browser'});constcontext=awaitbrowser.newContext();constpage=awaitcontext.newPage();awaitpage.goto(url);constelement=awaitpage.$(selector);awaitelement.screenshot({path:filepath});awaitbrowser.close();};// LINE Notify に通知する。constnotifyLINE=async({token,message,imageFilepath=null})=>{constLINE_NOTIFY_API_URL='https://notify-api.line.me/api/notify';constformData=newFormData();formData.append('message',message);if(imageFilepath){formData.append('imageFile',fs.createReadStream(imageFilepath));}constheaders={'Authorization':`Bearer ${token}`,...formData.getHeaders()};awaitaxios.post(LINE_NOTIFY_API_URL,formData,{headers});};(async()=>{awaittakeScreenshot({url:POLLEN_FORCAST_URL,selector:'.pollenFlying_city_day:first-child',filepath:SCREENSHOT_FILEPATH});if(!fs.existsSync(SCREENSHOT_FILEPATH)){process.exit(1);}awaitnotifyLINE({token:LINE_NOTIFY_TOKEN,message:'今日の花粉情報です。',imageFilepath:SCREENSHOT_FILEPATH});fs.unlinkSync(SCREENSHOT_FILEPATH);})();

上記の Node.js ファイルを cron で定期実行します。通知してほしい時刻を指定してください。

crontab
# 設定例
0 7 *** /bin/bash -c'export PATH=$HOME/.nodenv/bin:$PATH; eval "$(nodenv init -)"; cd $HOME/workspace/death_powder_forcast; node main.js'

これで通知が届きました 💖


Viewing all articles
Browse latest Browse all 9322

Trending Articles