Skip to content

建立 2026-09-15 更新 2026-09-15

用 Python 開發 Bot

有了 Token 並理解 Bot API 的運作方式後,這一頁用開源套件 python-telegram-bot 示範一支最小可行的 Bot:能回覆 /start 指令,也能重複傳回使用者傳來的文字。

安裝套件

pip install python-telegram-bot --upgrade

最小範例

bot.py
from telegram import Update
from telegram.ext import (
    ApplicationBuilder,
    CommandHandler,
    MessageHandler,
    ContextTypes,
    filters,
)

TOKEN = "在這裡貼上 BotFather 給你的 Token"


async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("哈囉!我是你的第一支 Telegram Bot。")


async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text(update.message.text)


if __name__ == "__main__":
    app = ApplicationBuilder().token(TOKEN).build()

    app.add_handler(CommandHandler("start", start))
    app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))

    app.run_polling()

執行 python bot.py 後,程式會用 Polling 方式持續向 Telegram 取得新訊息;用手機或電腦開啟與你 Bot 的聊天,傳送 /start 或任意文字測試看看。

程式邏輯拆解

  • ApplicationBuilder().token(TOKEN).build():用 Token 建立 Bot 應用程式實例。
  • CommandHandler("start", start):註冊處理器,當使用者傳送 /start 時執行 start 函式。
  • MessageHandler(filters.TEXT & ~filters.COMMAND, echo):註冊處理器,攔截「純文字、非指令」的訊息,交給 echo 函式處理。
  • app.run_polling():啟動主迴圈,不斷輪詢 Telegram 取得新的 Update

下一步可以嘗試

  • 加入更多 CommandHandler,實作 /help/menu 等指令,並用 BotFather 的 /setcommands 讓它們顯示在輸入框選單。
  • 改用 InlineKeyboardMarkup 加入按鈕,搭配 CallbackQueryHandler 處理點擊事件。
  • 正式上線時,將 run_polling() 改為 run_webhook(),並部署到有 HTTPS 的伺服器,對應 Webhook 的運作方式。

延伸影音教學

完整的實作過程可參考 影音教學:Bot 開發 中收錄的 Python Bot 教學影片。