v0.5.1

はじめに

最終更新


go-bot を Go module に追加し、1 つのプラットフォームで最小構成のエコー bot を動かします。

前提条件


項目要件
Go1.25.0 以降(go.mod)
TelegramBotFather から取得した Bot token
DiscordBot token。Developer Portal で Message Content Intent を有効にしておく必要があります
LINEChannel secret、長期の channel access token、webhook ポートへ転送する公開 HTTPS URL

Telegram と Discord はアウトバウンドで接続するため、NAT の内側でも動作します。LINE はイベントをサーバーへプッシュするため、インバウンドの HTTPS エンドポイントが必要です(ローカルでのテストには 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. )

最小構成のエコー bot


どのプラットフォームも同じ順序で呼び出します。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

ライブラリ自体は環境変数を読みません。上記の変数名はあなたのプログラム側のものです。

次のステップ