from telegram import Bot import asyncio from loguru import logger from dotenv import load_dotenv import os # 載入環境變數 load_dotenv() class TelegramNotifier: def __init__(self, token: str, chat_id: int): """ 初始化 TelegramNotifier 實例。 :param token: Telegram Bot 的 API Token。 :param chat_id: 接收通知的目標 chat_id。 """ self.bot = Bot(token=token) self.chat_id = chat_id async def send_notification(self, message: str): """ 發送通知至目標 chat_id。 :param message: 通知內容。 """ try: await self.bot.send_message(chat_id=self.chat_id, text=message) logger.info(f"通知已發送至 chat_id: {self.chat_id}") except Exception as e: logger.error(f"通知發送失敗: {e}") async def main(): # 從環境變數載入配置 TOKEN = os.getenv("TELEGRAM_BOT_TOKEN") CHAT_ID = int(os.getenv("TELEGRAM_CHAT_ID")) if not TOKEN or not CHAT_ID: logger.error("環境變數未正確配置,請檢查 TELEGRAM_BOT_TOKEN 和 TELEGRAM_CHAT_ID。") return # 建立 TelegramNotifier 實例 notifier = TelegramNotifier(token=TOKEN, chat_id=CHAT_ID) # 發送啟動通知 await notifier.send_notification("機器人啟動成功,這是一則通知!") if __name__ == "__main__": # 設定 Loguru 日誌輸出格式與檔案 logger.add("notifier.log", rotation="1 MB", level="DEBUG", format="{time} {level} {message}") asyncio.run(main())