2026年3月25日 星期三

利用telegram來控制 crontab 任務的啟動或關閉

既然用了telegram bot就想說用這個tool來控制系統中的crontab任務列表
先查看crontab -l
再利用crontab -e

再透過 python code:
import logging
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.ext import Application, CommandHandler, CallbackQueryHandler, ContextTypes
from crontab import CronTab

# --- 設定區 ---
TOKEN = 'your bot token'
USER_ID = your chat id 不是字串

# 初始化日誌
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)

def get_cron_keyboard():
    cron = CronTab(user=True)
    keyboard = []
   
    for index, job in enumerate(cron):
        status_icon = "🟢 啟用中" if job.is_enabled() else "🔴 已暫停"
       
        # --- 自定義名稱邏輯 ---
        cmd = job.command
        if "email_notify_v2.py" in cmd:
            display_name = "任務通知 V2"
        elif "email_notify.py" in cmd:
            display_name = "任務通知 V1"
        else:
            # 如果不是以上兩個,就顯示指令的前 20 個字
            display_name = cmd.split('/')[-1][:20]
        # ---------------------

        label = f"{status_icon} | {display_name}"
        keyboard.append([InlineKeyboardButton(label, callback_data=str(index))])
   
    return InlineKeyboardMarkup(keyboard) if keyboard else None

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """驗證身分並列出所有任務清單"""
    if update.effective_user.id != USER_ID:
        return
   
    markup = get_cron_keyboard()
    if markup:
        await update.message.reply_text("📋 **當前系統排程清單**\n點擊按鈕即可切換 啟動/暫停:",
                                      reply_markup=markup, parse_mode='Markdown')
    else:
        await update.message.reply_text("目前系統中沒有任何 Crontab 任務。")

async def button_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """處理按鈕點擊:切換任務狀態"""
    query = update.callback_query
    if query.from_user.id != USER_ID:
        await query.answer("權限不足")
        return

    await query.answer()
    job_index = int(query.data)
   
    # 重新讀取並操作
    cron = CronTab(user=True)
    try:
        job = cron[job_index]
        # 切換開關
        job.enable(not job.is_enabled())
        # 寫回系統
        cron.write()
       
        # 更新訊息與按鈕狀態
        await query.edit_message_text(
            text="✅ **狀態已更新**\n點擊下方按鈕繼續管理:",
            reply_markup=get_cron_keyboard(),
            parse_mode='Markdown'
        )
    except IndexError:
        await query.edit_message_text("❌ 找不到該任務,可能已被手動刪除。")

if __name__ == '__main__':
    app = Application.builder().token(TOKEN).build()
   
    app.add_handler(CommandHandler("start", start))
    app.add_handler(CallbackQueryHandler(button_callback))
   
    print("Bot 啟動中... 請在 Telegram 輸入 /start")
    app.run_polling()

運作情形

這樣控制定時任務就方便了!!!

沒有留言:

張貼留言