feat(messaging): run Telegram as an archipelago channel extension (#1399)

The bundled internal/channels/telegram package (17 files) is deleted; the
channel now ships as archipelago/channels/telegram, launched by archiemessaging
through the existing channel-extension machinery. An existing [chat.telegram]
config enables it with the same keys: the token stays a secret reference
(token_ref) the host resolves, allowed_user_ids and show_tool_calls map onto
extension settings. Per-org bots compose the same extension per org from the
org's credential binding. Reload support is now derived from a channels.Reloader
interface instead of a *telegram.Gateway assertion. The five host-only seams
(/update, release announcements, running versions, in-place show_tool_calls,
reload) are dropped from the channel and need a contract home or deletion.
This commit is contained in:
sam committed 2026-10-31 15:30:27 +11:00
1 parent d03062cad8
commit 86501fa1d4
10 files changed
+2115 -276

No files matched your search

+492
View File
@@ -0,0 +1,492 @@
// Command telegram is the Telegram chat channel. It long-polls the Bot API,
// routes messages from allowed user ids through the gateway ChatService, and
// replies in the chat. Settings: token_ref ("engine:key" naming the bot token
// from @BotFather), allowed_user_ids (comma-separated Telegram user ids; empty
// denies everyone) and show_tool_calls ("true"/"false", default false).
package main
import (
"context"
"errors"
"fmt"
"log/slog"
"slices"
"strconv"
"strings"
"sync"
"time"
"github.com/go-telegram/bot"
"github.com/go-telegram/bot/models"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/samcharles93/archipelago/sdk/channel"
gatewayv1 "github.com/samcharles93/archipelago/sdk/gateway/v1"
)
const platform = "telegram"
type settings struct {
token string
allowed []int64
showTools bool
}
func main() { channel.Serve(run) }
func run(ctx context.Context, cfg channel.Config, chat gatewayv1.ChatServiceClient, lifecycle channel.Lifecycle) error {
lifecycle.Starting()
s, err := parseSettings(cfg)
if err != nil {
return err
}
log := slog.Default().With("component", "telegram")
g := &gateway{
settings: s,
chat: chat,
log: log,
pending: map[pendingKey]*pendingAsk{},
}
b, err := bot.New(s.token,
bot.WithDefaultHandler(g.defaultHandler),
bot.WithErrorsHandler(func(err error) { log.WarnContext(ctx, "telegram error", "error", err) }),
bot.WithMiddlewares(g.panicRecovery()),
)
if err != nil {
return fmt.Errorf("telegram: create bot: %w", err)
}
g.bot = b
g.registerCommands(b)
if _, err := b.DeleteWebhook(ctx, &bot.DeleteWebhookParams{DropPendingUpdates: true}); err != nil {
log.WarnContext(ctx, "could not drop pending updates, backlog may be replayed", "error", err)
}
if _, err := b.SetMyCommands(ctx, &bot.SetMyCommandsParams{Commands: botCommands()}); err != nil {
log.WarnContext(ctx, "could not publish the command menu", "error", err)
}
lifecycle.Running()
log.InfoContext(ctx, "telegram channel polling", "allowed_user_ids", len(s.allowed))
b.Start(ctx)
return nil
}
// parseSettings reads the operator's settings. token comes from token_ref,
// which the host resolved into secrets under "token".
func parseSettings(cfg channel.Config) (settings, error) {
s := settings{
token: cfg.Secrets["token"],
showTools: cfg.Settings["show_tool_calls"] == "true",
}
for part := range strings.SplitSeq(cfg.Settings["allowed_user_ids"], ",") {
part = strings.TrimSpace(part)
if part == "" {
continue
}
id, err := strconv.ParseInt(part, 10, 64)
if err != nil || id <= 0 {
return s, fmt.Errorf("telegram: allowed_user_ids %q is not a positive Telegram user id", part)
}
s.allowed = append(s.allowed, id)
}
if s.token == "" {
return s, errors.New("telegram: token_ref is required")
}
if len(s.allowed) == 0 {
return s, errors.New("telegram: allowed_user_ids is required; the bot answers nobody without it")
}
return s, nil
}
// gateway is one running channel: the bot, the chat service and the asks
// waiting on a user decision.
type gateway struct {
settings settings
chat gatewayv1.ChatServiceClient
log *slog.Logger
bot *bot.Bot
mu sync.Mutex
pending map[pendingKey]*pendingAsk
}
// pendingKey identifies the chat an ask was posed to, so only that chat's
// next text or button answers it.
type pendingKey struct {
chatID int64
threadID int
}
// pendingAsk is one question the turn blocks on until Answer names its id.
type pendingAsk struct {
id string
kind string
}
func (g *gateway) allowedUser(userID int64) bool {
return slices.Contains(g.settings.allowed, userID)
}
// authorized returns the message when its sender is allowed, and tells the
// chat otherwise so a misconfigured allowlist is visible rather than silent.
func (g *gateway) authorized(ctx context.Context, update *models.Update) *models.Message {
msg := update.Message
if msg == nil || msg.From == nil {
return nil
}
if g.allowedUser(msg.From.ID) {
return msg
}
g.log.WarnContext(ctx, "message from unauthorized sender",
"user_id", msg.From.ID, "username", msg.From.Username, "chat_id", msg.Chat.ID)
g.sendText(ctx, msg.Chat.ID, msg.MessageThreadID,
"⛔ You are not authorised to use this bot.")
return nil
}
// conversationKey is the session a chat addresses: the chat id, and the topic
// thread within it for supergroups. It matches the host's session key for
// the conversation, so /stop reaches the turn the sender is watching.
func conversationKey(msg *models.Message) string {
if msg.MessageThreadID == 0 {
return strconv.FormatInt(msg.Chat.ID, 10)
}
return strconv.FormatInt(msg.Chat.ID, 10) + "/" + strconv.Itoa(msg.MessageThreadID)
}
// inboundMessage renders a Telegram message as the gateway's wire message.
func inboundMessage(msg *models.Message, text string, media []*gatewayv1.Media) *gatewayv1.Message {
m := &gatewayv1.Message{
MessageId: strconv.Itoa(msg.ID),
SourceId: strconv.Itoa(msg.ID), // redelivery is idempotent on this
ChannelId: strconv.FormatInt(msg.Chat.ID, 10),
From: msg.From.Username,
SenderId: strconv.FormatInt(msg.From.ID, 10),
Text: text,
At: timestampOf(msg.Date),
Platform: platform,
Media: media,
}
if msg.MessageThreadID != 0 {
m.ThreadId = strconv.Itoa(msg.MessageThreadID)
}
return m
}
func timestampOf(unix int) *timestamppb.Timestamp {
if unix == 0 {
return nil
}
return timestamppb.New(time.Unix(int64(unix), 0).UTC())
}
// defaultHandler routes every update that is not a registered command: an
// answer to a pending question first, then media and text as a new turn.
func (g *gateway) defaultHandler(ctx context.Context, b *bot.Bot, update *models.Update) {
if update.CallbackQuery != nil {
g.handleCallback(ctx, update.CallbackQuery)
return
}
msg := g.authorized(ctx, update)
if msg == nil {
return
}
if g.consumePendingAnswer(ctx, msg) {
return
}
text, media := msg.Text, []*gatewayv1.Media(nil)
if attachment, ok := inboundAttachment(msg); ok {
if data, err := g.download(ctx, attachment.fileID); err != nil {
g.log.WarnContext(ctx, "attachment download failed", "file_id", attachment.fileID, "error", err)
g.sendText(ctx, msg.Chat.ID, msg.MessageThreadID, "I couldn't download that file — try sending it again.")
return
} else {
media = []*gatewayv1.Media{{
Type: attachment.kind, FileId: attachment.fileID,
MimeType: attachment.mime, FileName: attachment.name, Data: data,
}}
text = strings.TrimSpace(attachment.note + " " + text)
}
}
if text == "" && len(media) == 0 {
return
}
g.submitTurn(ctx, msg, text, media)
}
// handleCallback answers a pending approval button.
func (g *gateway) handleCallback(ctx context.Context, q *models.CallbackQuery) {
data := q.Data
const prefix = "ask:"
if !strings.HasPrefix(data, prefix) {
_, _ = g.bot.AnswerCallbackQuery(ctx, &bot.AnswerCallbackQueryParams{CallbackQueryID: q.ID})
return
}
rest := strings.TrimPrefix(data, prefix)
askID, answer, ok := strings.Cut(rest, ":")
if !ok {
return
}
key := pendingKey{}
if msg := q.Message.Message; msg != nil {
key = pendingKey{chatID: msg.Chat.ID, threadID: msg.MessageThreadID}
}
g.mu.Lock()
_, pending := g.pending[key]
delete(g.pending, key)
g.mu.Unlock()
_, _ = g.bot.AnswerCallbackQuery(ctx, &bot.AnswerCallbackQueryParams{CallbackQueryID: q.ID})
if !pending {
return
}
if _, err := g.chat.Answer(ctx, &gatewayv1.AnswerRequest{AskId: askID, Answer: answer}); err != nil {
g.log.WarnContext(ctx, "answer failed", "ask_id", askID, "error", err)
return
}
if msg := q.Message.Message; msg != nil {
g.editText(ctx, msg.Chat.ID, msg.ID, "✅ Answered: "+answer)
}
}
// consumePendingAnswer routes a text message that answers a blocked clarify,
// picker or questionnaire instead of starting a new turn.
func (g *gateway) consumePendingAnswer(ctx context.Context, msg *models.Message) bool {
key := pendingKey{chatID: msg.Chat.ID, threadID: msg.MessageThreadID}
g.mu.Lock()
ask, ok := g.pending[key]
if ok {
delete(g.pending, key)
}
g.mu.Unlock()
if !ok || msg.Text == "" {
return false
}
if _, err := g.chat.Answer(ctx, &gatewayv1.AnswerRequest{AskId: ask.id, Answer: msg.Text}); err != nil {
g.log.WarnContext(ctx, "answer failed", "ask_id", ask.id, "error", err)
g.sendText(ctx, msg.Chat.ID, msg.MessageThreadID, "I couldn't deliver that answer; the question may have expired.")
}
return true
}
func (g *gateway) registerCommands(b *bot.Bot) {
for _, cmd := range []struct {
name string
handler bot.HandlerFunc
}{
{"/start", g.startHandler},
{"/help", g.helpHandler},
{"/version", g.versionHandler},
{"/stop", g.stopHandler},
} {
b.RegisterHandler(bot.HandlerTypeMessageText, cmd.name, bot.MatchTypeExact, cmd.handler)
}
b.RegisterHandler(bot.HandlerTypeCallbackQueryData, "ask:", bot.MatchTypePrefix, g.callbackHandler)
}
func (g *gateway) callbackHandler(ctx context.Context, b *bot.Bot, update *models.Update) {
g.handleCallback(ctx, update.CallbackQuery)
}
func (g *gateway) startHandler(ctx context.Context, b *bot.Bot, update *models.Update) {
msg := g.authorized(ctx, update)
if msg == nil {
return
}
g.sendText(ctx, msg.Chat.ID, msg.MessageThreadID,
"Archie is running. Send a message to chat, or type /help for available commands.")
}
func (g *gateway) helpHandler(ctx context.Context, b *bot.Bot, update *models.Update) {
msg := g.authorized(ctx, update)
if msg == nil {
return
}
g.sendText(ctx, msg.Chat.ID, msg.MessageThreadID, helpText())
}
// versionHandler reports the gateway's build, fetched per call.
func (g *gateway) versionHandler(ctx context.Context, b *bot.Bot, update *models.Update) {
msg := g.authorized(ctx, update)
if msg == nil {
return
}
snapshot, err := g.chat.Snapshot(ctx, &gatewayv1.SnapshotRequest{})
if err != nil || snapshot.GetVersion() == "" {
g.sendText(ctx, msg.Chat.ID, msg.MessageThreadID, "Version information is unavailable.")
return
}
g.sendText(ctx, msg.Chat.ID, msg.MessageThreadID, snapshot.GetVersion())
}
// stopHandler serves /stop: bare /stop cancels the conversation's running
// reply, else stops the tasks this conversation created; /stop <id> stops one
// task.
func (g *gateway) stopHandler(ctx context.Context, b *bot.Bot, update *models.Update) {
msg := g.authorized(ctx, update)
if msg == nil {
return
}
rest := strings.TrimSpace(strings.TrimPrefix(msg.Text, "/stop"))
if rest == "" {
g.sendText(ctx, msg.Chat.ID, msg.MessageThreadID, g.stopConversation(ctx, msg))
return
}
id, err := strconv.ParseInt(strings.TrimPrefix(rest, "#"), 10, 64)
if err != nil || id <= 0 {
g.sendText(ctx, msg.Chat.ID, msg.MessageThreadID, "Usage: /stop, or /stop <task-id>")
return
}
g.sendText(ctx, msg.Chat.ID, msg.MessageThreadID, g.stopTasks(ctx, originOf(msg), id))
}
// stopConversation cancels the chat's most recently active session; with none
// running it stops the conversation's tasks instead.
func (g *gateway) stopConversation(ctx context.Context, msg *models.Message) string {
sessions, err := g.chat.GetSessionsByChannel(ctx, &gatewayv1.GetSessionsByChannelRequest{
Platform: platform, ChannelId: strconv.FormatInt(msg.Chat.ID, 10),
})
if err == nil {
thread := ""
if msg.MessageThreadID != 0 {
thread = strconv.Itoa(msg.MessageThreadID)
}
var latest *gatewayv1.Session
for _, s := range sessions.GetSessions() {
if s.GetThreadId() != thread {
continue
}
if latest == nil || s.GetLastActiveAt().AsTime().After(latest.GetLastActiveAt().AsTime()) {
latest = s
}
}
if latest != nil {
if res, err := g.chat.Cancel(ctx, &gatewayv1.CancelRequest{SessionId: latest.GetSessionId()}); err == nil && (res.GetCancelled() || res.GetDropped() > 0) {
return stopReport(res.GetCancelled(), int(res.GetDropped()), nil)
}
}
}
return g.stopTasks(ctx, originOf(msg), 0)
}
func (g *gateway) stopTasks(ctx context.Context, origin string, id int64) string {
res, err := g.chat.StopTasks(ctx, &gatewayv1.StopTasksRequest{Origin: origin, TaskId: id})
if err != nil {
return "Could not stop: " + err.Error()
}
stopped := make([]int64, 0, len(res.GetStopped()))
stopped = append(stopped, res.GetStopped()...)
report := stopReport(false, 0, stopped)
if res.GetError() != "" {
report += "\n\n" + res.GetError()
}
return report
}
func originOf(msg *models.Message) string {
return platform + ":" + conversationKey(msg)
}
func stopReport(cancelled bool, dropped int, tasks []int64) string {
var parts []string
if cancelled {
parts = append(parts, "the running reply")
}
if dropped > 0 {
parts = append(parts, fmt.Sprintf("%d queued message(s)", dropped))
}
if len(tasks) > 0 {
ids := make([]string, len(tasks))
for i, id := range tasks {
ids[i] = "#" + strconv.FormatInt(id, 10)
}
parts = append(parts, "task(s) "+strings.Join(ids, ", "))
}
if len(parts) == 0 {
return "Nothing is running."
}
return "🛑 Stopped " + joinWithAnd(parts) + "."
}
func joinWithAnd(parts []string) string {
switch len(parts) {
case 1:
return parts[0]
case 2:
return parts[0] + " and " + parts[1]
default:
return strings.Join(parts[:len(parts)-1], ", ") + " and " + parts[len(parts)-1]
}
}
// botCommands is the published command menu; the handlers it names are the
// ones this channel answers locally. Everything else routes through the
// gateway like any other message.
func botCommands() []models.BotCommand {
return []models.BotCommand{
{Command: "start", Description: "Confirm that Archie is running"},
{Command: "help", Description: "See what Archie can do"},
{Command: "version", Description: "Show installed Archie versions"},
{Command: "stop", Description: "Stop the running reply or this chat's tasks"},
}
}
func helpText() string {
return "Send a message to chat. Commands: /start, /help, /version, /stop — every other slash command is answered by Archie itself."
}
// sendText sends one message, split under Telegram's 4096-character limit.
func (g *gateway) sendText(ctx context.Context, chatID int64, threadID int, text string) {
for _, part := range splitText(text, messageMaxLen) {
params := &bot.SendMessageParams{ChatID: chatID, Text: part}
if threadID != 0 {
params.MessageThreadID = threadID
}
if _, err := g.bot.SendMessage(ctx, params); err != nil {
g.log.WarnContext(ctx, "send message failed", "chat_id", chatID, "error", err)
}
}
}
func (g *gateway) editText(ctx context.Context, chatID int64, messageID int, text string) {
parts := splitText(text, messageMaxLen)
if _, err := g.bot.EditMessageText(ctx, &bot.EditMessageTextParams{ChatID: chatID, MessageID: messageID, Text: parts[0]}); err != nil {
g.log.DebugContext(ctx, "edit message failed", "chat_id", chatID, "error", err)
}
}
// messageMaxLen keeps one message under Telegram's 4096-character limit.
const messageMaxLen = 4000
// splitText splits on paragraph boundaries, then hard-wraps long lines.
func splitText(text string, max int) []string {
if len([]rune(text)) <= max {
return []string{text}
}
var parts []string
for _, para := range strings.Split(text, "\n\n") {
for len([]rune(para)) > max {
cut := max
if i := strings.LastIndex(para[:min(cut, len(para))], "\n"); i > 0 {
cut = i
}
parts = append(parts, para[:cut])
para = strings.TrimLeft(para[cut:], "\n")
}
if para != "" {
parts = append(parts, para)
}
}
return parts
}
func (g *gateway) panicRecovery() 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 {
g.log.ErrorContext(ctx, "panic in telegram handler", "panic", r)
}
}()
next(ctx, b, update)
}
}
}
+131
View File
@@ -0,0 +1,131 @@
package main
import (
"strings"
"testing"
"github.com/go-telegram/bot/models"
"github.com/samcharles93/archipelago/sdk/channel"
)
func TestParseSettings(t *testing.T) {
for _, tc := range []struct {
name string
cfg channel.Config
wantErr string
check func(t *testing.T, s settings)
}{
{
name: "token and allowlist",
cfg: channel.Config{
Settings: map[string]string{"allowed_user_ids": " 111, 222 ,,333 "},
Secrets: map[string]string{"token": "123:ABC"},
},
check: func(t *testing.T, s settings) {
if s.token != "123:ABC" {
t.Errorf("token = %q", s.token)
}
if len(s.allowed) != 3 || s.allowed[0] != 111 || s.allowed[2] != 333 {
t.Errorf("allowed = %v", s.allowed)
}
if s.showTools {
t.Error("showTools defaulted true")
}
},
},
{
name: "show_tool_calls on",
cfg: channel.Config{
Settings: map[string]string{"allowed_user_ids": "1", "show_tool_calls": "true"},
Secrets: map[string]string{"token": "t"},
},
check: func(t *testing.T, s settings) {
if !s.showTools {
t.Error("showTools = false, want true")
}
},
},
{name: "missing token", cfg: channel.Config{Settings: map[string]string{"allowed_user_ids": "1"}}, wantErr: "token_ref"},
{name: "missing allowlist", cfg: channel.Config{Secrets: map[string]string{"token": "t"}}, wantErr: "allowed_user_ids"},
{name: "empty allowlist", cfg: channel.Config{Secrets: map[string]string{"token": "t"}, Settings: map[string]string{"allowed_user_ids": " ,"}}, wantErr: "allowed_user_ids"},
{name: "bad user id", cfg: channel.Config{Secrets: map[string]string{"token": "t"}, Settings: map[string]string{"allowed_user_ids": "abc"}}, wantErr: "not a positive"},
{name: "negative user id", cfg: channel.Config{Secrets: map[string]string{"token": "t"}, Settings: map[string]string{"allowed_user_ids": "-5"}}, wantErr: "not a positive"},
} {
t.Run(tc.name, func(t *testing.T) {
s, err := parseSettings(tc.cfg)
if tc.wantErr != "" {
if err == nil || !strings.Contains(err.Error(), tc.wantErr) {
t.Fatalf("err = %v, want it to mention %q", err, tc.wantErr)
}
return
}
if err != nil {
t.Fatalf("parseSettings: %v", err)
}
if tc.check != nil {
tc.check(t, s)
}
})
}
}
func TestSplitText(t *testing.T) {
long := strings.Repeat("a", 9000)
parts := splitText(long, messageMaxLen)
if len(parts) != 3 {
t.Fatalf("splitText gave %d parts, want 3", len(parts))
}
for _, p := range parts {
if len([]rune(p)) > messageMaxLen {
t.Errorf("part is %d runes, over the limit", len([]rune(p)))
}
}
if got := splitText("short", messageMaxLen); len(got) != 1 || got[0] != "short" {
t.Errorf("splitText(short) = %v", got)
}
paras := splitText("one\n\n"+long, messageMaxLen)
if paras[0] != "one" {
t.Errorf("first part = %q, want %q", paras[0], "one")
}
}
func TestConversationKey(t *testing.T) {
for _, tc := range []struct {
chatID, thread int64
want string
}{
{123, 0, "123"},
{123, 7, "123/7"},
{-100, 42, "-100/42"},
} {
msg := &models.Message{Chat: models.Chat{ID: tc.chatID}, MessageThreadID: int(tc.thread)}
if got := conversationKey(msg); got != tc.want {
t.Errorf("conversationKey(%d, %d) = %q, want %q", tc.chatID, tc.thread, got, tc.want)
}
}
}
func TestInboundMessage(t *testing.T) {
msg := &models.Message{
ID: 42,
Chat: models.Chat{ID: -100},
MessageThreadID: 7,
From: &models.User{ID: 111, Username: "sam"},
Text: "hello",
Date: 1700000000,
}
m := inboundMessage(msg, "hello", nil)
if m.GetMessageId() != "42" || m.GetSourceId() != "42" {
t.Errorf("ids = %q/%q, want both 42", m.GetMessageId(), m.GetSourceId())
}
if m.GetChannelId() != "-100" || m.GetThreadId() != "7" {
t.Errorf("channel/thread = %q/%q", m.GetChannelId(), m.GetThreadId())
}
if m.GetFrom() != "sam" || m.GetSenderId() != "111" || m.GetPlatform() != "telegram" {
t.Errorf("from/sender/platform = %q/%q/%q", m.GetFrom(), m.GetSenderId(), m.GetPlatform())
}
if m.GetAt() == nil || m.GetAt().GetSeconds() != 1700000000 {
t.Errorf("at = %v", m.GetAt())
}
}
+149
View File
@@ -0,0 +1,149 @@
package main
import (
"context"
"fmt"
"io"
"net/http"
"github.com/go-telegram/bot"
"github.com/go-telegram/bot/models"
gatewayv1 "github.com/samcharles93/archipelago/sdk/gateway/v1"
)
// attachment is one inbound file Telegram carries.
type attachment struct {
fileID, kind, mime, name, note string
}
// inboundAttachment maps a Telegram message's file onto an attachment. A
// message carries at most one file; a photo collapses to its largest size.
func inboundAttachment(msg *models.Message) (attachment, bool) {
switch {
case len(msg.Photo) > 0:
largest := msg.Photo[len(msg.Photo)-1]
for _, size := range msg.Photo {
if size.FileSize >= largest.FileSize {
largest = size
}
}
return attachment{fileID: largest.FileID, kind: "image", mime: "image/jpeg", note: "[photo]"}, true
case msg.Document != nil:
return attachment{
fileID: msg.Document.FileID, kind: "document", mime: msg.Document.MimeType,
name: msg.Document.FileName, note: "[document: " + msg.Document.FileName + "]",
}, true
case msg.Video != nil:
return attachment{fileID: msg.Video.FileID, kind: "video", mime: msg.Video.MimeType, note: "[video]"}, true
case msg.VideoNote != nil:
return attachment{fileID: msg.VideoNote.FileID, kind: "video", mime: "video/mp4", note: "[video message]"}, true
case msg.Voice != nil:
return attachment{fileID: msg.Voice.FileID, kind: "audio", mime: msg.Voice.MimeType, note: "[voice message]"}, true
case msg.Audio != nil:
return attachment{
fileID: msg.Audio.FileID, kind: "audio", mime: msg.Audio.MimeType,
name: msg.Audio.FileName, note: "[audio: " + msg.Audio.FileName + "]",
}, true
}
return attachment{}, false
}
// download fetches an attachment's bytes through the Bot API file link. The
// gateway process never holds the bot token, so the bytes ride on the inbound
// message.
func (g *gateway) download(ctx context.Context, fileID string) ([]byte, error) {
file, err := g.bot.GetFile(ctx, &bot.GetFileParams{FileID: fileID})
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, g.bot.FileDownloadLink(file), nil)
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("telegram: download %s: %s", fileID, resp.Status)
}
return io.ReadAll(io.LimitReader(resp.Body, maxAttachmentBytes))
}
// maxAttachmentBytes bounds one inbound attachment.
const maxAttachmentBytes = 20 << 20
// sendMedia delivers an outbound media event: photos and documents by file id
// or url, anything else as a link.
func (g *gateway) sendMedia(ctx context.Context, chatID int64, threadID int, media *gatewayv1.Media) {
if media == nil {
return
}
var file any
switch {
case media.GetFileId() != "":
file = models.InputFileString{Data: media.GetFileId()}
case media.GetUrl() != "":
file = models.InputFileString{Data: media.GetUrl()}
}
send := func(err error) {
if err != nil {
g.log.WarnContext(ctx, "send media failed", "type", media.GetType(), "error", err)
}
}
switch media.GetType() {
case "image":
if file == nil {
g.sendText(ctx, chatID, threadID, media.GetUrl())
return
}
params := &bot.SendPhotoParams{ChatID: chatID, Photo: file.(models.InputFile)}
if threadID != 0 {
params.MessageThreadID = threadID
}
if media.GetFileName() != "" {
params.Caption = media.GetFileName()
}
_, err := g.bot.SendPhoto(ctx, params)
send(err)
case "video":
if file == nil {
g.sendText(ctx, chatID, threadID, media.GetUrl())
return
}
params := &bot.SendVideoParams{ChatID: chatID, Video: file.(models.InputFile)}
if threadID != 0 {
params.MessageThreadID = threadID
}
_, err := g.bot.SendVideo(ctx, params)
send(err)
case "audio":
if file == nil {
g.sendText(ctx, chatID, threadID, media.GetUrl())
return
}
params := &bot.SendAudioParams{ChatID: chatID, Audio: file.(models.InputFile)}
if threadID != 0 {
params.MessageThreadID = threadID
}
_, err := g.bot.SendAudio(ctx, params)
send(err)
default:
if file == nil {
if media.GetUrl() != "" {
g.sendText(ctx, chatID, threadID, media.GetUrl())
} else if media.GetPath() != "" {
g.sendText(ctx, chatID, threadID, media.GetPath())
}
return
}
params := &bot.SendDocumentParams{ChatID: chatID, Document: file.(models.InputFile)}
if threadID != 0 {
params.MessageThreadID = threadID
}
_, err := g.bot.SendDocument(ctx, params)
send(err)
}
}
+11
View File
@@ -0,0 +1,11 @@
apiVersion: dev.archie.package.v1
displayName: Telegram
description: "Telegram chat channel: long-polls the Bot API, routes messages from allowed user ids through the gateway, and replies in the chat. The bot token is a secret reference (token_ref) resolved by the host."
version: 1.0.0
contributes:
extensions:
- surface: channel
path: bin/telegram
files:
- path: bin/telegram
mode: 493
+257
View File
@@ -0,0 +1,257 @@
package main
import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/go-telegram/bot"
"github.com/go-telegram/bot/models"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
gatewayv1 "github.com/samcharles93/archipelago/sdk/gateway/v1"
)
// typingRefresh is how often the typing indicator is re-sent; Telegram clears
// it after ~5s.
const typingRefresh = 4 * time.Second
// liveEditInterval bounds how often a streaming reply is edited in place.
const liveEditInterval = 2 * time.Second
// submitTurn routes one inbound message as a streamed chat turn and renders
// the reply live: deltas edit one message, tools and media post alongside, and
// the done text replaces what was streamed.
func (g *gateway) submitTurn(ctx context.Context, msg *models.Message, text string, media []*gatewayv1.Media) {
chatID, threadID := msg.Chat.ID, msg.MessageThreadID
in := inboundMessage(msg, text, media)
stopTyping := g.startTyping(ctx, chatID, threadID)
defer stopTyping()
stream, err := g.chat.Stream(ctx, &gatewayv1.StreamRequest{
Message: in,
CanApprove: true,
CanClarify: true,
CanPick: true,
CanQuestion: true,
})
switch status.Code(err) {
case codes.OK:
case codes.InvalidArgument, codes.PermissionDenied:
g.sendText(ctx, chatID, threadID, "Archie refused that message: "+status.Convert(err).Message())
return
default:
if err != nil {
g.log.ErrorContext(ctx, "stream failed", "error", err)
g.sendText(ctx, chatID, threadID, "Something went wrong on my side — try again in a moment.")
return
}
}
live := &liveReply{g: g, chatID: chatID, threadID: threadID}
var reply string
var streamErr error
lastEdit := time.Time{}
for {
ev, err := stream.Recv()
if errors.Is(err, context.Canceled) || ctx.Err() != nil {
return
}
if err != nil {
if status.Code(err) != codes.Canceled {
streamErr = err
}
break
}
switch ev.GetKind() {
case "delta":
live.buf.WriteString(ev.GetText())
if time.Since(lastEdit) >= liveEditInterval {
live.edit(ctx, false)
lastEdit = time.Now()
}
case "tool":
live.toolCall(ctx, ev.GetTool())
case "media":
g.sendMedia(ctx, chatID, threadID, ev.GetMedia())
case "ask":
g.presentAsk(ctx, chatID, threadID, ev.GetAsk())
case "done":
reply = ev.GetText()
case "error":
streamErr = errors.New(ev.GetText())
}
}
stopTyping()
switch {
case streamErr != nil:
g.log.ErrorContext(ctx, "stream turn failed", "error", streamErr)
live.editText(ctx, "⚠️ "+streamErr.Error(), true)
case reply != "":
live.editText(ctx, reply, true)
default:
live.finish(ctx)
}
}
// liveReply is one streamed reply: the deltas accumulate in buf and are edited
// into a single Telegram message.
type liveReply struct {
g *gateway
chatID int64
threadID int
buf strings.Builder
messageID int
}
func (l *liveReply) edit(ctx context.Context, final bool) {
text := l.buf.String()
if l.messageID == 0 {
params := &bot.SendMessageParams{ChatID: l.chatID, Text: clip(text, messageMaxLen)}
if l.threadID != 0 {
params.MessageThreadID = l.threadID
}
if sent, err := l.g.bot.SendMessage(ctx, params); err == nil {
l.messageID = sent.ID
}
return
}
l.g.editText(ctx, l.chatID, l.messageID, clip(text, messageMaxLen))
}
func (l *liveReply) editText(ctx context.Context, text string, final bool) {
if l.messageID == 0 {
l.buf.Reset()
l.buf.WriteString(text)
l.edit(ctx, final)
return
}
l.g.editText(ctx, l.chatID, l.messageID, text)
}
func (l *liveReply) finish(ctx context.Context) {
if l.messageID != 0 {
l.g.editText(ctx, l.chatID, l.messageID, clip(l.buf.String(), messageMaxLen))
}
}
// toolCall posts a completed tool call as its own short message when the
// operator turned show_tool_calls on.
func (l *liveReply) toolCall(ctx context.Context, tool *gatewayv1.ToolCall) {
if !l.g.settings.showTools || tool == nil {
return
}
name := tool.GetName()
if tool.GetError() != "" {
l.g.sendText(ctx, l.chatID, l.threadID, "🔧 "+name+" failed: "+tool.GetError())
return
}
l.g.sendText(ctx, l.chatID, l.threadID, "🔧 "+name)
}
// presentAsk poses a blocking question to the chat. Approvals get inline
// buttons; clarify, picker and questionnaire questions are posed as text and
// the chat's next message is consumed as the answer.
func (g *gateway) presentAsk(ctx context.Context, chatID int64, threadID int, ask *gatewayv1.Ask) {
if ask == nil {
return
}
key := pendingKey{chatID: chatID, threadID: threadID}
g.mu.Lock()
g.pending[key] = &pendingAsk{id: ask.GetId(), kind: ask.GetKind()}
g.mu.Unlock()
switch ask.GetKind() {
case "approval":
prompt := ask.GetPrompt()
if ask.GetDetail() != "" {
prompt += "\n\n" + ask.GetDetail()
}
g.sendApproval(ctx, chatID, threadID, ask.GetId(), prompt)
default:
g.sendText(ctx, chatID, threadID, askPrompt(ask))
}
}
func askPrompt(ask *gatewayv1.Ask) string {
var b strings.Builder
b.WriteString(ask.GetPrompt())
if len(ask.GetChoices()) > 0 {
b.WriteString("\n")
for i, c := range ask.GetChoices() {
fmt.Fprintf(&b, "%d. %s\n", i+1, c.GetLabel())
}
b.WriteString("Reply with a number or the text.")
}
if len(ask.GetQuestions()) > 0 {
for _, q := range ask.GetQuestions() {
fmt.Fprintf(&b, "\n• %s", q.GetTitle())
if q.GetDescription() != "" {
fmt.Fprintf(&b, " — %s", q.GetDescription())
}
}
}
return b.String()
}
// sendApproval posts the approval question with Approve / Always / Deny
// buttons whose callback carries the ask id and the answer.
func (g *gateway) sendApproval(ctx context.Context, chatID int64, threadID int, askID, prompt string) {
row := [][]models.InlineKeyboardButton{{
{Text: "Approve", CallbackData: "ask:" + askID + ":approve"},
{Text: "Always", CallbackData: "ask:" + askID + ":always"},
{Text: "Deny", CallbackData: "ask:" + askID + ":deny"},
}}
params := &bot.SendMessageParams{
ChatID: chatID,
Text: "🛑 Approval needed\n\n" + prompt,
ReplyMarkup: &models.InlineKeyboardMarkup{InlineKeyboard: row},
}
if threadID != 0 {
params.MessageThreadID = threadID
}
if _, err := g.bot.SendMessage(ctx, params); err != nil {
g.log.WarnContext(ctx, "send approval failed", "error", err)
}
}
// startTyping shows the typing indicator until the returned stop is called.
func (g *gateway) startTyping(ctx context.Context, chatID int64, threadID int) func() {
send := func(c context.Context) {
params := &bot.SendChatActionParams{ChatID: chatID, Action: models.ChatActionTyping}
if threadID != 0 {
params.MessageThreadID = threadID
}
if _, err := g.bot.SendChatAction(c, params); err != nil {
g.log.DebugContext(c, "send chat action failed", "error", err)
}
}
typingCtx, cancel := context.WithCancel(ctx)
send(typingCtx)
go func() {
ticker := time.NewTicker(typingRefresh)
defer ticker.Stop()
for {
select {
case <-typingCtx.Done():
return
case <-ticker.C:
send(typingCtx)
}
}
}()
return cancel
}
// clip truncates text to max runes.
func clip(text string, max int) string {
runes := []rune(text)
if len(runes) <= max {
return text
}
return string(runes[:max]) + "…"
}