搜尋此網誌

2026年1月20日 星期二

Line 美元匯率通知

緣起:


    忘了哪天,反正就不久前,我姐跟我說,如果美元的匯率到 30 以下時,通知她一下,她想換錢。這就讓我開始思考,能不能寫個程式,當匯率 30 以下時,用 Line Bot 通知我一聲。

    之前還在工作時,工作上有需求,所以有弄個 Line 的官帳來玩,詳細可以看那些上了 LINE API tag 的文章。


Currency Freak API:


    我選用這個 API 來查匯率,它的免費方案每個月可以有 1000 次的 request,匯率的變動不會很頻繁,2 小時檢查一次就夠了,所以一天 12 次 request,用一個月也不會爆。

    用 google 帳號即可註冊,然後就可以拿到 API Key 了


    我看了看官方 api 文件,如果想知道最新的匯率,打這 api

https://api.currencyfreaks.com/v2.0/rates/latest?apikey={你的api key}&symbols=TWD

    我只需要美元台幣的匯率,所以加上 symbols=TWD 的條件,查匯率的這段就 ok 了。


Python 程式:


    弄個 pyenv


    我把一些設定跟 api key 之類的東西統一放到 appsettings.json,檔案是這樣

{
	"line_api_push":"https://api.line.me/v2/bot/message/push",
	"exchange_api_rate":"https://api.currencyfreaks.com/v2.0/rates/latest",
	"rate_threshold":"30",
	"secret":{
		"line_token":<我的長期line api token>,
		"exchange_api_key":<Currency Freak api key>,
		"my_line_id":<我的Line ID>
	}
}

    然後是 main.py 的程式碼

import json
import requests
from datetime import datetime

appsettings={}

def get_exchange_rate():
	# get USD/TWD exchange rate
	api_request=requests.get(f"{appsettings['exchange_api_rate']}?apikey={appsettings['secret']['exchange_api_key']}&symbols=TWD")
	result_json=json.loads(api_request.text)
	return float(result_json["rates"]["TWD"])

def line_notify_message(message):
	#send me a message
	headers={
		"Content-Type":"application/json",
		"Authorization": f"Bearer {appsettings['secret']['line_token']}" 
	}
	
	now=datetime.now()
	
	body_contents={
		"to": appsettings['secret']['my_line_id'],
		"messages":[
			{
				"type":"text",
				"text": message
			}
		]
	}
	
	api_request=requests.post(appsettings['line_api_push'], headers=headers, data=json.dumps(body_contents))
	print(api_request.text)
	
	

if __name__ == "__main__":
	#load settings
	with open('appsettings.json') as f:
		appsettings = json.load(f)
	
	TWD=get_exchange_rate()
	rate_threshold=float(appsettings['rate_threshold'])
	
	#notify if USD to TWD exchange < threshold
	if rate_threshold > TWD:
		line_notify_message(f'當前每元:{TWD}新台幣')


    有用到 requests 的套件,這程式很單純,先是打 Currency Freak API,確定美元 to 台幣小於 30 後,打 Line 的 API,向我通知。

Line API 有點忘了怎麼用,所以有先測試看看傳日期來練習

    

crontab 排程:


    借這個機會來練習一下 Linux 的排程,用 crontab,第一次看到它是在鳥哥的LINUX書,很久之前了,那時也沒實際動手操作過,看到那一串指令就有點怕。現在仔細看了看說明後,發現它其實還蠻簡單好懂的。

    我想要每兩小時執行一次我的 python 程式碼,寫成這樣即可

0 */2 * * * /home/birdshiu/Program/exchange-line-notify/bin/python3 /home/birdshiu/Program/exchange-line-notify/main.py

    我在測試時,最前面的時間條件是先寫成 */1 * * * *,每分鐘跑一次,要確認能不能正常執行.....,沒有,我 Line 一直沒跳通知,我想說,我是不是應該要把執行 python 的部份寫成 shell scrip,再用 crontab 跑那 script 才對?所以我在專案下新增一個 run.bash

#!/bin/bash
./bin/python3 ./main.py

    改一下 crontab

*/1 * * * * /home/birdshiu/Program/exchange-line-notify/run.bash

    嗯....,還是沒結果,問了一下 gpt,它跟我說可以試著把錯誤結果輸出 log,再修改一下 crontab

*/1 * * * * /home/birdshiu/Program/exchange-line-notify/run.bash >> /home/birdshiu/cron.log 2>1&

    等 log 檔生出來後,我查看


    哦,那我大概知道是啥問題了,我 python 程式在讀 appsettings.json 時是用相對路徑,我以為用 shell script 執行 python 程式時,它預設的當前路徑會是 shell script 的所在路徑,但並不會如此,所以我還要在 shell script 加上 cd 的指令,把 script 改成

#!/bin/bash
cd /home/birdshiu/Program/exchange-line-notify
./bin/python3 ./main.py

    測試後沒問題,Yeah ~~,最後把 crontab 的時間條件修回每兩小時一次,這個專案就完成了(灑花


沒有留言:

張貼留言