可惜免費的 LINE Notify 已於 4/1 結束服務, 所以我春假連假時研究了一下, 決定改用 Telegram Bot API 來傳訊息, 參考 :
今天把 reportip4.py 改成如下的 Telegram 版 :
# reportip5.py
import socket
import requests
def telegram_msg(token, chat_id, text):
url='https://api.telegram.org/bot{}/sendMessage'.format(token)
data={'chat_id': chat_id, 'text': text}
try:
with requests.post(url, data=data, timeout=10) as r:
r.raise_for_status() # 若 status_code != 2xx 會拋出例外
result=r.json()
if result.get('ok'):
print('Message sent successfully.')
return True
else:
print('Telegram API Error: {}'.format(result))
return False
except requests.exceptions.RequestException as e:
print('Request error: {}'.format(e))
return False
def private_ip(host_name='google.org'):
remote_ip=socket.gethostbyname(host_name)
cs=socket.socket()
cs.connect((remote_ip, 80))
return cs.getsockname()[0]
def public_ip():
hostname='https://api.ipify.org'
return requests.get(hostname).text
if __name__ == '__main__':
msg='\n外網: {}\n內網: {}'.format(public_ip(), private_ip())
token='Telegram 權杖'
chat_id='Telegram 聊天室識別碼'
result=telegram_msg(token, chat_id, msg)
if result:
print('Telegram 訊息發送成功!')
else:
print('Telegram 訊息發送失敗!')
由於這台 Pi 的 Python 版本為 3.5, 不支援 f 字串, 所以變數嵌入字串改用字串的 format() 方法, 用 nano 編輯好 reportip5.py 後用 chmod 將其改為可執行, 測試 OK :
pi@raspberrypi:~ $ nano reportip5.py
pi@raspberrypi:~ $ ls reportip5.py -ls
4 -rw-r--r-- 1 pi pi 1334 4月 7 21:53 reportip5.py
pi@raspberrypi:~ $ sudo chmod +x /home/pi/reportip5.py
pi@raspberrypi:~ $ ls reportip5.py -ls
4 -rwxr-xr-x 1 pi pi 1334 4月 7 21:53 reportip5.py
pi@raspberrypi:~ $ python3 reportip5.py
Message sent successfully.
Telegram 訊息發送成功!
檢查 Telegram App 果然有收到 IP 訊息 :
接下來修改 crontab, 將原先執行的 reportip4.py 改為 reportip5.py :
pi@raspberrypi:~ $ sudo crontab -e
crontab: installing new crontab
pi@raspberrypi:~ $ sudo crontab -l
0 * * * * sudo /usr/local/bin/checkwifi.sh
0 * * * * /usr/bin/python3 /home/pi/reportip5.py
經過一個晚上, 早上醒來檢視 Telegram 每小時整點都有正常收到訊息 :
哈哈, Telegram 還不錯用!
沒有留言 :
張貼留言