2025年7月24日 星期四

Python 學習筆記 : 網頁爬蟲實戰 (十八) 擷取隨機的格言 (中)

前一篇測試中利用格言爬蟲從網路上擷取隨機格言 (英文), 然後透過 Gemini API 將其翻譯為繁體中文組成中英雙語格言字串, 最後再利用 Google STMP 郵件伺服器將每日格言寄到指定的 Email 信箱. 本篇則是要將這個 dailly_quote 程式改寫為傳送 Telegram 訊息. 

本系列全部測試文章索引參考 :


關於使用 Telegram Bot API 傳訊息方法參考 :


每日格言程式修改如下 :

# dailly_quote.py
import requests
import google.generativeai as genai

def get_quote():
    url='https://zenquotes.io/api/random'
    try:
        res=requests.get(url, timeout=10)
        data=res.json()
        return data[0]['q'], data[0]['a']  # 成功傳回 (quote, author)
    except Exception as e:
        return None, f'Failed to fetch quote: {e}'  # 失敗傳回 (None, '失敗訊息')
    
def translate_quote(quote, api_key):
    genai.configure(api_key=api_key)
    model=genai.GenerativeModel('gemini-2.0-flash')
    prompt=f'請將以下英文翻譯為繁體中文, 只要翻譯一次即可:{quote}'
    try:
        reply=model.generate_content(prompt)
        return reply.text.strip().strip('\"\n ')  # 清除結尾開頭之雙引號跳行與空格
    except Exception as e:
        return f'格言翻譯失敗:{e}'
 
def bilingual_quote(quote, quote_zh_tw, author):
    return f'早安! 今日格言:\n「{quote_zh_tw}」\n{quote}\n—— {author}'

def telegram_msg(token, chat_id, text):
    url=f'https://api.telegram.org/bot{token}/sendMessage'
    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(f'Telegram API Error: {result}')
                return False
    except requests.exceptions.RequestException as e:
        print(f'Request error: {e}')
        return False

# 取得每日格言與其中文翻譯
quote, author=get_quote()
gemini_api_key='我的 Gemini API Key'
quote_zh_tw=translate_quote(quote, gemini_api_key)
msg=bilingual_quote(quote, quote_zh_tw, author)
# 用 Telegram Bot API 傳訊息
token='我的 Telegram 金鑰'
chat_id='我的 Telegram chat id'
telegram_msg(token, chat_id, msg) 

此處因為爬蟲本身就要用到 requests 模組, 所以 Telegram Bot API 就使用 RESTful API 就好 (當然也可以用 Bot 物件來做), 結果如下 :




嗯, 效果還不錯. 

沒有留言 :