快速開始
最後更新
把 go-bot 加進 Go module,並在單一平台跑起最小的回聲機器人。
前置需求
| 項目 | 需求 |
|---|---|
| Go | 1.25.0 以上(go.mod) |
| Telegram | 從 BotFather 取得的 bot token |
| Discord | Bot token,並在 Developer Portal 啟用 Message Content Intent |
| LINE | Channel secret、長效 channel access token,以及轉發到 webhook port 的公開 HTTPS URL |
Telegram 與 Discord 皆由 bot 往外連線,在 NAT 後也能執行。LINE 由平台把事件推到你的 server,因此需要可從外部連入的 HTTPS endpoint(本機測試可用 ngrok 等反向代理)。
安裝
- go get github.com/pardnchiu/go-bot@latest
只 import 需要的平台套件:
- import (
- "github.com/pardnchiu/go-bot/core/telegram"
- "github.com/pardnchiu/go-bot/core/discord"
- "github.com/pardnchiu/go-bot/core/line"
- )
最小回聲機器人
每個平台的順序相同:
New、Reply、Start,關閉時呼叫 Close。handler 回傳的非空字串會作為回覆送出。- package main
- import (
- "context"
- "log"
- "os"
- "os/signal"
- "syscall"
- "github.com/pardnchiu/go-bot/core/telegram"
- )
- func main() {
- bot, err := telegram.New(os.Getenv("TELEGRAM_TOKEN"))
- if err != nil {
- log.Fatal(err)
- }
- bot.Reply(func(ctx context.Context, in telegram.Input) string {
- return "you said: " + in.Text
- })
- ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
- defer stop()
- if err := bot.Start(ctx); err != nil {
- log.Fatal(err)
- }
- <-ctx.Done()
- bot.Close()
- }
Discord 與 LINE 版本只需替換建構子與
Input 型別:| 平台 | 建構子 | Handler 輸入 |
|---|---|---|
| Telegram | telegram.New(token) | telegram.Input |
| Discord | discord.New(token) | discord.Input |
| LINE | line.New(secret, token, "8080") | line.Input |
函式庫本身不讀環境變數;上例的變數名稱屬於你的程式。
下一步
- Bot 生命週期 —
Start驗證什麼、Close如何關閉 - Reply Handler — 回覆送往何處、panic 時會怎樣
- 平台設定:Telegram、Discord、LINE