// Package telegram implements gateway.Gateway using the Telegram Bot API // via go-telegram/bot. Ported from GopherClaw's telegram.go and adapted // for archie-core's gateway architecture. package telegram import ( "context" "encoding/json" "errors" "fmt" "log/slog" "net/http" "runtime/debug" "slices" "strconv" "strings" "sync" "sync/atomic" "time" "github.com/go-telegram/bot" "github.com/go-telegram/bot/models" "github.com/samcharles93/archie-core/internal/channels" "github.com/samcharles93/archie-core/internal/domain/messaging" "github.com/samcharles93/archie-core/internal/releaseupdate" ) // Gateway is a Telegram gateway.Gateway backed by go-telegram/bot. type Gateway struct { Token string // AllowedUserIDs lists the sender IDs allowed to use the bot. Empty denies // everyone. AllowedUserIDs []int64 // Reload re-reads configuration during /restart and applies it to g. // Supplied by the composition root, which owns config paths. Nil // restarts with the settings already in memory. Reload func(*Gateway) error // ReleaseAnnouncements sends one-time upgrade notes to authorized users. // It is supplied by the composition root because version, changelog, and // persistence paths are deployment concerns. ReleaseAnnouncements ReleaseAnnouncer // Version reports installed component versions. The composition root owns // build metadata; Telegram only renders it for authorized users. Version func() string // Updates is injected by the composition root. It owns release discovery, // deferral persistence, and installation; Telegram only presents it. Updates UpdateService // Settings executes control-plane commands in this authenticated adapter. Settings *messaging.SettingsCommand // ResolveActor maps a channel-native sender to an authenticated Archie // identity. Nil deliberately permits reads but makes writes fail closed. ResolveActor func(int64) (string, bool) // UpdateReportPath is where the update watchdog leaves an update's outcome, // relayed on each launch. Empty disables it. UpdateReportPath string // RunningVersions reports the version each component reports for itself, to // verify update reports. Nil leaves claims unverified. RunningVersions func() map[string]string // showToolCalls controls whether new live replies render completed tool // calls. Each reply snapshots it so reloads affect only later turns. showToolCalls atomic.Bool // restartCh carries /restart requests from a bot handler to the // supervisor loop in Start. Buffered so a handler never blocks. restartCh chan restartRequest pendingRestart *restartRequest modelMu sync.RWMutex modelCallbacks map[string]string modelPages map[string]modelPage providerMu sync.RWMutex providerCallbacks map[string]string updateMu sync.Mutex updateInProgress bool updateActions map[string]updateAction updateReportMu sync.Mutex // tool approval state (gateway.ApprovalRequester): tool approvals // deliver the human's decision on a channel to the blocked // RequestApproval call. approvalMu sync.Mutex pendingApprovals map[string]*pendingApproval // permanentMu guards the 24-hour approvals a human granted per tool. permanentMu sync.Mutex permanentApprovals []permanentApproval // interactive state (gateway clarify/picker). A blocked clarify or // picker waits on one entry here, keyed by the chat it was posed to, so // the next text from that human is consumed as the answer rather than // dispatched as a new turn. interactiveMu sync.Mutex pendingReplies map[pendingReplyKey]*pendingReply // turns serialises chat turns per session off the update worker and // makes the running one cancellable by /stop. Rebuilt on every launch // so a restart abandons in-flight turns with the old bot instance. turns *messaging.Turns // liveMu guards liveReplies and liveStopped. liveMu sync.Mutex // liveReplies tracks in-flight live replies so Stop can abandon them. liveReplies map[*liveReply]struct{} // liveDrainTimeout bounds abandonAllLive's wait for in-flight replies to // be marked. Zero uses abandonAllLiveTimeout; tests shrink it so a // deliberately-hung reply doesn't make the suite slow. liveDrainTimeout time.Duration // liveStopped is set when abandonAllLive claims the registry, and reset at // the next launch. liveStopped bool log *slog.Logger bot *bot.Bot running bool // outbound is the running bot as Send sees it: Send is called from the // Messaging Service's RPC goroutines, not the update loop that owns bot. outbound atomic.Pointer[bot.Bot] // serverURL redirects the Bot API at a test server. Empty in production, // where the library's default endpoint is used. It exists so launch's // wiring can be tested without reaching api.telegram.org. serverURL string // newEphemeralSender builds the retracting sender sendEphemeral uses. // Defaults to channels.NewEphemeralSender; tests override it to inject a // clock so a status notice's retraction fires without waiting out its // TTL, matching liveReply's newMediaSender seam. newEphemeralSender func() *channels.EphemeralSender } type UpdateService interface { Check(context.Context, int64) (releaseupdate.Snapshot, error) Defer(context.Context, int64, releaseupdate.Snapshot) error Install(context.Context, releaseupdate.Snapshot, releaseupdate.InstallMeta, func(string)) (releaseupdate.Result, error) CanInstall() bool } type ReleaseAnnouncer interface { Announce( ctx context.Context, recipients []int64, send func(context.Context, int64, string) error, ) error } // New returns an unstarted Gateway. Call Start to begin long-polling. func New(token string, allowedUserIDs []int64, log *slog.Logger) *Gateway { g := &Gateway{ Token: token, AllowedUserIDs: allowedUserIDs, restartCh: make(chan restartRequest, 1), modelCallbacks: make(map[string]string), modelPages: make(map[string]modelPage), providerCallbacks: make(map[string]string), updateActions: make(map[string]updateAction), pendingApprovals: make(map[string]*pendingApproval), pendingReplies: make(map[pendingReplyKey]*pendingReply), log: log.With("component", "gateway-telegram"), } g.newEphemeralSender = func() *channels.EphemeralSender { return channels.NewEphemeralSender(g.log, nil) } return g } func (g *Gateway) Name() string { return "telegram" } // SetShowToolCalls controls tool visibility for replies created after the call. func (g *Gateway) SetShowToolCalls(show bool) { g.showToolCalls.Store(show) } // ShowToolCalls reports the visibility setting that a new reply must snapshot. func (g *Gateway) ShowToolCalls() bool { return g.showToolCalls.Load() } // RequestRestart asks the gateway supervisor to reload this adapter. It is // safe for callers outside Telegram (such as the local Web UI) and never // blocks when a restart is already queued. func (g *Gateway) RequestRestart() error { select { case g.restartCh <- restartRequest{}: return nil default: return errors.New("telegram gateway restart already in progress") } } // Start runs the bot and relaunches it on restart requests until ctx ends. func (g *Gateway) Start(ctx context.Context, client messaging.ChatContract, lifecycle channels.Lifecycle) error { if g.Token == "" { return fmt.Errorf("telegram bot token is required") } g.log.Info("starting telegram gateway") for { lifecycle.ReportStarting() runCtx, cancel := context.WithCancel(ctx) b, err := g.launch(runCtx, client, lifecycle) if err != nil { cancel() return err } // Confirm the restart with a self-deleting notice. if req := g.pendingRestart; req != nil && req.chatID != 0 { g.sendEphemeral(runCtx, b, req.chatID, req.threadID, "✅ Archie reloaded.") } if g.pendingRestart != nil { g.pendingRestart = nil } select { case <-ctx.Done(): cancel() return g.Stop(context.WithoutCancel(ctx)) case req := <-g.restartCh: g.log.Info("restarting telegram gateway", "requested_by", req.chatID) cancel() if err := g.Stop(context.WithoutCancel(ctx)); err != nil { g.log.Warn("stop during restart failed", "error", err) } if g.Reload != nil { if err := g.Reload(g); err != nil { // Keep the previous settings rather than dying: a bad // config edit must not take the gateway down for good. g.log.Error("config reload failed, restarting with previous settings", "error", err) } } g.pendingRestart = &req } } } // telegramTextHandler is one text command the Telegram adapter answers itself, // before the shared router sees it. type telegramTextHandler struct { command string match bot.MatchType build func(*Gateway, messaging.ChatContract) bot.HandlerFunc } // telegramTextHandlers is the single source for the commands Telegram answers // locally. var telegramTextHandlers = []telegramTextHandler{ {"/status", bot.MatchTypeExact, func(g *Gateway, c messaging.ChatContract) bot.HandlerFunc { return g.statusHandler(c) }}, {"/whoami", bot.MatchTypeExact, func(g *Gateway, c messaging.ChatContract) bot.HandlerFunc { return g.whoamiHandler(c) }}, {"/profile", bot.MatchTypeExact, func(g *Gateway, c messaging.ChatContract) bot.HandlerFunc { return g.profileHandler(c) }}, {"/sessions", bot.MatchTypeExact, func(g *Gateway, c messaging.ChatContract) bot.HandlerFunc { return g.sessionsHandler(c) }}, {"/resume", bot.MatchTypeExact, func(g *Gateway, c messaging.ChatContract) bot.HandlerFunc { return g.resumeHandler(c) }}, {"/agents", bot.MatchTypeExact, func(g *Gateway, c messaging.ChatContract) bot.HandlerFunc { return g.agentsHandler(c) }}, {"/version", bot.MatchTypeExact, func(g *Gateway, _ messaging.ChatContract) bot.HandlerFunc { return g.versionHandler() }}, {"/update", bot.MatchTypeExact, func(g *Gateway, _ messaging.ChatContract) bot.HandlerFunc { return g.updateHandler() }}, {"/settings", bot.MatchTypePrefix, func(g *Gateway, _ messaging.ChatContract) bot.HandlerFunc { return g.settingsHandler() }}, {"/start", bot.MatchTypeExact, func(g *Gateway, _ messaging.ChatContract) bot.HandlerFunc { return g.startHandler() }}, {"/help", bot.MatchTypeExact, func(g *Gateway, _ messaging.ChatContract) bot.HandlerFunc { return g.helpHandler() }}, {"/restart", bot.MatchTypeExact, func(g *Gateway, _ messaging.ChatContract) bot.HandlerFunc { return g.restartHandler() }}, {"/stop", bot.MatchTypePrefix, func(g *Gateway, c messaging.ChatContract) bot.HandlerFunc { return g.stopHandler(c) }}, } func (g *Gateway) registerCommandHandlers(b *bot.Bot, client messaging.ChatContract) { for _, handler := range telegramTextHandlers { b.RegisterHandler(bot.HandlerTypeMessageText, handler.command, handler.match, handler.build(g, client)) } } func (g *Gateway) startListening(ctx context.Context, b *bot.Bot, _ channels.Lifecycle) error { g.dropPendingUpdates(ctx, b) g.running = true go b.Start(ctx) return nil } // launch builds one bot instance, registers handlers and starts its // long-poll delivery worker. Readiness is reported by pollReadinessClient // after the first successful getUpdates response. func (g *Gateway) launch(ctx context.Context, client messaging.ChatContract, lifecycle channels.Lifecycle) (*bot.Bot, error) { // Turns are per-launch. Each queued turn carries the update handler's // context, which is this launch's, so a /restart cancels everything // still running under the outgoing bot instance. g.turns = messaging.NewTurns(g.log) g.resetLiveRegistry() opts := []bot.Option{ bot.WithErrorsHandler(g.pipelineErrorHandler(ctx)), bot.WithDebugHandler(func(format string, args ...any) { g.log.Debug("telegram debug", "message", fmt.Sprintf(format, args...)) }), bot.WithDefaultHandler(g.defaultHandler(client)), bot.WithMiddlewares(g.panicRecoveryMiddleware(), g.updateLoggingMiddleware()), bot.WithHTTPClient(telegramPollTimeout, &pollReadinessClient{ client: &http.Client{Timeout: telegramPollTimeout}, onRunning: lifecycle.ReportRunning, }), } if g.serverURL != "" { opts = append(opts, bot.WithServerURL(g.serverURL), bot.WithSkipGetMe()) } b, err := bot.New(g.Token, opts...) if err != nil { return nil, fmt.Errorf("create bot: %w", err) } g.bot = b g.outbound.Store(b) g.registerCommandHandlers(b, client) // Publish the command list so Telegram renders a menu. Without this // the commands are undiscoverable and the LLM, having no idea they // exist, tells users there are none. g.registerCommands(ctx, b) g.notifyLaunch(ctx, b) if err := g.startListening(ctx, b, lifecycle); err != nil { return nil, err } return b, nil } // notifyLaunch sends the one-time notifications that belong to every // gateway launch, not just a process boot: a newly installed release's // changelog, and the phase-2 outcome of an update the watchdog finished // while this gateway was down. func (g *Gateway) notifyLaunch(ctx context.Context, b *bot.Bot) { g.announceRelease(ctx, b) g.reportPendingUpdate(ctx, b) go g.watchPendingUpdate(ctx, b) } // watchPendingUpdate closes the watchdog/startup race: the watchdog writes // the health result only after this process answers its health probe, so the // launch-time read can miss the report for the boot it describes. func (g *Gateway) watchPendingUpdate(ctx context.Context, b *bot.Bot) { ticker := time.NewTicker(2 * time.Second) defer ticker.Stop() for { select { case <-ctx.Done(): return case <-ticker.C: g.reportPendingUpdate(ctx, b) } } } func (g *Gateway) announceRelease(ctx context.Context, b *bot.Bot) { if g.ReleaseAnnouncements == nil { return } err := g.ReleaseAnnouncements.Announce( ctx, slices.Clone(g.AllowedUserIDs), func(ctx context.Context, recipient int64, message string) error { _, err := b.SendMessage(ctx, &bot.SendMessageParams{ ChatID: recipient, Text: message, }) return err }, ) if err != nil { // Notifications are ancillary to chat availability. Keep the gateway // running and let the announcer retry unrecorded recipients next time. g.log.Warn("release announcement failed", "error", err) } } // Stop gracefully shuts down the bot. func (g *Gateway) Stop(ctx context.Context) error { if !g.running { return nil } g.log.Info("stopping telegram gateway") g.running = false g.outbound.Store(nil) g.abandonAllLive(ctx) return nil } // ── command handlers (gateway-local -- no LLM) ──────────────── func (g *Gateway) statusHandler(client messaging.ChatContract) bot.HandlerFunc { return g.routeCmdHandler(client, "/status") } func (g *Gateway) whoamiHandler(client messaging.ChatContract) bot.HandlerFunc { return g.routeCmdHandler(client, "/whoami") } func (g *Gateway) profileHandler(client messaging.ChatContract) bot.HandlerFunc { return g.routeCmdHandler(client, "/profile") } func (g *Gateway) sessionsHandler(client messaging.ChatContract) bot.HandlerFunc { return g.routeCmdHandler(client, "/sessions") } func (g *Gateway) agentsHandler(client messaging.ChatContract) bot.HandlerFunc { return g.routeCmdHandler(client, "/agents") } func (g *Gateway) resumeHandler(client messaging.ChatContract) bot.HandlerFunc { return func(ctx context.Context, b *bot.Bot, update *models.Update) { msg, ok := g.authorizedMessage(ctx, b, update) if !ok { return } reply, err := client.Route(ctx, messaging.Inbound{Platform: "telegram", Message: messaging.Message{ ConversationID: conversationID(msg), Sender: msg.From.Username, Role: messaging.RoleUser, Text: msg.Text, }}) if err != nil { g.log.Error("resume handler failed", "error", err) return } g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, reply.Text) } } // routeCmdHandler builds a handler that routes a fixed command through the // messaging.ChatContract and sends the reply. func (g *Gateway) routeCmdHandler(client messaging.ChatContract, cmd string) bot.HandlerFunc { return func(ctx context.Context, b *bot.Bot, update *models.Update) { msg, ok := g.authorizedMessage(ctx, b, update) if !ok { return } reply, err := client.Route(ctx, messaging.Inbound{Platform: "telegram", Message: messaging.Message{ ConversationID: conversationID(msg), Sender: msg.From.Username, Role: messaging.RoleUser, Text: cmd, }}) if err != nil { g.log.Error("command handler failed", "command", cmd, "error", err) return } g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, reply.Text) } } func (g *Gateway) settingsHandler() bot.HandlerFunc { return func(ctx context.Context, b *bot.Bot, update *models.Update) { msg, ok := g.authorizedMessage(ctx, b, update) if !ok { return } actor := "" if g.ResolveActor != nil { actor, _ = g.ResolveActor(msg.From.ID) } input := strings.TrimSpace(strings.TrimPrefix(msg.Text, "/settings")) reply := g.Settings.Execute(ctx, actor, input) g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, reply) } } func (g *Gateway) versionHandler() bot.HandlerFunc { return func(ctx context.Context, b *bot.Bot, update *models.Update) { msg, ok := g.authorizedMessage(ctx, b, update) if !ok { return } if g.Version == nil { g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "Version information is not configured.") return } g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, g.Version()) } } func (g *Gateway) helpHandler() bot.HandlerFunc { return func(ctx context.Context, b *bot.Bot, update *models.Update) { msg, ok := g.authorizedMessage(ctx, b, update) if !ok { return } g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, gatewayHelpText()) } } func (g *Gateway) startHandler() bot.HandlerFunc { return func(ctx context.Context, b *bot.Bot, update *models.Update) { msg, ok := g.authorizedMessage(ctx, b, update) if !ok { return } g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "Archie is running. Send a message to chat, or type /help for available commands.") } } // ── default handler (commands and non-command messages → router) ───── func (g *Gateway) defaultHandler(client messaging.ChatContract) bot.HandlerFunc { return func(ctx context.Context, b *bot.Bot, update *models.Update) { if update.CallbackQuery != nil { g.handleCallback(ctx, b, update, client) return } msg, ok := g.authorizedMessage(ctx, b, update) if !ok { return } // A text reply to a pending clarify/picker prompt is consumed here so // it answers the blocked interaction instead of starting a new turn. if g.deliverInteractiveReply(msg) { return } // Media messages arrive before the text gates: a photo has no text, // so checking it first is what keeps attachments from being dropped. if _, isMedia := extractInboundMedia(msg); isMedia { g.submitTurn(ctx, b, msg, client) return } if notice := unsupportedMediaNotice(msg); notice != "" { g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, notice) return } if msg.Text == "" { return } if isModelSelectorRequest(msg.Text) { g.sendProviderSelector(ctx, b, msg, client) return } if isModelCommand(msg.Text) { g.handleModelCommand(ctx, b, msg, client) return } g.submitTurn(ctx, b, msg, client) } } // handleCallback dispatches an inline-button callback query to the handler // for its prefix. Callback prefixes are mutually exclusive; an unknown // callback is ignored. func (g *Gateway) handleCallback(ctx context.Context, b *bot.Bot, update *models.Update, client messaging.ChatContract) { switch { case strings.HasPrefix(update.CallbackQuery.Data, approvalCallbackPrefix): g.handleApprovalCallback(ctx, b, update) case strings.HasPrefix(update.CallbackQuery.Data, providerCallbackPrefix): g.handleProviderCallback(ctx, b, update, client) case strings.HasPrefix(update.CallbackQuery.Data, modelCallbackPrefix): g.handleModelCallback(ctx, b, update, client) case strings.HasPrefix(update.CallbackQuery.Data, modelPageCallbackPrefix): g.handleModelPageCallback(ctx, b, update, client) case update.CallbackQuery.Data == modelBackCallback: g.handleModelBackCallback(ctx, b, update, client) case update.CallbackQuery.Data == modelCancelCallback: g.handleModelCancelCallback(ctx, b, update) case update.CallbackQuery.Data == modelNoopCallback: g.handleModelNoopCallback(ctx, b, update) case strings.HasPrefix(update.CallbackQuery.Data, updateCallbackPrefix): g.handleUpdateCallback(ctx, b, update) } } // turnInbound converts a Telegram message into an inbound turn. ok is false // for messages with no text or media. func turnInbound(msg *models.Message, media inboundMedia, hasMedia bool) (messaging.Inbound, bool) { if !hasMedia && msg.Text == "" { return messaging.Inbound{}, false } gm := messaging.Inbound{ Platform: "telegram", Message: messaging.Message{ // The message ID makes redelivery idempotent. SourceID: fmt.Sprintf("%d", msg.ID), ConversationID: conversationID(msg), Sender: msg.From.Username, SenderID: fmt.Sprintf("%d", msg.From.ID), Role: messaging.RoleUser, Text: turnMessageText(msg, media, hasMedia), At: time.Unix(int64(msg.Date), 0).UTC(), }, } if hasMedia { gm.Media = []messaging.MediaAttachment{media.attachment} } return gm, true } func (g *Gateway) submitTurn(ctx context.Context, b *bot.Bot, msg *models.Message, client messaging.ChatContract) { media, hasMedia := extractInboundMedia(msg) gm, isTurn := turnInbound(msg, media, hasMedia) if !isTurn { return } // The lane key must be the session, so that /stop -- which resolves // the same key -- reaches the turn the sender is actually watching. session := conversationID(msg).String() chatID, threadID := msg.Chat.ID, msg.MessageThreadID g.turns.Submit(ctx, session, func(turnCtx context.Context) { if !g.fetchTurnMedia(turnCtx, b, &gm, chatID, threadID) { return } // If the turn invokes a tool that requires human approval, // the dispatch layer blocks on this approver. Nil is fine // — most turns need no gating. approver := g.NewApprover(b, chatID, threadID, msg.From.ID) turnCtx = messaging.WithApprovalRequester(turnCtx, approver) // A clarify or picker prompt blocks the turn on this adapter; when the // channel cannot carry one the question tool is simply not offered. turnCtx = messaging.WithInteractive(turnCtx, g.NewInteractor(b, chatID, threadID, msg.From.ID)) // reply appears as it is written; the typing indicator covers the // gap before the first token and any non-streaming path. stopTyping := g.startTyping(turnCtx, b, chatID, threadID) live := g.newLiveReply(turnCtx, b, chatID, threadID, g.ShowToolCalls()) events, err := client.Stream(turnCtx, gm) if err != nil { stopTyping() if errors.Is(err, context.Canceled) || errors.Is(turnCtx.Err(), context.Canceled) { g.log.Info("chat turn stopped", "session", session) live.abandon(turnCtx) } else { g.log.Error("stream failed", "error", err) live.abandonFailed(turnCtx) } return } reply, aborted := g.drainTurnEvents(turnCtx, session, live, stopTyping, events) if aborted { return } live.finalize(turnCtx, reply) }) } // drainTurnEvents renders a streamed turn's events and returns the final // reply. A cancelled turn is abandoned cleanly; a failed one is marked // failed. aborted means the reply must not be finalized. func (g *Gateway) drainTurnEvents( turnCtx context.Context, session string, live *liveReply, stopTyping func(), events <-chan messaging.ChatEvent, ) (string, bool) { var reply string var streamErr error for ev := range events { switch ev.Kind { case "delta": live.Delta(ev.Text) case "tool": live.ToolCall(ev.Tool) case "media": live.Media(turnCtx, ev.Media) case "done": reply = ev.Text case "error": streamErr = errors.New(ev.Text) } } stopTyping() if streamErr != nil || turnCtx.Err() != nil { if errors.Is(turnCtx.Err(), context.Canceled) || (streamErr != nil && errors.Is(streamErr, context.Canceled)) { g.log.Info("chat turn stopped", "session", session) live.abandon(turnCtx) } else { g.log.Error("stream turn failed", "error", streamErr) live.abandonFailed(turnCtx) } return "", true } return reply, false } // fetchTurnMedia downloads the turn's attachment. A failed download is // reported and the turn does not start. func (g *Gateway) fetchTurnMedia(ctx context.Context, b *bot.Bot, gm *messaging.Inbound, chatID int64, threadID int) bool { if len(gm.Media) == 0 || gm.Media[0].Data != nil { return true } data, err := g.downloadMedia(ctx, b, gm.Media[0]) if err != nil { g.log.Warn("inbound media download failed", "media_type", gm.Media[0].Type, "error", err) g.sendMessage(ctx, b, chatID, threadID, mediaReplyLabel(gm.Media[0])+"but I couldn't download it — try sending it again.") return false } gm.Media[0].Data = data return true } // ── helpers ────────────────────────────────────────────────────── // conversationID addresses the chat a Telegram message arrived in: the // chat ID, and the topic thread within it for supergroups. func conversationID(msg *models.Message) messaging.ConversationID { return messaging.ConversationID{ ChannelID: fmt.Sprintf("%d", msg.Chat.ID), ThreadID: threadIDString(msg.MessageThreadID), } } // threadIDString converts a Telegram message_thread_id to a string suitable // for messaging.ConversationID.ThreadID and SessionSource.ThreadID. A zero // value (no topic thread, or the General topic) maps to empty string so that // flat-chat routing continues to work without changes. func threadIDString(id int) string { if id == 0 { return "" } return fmt.Sprintf("%d", id) } func (g *Gateway) authorizedMessage(ctx context.Context, b *bot.Bot, update *models.Update) (*models.Message, bool) { if update.Message == nil || update.Message.From == nil { return nil, false } if g.isSenderAllowed(update.Message.From.ID) { return update.Message, true } g.log.Warn( "message from unauthorized sender", "user_id", update.Message.From.ID, "username", update.Message.From.Username, "chat_id", update.Message.Chat.ID, ) // Reply so an authorised user who is simply missing from the list can // tell the bot is alive and misconfigured, rather than dead. g.sendMessage(ctx, b, update.Message.Chat.ID, update.Message.MessageThreadID, "⛔ You are not authorised to use this bot.") return nil, false } // typingRefresh is how often the typing action is re-sent. Telegram clears // the indicator after ~5s, so it must be refreshed to stay visible for the // length of an LLM turn. const typingRefresh = 4 * time.Second // startTyping shows the "typing…" indicator and keeps it alive until the // returned stop function is called. Errors are logged at debug level only: // a missing typing indicator must never block or fail the actual reply. func (g *Gateway) startTyping(ctx context.Context, b *bot.Bot, chatID int64, messageThreadID int) (stop func()) { send := func() { params := &bot.SendChatActionParams{ ChatID: chatID, Action: models.ChatActionTyping, } if messageThreadID != 0 { params.MessageThreadID = messageThreadID } if _, err := b.SendChatAction(ctx, params); err != nil { g.log.Debug("send chat action failed", "error", err) } } typingCtx, cancel := context.WithCancel(ctx) send() go func() { ticker := time.NewTicker(typingRefresh) defer ticker.Stop() for { select { case <-typingCtx.Done(): return case <-ticker.C: send() } } }() return cancel } // isSenderAllowed reports whether a message's sender may use the bot. // An empty allowlist denies everyone (see Gateway.AllowedUserIDs). func (g *Gateway) isSenderAllowed(userID int64) bool { return slices.Contains(g.AllowedUserIDs, userID) } // messageMaxLen keeps a single message under Telegram's 4096 character // limit, with room for the continuation marker split adds. const messageMaxLen = 4000 // telegramRenderVersion identifies the renderer applied to outgoing Telegram // messages. It is included in the per-send log line so an old deployment // cannot be mistaken for the current code when diagnosing rendering // differences. const telegramRenderVersion = "rich-markdown-v2" func (g *Gateway) sendMessage(ctx context.Context, b *bot.Bot, chatID int64, messageThreadID int, text string) { blocks := markdownToBlocks(text) if total := blockTextLen(blocks); total <= messageMaxLen { g.sendBlocks(ctx, b, chatID, messageThreadID, blocks, "send message failed") return } parts := splitBlocks(blocks, messageMaxLen) for i, part := range parts { if i < len(parts)-1 { part = append(part, paragraphBlock("_(continued...)_")) } g.sendBlocks(ctx, b, chatID, messageThreadID, part, "send message part failed") } } // Send delivers text to chatID, split like a reply. It fails if the bot is not // running or any part is rejected. func (g *Gateway) Send(ctx context.Context, chatID, text string) error { b := g.outbound.Load() if b == nil { return channels.ErrNotRunning } id, err := strconv.ParseInt(chatID, 10, 64) if err != nil { return fmt.Errorf("telegram chat id %q: %w", chatID, err) } for _, part := range splitBlocks(markdownToBlocks(text), messageMaxLen) { if g.sendBlocks(ctx, b, id, 0, part, "deliver message failed") == 0 { return fmt.Errorf("telegram rejected a message to chat %d", id) } } return nil } // sendBlocks sends one rich message and returns its ID, or 0. A rejected rich // message is resent as plain text. func (g *Gateway) sendBlocks(ctx context.Context, b *bot.Bot, chatID int64, messageThreadID int, blocks []models.InputRichBlock, errMsg string) int { rich := &bot.SendRichMessageParams{ ChatID: chatID, RichMessage: models.InputRichMessage{Blocks: blocks}, } if messageThreadID != 0 { rich.MessageThreadID = messageThreadID } if msg, err := b.SendRichMessage(ctx, rich); err == nil { g.log.Debug("telegram message sent", "renderer", telegramRenderVersion, "mode", "rich") return msg.ID } else { g.log.Warn("rich send failed, retrying unformatted", "error", err) } plain := &bot.SendMessageParams{ChatID: chatID, Text: strings.Join(blocksToPlainText(blocks), "\n\n")} if messageThreadID != 0 { plain.MessageThreadID = messageThreadID } if msg, err := b.SendMessage(ctx, plain); err != nil { g.log.Error(errMsg, "error", err) return 0 } else { g.log.Warn("telegram message sent via plain fallback", "renderer", telegramRenderVersion, "mode", "plain") return msg.ID } } // blockTextLen is the rune length of a block slice as rendered plain text. func blockTextLen(blocks []models.InputRichBlock) int { return len([]rune(strings.Join(blocksToPlainText(blocks), "\n"))) } // ── middlewares ────────────────────────────────────────────── func (g *Gateway) panicRecoveryMiddleware() bot.Middleware { return func(next bot.HandlerFunc) bot.HandlerFunc { return func(ctx context.Context, b *bot.Bot, update *models.Update) { defer func() { if r := recover(); r != nil { kind, chatID, hasChat := updateMetadata(update) attrs := []any{ "panic", r, "update_kind", kind, "update_id", update.ID, "stack", string(debug.Stack()), } if hasChat { attrs = append(attrs, "chat_id", chatID) } g.log.Error("panic in telegram middleware", attrs...) } }() next(ctx, b, update) } } } func (g *Gateway) updateLoggingMiddleware() bot.Middleware { return func(next bot.HandlerFunc) bot.HandlerFunc { return func(ctx context.Context, b *bot.Bot, update *models.Update) { kind, chatID, hasChat := updateMetadata(update) attrs := []any{"update_kind", kind, "update_id", update.ID} if hasChat { attrs = append(attrs, "chat_id", chatID) } if threadID := updateThreadID(update); threadID != 0 { attrs = append(attrs, "thread_id", threadID) } g.log.Debug("telegram update", attrs...) next(ctx, b, update) } } } func updateMetadata(update *models.Update) (kind string, chatID int64, hasChat bool) { switch { case update == nil: return "unknown", 0, false case update.Message != nil: return "message", update.Message.Chat.ID, true case update.CallbackQuery != nil: if update.CallbackQuery.Message.Message != nil { return "callback_query", update.CallbackQuery.Message.Message.Chat.ID, true } return "callback_query", 0, false default: return "other", 0, false } } // updateThreadID extracts the message_thread_id from an update for logging // and session routing. Returns 0 for flat chats / non-message updates. func updateThreadID(update *models.Update) int { if update == nil || update.Message == nil { return 0 } return update.Message.MessageThreadID } // ConfigSchema returns the JSON Schema for the Telegram channel config. // The bot token is a secret reference object with engine/key. func (g *Gateway) ConfigSchema() json.RawMessage { return json.RawMessage(`{ "type": "object", "required": ["token"], "properties": { "token": { "type": "object", "description": "Secret reference for the Telegram bot token from @BotFather, resolved through the configured secret engine.", "properties": { "engine": { "type": "string" }, "key": { "type": "string" } } }, "allowed_user_ids": { "type": "array", "items": { "type": "integer" }, "description": "Restrict bot access to specific Telegram user ids" } } }`) } // ValidateConfig checks the Telegram channel configuration. A token // secret reference is required. func (g *Gateway) ValidateConfig(cfg map[string]any) error { if cfg == nil { return fmt.Errorf("telegram config is required") } if _, ok := cfg["token"]; !ok { return fmt.Errorf("telegram.token is required") } return nil } // Compile-time guard. var _ channels.Channel = (*Gateway)(nil) // dropPendingUpdates discards queued updates before long polling starts, // via deleteWebhook. Best-effort. func (g *Gateway) dropPendingUpdates(ctx context.Context, b *bot.Bot) { ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() if _, err := b.DeleteWebhook(ctx, &bot.DeleteWebhookParams{DropPendingUpdates: true}); err != nil { g.log.Warn("could not drop pending telegram updates, backlog may be replayed", "error", err) } }