Documentation
¶
Index ¶
- Constants
- Variables
- func AddonsKeyboard(plan *aggregate.Plan, selectedAddons []string) *models.InlineKeyboardMarkup
- func ConfirmPurchaseKeyboard(planID string, addonIDs []string) *models.InlineKeyboardMarkup
- func FormatPlanDetail(plan *aggregate.Plan) string
- func FormatSubscription(sub *aggregate.Subscription, planName string, ...) string
- func FormatTrafficUsage(bindings []*msaggregate.RemnawaveBinding) string
- func NewBotPluginValidator(reg *BuiltinBotRegistry, plugins PluginReader) resellerservice.BotPluginValidator
- func NewCheckoutStarterAdapter(svc *billingservice.CheckoutService) bothost.CheckoutStarter
- func NewInvoiceReaderAdapter(r billing.InvoiceReader) bothost.InvoiceReader
- func NewSubscriptionMutatorAdapter(svc *billingservice.BillingService) bothost.SubscriptionMutator
- func NewSubscriptionReaderAdapter(r billing.SubscriptionReader) bothost.SubscriptionReader
- func PlansKeyboard(plans []*aggregate.Plan) *models.InlineKeyboardMarkup
- func SubscriptionKeyboard(sub *aggregate.Subscription, bindings []*msaggregate.RemnawaveBinding) *models.InlineKeyboardMarkup
- type Bot
- func (b *Bot) AnswerCallback(ctx context.Context, callbackID, text string) error
- func (b *Bot) EditMessage(ctx context.Context, chatID int64, messageID int, text string, ...) error
- func (b *Bot) Init(_ context.Context) error
- func (b *Bot) Run(ctx context.Context) error
- func (b *Bot) SendKeyboard(ctx context.Context, chatID int64, text string, kb bothost.Keyboard) error
- func (b *Bot) SendText(ctx context.Context, chatID int64, text string) error
- func (b *Bot) WebhookHandler() http.HandlerFunc
- type BotHandler
- type BotManager
- func (m *BotManager) Load(ctx context.Context) error
- func (m *BotManager) PlatformWebhookHandler() http.HandlerFunc
- func (m *BotManager) Reload(ctx context.Context) error
- func (m *BotManager) Run(ctx context.Context)
- func (m *BotManager) ShopWebhookHandler() http.HandlerFunc
- func (m *BotManager) Stop()
- type BotPluginCatalog
- type BotPluginInfo
- type BuiltinBotRegistry
- type DomainReaders
- type PluginLister
- type PluginReader
- type ShopBotLister
- type WASMBotDispatcher
Constants ¶
const ( BotPluginKindBuiltin = "builtin" BotPluginKindWASM = "wasm" )
Bot-plugin kinds distinguish native Go bot plugins from WASM bot plugins in the catalog listing.
const ( CmdStart = "start" CmdPlans = "plans" CmdSubscribe = "subscribe" CmdMy = "my" CmdTraffic = "traffic" CmdSupport = "support" CmdReferral = "referral" )
Bot command names (without the leading slash).
const ( CallbackPrefixPlan = "plan:" CallbackPrefixAddon = "addon:" CallbackPrefixConfirm = "confirm:" CallbackPrefixCancel = "cancel:" )
Callback data prefixes used for inline keyboard buttons.
const MaxMessageLength = 4096
MaxMessageLength is the Telegram Bot API limit for a single message.
const WebhookPathPrefix = "/webhooks/telegram/"
WebhookPathPrefix is the per-shop webhook path; the tenant id is appended.
Variables ¶
var Module = fx.Module("telegram", fx.Provide(NewBot), fx.Provide(NewBuiltinBotRegistry), fx.Provide(provideBotOps), fx.Provide(NewBotPluginValidator), fx.Provide(func(r plugin.PluginRepository) PluginReader { return r }), fx.Provide(NewWASMBotDispatcher), fx.Provide(func(r plugin.PluginRepository) PluginLister { return r }), fx.Provide(NewBotPluginCatalog), fx.Invoke(registerCabinetBot), fx.Provide(NewSubscriptionReaderAdapter), fx.Provide(NewInvoiceReaderAdapter), fx.Provide(NewCheckoutStarterAdapter), fx.Provide(NewSubscriptionMutatorAdapter), fx.Provide(newDomainReaders), fx.Provide(provideBotManager), )
Module provides the Telegram bot and bot manager to the Fx dependency graph.
Functions ¶
func AddonsKeyboard ¶
func AddonsKeyboard(plan *aggregate.Plan, selectedAddons []string) *models.InlineKeyboardMarkup
AddonsKeyboard builds an inline keyboard for addon selection during subscribe flow. Selected addons are marked with a checkmark.
func ConfirmPurchaseKeyboard ¶
func ConfirmPurchaseKeyboard(planID string, addonIDs []string) *models.InlineKeyboardMarkup
ConfirmPurchaseKeyboard builds a confirmation keyboard for checkout.
func FormatPlanDetail ¶
FormatPlanDetail returns an HTML-formatted description of a plan.
func FormatSubscription ¶
func FormatSubscription(sub *aggregate.Subscription, planName string, bindings []*msaggregate.RemnawaveBinding) string
FormatSubscription returns a text summary of a subscription with its bindings.
func FormatTrafficUsage ¶
func FormatTrafficUsage(bindings []*msaggregate.RemnawaveBinding) string
FormatTrafficUsage returns a text summary of traffic usage per binding.
func NewBotPluginValidator ¶
func NewBotPluginValidator(reg *BuiltinBotRegistry, plugins PluginReader) resellerservice.BotPluginValidator
NewBotPluginValidator returns a resellerservice.BotPluginValidator backed by the BuiltinBotRegistry and the PluginReader. The reseller domain only imports this interface; the telegram package imports the reseller service package for the type — not the other way around — so there is no import cycle.
func NewCheckoutStarterAdapter ¶
func NewCheckoutStarterAdapter(svc *billingservice.CheckoutService) bothost.CheckoutStarter
NewCheckoutStarterAdapter returns a bothost.CheckoutStarter backed by svc.
Note: CheckoutService.StartCheckout self-wraps its own RunInTx internally. Callers must NOT wrap Start inside another RunInTx.
func NewInvoiceReaderAdapter ¶
func NewInvoiceReaderAdapter(r billing.InvoiceReader) bothost.InvoiceReader
NewInvoiceReaderAdapter returns a bothost.InvoiceReader backed by r. In production, pass a billing.InvoiceReader directly — it satisfies the narrow invoiceFetcher interface used internally.
Tenant scoping is the caller's responsibility: the ctx passed to each method must carry the tenant GUC (set via RunInTx + WithTenantID); this adapter must NOT set the GUC itself.
func NewSubscriptionMutatorAdapter ¶
func NewSubscriptionMutatorAdapter(svc *billingservice.BillingService) bothost.SubscriptionMutator
NewSubscriptionMutatorAdapter returns a bothost.SubscriptionMutator backed by svc.
func NewSubscriptionReaderAdapter ¶
func NewSubscriptionReaderAdapter(r billing.SubscriptionReader) bothost.SubscriptionReader
NewSubscriptionReaderAdapter returns a bothost.SubscriptionReader backed by r. In production, pass a billing.SubscriptionReader directly — it satisfies the narrow subscriptionFetcher interface used internally.
Tenant scoping is the caller's responsibility: the ctx passed to each method must carry the tenant GUC (set via RunInTx + WithTenantID); this adapter must NOT set the GUC itself.
func PlansKeyboard ¶
func PlansKeyboard(plans []*aggregate.Plan) *models.InlineKeyboardMarkup
PlansKeyboard builds an inline keyboard with one button per plan.
func SubscriptionKeyboard ¶
func SubscriptionKeyboard(sub *aggregate.Subscription, bindings []*msaggregate.RemnawaveBinding) *models.InlineKeyboardMarkup
SubscriptionKeyboard builds an inline keyboard for a single subscription showing its bindings and a cancel option.
Types ¶
type Bot ¶
type Bot struct {
// contains filtered or unexported fields
}
Bot wraps the Telegram bot instance and all domain services needed to handle commands and callback queries.
Architecture: The bot uses domain services for all write operations (checkout, cancel subscription) and repositories directly for read-only queries (plans, subscriptions, bindings). This follows the CQRS read path pattern -- reads bypass the write-side services for performance and simplicity.
func NewBot ¶
func NewBot( cfg *config.Config, identitySvc *identity.Service, billingSvc *billingservice.BillingService, checkoutSvc *billingservice.CheckoutService, bindingRepo multisub.BindingRepository, planRepo billing.PlanReader, subRepo billing.SubscriptionReader, txRunner txmanager.Runner, logger *slog.Logger, ) *Bot
NewBot creates the platform Bot. The underlying tgbot.Bot is initialized lazily in Init so that the constructor does not block on a network call.
func NewShopBot ¶
func NewShopBot( token, webhookURL, webhookSecret, tenantID, cabinetURL string, identitySvc *identity.Service, botPluginSlug string, botRegistry *BuiltinBotRegistry, botOps *bothost.Registry, txRunner txmanager.Runner, wasmBots WASMBotDispatcher, readers DomainReaders, logger *slog.Logger, ) *Bot
NewShopBot builds a per-shop bot that dispatches all updates through the BuiltinBotRegistry (or a WASM plugin when wasmBots resolves the slug) using the configured plugin slug (default: cabinet-bot). Platform-only services are nil — a shop bot never reaches the other command handlers.
func (*Bot) AnswerCallback ¶
AnswerCallback implements bothost.MessageSender by delegating to answerCallback. Returns nil to satisfy the interface.
func (*Bot) EditMessage ¶
func (b *Bot) EditMessage(ctx context.Context, chatID int64, messageID int, text string, kb *bothost.Keyboard) error
EditMessage implements bothost.MessageSender by translating an optional bothost.Keyboard and delegating to editMessageText. A nil kb passes nil markup, leaving the existing keyboard unchanged. Returns nil to satisfy the interface.
func (*Bot) Init ¶
Init constructs the underlying tgbot.Bot and registers handlers. It makes no network call (WithSkipGetMe), so the manager can build every bot synchronously before serving webhooks. An empty token leaves the bot disabled (b.bot nil).
func (*Bot) Run ¶
Run sets the webhook (when configured) and processes updates until ctx is cancelled. A disabled bot (b.bot nil) returns immediately.
func (*Bot) SendKeyboard ¶
func (b *Bot) SendKeyboard(ctx context.Context, chatID int64, text string, kb bothost.Keyboard) error
SendKeyboard implements bothost.MessageSender by translating the bothost.Keyboard and delegating to sendTextWithKeyboard. Returns nil to satisfy the interface.
func (*Bot) SendText ¶
SendText implements bothost.MessageSender by delegating to the fire-and-forget sendText helper (which logs on error). Returns nil to satisfy the interface.
func (*Bot) WebhookHandler ¶
func (b *Bot) WebhookHandler() http.HandlerFunc
WebhookHandler returns an http.HandlerFunc that processes Telegram webhook updates. Only meaningful when running in webhook mode.
type BotHandler ¶
BotHandler handles one inbound Telegram update for a shop, producing effects only through the bothost.Host op interface (never the raw bot token or a DB handle). Built-in Go bot plugins register one of these; WASM bot plugins (BP2) go through RuntimePool.CallHook instead.
type BotManager ¶
type BotManager struct {
// contains filtered or unexported fields
}
BotManager runs one bot per shop plus an optional platform bot, and routes inbound webhooks to the right bot by tenant id.
func NewBotManager ¶
func NewBotManager( platform *Bot, identitySvc *identity.Service, lister ShopBotLister, cfg *config.Config, botRegistry *BuiltinBotRegistry, botOps *bothost.Registry, txRunner txmanager.Runner, wasmBots WASMBotDispatcher, readers DomainReaders, logger *slog.Logger, ) *BotManager
NewBotManager builds the manager. The per-shop webhook origin (scheme://host) is derived from cfg.Telegram.WebhookURL; empty/unparseable → long-polling.
func (*BotManager) Load ¶
func (m *BotManager) Load(ctx context.Context) error
Load initialises the platform bot and every enabled shop bot. A single bot's init failure is logged and skipped — it never aborts the others or boot.
func (*BotManager) PlatformWebhookHandler ¶
func (m *BotManager) PlatformWebhookHandler() http.HandlerFunc
PlatformWebhookHandler preserves the legacy /webhooks/telegram path for the optional platform bot.
func (*BotManager) Reload ¶
func (m *BotManager) Reload(ctx context.Context) error
Reload rebuilds the full bot set (stop → load → run).
func (*BotManager) Run ¶
func (m *BotManager) Run(ctx context.Context)
Run launches each initialised bot's processing loop in its own goroutine. The lock is held while mutating cancels and reading shops (startLocked records the cancel func); the launched goroutines touch only their own bot, never m.
func (*BotManager) ShopWebhookHandler ¶
func (m *BotManager) ShopWebhookHandler() http.HandlerFunc
ShopWebhookHandler routes POST /webhooks/telegram/{tenantID} to that shop's bot, which verifies the per-bot secret token before processing.
type BotPluginCatalog ¶
type BotPluginCatalog struct {
// contains filtered or unexported fields
}
BotPluginCatalog lists every bot plugin selectable as a shop bot: registered built-in bots plus enabled WASM plugins whose manifest declares ProvidesBot.
func NewBotPluginCatalog ¶
func NewBotPluginCatalog(reg *BuiltinBotRegistry, plugins PluginLister) *BotPluginCatalog
NewBotPluginCatalog constructs a BotPluginCatalog backed by the built-in bot registry and a PluginLister for enabled WASM plugins.
func (*BotPluginCatalog) ListBotPlugins ¶
func (c *BotPluginCatalog) ListBotPlugins(ctx context.Context) ([]BotPluginInfo, error)
ListBotPlugins returns every selectable bot plugin: registered built-in bots first (sorted by name), then enabled WASM bot plugins (sorted by name).
type BotPluginInfo ¶
type BotPluginInfo struct {
Slug string `json:"slug"`
Name string `json:"name"`
Kind string `json:"kind"`
Description string `json:"description,omitempty"`
}
BotPluginInfo describes a bot plugin a shop may select as its Telegram bot.
type BuiltinBotRegistry ¶
type BuiltinBotRegistry struct {
// contains filtered or unexported fields
}
BuiltinBotRegistry maps a built-in bot-plugin slug to its native Go handler and the op-permissions it is granted. It is the bot-dispatch analog of gateway.BuiltinRouteRegistry. Safe for concurrent use.
func NewBuiltinBotRegistry ¶
func NewBuiltinBotRegistry() *BuiltinBotRegistry
NewBuiltinBotRegistry returns an empty BuiltinBotRegistry.
func (*BuiltinBotRegistry) Lookup ¶
func (r *BuiltinBotRegistry) Lookup(slug string) (BotHandler, bothost.PermSet, bool)
Lookup returns the handler and granted permissions for slug, and whether it is registered.
func (*BuiltinBotRegistry) Register ¶
func (r *BuiltinBotRegistry) Register(slug string, perms bothost.PermSet, h BotHandler)
Register binds a built-in bot slug to its handler and granted permission set. Re-registering a slug replaces it.
type DomainReaders ¶
type DomainReaders struct {
Tariffs bothost.TariffReader
Subs bothost.SubscriptionReader
Invoices bothost.InvoiceReader
Balance bothost.BalanceReader
Checkout bothost.CheckoutStarter
SubMutator bothost.SubscriptionMutator
}
DomainReaders bundles the tenant-scoped domain read/act ports handed to shop-bot op dispatch (bothost.OpContext). Nil fields disable their ops. It is passed as one parameter so the Bot/BotManager constructors do not gain five individual parameters each time a new reader is added.
type PluginLister ¶
PluginLister is the narrow slice of the plugin repository the bot-plugin catalog needs: listing every enabled plugin. Depending on this keeps the catalog decoupled from the full plugin.PluginRepository.
type PluginReader ¶
PluginReader is the narrow slice of the plugin repository the WASM bot dispatcher needs: resolving a plugin by slug. Depending on this instead of the full plugin.PluginRepository keeps the dispatcher decoupled and its test double to a single method.
type ShopBotLister ¶
type ShopBotLister interface {
ListEnabledShopBots(ctx context.Context) ([]vo.ShopBotWithTenant, error)
}
ShopBotLister loads enabled per-shop bot configs (satisfied by *reseller.ResellerService). It self-scopes to the platform sentinel.
type WASMBotDispatcher ¶
type WASMBotDispatcher interface {
// Resolve checks whether slug names an enabled, ProvidesBot WASM plugin.
// On success it returns the permission set from the plugin manifest and the
// WASM export entry point name. ok=false means the caller should fall through
// to the next resolution strategy (typically the cabinet-bot fallback).
Resolve(ctx context.Context, slug string) (perms bothost.PermSet, entry string, ok bool)
// Invoke serialises the update envelope and executes the plugin's entry
// function via the runtime pool. ctx must carry a plugin.BotHostBridge
// (injected by the caller via plugin.WithBotHost) so the plugin can issue
// host_call operations during the invocation.
Invoke(ctx context.Context, slug, entry string, envelope []byte) error
}
WASMBotDispatcher abstracts WASM bot plugin resolution and invocation so that dispatchUpdate can route updates to WASM plugins without knowing the runtime pool internals, and tests can inject a fake.
func NewWASMBotDispatcher ¶
func NewWASMBotDispatcher(pool *plugin.RuntimePool, plugins PluginReader) WASMBotDispatcher
NewWASMBotDispatcher wires the production runtimePoolDispatcher into the fx dependency graph. pool and plugins are provided by the plugin module (plugin.PluginRepository satisfies PluginReader).