| 1 | TELEGRAM_BOT_TOKEN=你的_bot_token |
| 2 | TELEGRAM_CHAT_ID=你的_chat_id |
| 3 |
telegram_notifier.py
· 1.6 KiB · Python
Originalformat
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())
| 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 | |
| 53 |