publish / publish (push) Successful in 1m22s
The connector sent title and body as one sendMessage, so any notification over Telegram's 4096 UTF-16 unit limit was refused with 'message is too long' and, because a delivery is retried until the channel confirms it, retried every ten minutes for ever without ever arriving. The chat channel had its own splitter; both now share one in sdk/telegramtext, which counts UTF-16 units rather than runes so an emoji-heavy body isn't over the limit either.
472 lines
15 KiB
Go
472 lines
15 KiB
Go
// 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"
|
|
"github.com/samcharles93/archipelago/sdk/telegramtext"
|
|
)
|
|
|
|
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 telegramtext.Split(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 := telegramtext.Split(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
|
|
|
|
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)
|
|
}
|
|
}
|
|
}
|