
Chatbot (聊天機器人) 是最有趣的 Python 應用之一。無論是 Discord、Telegram 還是 Line,Python 都有強大的 SDK 支援。
本章以 Discord 為例,因為它的 API 對開發者最友善,且完全免費。
1. 準備工作
- 到 Discord Developer Portal 建立一個 Application。
- 在 “Bot” 分頁點擊 “Add Bot”。
- 複製 TOKEN (這是機器人的靈魂,絕對不能洩漏!)。
- 在 “OAuth2” -> “URL Generator” 勾選 “bot”,並給予權限 (例如 Send Messages),產生邀請連結。
- 貼上連結,把機器人邀請到自已的伺服器。
2. 安裝 discord.py
pip install discord.py
3. Hello Bot!
這是一個基於 asyncio 的框架,所以你會看到很多 async/await。
# bot.py
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
# 設定 Intent (意圖),讓機器人有權限讀取訊息內容
intents = discord.Intents.default()
intents.message_content = True
# 定義指令前綴為 "!"
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'目前登入身分:{bot.user}')
@bot.command()
async def helloworld(ctx):
# 當使用者輸入 !helloworld 時觸發
await ctx.send('Hello! 我是 Python 機器人 🤖')
@bot.command()
async def repeat(ctx, *, message):
# 重複使用者的話
await ctx.send(f'你剛才說:{message}')
bot.run(TOKEN)
執行 python bot.py,你的機器人就會上線了!試著在頻道輸入 !helloworld 看看。
4. 進階:聽懂關鍵字 (Event Listener)
除了指令,我們也可以監聽所有訊息 (例如髒話過濾器)。
@bot.event
async def on_message(message):
# 避免機器人自己跟自己講話陷入無窮迴圈
if message.author == bot.user:
return
if 'python' in message.content.lower():
await message.channel.send('Python 是世界上最棒的語言!🐍')
# 重要:如果覆寫了 on_message,要補這行才能讓 commands 繼續運作
await bot.process_commands(message)
5. 其他平台:Line Bot
如果你比較想寫 Line Bot,流程大同小異:
- 去 Line Developers Console 申請 Channel。
- 安裝
line-bot-sdk。 - 但 Line Bot 需要一個 Webhook URL (公開的 HTTPS 網址)。
- 你需要使用 FastAPI 或 Flask 架設一個網頁伺服器來接收 Line 的 POST 請求。
# Line Bot 概念範例 (需搭配 FastAPI)
@app.post("/callback")
async def callback(request: Request):
# 驗證湊章 -> 解析事件 -> 回覆訊息
...
6. 總結
寫機器人是練習 AsyncIO 和 API 互動 的絕佳專案。你可以結合前幾章的知識:
- 結合 Requests (Ch 24):製作天氣預報機器人。
- 結合 NumPy/Pandas (Ch 26-28):製作股票分析機器人。
- 結合 OpenAI (Ch 30):製作 ChatGPT 聊天機器人。
下一章,我們將進入本教學的最終高潮——Capstone Project:打造個人金融儀表板!我們將從零開始,把所有學過的武功全部串起來!
延伸閱讀: