最后活跃于 10 months ago

這段程式碼提供了一個 TelegramNotifier 類別,透過 Telegram Bot API 發送訊息到指定的聊天 ID (chat_id),並透過 loguru 記錄發送狀態。程式會從環境變數載入 Bot Token 和 Chat ID,並在啟動時發送通知,適用於自動化系統監控或事件提醒。

timmy 修订了这个 Gist 10 months ago. 转到此修订

没有任何变更

timmy 修订了这个 Gist 10 months ago. 转到此修订

没有任何变更

timmy 修订了这个 Gist 10 months ago. 转到此修订

没有任何变更

timmy 修订了这个 Gist 10 months ago. 转到此修订

2 files changed, 54 insertions

.env(文件已创建)

@@ -0,0 +1,2 @@
1 + TELEGRAM_BOT_TOKEN=你的_bot_token
2 + TELEGRAM_CHAT_ID=你的_chat_id

telegram_notifier.py(文件已创建)

@@ -0,0 +1,52 @@
1 + from telegram import Bot
2 + import asyncio
3 + from loguru import logger
4 + from dotenv import load_dotenv
5 + import os
6 +
7 + # 載入環境變數
8 + load_dotenv()
9 +
10 + class TelegramNotifier:
11 + def __init__(self, token: str, chat_id: int):
12 + """
13 + 初始化 TelegramNotifier 實例。
14 +
15 + :param token: Telegram Bot 的 API Token。
16 + :param chat_id: 接收通知的目標 chat_id。
17 + """
18 + self.bot = Bot(token=token)
19 + self.chat_id = chat_id
20 +
21 + async def send_notification(self, message: str):
22 + """
23 + 發送通知至目標 chat_id。
24 +
25 + :param message: 通知內容。
26 + """
27 + try:
28 + await self.bot.send_message(chat_id=self.chat_id, text=message)
29 + logger.info(f"通知已發送至 chat_id: {self.chat_id}")
30 + except Exception as e:
31 + logger.error(f"通知發送失敗: {e}")
32 +
33 + async def main():
34 + # 從環境變數載入配置
35 + TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
36 + CHAT_ID = int(os.getenv("TELEGRAM_CHAT_ID"))
37 +
38 + if not TOKEN or not CHAT_ID:
39 + logger.error("環境變數未正確配置,請檢查 TELEGRAM_BOT_TOKEN 和 TELEGRAM_CHAT_ID。")
40 + return
41 +
42 + # 建立 TelegramNotifier 實例
43 + notifier = TelegramNotifier(token=TOKEN, chat_id=CHAT_ID)
44 +
45 + # 發送啟動通知
46 + await notifier.send_notification("機器人啟動成功,這是一則通知!")
47 +
48 + if __name__ == "__main__":
49 + # 設定 Loguru 日誌輸出格式與檔案
50 + logger.add("notifier.log", rotation="1 MB", level="DEBUG", format="{time} {level} {message}")
51 + asyncio.run(main())
52 +
上一页 下一页