bot

package
v0.5.3 Latest Latest
Warning

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

Go to latest
Published: Jan 18, 2026 License: MIT Imports: 29 Imported by: 0

Documentation

Index

Constants

View Source
const (
	AnomalyEmptyResponse = "empty_response"
	AnomalySanitized     = "sanitized"
	AnomalyRetrySuccess  = "retry_success"
	AnomalyRetryFailed   = "retry_failed"
)

LLM anomaly types

View Source
const (
	ContextSourceSystem  = "system"
	ContextSourceProfile = "profile"
	ContextSourceTopics  = "topics"
	ContextSourceSession = "session"
)

Context source types

Variables

This section is empty.

Functions

func DecActiveSessions added in v0.3.0

func DecActiveSessions()

DecActiveSessions уменьшает счётчик активных сессий на 1.

func IncActiveSessions added in v0.3.0

func IncActiveSessions()

IncActiveSessions увеличивает счётчик активных сессий на 1.

func RecordContextTokens added in v0.3.0

func RecordContextTokens(tokens int)

RecordContextTokens записывает размер контекста в токенах.

func RecordContextTokensBySource added in v0.3.3

func RecordContextTokensBySource(userID int64, source string, tokens int)

RecordContextTokensBySource записывает токены по источнику контекста.

func RecordLLMAnomaly added in v0.3.8

func RecordLLMAnomaly(userID int64, anomalyType string)

RecordLLMAnomaly records an LLM response anomaly. anomalyType should be one of: AnomalyEmptyResponse, AnomalySanitized, AnomalyRetrySuccess, AnomalyRetryFailed

func RecordMessageLLM added in v0.3.8

func RecordMessageLLM(userID int64, totalDuration float64, callCount int)

RecordMessageLLM records total LLM duration and call count for a message.

func RecordMessageProcessing added in v0.3.0

func RecordMessageProcessing(userID int64, durationSeconds float64, success bool)

RecordMessageProcessing записывает метрики обработки сообщения.

func RecordMessageReaction added in v0.3.8

func RecordMessageReaction(userID int64, duration float64)

RecordMessageReaction records SetMessageReaction duration.

func RecordMessageTelegram added in v0.3.8

func RecordMessageTelegram(userID int64, totalDuration float64, callCount int)

RecordMessageTelegram records total Telegram send duration and call count for a message.

func RecordMessageTools added in v0.3.8

func RecordMessageTools(userID int64, totalDuration float64, callCount int)

RecordMessageTools records total tool execution duration and call count for a message.

func SetActiveSessions added in v0.3.0

func SetActiveSessions(count int)

SetActiveSessions устанавливает текущее количество активных сессий.

Types

type Bot

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

func NewBot

func NewBot(logger *slog.Logger, api telegram.BotAPI, cfg *config.Config, userRepo storage.UserRepository, msgRepo storage.MessageRepository, statsRepo storage.StatsRepository, factRepo storage.FactRepository, factHistoryRepo storage.FactHistoryRepository, peopleRepo storage.PeopleRepository, orClient openrouter.Client, speechKitClient yandex.Client, ragService *rag.Service, contextService *agent.ContextService, translator *i18n.Translator) (*Bot, error)

func (*Bot) API

func (b *Bot) API() telegram.BotAPI

func (*Bot) ForceCloseSession added in v0.3.0

func (b *Bot) ForceCloseSession(ctx context.Context, userID int64) (int, error)

ForceCloseSession immediately processes unprocessed messages for a user into topics.

func (*Bot) ForceCloseSessionWithProgress added in v0.3.0

func (b *Bot) ForceCloseSessionWithProgress(ctx context.Context, userID int64, onProgress rag.ProgressCallback) (*rag.ProcessingStats, error)

ForceCloseSessionWithProgress immediately processes unprocessed messages with progress reporting.

func (*Bot) GetActiveSessions added in v0.3.0

func (b *Bot) GetActiveSessions() ([]rag.ActiveSessionInfo, error)

GetActiveSessions returns information about active sessions (unprocessed messages) for all users.

func (*Bot) HandleUpdate

func (b *Bot) HandleUpdate(ctx context.Context, rawUpdate json.RawMessage, remoteAddr string)

func (*Bot) HandleUpdateAsync added in v0.2.0

func (b *Bot) HandleUpdateAsync(ctx context.Context, rawUpdate json.RawMessage, remoteAddr string)

HandleUpdateAsync starts processing a raw update in a goroutine. It properly handles WaitGroup to ensure graceful shutdown. Used by webhook handler.

func (*Bot) ProcessUpdate

func (b *Bot) ProcessUpdate(ctx context.Context, update *telegram.Update, source string)

func (*Bot) ProcessUpdateAsync added in v0.2.0

func (b *Bot) ProcessUpdateAsync(ctx context.Context, update *telegram.Update, source string)

ProcessUpdateAsync starts processing an update in a goroutine. It properly handles WaitGroup to ensure graceful shutdown.

func (*Bot) SendTestMessage added in v0.3.0

func (b *Bot) SendTestMessage(ctx context.Context, userID int64, text string, saveToHistory bool) (*rag.TestMessageResult, error)

SendTestMessage sends a test message through the bot pipeline without Telegram. It returns detailed metrics for debugging purposes.

func (*Bot) SetAgentLogger added in v0.4.8

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

SetAgentLogger sets the agent logger for debug logging

func (*Bot) SetLaplaceAgent added in v0.5.0

func (b *Bot) SetLaplaceAgent(agent *laplace.Laplace)

SetLaplaceAgent sets the Laplace chat agent

func (*Bot) SetWebhook

func (b *Bot) SetWebhook(webhookURL, secretToken string) error

func (*Bot) Stop

func (b *Bot) Stop()

type Chat

type Chat struct {
	ID       int64  `json:"id"`
	Type     string `json:"type"`
	Title    string `json:"title"`
	Username string `json:"username"`
}

Chat represents a chat.

type Document

type Document struct {
	FileID       string     `json:"file_id"`
	FileUniqueID string     `json:"file_unique_id"`
	Thumbnail    *PhotoSize `json:"thumbnail,omitempty"`
	FileName     string     `json:"file_name,omitempty"`
	MimeType     string     `json:"mime_type,omitempty"`
	FileSize     int        `json:"file_size,omitempty"`
}

Document represents a general file (as opposed to photos, voice messages and audio files).

type Message

type Message struct {
	MessageID        int            `json:"message_id"`
	From             *User          `json:"from"`
	Chat             *Chat          `json:"chat"`
	Date             int            `json:"date"`
	Text             string         `json:"text"`
	Caption          string         `json:"caption"`
	Photo            []PhotoSize    `json:"photo"`
	Document         *Document      `json:"document"`
	Voice            *Voice         `json:"voice"`
	ForwardOrigin    *MessageOrigin `json:"forward_origin"`
	IsCommand        bool           `json:"-"` // This will be determined manually
	Command          string         `json:"-"` // This will be determined manually
	CommandArguments string         `json:"-"` // This will be determined manually
}

Message represents a message.

type MessageGroup

type MessageGroup struct {
	Messages   []*telegram.Message
	Timer      *time.Timer
	CancelFunc context.CancelFunc
	UserID     int64
	StartedAt  time.Time // When the first message in this group was received
}

MessageGroup represents a collection of messages from a single user that are processed together.

type MessageGrouper

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

MessageGrouper handles the grouping of incoming messages from users.

func NewMessageGrouper

func NewMessageGrouper(b *Bot, logger *slog.Logger, turnWait time.Duration, onGroupReady func(ctx context.Context, group *MessageGroup)) *MessageGrouper

NewMessageGrouper creates a new MessageGrouper.

func (*MessageGrouper) AddMessage

func (mg *MessageGrouper) AddMessage(msg *telegram.Message)

AddMessage adds a new message to a user's group.

func (*MessageGrouper) ForceCloseSession added in v0.3.0

func (mg *MessageGrouper) ForceCloseSession(userID int64) bool

ForceCloseSession immediately processes and closes a session for the given user. Returns true if a session was found and closed, false otherwise.

func (*MessageGrouper) GetActiveSessions added in v0.3.0

func (mg *MessageGrouper) GetActiveSessions() []SessionInfo

GetActiveSessions returns information about all active message grouping sessions.

func (*MessageGrouper) Stop added in v0.2.0

func (mg *MessageGrouper) Stop()

Stop processes all pending message groups and waits for completion. Should be called during graceful shutdown.

type MessageOrigin

type MessageOrigin struct {
	Type            string `json:"type"`
	Date            int    `json:"date"`
	SenderUser      *User  `json:"sender_user,omitempty"`
	SenderUserName  string `json:"sender_user_name,omitempty"`
	SenderChat      *Chat  `json:"sender_chat,omitempty"`
	AuthorSignature string `json:"author_signature,omitempty"`
	MessageID       int    `json:"message_id,omitempty"`
}

MessageOrigin is a union type that can be one of MessageOriginUser, MessageOriginHiddenUser, MessageOriginChat, or MessageOriginChannel.

func (*MessageOrigin) UnmarshalJSON

func (mo *MessageOrigin) UnmarshalJSON(data []byte) error

UnmarshalJSON is a custom unmarshaler for MessageOrigin to handle the union type.

type PhotoSize

type PhotoSize struct {
	FileID       string `json:"file_id"`
	FileUniqueID string `json:"file_unique_id"`
	Width        int    `json:"width"`
	Height       int    `json:"height"`
	FileSize     int    `json:"file_size,omitempty"`
}

PhotoSize represents one size of a photo or a file / sticker thumbnail.

type ReactionType

type ReactionType struct {
	Type  string `json:"type"`
	Emoji string `json:"emoji,omitempty"`
}

ReactionType represents a reaction type.

type SessionInfo added in v0.3.0

type SessionInfo struct {
	UserID       int64
	MessageCount int
	StartedAt    time.Time
	LastMessage  time.Time
}

SessionInfo represents information about an active message grouping session.

type SetMessageReactionConfig

type SetMessageReactionConfig struct {
	ChatID    int64
	MessageID int
	Reaction  []ReactionType
	IsBig     bool
}

SetMessageReactionConfig contains information about a reaction to be set on a message.

func (SetMessageReactionConfig) Method

func (config SetMessageReactionConfig) Method() string

Method returns the method name for the SetMessageReaction method.

func (SetMessageReactionConfig) Params

func (config SetMessageReactionConfig) Params() (map[string]string, error)

Params returns a map of parameters for the SetMessageReaction method.

type Update

type Update struct {
	UpdateID int      `json:"update_id"`
	Message  *Message `json:"message"`
}

Update is a Telegram object that represents an incoming update.

type User

type User struct {
	ID        int64  `json:"id"`
	IsBot     bool   `json:"is_bot"`
	FirstName string `json:"first_name"`
	LastName  string `json:"last_name"`
	UserName  string `json:"username"`
}

User represents a Telegram user or bot.

type Voice

type Voice struct {
	FileID       string `json:"file_id"`
	FileUniqueID string `json:"file_unique_id"`
	Duration     int    `json:"duration"`
	MimeType     string `json:"mime_type,omitempty"`
	FileSize     int    `json:"file_size,omitempty"`
}

Voice represents a voice note.

Jump to

Keyboard shortcuts

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