tgbotkit-runtime is a Go-based runtime environment designed for building Telegram bots. It provides a robust foundation for handling API interactions, event dispatching, and extensible logic via listeners and handlers, allowing developers to focus on bot logic.
For detailed information, please refer to the official documentation:
- OpenAPI Client: Utilizes the most fresh, autogenerated client (
github.com/tgbotkit/client) derived directly from the Telegram Bot API OpenAPI specification. - Event-Driven Architecture: Built around a pluggable
EventEmittersystem. - Middleware Support: Supports middleware for the event emitter (context injection, logging, recovery).
- Modular Design: Core functionalities like update polling, command parsing, and message classification are implemented as distinct listeners.
- Flexible Configuration: Uses the functional options pattern for type-safe configuration.
- Pluggable Logging: Interfaces for logging allow for easy swapping of implementations (
slog,zerolog,noop).
Here is a simple webhook bot example:
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"github.com/tgbotkit/client"
"github.com/tgbotkit/runtime"
"github.com/tgbotkit/runtime/events"
"github.com/tgbotkit/runtime/messagetype"
"github.com/tgbotkit/runtime/webhook"
)
func main() {
token := os.Getenv("TELEGRAM_TOKEN")
if token == "" {
log.Fatal("TELEGRAM_TOKEN is required")
}
// Initialize webhook update source
wh, _ := webhook.New(webhook.NewOptions())
bot, err := runtime.New(runtime.NewOptions(
token,
runtime.WithUpdateSource(wh),
))
if err != nil {
log.Fatalf("failed to create bot: %v", err)
}
// Register a handler for text message events only
bot.Handlers().OnMessageType(messagetype.Text, func(ctx context.Context, event *events.MessageEvent) error {
if event.Message.Text != nil && *event.Message.Text == "ping" {
_, _ = bot.Client().SendMessageWithResponse(ctx, client.SendMessageJSONRequestBody{
ChatId: event.Message.Chat.Id,
Text: "pong",
})
}
return nil
})
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
go func() {
log.Printf("Webhook server listening on :8080")
if err := http.ListenAndServe(":8080", wh); err != nil {
log.Fatalf("server error: %v", err)
}
}()
if err := bot.Run(ctx); err != nil {
log.Fatalf("bot error: %v", err)
}
}MIT