2025年4月17日 星期四

Python 學習筆記 : 用 Telegram 傳送科技新聞摘要

今天持續修復之前依賴 LINE Notify 推播訊息的爬蟲程式, 這次輪到去年大約這個時候寫的科技新聞網站爬蟲, 它主要是透過 technews-tw 套件去爬三個知名的科技新聞網站 (ithome 電腦報, business 數位時代, inside 硬塞的) 的重要新聞並做成摘要推播到手機, 作法參考 :


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


本篇旨在將原先由爬蟲機器人推播到 LINE 的科技新聞摘要改成推播到 Telegram 而已, 原程式 technews_2.py (LINE Notify 版) 修改為如下之technews_3.py (Telegram 版) : 

# technews_3.py
import time
import requests
from technews import TechNews
import asyncio 
from telegram import Bot  

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

def get_today_news(tn):
    msg=[]
    news=TechNews(tn)
    try:
        today_news=news.get_today_news()
        time.sleep(5)
        if today_news['news_counts'] > 0:
            msg.append(f'@ {tn} ({technews[tn]})')
            news_contents=today_news['news_contents']
            the_date=''
            n=0
            for key in news_contents:    
                contents=news_contents[key]
                title=f'❖ {contents["title"]}'
                msg.append(title)
                msg.append(f'▶ {contents["link"]}')
                the_date=contents["date"]
                n += 1
                if n >= 5:
                    break
            msg.insert(0, f'\n今日科技新聞 ({the_date})')        
    except Exception as e:
        print(e)
    return '\n'.join(msg)

if __name__ == '__main__':
    technews={'ithome': '電腦報',
              'business': '數位時代',
              'inside': '硬塞的'}
    msg=[]
    token='Telegram Bot API Token'
    chat_id='Telegram Chat ID'    
    for tn in technews:    
        msg=get_today_news(tn) 
        print(msg)
        print(f'訊息長度={len(msg)} 字元')
        if len(msg):
            if asyncio.run(telegram_send_text(msg)):
                print('訊息傳送成功!')
            else:
                print('訊息傳送失敗!')
        else:
            print(f'{technews[tn]} ({tn}) 無資料')

上面 token 與 chat_id 須填入自己的 Telegram 權杖與聊天室識別碼, 執行結果如下 :

>>> %Run technews_3.py   

今日科技新聞 (2025-04-17)
@ ithome (電腦報)
❖ Google影片生成Veo 2推向付費版Gemini Whisk圖生影片服務上線
▶ https://www.ithome.com.tw/news/168452
訊息長度=118 字元
訊息傳送成功!

訊息長度=0 字元
數位時代 (business) 無資料

訊息長度=0 字元
硬塞的 (inside) 無資料

測試時只爬到 iThome 一篇新聞, 查看 Telegram App 有收到該則訊息 : 




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

pi@raspberrypi:~ $ sudo chmod +x /home/pi/technews_3.py   
pi@raspberrypi:~ $ ls -l technews_3.py    
-rwxr-xr-x 1 pi pi 1851  4月 17 06:52 technews_3.py

這樣就可以用 python3 執行它了 : 

pi@raspberrypi:~ $ python3 technews_3.py   

今日科技新聞 (2025-04-17)
@ ithome (電腦報)
❖ 蘋果修補已被用於實際攻擊iPhone的CoreAudio、RPAC零時差漏洞
▶ https://www.ithome.com.tw/news/168453
❖ Google影片生成Veo 2推向付費版Gemini Whisk圖生影片服務上線
▶ https://www.ithome.com.tw/news/168452
訊息長度=199 字元
訊息傳送成功!

訊息長度=0 字元
數位時代 (business) 無資料

訊息長度=0 字元
硬塞的 (inside) 無資料

這次取得了 iThome 兩則新聞, App 收到的訊息如下 : 




接下來修改 crontab 將原先執行的 technews_2.py 改成 technews_3.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.py
0 13 * * * /usr/bin/python3 /home/pi/ksml_books_8.py

這個爬蟲機器人會在每天 12:01 與 17:01 時各執行一次. 

沒有留言 :