runtime

package module
v0.0.0-...-889dc0d Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 9, 2026 License: MIT Imports: 17 Imported by: 0

README

tgbotkit-runtime

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.

Key Features

  • 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 EventEmitter system.
  • 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).

Example

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)
	}
}

License

MIT

Documentation

Overview

Package runtime provides the main bot logic and orchestration for the Telegram bot.

Index

Constants

This section is empty.

Variables

View Source
var ToRunnable = lifecycle.ToRunnable

ToRunnable converts a Lifecycle to a Runnable.

View Source
var WithStartTimeout = lifecycle.WithStartTimeout

WithStartTimeout sets the timeout for the Start operation.

View Source
var WithStopTimeout = lifecycle.WithStopTimeout

WithStopTimeout sets the timeout for the Stop operation.

Functions

This section is empty.

Types

type Bot

type Bot struct {
	// contains filtered or unexported fields
}

Bot is the main bot structure.

func New

func New(opts Options) (*Bot, error)

New creates a new Bot instance with the given options.

func (*Bot) Client

Client returns the underlying Telegram Bot API client.

func (*Bot) EventEmitter

func (b *Bot) EventEmitter() eventemitter.EventEmitter

EventEmitter returns the bot's event emitter.

func (*Bot) Handlers

func (b *Bot) Handlers() handlers.RegistryInterface

Handlers returns the bot's handler registry.

func (*Bot) Logger

func (b *Bot) Logger() logger.Logger

Logger returns the bot's logger.

func (*Bot) Run

func (b *Bot) Run(ctx context.Context) error

Run starts the bot's update processing loop and blocks until the context is canceled. It initializes a default update poller if no update source is configured.

type Lifecycle

type Lifecycle = lifecycle.Lifecycle

Lifecycle represents a component that has a distinct start and stop phase.

type OptOptionsSetter

type OptOptionsSetter func(o *Options)

func WithClient

client is the Telegram API client.

func WithEventEmitter

func WithEventEmitter(opt eventemitter.EventEmitter) OptOptionsSetter

eventEmitter is the event emitter to use.

func WithLogger

func WithLogger(opt logger.Logger) OptOptionsSetter

logger is the logger to use.

func WithUpdateSource

func WithUpdateSource(opt UpdateSource) OptOptionsSetter

updateSource is the update source to use.

type Options

type Options struct {
	// contains filtered or unexported fields
}

Options is the options for the Bot.

func NewOptions

func NewOptions(
	botToken string,
	options ...OptOptionsSetter,
) Options

func (*Options) Validate

func (o *Options) Validate() error

type Runnable

type Runnable = lifecycle.Runnable

Runnable represents a long-running process that blocks until the context is canceled or an error occurs.

type RunnableFunc

type RunnableFunc = lifecycle.RunnableFunc

RunnableFunc is a function adapter for the Runnable interface.

type RunnableOption

type RunnableOption = lifecycle.Option

RunnableOption configures the ToRunnable adapter.

type UpdateChan

type UpdateChan <-chan client.Update

UpdateChan is a channel that receives updates from the Telegram API.

type UpdateSource

type UpdateSource interface {
	lifecycle.Lifecycle

	// UpdateChan returns a channel that receives updates.
	UpdateChan() <-chan client.Update
}

UpdateSource represents a source of updates.

Directories

Path Synopsis
Package botcontext provides a mechanism to embed and retrieve bot-specific context (Client, EventEmitter, Logger) within a standard context.Context.
Package botcontext provides a mechanism to embed and retrieve bot-specific context (Client, EventEmitter, Logger) within a standard context.Context.
Package eventemitter provides a flexible event bus implementation for handling bot events.
Package eventemitter provides a flexible event bus implementation for handling bot events.
Package events defines the events emitted by the bot and their associated payload types.
Package events defines the events emitted by the bot and their associated payload types.
examples
command command
Package main provides an example of a bot that handles commands.
Package main provides an example of a bot that handles commands.
pingpong command
Package main provides a simple ping-pong bot example.
Package main provides a simple ping-pong bot example.
webhook command
Package main provides an example of a bot using webhooks.
Package main provides an example of a bot using webhooks.
Package handlers provides a type-safe way to register and manage event handlers.
Package handlers provides a type-safe way to register and manage event handlers.
Package listeners provides core event listeners for the bot, such as update classification and command parsing.
Package listeners provides core event listeners for the bot, such as update classification and command parsing.
Package logger defines a common logging interface and provides implementations for various logging libraries.
Package logger defines a common logging interface and provides implementations for various logging libraries.
Package messagetype provides constants and utilities for identifying the type of a Telegram message.
Package messagetype provides constants and utilities for identifying the type of a Telegram message.
Package middleware provides various middleware implementations for the bot's event emitter.
Package middleware provides various middleware implementations for the bot's event emitter.
Package updatepoller provides a long-polling mechanism for receiving updates from the Telegram Bot API.
Package updatepoller provides a long-polling mechanism for receiving updates from the Telegram Bot API.
offsetstore
Package offsetstore provides implementations for storing the update offset.
Package offsetstore provides implementations for storing the update offset.
Package webhook provides an implementation of UpdateSource using Telegram webhooks.
Package webhook provides an implementation of UpdateSource using Telegram webhooks.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL