Python TKinter 與 Telegram 交談
import tkinter as tk
from telegram import Update, Bot
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters, ContextTypes
import threading
import asyncio
import datetime
import pytz
# --- Telegram Bot 設定 ---
TOKEN = "你的 Bot Token"
TARGET_CHAT_ID = 你的 chat_id 數字
application = None
bot_loop = None
bot = Bot(token=TOKEN)
# 使用台灣時區(只用於時間顯示)
tz = pytz.timezone("Asia/Taipei")
# --- Tkinter GUI 設定 ---
root = tk.Tk()
root.title("Telegram Bot 對話介面")
root.geometry("460x500")
label = tk.Label(root, text="輸入訊息:", font=("Arial", 12))
label.pack(pady=(10, 0))
entry = tk.Entry(root, width=50)
entry.pack(pady=5)
send_button = tk.Button(root, text="發送")
send_button.pack(pady=5)
frame = tk.Frame(root)
frame.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
scrollbar = tk.Scrollbar(frame)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
message_box = tk.Listbox(frame, width=60, height=20, yscrollcommand=scrollbar.set)
message_box.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar.config(command=message_box.yview)
def log_message(text):
message_box.insert(tk.END, text)
message_box.yview(tk.END)
# --- 發送訊息 ---
def send_message():
text = entry.get().strip()
if not text:
log_message("請輸入訊息。")
return
async def _send():
try:
await bot.send_message(chat_id=TARGET_CHAT_ID, text=text)
root.after(0, lambda: log_message(f"[我] {text}"))
root.after(0, lambda: entry.delete(0, tk.END))
except Exception as e:
root.after(0, lambda: log_message(f"[錯誤] 發送失敗:{e}"))
if bot_loop:
bot_loop.call_soon_threadsafe(lambda: asyncio.create_task(_send()))
send_button.config(command=send_message)
entry.bind("<Return>", lambda e: send_message())
# --- 接收訊息處理 ---
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
sender = update.effective_user.first_name
text = update.message.text
timestamp = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
formatted = f"[{timestamp}] {sender}: {text}"
root.after(0, lambda: log_message(formatted))
async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("Bot 已啟動,歡迎對話!")
async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE):
print(f"[錯誤] Bot 發生例外:{context.error}")
# --- 啟動 Telegram Bot ---
def start_bot():
def bot_thread():
global application, bot_loop
bot_loop = asyncio.new_event_loop()
asyncio.set_event_loop(bot_loop)
async def bot_main():
global application
application = (
ApplicationBuilder()
.token(TOKEN)
.build()
)
application.add_handler(CommandHandler("start", start_command))
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
application.add_error_handler(error_handler)
print("Telegram Bot 已啟動並正在等待訊息...")
await application.initialize()
await application.start()
await application.updater.start_polling()
bot_loop.create_task(bot_main())
bot_loop.run_forever()
threading.Thread(target=bot_thread, daemon=True).start()
# --- 關閉視窗時停止事件迴圈 ---
def on_close():
if bot_loop:
bot_loop.call_soon_threadsafe(bot_loop.stop)
root.destroy()
root.protocol("WM_DELETE_WINDOW", on_close)
# --- 主程式啟動 ---
start_bot()
log_message("Bot 已啟動,準備接收與發送訊息。")
root.mainloop()
- 啟動程式。
- 在 Telegram 傳送
/start或任意訊息給你的 Bot。 - GUI 即時顯示訊息。
- 在 GUI 輸入訊息並按「發送」,Bot 回覆你。



沒有留言:
張貼留言