Two gaps visible in the live heyarchie bot: 1. No typing indicator. A non-command message runs a full LLM turn (seconds), during which the chat looked dead. defaultHandler now shows the typing action for the duration, refreshed every 4s since Telegram clears it after ~5s. 2. ParseMode was never set, so LLM Markdown reached users verbatim: literal **bold**, backticks, and pipe tables. helpHandler was worse -- it emitted <b>Archie Gateway</b> with no ParseMode, so the raw tags were shown. The SDK has no Markdown->Telegram converter (EscapeMarkdown does the inverse: it escapes text so it renders literally), and neither native parse mode helps, since Telegram's Markdown dialects use single-asterisk *bold* whereas LLMs emit **bold**. So markdownToHTML converts to the HTML subset Telegram accepts, mapping headings to <b>, bullets to '•', and tables to <pre> (Telegram has no table element). Send falls back to unformatted text if Telegram rejects the markup, so a conversion bug can never swallow a reply.
483 lines
14 KiB
Go
483 lines
14 KiB
Go
// 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"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
"runtime/debug"
|
|
"slices"
|
|
"strings"
|
|
"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/gateway"
|
|
)
|
|
|
|
// Gateway is a Telegram gateway.Gateway backed by go-telegram/bot.
|
|
type Gateway struct {
|
|
Token string
|
|
WebhookURL string
|
|
WebhookSecret string
|
|
// AllowedChatIDs restricts which chats may use the bot. Empty = anyone.
|
|
AllowedChatIDs []int64
|
|
log *slog.Logger
|
|
bot *bot.Bot
|
|
webhookCancel context.CancelFunc
|
|
running bool
|
|
}
|
|
|
|
// New returns an unstarted Gateway. Call Start to begin webhook
|
|
// processing.
|
|
func New(token, webhookURL, webhookSecret string, allowedChatIDs []int64, log *slog.Logger) *Gateway {
|
|
return &Gateway{
|
|
Token: token,
|
|
WebhookURL: webhookURL,
|
|
WebhookSecret: webhookSecret,
|
|
AllowedChatIDs: allowedChatIDs,
|
|
log: log.With("component", "gateway-telegram"),
|
|
}
|
|
}
|
|
|
|
func (g *Gateway) Name() string { return "telegram" }
|
|
|
|
// Start builds the bot, registers handlers, sets the webhook (if
|
|
// configured), and begins processing. Blocks until ctx is cancelled.
|
|
func (g *Gateway) Start(ctx context.Context, router *gateway.Router) error {
|
|
if g.Token == "" {
|
|
return fmt.Errorf("telegram bot token is required")
|
|
}
|
|
g.log.Info("starting telegram gateway")
|
|
|
|
opts := []bot.Option{
|
|
bot.WithErrorsHandler(func(err error) {
|
|
g.log.Error("telegram pipeline error", "error", err)
|
|
}),
|
|
bot.WithDebugHandler(func(format string, args ...any) {
|
|
g.log.Debug("telegram debug", "message", fmt.Sprintf(format, args...))
|
|
}),
|
|
bot.WithDefaultHandler(g.defaultHandler(router)),
|
|
bot.WithMiddlewares(g.panicRecoveryMiddleware(), g.updateLoggingMiddleware()),
|
|
}
|
|
if g.WebhookSecret != "" {
|
|
opts = append(opts, bot.WithWebhookSecretToken(g.WebhookSecret))
|
|
}
|
|
|
|
b, err := bot.New(g.Token, opts...)
|
|
if err != nil {
|
|
return fmt.Errorf("create bot: %w", err)
|
|
}
|
|
g.bot = b
|
|
|
|
// Gateway-local commands: handled directly, no LLM.
|
|
b.RegisterHandler(bot.HandlerTypeMessageText, "/status", bot.MatchTypePrefix, g.statusHandler(router))
|
|
b.RegisterHandler(bot.HandlerTypeMessageText, "/help", bot.MatchTypePrefix, g.helpHandler())
|
|
|
|
// Set up webhook or fall back to long polling.
|
|
if g.WebhookURL != "" {
|
|
params := &bot.SetWebhookParams{
|
|
URL: g.WebhookURL,
|
|
SecretToken: g.WebhookSecret,
|
|
MaxConnections: 40,
|
|
AllowedUpdates: []string{"message"},
|
|
DropPendingUpdates: true,
|
|
}
|
|
if _, err := b.SetWebhook(ctx, params); err != nil {
|
|
return fmt.Errorf("set webhook: %w", err)
|
|
}
|
|
g.log.Info("webhook set", "url", g.WebhookURL)
|
|
|
|
info, err := b.GetWebhookInfo(ctx)
|
|
if err != nil {
|
|
g.log.Warn("failed to get webhook info", "error", err)
|
|
} else {
|
|
g.log.Info("webhook info",
|
|
"url", info.URL,
|
|
"pending_update_count", info.PendingUpdateCount,
|
|
"last_error_message", info.LastErrorMessage,
|
|
"max_connections", info.MaxConnections,
|
|
)
|
|
}
|
|
|
|
webhookCtx, cancel := context.WithCancel(ctx)
|
|
g.webhookCancel = cancel
|
|
g.running = true
|
|
go b.StartWebhook(webhookCtx)
|
|
} else {
|
|
g.running = true
|
|
go b.Start(ctx)
|
|
}
|
|
|
|
<-ctx.Done()
|
|
return nil
|
|
}
|
|
|
|
// Stop gracefully shuts down the bot and deletes the webhook.
|
|
func (g *Gateway) Stop(ctx context.Context) error {
|
|
if !g.running {
|
|
return nil
|
|
}
|
|
g.log.Info("stopping telegram gateway")
|
|
g.running = false
|
|
|
|
if g.webhookCancel != nil {
|
|
g.webhookCancel()
|
|
g.webhookCancel = nil
|
|
}
|
|
if g.WebhookURL != "" && g.bot != nil {
|
|
if _, err := g.bot.DeleteWebhook(ctx, &bot.DeleteWebhookParams{DropPendingUpdates: true}); err != nil {
|
|
g.log.Warn("error deleting webhook", "error", err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// WebhookHandler returns the HTTP handler for Telegram webhooks.
|
|
func (g *Gateway) WebhookHandler() http.Handler {
|
|
if g.bot == nil {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
http.Error(w, "bot not initialized", http.StatusServiceUnavailable)
|
|
})
|
|
}
|
|
return g.bot.WebhookHandler()
|
|
}
|
|
|
|
// ── command handlers (gateway-local -- no LLM) ────────────────
|
|
|
|
func (g *Gateway) statusHandler(router *gateway.Router) 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 := router.Route(ctx, gateway.Message{
|
|
ChannelID: fmt.Sprintf("%d", msg.Chat.ID),
|
|
ThreadID: threadIDString(msg.MessageThreadID),
|
|
From: msg.From.Username,
|
|
Text: "/status",
|
|
})
|
|
if err != nil {
|
|
g.log.Error("status handler failed", "error", err)
|
|
return
|
|
}
|
|
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, reply)
|
|
}
|
|
}
|
|
|
|
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,
|
|
"🤖 **Archie Gateway**\n\n"+
|
|
"/status -- Show task status\n"+
|
|
"/help -- This message\n\n"+
|
|
"Anything else: chat with the LLM (not yet wired -- coming soon).")
|
|
}
|
|
}
|
|
|
|
// ── default handler (non-command text → router) ─────────────
|
|
|
|
func (g *Gateway) defaultHandler(router *gateway.Router) bot.HandlerFunc {
|
|
return func(ctx context.Context, b *bot.Bot, update *models.Update) {
|
|
msg, ok := g.authorizedMessage(ctx, b, update)
|
|
if !ok || msg.Text == "" {
|
|
return
|
|
}
|
|
|
|
// Routing a non-command message runs an LLM turn, which can take
|
|
// many seconds. Show a typing indicator for the whole wait so the
|
|
// chat doesn't look dead.
|
|
stopTyping := g.startTyping(ctx, b, msg.Chat.ID, msg.MessageThreadID)
|
|
|
|
// If it starts with / but wasn't matched by a registered
|
|
// handler, it's unknown -- let the router handle it (which
|
|
// will say "unrecognized").
|
|
reply, err := router.Route(ctx, gateway.Message{
|
|
ChannelID: fmt.Sprintf("%d", msg.Chat.ID),
|
|
ThreadID: threadIDString(msg.MessageThreadID),
|
|
From: msg.From.Username,
|
|
Text: msg.Text,
|
|
})
|
|
stopTyping()
|
|
if err != nil {
|
|
g.log.Error("route failed", "error", err)
|
|
return
|
|
}
|
|
if reply != "" {
|
|
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, reply)
|
|
}
|
|
}
|
|
}
|
|
|
|
// ── helpers ──────────────────────────────────────────────────
|
|
|
|
// threadIDString converts a Telegram message_thread_id to a string suitable
|
|
// for gateway.Message.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 {
|
|
return nil, false
|
|
}
|
|
if g.isChatAllowed(update.Message.Chat.ID) {
|
|
return update.Message, true
|
|
}
|
|
g.log.Warn("message from unauthorized chat", "chat_id", update.Message.Chat.ID)
|
|
g.sendMessage(ctx, b, update.Message.Chat.ID, update.Message.MessageThreadID,
|
|
"⛔ This bot is not available in this chat.")
|
|
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
|
|
}
|
|
|
|
func (g *Gateway) isChatAllowed(chatID int64) bool {
|
|
if len(g.AllowedChatIDs) == 0 {
|
|
return true
|
|
}
|
|
return slices.Contains(g.AllowedChatIDs, chatID)
|
|
}
|
|
|
|
func (g *Gateway) sendMessage(ctx context.Context, b *bot.Bot, chatID int64, messageThreadID int, text string) {
|
|
// Split long messages to stay under Telegram's 4096 character limit.
|
|
const maxLen = 4000
|
|
if len(text) <= maxLen {
|
|
g.send(ctx, b, chatID, messageThreadID, text, "send message failed")
|
|
return
|
|
}
|
|
parts := splitLongMessage(text, maxLen)
|
|
for i, part := range parts {
|
|
partText := part
|
|
if i < len(parts)-1 {
|
|
partText += "\n\n_(continued...)_"
|
|
}
|
|
g.send(ctx, b, chatID, messageThreadID, partText, "send message part failed")
|
|
}
|
|
}
|
|
|
|
// send delivers one message, rendering Markdown as Telegram HTML.
|
|
//
|
|
// Splitting a long reply can cut an HTML tag in half, and a hand-written
|
|
// converter can always meet Markdown it maps wrongly; in both cases
|
|
// Telegram rejects the whole message with a parse error. Rather than lose
|
|
// the reply, fall back to sending the original unformatted text -- the user
|
|
// sees raw Markdown, which is what happened before formatting existed, but
|
|
// never silence.
|
|
func (g *Gateway) send(ctx context.Context, b *bot.Bot, chatID int64, messageThreadID int, text, errMsg string) {
|
|
params := &bot.SendMessageParams{
|
|
ChatID: chatID,
|
|
Text: markdownToHTML(text),
|
|
ParseMode: models.ParseModeHTML,
|
|
}
|
|
if messageThreadID != 0 {
|
|
params.MessageThreadID = messageThreadID
|
|
}
|
|
if _, err := b.SendMessage(ctx, params); err == nil {
|
|
return
|
|
} else {
|
|
g.log.Warn("formatted send failed, retrying unformatted", "error", err)
|
|
}
|
|
|
|
plain := &bot.SendMessageParams{ChatID: chatID, Text: text}
|
|
if messageThreadID != 0 {
|
|
plain.MessageThreadID = messageThreadID
|
|
}
|
|
if _, err := b.SendMessage(ctx, plain); err != nil {
|
|
g.log.Error(errMsg, "error", err)
|
|
}
|
|
}
|
|
|
|
func splitLongMessage(text string, maxLen int) []string {
|
|
if len(text) <= maxLen {
|
|
return []string{text}
|
|
}
|
|
var parts []string
|
|
lines := strings.Split(text, "\n")
|
|
var cur strings.Builder
|
|
for _, line := range lines {
|
|
if cur.Len()+len(line)+1 > maxLen {
|
|
if cur.Len() > 0 {
|
|
parts = append(parts, cur.String())
|
|
cur.Reset()
|
|
}
|
|
if len(line) > maxLen {
|
|
for i := 0; i < len(line); i += maxLen {
|
|
end := min(i+maxLen, len(line))
|
|
parts = append(parts, line[i:end])
|
|
}
|
|
continue
|
|
}
|
|
}
|
|
if cur.Len() > 0 {
|
|
cur.WriteByte('\n')
|
|
}
|
|
cur.WriteString(line)
|
|
}
|
|
if cur.Len() > 0 {
|
|
parts = append(parts, cur.String())
|
|
}
|
|
return parts
|
|
}
|
|
|
|
// ── 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.
|
|
func (g *Gateway) ConfigSchema() json.RawMessage {
|
|
return json.RawMessage(`{
|
|
"type": "object",
|
|
"required": ["token_env"],
|
|
"properties": {
|
|
"token_env": {
|
|
"type": "string",
|
|
"description": "Environment variable holding the Telegram bot token from @BotFather"
|
|
},
|
|
"webhook_url": {
|
|
"type": "string",
|
|
"description": "Public HTTPS URL for Telegram webhook delivery"
|
|
},
|
|
"webhook_secret": {
|
|
"type": "string",
|
|
"description": "Secret token for webhook validation"
|
|
},
|
|
"allowed_chat_ids": {
|
|
"type": "array",
|
|
"items": { "type": "integer" },
|
|
"description": "Restrict bot access to specific chat IDs"
|
|
}
|
|
}
|
|
}`)
|
|
}
|
|
|
|
// ValidateConfig checks the Telegram channel configuration.
|
|
func (g *Gateway) ValidateConfig(cfg map[string]any) error {
|
|
if cfg == nil {
|
|
return fmt.Errorf("telegram config is required")
|
|
}
|
|
tokenEnv, _ := cfg["token_env"].(string)
|
|
if tokenEnv == "" {
|
|
return fmt.Errorf("telegram.token_env is required")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Compile-time guard.
|
|
var _ channels.Channel = (*Gateway)(nil)
|