v0.5.0

快速開始

最後更新


把 go-bot 加進 Go module,並在單一平台跑起最小的回聲機器人。

前置需求


項目需求
Go1.25.0 以上(go.mod)
Telegram從 BotFather 取得的 bot token
DiscordBot token,並在 Developer Portal 啟用 Message Content Intent
LINEChannel secret、長效 channel access token,以及轉發到 webhook port 的公開 HTTPS URL

Telegram 與 Discord 皆由 bot 往外連線,在 NAT 後也能執行。LINE 由平台把事件推到你的 server,因此需要可從外部連入的 HTTPS endpoint(本機測試可用 ngrok 等反向代理)。

安裝


  1. go get github.com/pardnchiu/go-bot@latest

只 import 需要的平台套件:
  1. import (
  2. "github.com/pardnchiu/go-bot/core/telegram"
  3. "github.com/pardnchiu/go-bot/core/discord"
  4. "github.com/pardnchiu/go-bot/core/line"
  5. )

最小回聲機器人


每個平台的順序相同:New、Reply、Start,關閉時呼叫 Close。handler 回傳的非空字串會作為回覆送出。
  1. package main
  2. import (
  3. "context"
  4. "log"
  5. "os"
  6. "os/signal"
  7. "syscall"
  8. "github.com/pardnchiu/go-bot/core/telegram"
  9. )
  10. func main() {
  11. bot, err := telegram.New(os.Getenv("TELEGRAM_TOKEN"))
  12. if err != nil {
  13. log.Fatal(err)
  14. }
  15. bot.Reply(func(ctx context.Context, in telegram.Input) string {
  16. return "you said: " + in.Text
  17. })
  18. ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
  19. defer stop()
  20. if err := bot.Start(ctx); err != nil {
  21. log.Fatal(err)
  22. }
  23. <-ctx.Done()
  24. bot.Close()
  25. }

Discord 與 LINE 版本只需替換建構子與 Input 型別:
平台建構子Handler 輸入
Telegramtelegram.New(token)telegram.Input
Discorddiscord.New(token)discord.Input
LINEline.New(secret, token, "8080")line.Input

函式庫本身不讀環境變數;上例的變數名稱屬於你的程式。

下一步


EN