base

package
v0.11.1 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Index

Constants

View Source
const ErrSenderNotConfigured = "sender not configured"

ErrSenderNotConfigured is returned when SendMessage is called but no sender function has been configured.

Variables

This section is empty.

Functions

func ExtractInt64FromMetadata

func ExtractInt64FromMetadata(msg *ChatMessage, key string) int64

ExtractInt64FromMetadata extracts an int64 value from message metadata. Returns 0 if the key doesn't exist or the value is not a numeric type.

func ExtractStringFromMetadata

func ExtractStringFromMetadata(msg *ChatMessage, key string) string

ExtractStringFromMetadata extracts a string value from message metadata. Returns empty string if the key doesn't exist or the value is not a string.

func ReadBody

func ReadBody(r *http.Request) ([]byte, error)

func RespondWithError

func RespondWithError(w http.ResponseWriter, code int, message string)

func RespondWithJSON

func RespondWithJSON(w http.ResponseWriter, code int, data any) error

func RespondWithText

func RespondWithText(w http.ResponseWriter, code int, text string)

Types

type Adapter

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

Adapter is the base adapter implementing common functionality

func NewAdapter

func NewAdapter(
	platform string,
	config Config,
	logger *slog.Logger,
	opts ...AdapterOption,
) *Adapter

NewAdapter creates a new base adapter

func (*Adapter) GetOrCreateSession

func (a *Adapter) GetOrCreateSession(key, userID string) string

GetOrCreateSession gets or creates a session

func (*Adapter) GetSession

func (a *Adapter) GetSession(key string) (*Session, bool)

GetSession retrieves a session by key

func (*Adapter) HandleMessage

func (a *Adapter) HandleMessage(ctx context.Context, msg *ChatMessage) error

HandleMessage handles incoming message (stub for interface compliance)

func (*Adapter) Handler

func (a *Adapter) Handler() MessageHandler

Handler returns the message handler (thread-safe)

func (*Adapter) Logger

func (a *Adapter) Logger() *slog.Logger

Logger returns the logger

func (*Adapter) Platform

func (a *Adapter) Platform() string

Platform returns the platform name

func (*Adapter) SendMessage

func (a *Adapter) SendMessage(ctx context.Context, sessionID string, msg *ChatMessage) error

SendMessage sends a message (requires messageSender to be set)

func (*Adapter) SetHandler

func (a *Adapter) SetHandler(handler MessageHandler)

SetHandler sets the message handler (thread-safe)

func (*Adapter) SetLogger

func (a *Adapter) SetLogger(logger *slog.Logger)

SetLogger sets the logger

func (*Adapter) Start

func (a *Adapter) Start(ctx context.Context) error

Start starts the adapter

func (*Adapter) Stop

func (a *Adapter) Stop() error

Stop stops the adapter

func (*Adapter) SystemPrompt

func (a *Adapter) SystemPrompt() string

SystemPrompt returns the system prompt

func (*Adapter) WebhookHandler

func (a *Adapter) WebhookHandler() http.Handler

WebhookHandler returns an http.Handler with all webhook endpoints registered

func (*Adapter) WebhookPath

func (a *Adapter) WebhookPath() string

WebhookPath returns the primary webhook path for this adapter

type AdapterOption

type AdapterOption func(*Adapter)

AdapterOption configures the base adapter

func WithHTTPHandler

func WithHTTPHandler(path string, handler http.HandlerFunc) AdapterOption

WithHTTPHandler adds an HTTP handler

func WithMessageParser

func WithMessageParser(parser MessageParser) AdapterOption

WithMessageParser sets the message parser

func WithMessageSender

func WithMessageSender(sender MessageSender) AdapterOption

WithMessageSender sets the message sender

func WithMetadataExtractor

func WithMetadataExtractor(extractor MetadataExtractor) AdapterOption

WithMetadataExtractor sets the metadata extractor

func WithSessionTimeout

func WithSessionTimeout(timeout time.Duration) AdapterOption

WithSessionTimeout sets the session timeout

func WithoutServer

func WithoutServer() AdapterOption

WithoutServer disables the embedded HTTP server Use this when running adapters under a unified server

type Attachment

type Attachment struct {
	Type     string `json:"type"`
	URL      string `json:"url"`
	Title    string `json:"title"`
	Text     string `json:"text"`
	ThumbURL string `json:"thumb_url,omitempty"`
}

type ChatAdapter

type ChatAdapter interface {
	Platform() string
	SystemPrompt() string
	Start(ctx context.Context) error
	Stop() error
	SendMessage(ctx context.Context, sessionID string, msg *ChatMessage) error
	HandleMessage(ctx context.Context, msg *ChatMessage) error
	SetHandler(MessageHandler)
}

type ChatMessage

type ChatMessage struct {
	Platform    string
	SessionID   string
	UserID      string
	Content     string
	MessageID   string
	Timestamp   time.Time
	Metadata    map[string]any
	RichContent *RichContent
}

type Config

type Config struct {
	ServerAddr   string
	SystemPrompt string
}

Config is the common configuration for all adapters

type HTTPClient

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

HTTPClient provides common HTTP request patterns for chat adapters. This eliminates the duplicate HTTP request building code across adapters.

func NewHTTPClient

func NewHTTPClient() *HTTPClient

NewHTTPClient creates a new HTTPClient with the default http.Client.

func NewHTTPClientWithConfig

func NewHTTPClientWithConfig(timeout time.Duration, maxRetries int) *HTTPClient

NewHTTPClientWithConfig creates a new HTTPClient with custom configuration.

func (*HTTPClient) Get

func (c *HTTPClient) Get(ctx context.Context, url string, headers map[string]string) ([]byte, error)

Get sends a GET request and returns the response body.

func (*HTTPClient) PostJSON

func (c *HTTPClient) PostJSON(ctx context.Context, url string, payload any, headers map[string]string) ([]byte, error)

PostJSON sends a POST request with a JSON body and returns the response body. headers is a map of header key-value pairs to add to the request.

func (*HTTPClient) PostJSONWithResponse

func (c *HTTPClient) PostJSONWithResponse(ctx context.Context, url string, payload any, headers map[string]string, dest any) error

PostJSONWithResponse sends a POST request and decodes the JSON response into dest.

type MessageHandler

type MessageHandler func(ctx context.Context, msg *ChatMessage) error

type MessageParser

type MessageParser func(body []byte, metadata map[string]any) (*ChatMessage, error)

MessageParser parses incoming requests into ChatMessage

type MessageSender

type MessageSender func(ctx context.Context, sessionID string, msg *ChatMessage) error

MessageSender sends messages to the platform

type MetadataExtractor

type MetadataExtractor func(update any) map[string]any

MetadataExtractor extracts platform-specific metadata from incoming requests

type ParseMode

type ParseMode string
const (
	ParseModeNone     ParseMode = ""
	ParseModeMarkdown ParseMode = "markdown"
	ParseModeHTML     ParseMode = "html"
)

type Reaction added in v0.11.1

type Reaction struct {
	Name      string // emoji name (e.g., "thumbsup", "+1")
	Channel   string
	Timestamp string // message timestamp to react to
}

Reaction represents a reaction to add to a message

type RichContent

type RichContent struct {
	ParseMode      ParseMode
	InlineKeyboard any
	Blocks         []any
	Embeds         []any
	Attachments    []Attachment
	Reactions      []Reaction
}

type SenderFunc

type SenderFunc func(ctx context.Context, sessionID string, msg *ChatMessage) error

SenderFunc is the function signature for sending messages to a platform.

type SenderWithMutex

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

SenderWithMutex provides thread-safe sender management for chat adapters. This eliminates the duplicate sender/senderMu pattern across all adapters.

func NewSenderWithMutex

func NewSenderWithMutex() *SenderWithMutex

NewSenderWithMutex creates a new SenderWithMutex with no sender configured.

func NewSenderWithMutexFunc

func NewSenderWithMutexFunc(sender SenderFunc) *SenderWithMutex

NewSenderWithMutexFunc creates a new SenderWithMutex with an initial sender.

func (*SenderWithMutex) HasSender

func (s *SenderWithMutex) HasSender() bool

HasSender returns true if a sender has been configured.

func (*SenderWithMutex) SendMessage

func (s *SenderWithMutex) SendMessage(ctx context.Context, sessionID string, msg *ChatMessage) error

SendMessage sends a message using the configured sender. Thread-safe. Returns ErrSenderNotConfigured if no sender has been set.

func (*SenderWithMutex) Sender

func (s *SenderWithMutex) Sender() SenderFunc

Sender returns the current sender function (may be nil). Note: This does not acquire the lock, so the caller should ensure thread-safety if the sender might be modified concurrently.

func (*SenderWithMutex) SetSender

func (s *SenderWithMutex) SetSender(fn SenderFunc)

SetSender sets the sender function. Thread-safe.

type Session

type Session struct {
	SessionID  string
	UserID     string
	Platform   string
	LastActive time.Time
}

Session represents a user session in a chat platform

type WebhookProvider

type WebhookProvider interface {
	WebhookPath() string
	WebhookHandler() http.Handler
}

WebhookProvider exposes HTTP handlers for unified server integration

type WebhookRunner

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

WebhookRunner manages the lifecycle of webhook processing goroutines. This eliminates the duplicate webhookWg pattern across all adapters.

func NewWebhookRunner

func NewWebhookRunner(logger *slog.Logger) *WebhookRunner

NewWebhookRunner creates a new WebhookRunner.

func (*WebhookRunner) Run

func (r *WebhookRunner) Run(ctx context.Context, handler MessageHandler, msg *ChatMessage)

Run executes the handler in a goroutine and tracks its completion. If handler is nil, this is a no-op.

func (*WebhookRunner) Stop

func (r *WebhookRunner) Stop() bool

Stop is an alias for WaitDefault for API consistency with adapters.

func (*WebhookRunner) Wait

func (r *WebhookRunner) Wait(timeout time.Duration) bool

Wait blocks until all running goroutines complete or timeout occurs. Returns true if all goroutines completed, false if timeout occurred.

func (*WebhookRunner) WaitDefault

func (r *WebhookRunner) WaitDefault() bool

WaitDefault blocks with the default 5 second timeout.

Jump to

Keyboard shortcuts

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