2025年4月17日 星期四

Python 學習筆記 : 用 Telegram 傳送博客來 66 折優惠訊息

本篇旨在將原先由爬蟲推播到 LINE 的博客來 66 折優惠訊息改成推播到 Telegram, 原文參考 : 


關於 Telgram Bot API 用法參考下面的索引 : 


原程式 books.com.tw_66.py 修改為如下之 books.com.tw_66_telegram.py : 

# books.com.tw_66_telegram.py
import requests   
from bs4 import BeautifulSoup
import asyncio 
from telegram import Bot

async def telegram_send_text(text, parse_mode='HTML'):
    bot=Bot(token=token)
    try:
        await bot.send_message(
            chat_id=chat_id,
            text=text,
            parse_mode=parse_mode
            )
        return True
    except Exception as e:
        print(f'Error sending text: {e}')
        return False

def get_today_66():
    url='https://activity.books.com.tw/crosscat/ajaxinfo/' +\
        'getBooks66OfTheDayAjax/P?uniqueID=E180629000000001_94'
    try:
        res=requests.get(url)
        soup=BeautifulSoup(res.text, 'lxml') 
        book_url=soup.find('a').get('href', None)
        book_name=soup.find('img').get('alt', None)
        book_img=soup.find('img').get('src', None)
        book_price=soup.select_one('ul.price').get_text()
        book_price=book_price.replace('\n', '').replace('66', ' 66')
        msg=f'\n❖ {book_name}\n{book_price}\n▶ {book_url}'
        return msg 
    except Exception as e: 
        return None

if __name__ == '__main__':
    token='Telegram Bot API Token'
    chat_id='Telegram Chat ID'
    msg=get_today_66()
    print(msg)
    if msg:  
        if asyncio.run(telegram_send_text(msg)):
            print('訊息傳送成功!')
        else:
            print('訊息傳送失敗!')
    else:
        print(f'無資料')    

注意, 此處將 telegram_send_text() 的 parse_mode 參數預設值改為 'HTML', 因為若是用 'Markdown' 會出現字元解析錯誤, 詢問 ChatGPT 答覆是若傳送的文字中含有不完整的 Markdown 語法時會讓 API 拋出例外, 因此程式中的 token 與 chat_id 須填入自己的 Telegram API 權杖與聊天室 ID, 執行結果如下 :

>>> %Run books.com.tw_66_telegram.py   

❖ 媽媽是房子(法國千頁獎童書大獎)
定價399元 66折優惠價263元
▶ https://www.books.com.tw/products/0010986635?loc=P_books66_title_002
訊息傳送成功!

查看 Telegram App 有收到這則推播訊息 :




將此程式上傳 Pi 3, 先用 chmod 指令將其改為可執行 (x 屬性) :

pi@raspberrypi:~ $ sudo chmod +x /home/pi/books.com.tw_66_telegram.py   
pi@raspberrypi:~ $ ls -l books.com.tw_66_telegram.py   
-rwxr-xr-x 1 pi pi 1446  4月 17 12:50 books.com.tw_66_telegram.py  

用 python3 指令執行 : 

pi@raspberrypi:~ $ python3 books.com.tw_66_telegram.py

❖ 媽媽是房子(法國千頁獎童書大獎)
定價399元 66折優惠價263元
▶ https://www.books.com.tw/products/0010986635?loc=P_books66_title_002
訊息傳送成功!

App 得到與上面一樣的訊息, 最後修改 crontab 中的執行程式為 books.com.tw_66_telegram.py 即大功告成 : 

pi@raspberrypi:~ $ crontab -e  
crontab: installing new crontab
pi@raspberrypi:~ $ crontab -l   
0 16 * * 1-5 /usr/bin/python3 /home/pi/twstock_dashboard_update.py
*/31 9-13 * * 1-5 /usr/bin/python3 /home/pi/yahoo_twstock_monitor_table_2.py
0 8,18 * * * /usr/bin/python3 /home/pi/btc_eth_prices_line_notify.py
1 12,17 * * * /usr/bin/python3 /home/pi/technews_3.py
0 9 * * * /usr/bin/python3 /home/pi/books.com.tw_66_telegram.py
0 13 * * * /usr/bin/python3 /home/pi/ksml_books_8.py


沒有留言 :