From 0047ec5e7490215f2202f258b05ac9f8d4edef98 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sun, 23 Aug 2026 02:48:01 +1000 Subject: [PATCH] feat(telegram): deliver media attachments, capability-gated telegramMediaSender routes a MediaAttachment to the matching Bot API method (sendVideo/sendPhoto/sendAudio/sendDocument) rather than sendMessage, which cannot carry a file. It is constructed per-launch from the same *bot.Bot the update handler already has, matching telegramApprover's lifetime rule: a /restart abandons an in-flight send against the outgoing bot instance rather than silently redirecting it through the new one. liveReply.Media wires TurnStream into this: it checks gateway.CapabilitiesOf before attempting delivery -- not just on failure -- so a sender that already knows it cannot deliver a given media kind never costs a doomed network round trip. Either path (capability-limited or a failed send) falls back to rendering the attachment's URL as a visible link, so a generated asset is never silently dropped. newMediaSender is an injectable field so tests can prove the capability check actually short-circuits, since the real Telegram sender always reports Media: true and can't exercise that path itself. --- internal/channels/telegram/live.go | 88 ++++++++ internal/channels/telegram/live_test.go | 119 ++++++++++ internal/channels/telegram/media.go | 168 +++++++++++++++ internal/channels/telegram/media_test.go | 263 +++++++++++++++++++++++ 4 files changed, 638 insertions(+) create mode 100644 internal/channels/telegram/media.go create mode 100644 internal/channels/telegram/media_test.go diff --git a/internal/channels/telegram/live.go b/internal/channels/telegram/live.go index bea66541b..645085ce6 100644 --- a/internal/channels/telegram/live.go +++ b/internal/channels/telegram/live.go @@ -30,6 +30,10 @@ const ( // toolCallPrefix opens an inline tool-activity line. toolCallPrefix = "🔧 " + // fallbackMediaLinePrefix opens the line Media appends when it could + // not deliver an attachment inline, so the user still gets the asset. + fallbackMediaLinePrefix = "📎 " + // liveBodyMaxRunes bounds one mid-turn frame. Telegram rejects a // message over its character limit outright, so an unbounded frame // means every edit past that point fails and the live message freezes @@ -77,6 +81,19 @@ type liveReply struct { // interval throttles updates; zero renders every change. interval time.Duration + // mediaWg lets tests (and a future bounded drain, mirroring + // abandonAllLive) wait for in-flight Media deliveries. Callers other + // than tests must not block on it: Media is fire-and-forget by + // contract, same as Delta and ToolCall. + mediaWg sync.WaitGroup + + // newMediaSender builds the MediaSender Media delivers through. + // Defaults to g.NewMediaSender; tests override it to inject a sender + // with fixed Capabilities(), which the real Telegram one can't + // express (it always reports Media: true) but a future channel or a + // capability-limited deployment might. + newMediaSender func(b *bot.Bot, chatID int64, threadID int) gateway.MediaSender + cancelRender context.CancelFunc renderRequests chan chan struct{} renderDone chan struct{} @@ -124,6 +141,7 @@ func (g *Gateway) newLiveReply(ctx context.Context, b *bot.Bot, chatID int64, me messageThreadID: messageThreadID, showToolCalls: showToolCalls, interval: liveInterval, + newMediaSender: g.NewMediaSender, cancelRender: cancelRender, renderRequests: make(chan chan struct{}, 1), renderDone: make(chan struct{}), @@ -318,6 +336,76 @@ func (l *liveReply) ToolCall(event gateway.ToolCallEvent) { l.requestRender() } +// mediaSendTimeout bounds one Media delivery. It is independent of the +// render loop's own lifecycle (unlike answerBuf/toolLines, which a +// /restart abandons via abandonAllLive): an upload in flight when the live +// reply finalizes should still be allowed to land, since the asset is worth +// delivering on its own even after the surrounding turn is done narrating. +const mediaSendTimeout = 30 * time.Second + +// Media delivers the attachment through the media-specific Bot API, off the +// generating goroutine: unlike Delta/ToolCall, this is a real network +// upload, and TurnStream implementations must not block generation on one. +// It satisfies gateway.TurnStream. +// +// A missing URL is silently skipped rather than surfaced: an attachment +// telegramMediaSender.SendMedia would reject as invalid_message has nothing +// worth falling back to either, and Media has no error return to report it +// through. +func (l *liveReply) Media(event gateway.MediaEvent) { + if event.Attachment.URL == "" { + return + } + + l.mediaWg.Go(func() { + sender := l.newMediaSender(l.b, l.chatID, l.messageThreadID) + + // Checked before attempting delivery, not just on failure: that is + // the entire point of CapabilityReporter over attempt-then-catch + // -- a sender that already knows it cannot deliver a given media + // kind should never cost a doomed network round trip to find out. + if !gateway.CapabilitiesOf(sender).Media { + l.g.log.Debug("channel cannot deliver media inline, falling back to a link", + "tool", event.ToolName, "type", event.Attachment.Type) + l.appendFallbackLine(event.Attachment) + return + } + + ctx, cancel := context.WithTimeout(context.Background(), mediaSendTimeout) + defer cancel() + + _, err := sender.SendMedia(ctx, gateway.MessageEvent{ + Media: []gateway.MediaAttachment{event.Attachment}, + }) + if err == nil { + return + } + + l.g.log.Warn("media delivery failed, falling back to a link", + "tool", event.ToolName, "type", event.Attachment.Type, "error", err) + l.appendFallbackLine(event.Attachment) + }) +} + +// appendFallbackLine renders att as a visible link in the reply, for a +// MediaEvent that could not be (or was not attempted to be) delivered +// inline. +func (l *liveReply) appendFallbackLine(att gateway.MediaAttachment) { + line := fallbackMediaLinePrefix + bot.EscapeMarkdown(att.Type) + ": " + att.URL + + l.mu.Lock() + l.toolLines = append(l.toolLines, line) + l.mu.Unlock() + l.requestRender() +} + +// waitMedia blocks until every Media delivery started so far has finished. +// Tests only: production callers never wait on Media's fire-and-forget +// goroutines. +func (l *liveReply) waitMedia() { + l.mediaWg.Wait() +} + // render writes the current buffer, cursor and all, to the live message. func (l *liveReply) render(ctx context.Context) { l.mu.Lock() diff --git a/internal/channels/telegram/live_test.go b/internal/channels/telegram/live_test.go index dbb2853f9..a72917e7f 100644 --- a/internal/channels/telegram/live_test.go +++ b/internal/channels/telegram/live_test.go @@ -940,3 +940,122 @@ func TestGatewayRegisterLiveAfterStopAbandonsImmediately(t *testing.T) { t.Fatal("a liveReply registered after stop was never abandoned") } } + +// Media must actually deliver the attachment through the Bot API's +// media-specific endpoint, not just buffer it like Delta/ToolCall -- +// there is no later render pass that turns a MediaEvent into anything. +func TestLiveReplyMediaDeliversTheAttachment(t *testing.T) { + live, calls := newTestLiveReply(t, false) + + live.Media(gateway.MediaEvent{ + ToolName: "video_gen", + Attachment: gateway.MediaAttachment{Type: "video", URL: "https://example.com/v.mp4"}, + }) + live.waitMedia() + + if len(*calls) != 1 { + t.Fatalf("api calls = %d, want 1", len(*calls)) + } + if (*calls)[0].method != "sendVideo" { + t.Fatalf("called %q, want sendVideo", (*calls)[0].method) + } +} + +// An event with no URL has nothing to deliver and nothing to fall back to, +// so it must not reach the API at all. +func TestLiveReplyMediaWithNoURLIsANoop(t *testing.T) { + live, calls := newTestLiveReply(t, false) + + live.Media(gateway.MediaEvent{ToolName: "video_gen", Attachment: gateway.MediaAttachment{Type: "video"}}) + live.waitMedia() + + if len(*calls) != 0 { + t.Fatalf("api calls = %d, want 0", len(*calls)) + } +} + +// When delivery fails, the user must still get the URL as a link rather +// than silence: a generated video that can't be uploaded is still a result +// worth handing back. +func TestLiveReplyMediaFallsBackToALinkOnFailure(t *testing.T) { + failing := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"ok":false,"error_code":400,"description":"boom"}`)) + })) + t.Cleanup(failing.Close) + b, err := bot.New("1:test", bot.WithServerURL(failing.URL), bot.WithSkipGetMe()) + if err != nil { + t.Fatalf("new test bot: %v", err) + } + + g := New("1:test", "", "", []int64{42}, slog.New(slog.DiscardHandler)) + live := g.newLiveReply(context.Background(), b, 7, 0, false) + t.Cleanup(live.stopRendering) + live.interval = 0 + + live.Media(gateway.MediaEvent{ + ToolName: "video_gen", + Attachment: gateway.MediaAttachment{Type: "video", URL: "https://example.com/v.mp4"}, + }) + live.waitMedia() + + live.mu.Lock() + lines := strings.Join(live.toolLines, "\n") + live.mu.Unlock() + if !strings.Contains(lines, "https://example.com/v.mp4") { + t.Fatalf("fallback lines = %q, want it to contain the asset URL", lines) + } +} + +// capabilityLimitedSender reports Media: false regardless of what it is +// asked to send, so tests can prove Media actually consults +// gateway.CapabilitiesOf before attempting delivery, rather than always +// attempting and only ever falling back on a network failure. +type capabilityLimitedSender struct { + sendCalled bool +} + +func (s *capabilityLimitedSender) SendMedia(context.Context, gateway.MessageEvent) (gateway.SendResult, error) { + s.sendCalled = true + return gateway.SendResult{Success: true}, nil +} + +func (s *capabilityLimitedSender) Capabilities() gateway.AdapterCapabilities { + return gateway.AdapterCapabilities{Media: false} +} + +var ( + _ gateway.MediaSender = (*capabilityLimitedSender)(nil) + _ gateway.CapabilityReporter = (*capabilityLimitedSender)(nil) +) + +// When the bound sender reports it cannot deliver media at all, Media must +// go straight to the text-link fallback without attempting SendMedia -- +// checking capability first is the whole point of CapabilityReporter over +// attempt-then-catch, so a call site that ignores it makes the mechanism +// dead weight. +func TestLiveReplyMediaSkipsDeliveryWhenCapabilityReportsUnsupported(t *testing.T) { + live, calls := newTestLiveReply(t, false) + sender := &capabilityLimitedSender{} + live.newMediaSender = func(*bot.Bot, int64, int) gateway.MediaSender { return sender } + + live.Media(gateway.MediaEvent{ + ToolName: "video_gen", + Attachment: gateway.MediaAttachment{Type: "video", URL: "https://example.com/v.mp4"}, + }) + live.waitMedia() + + if sender.sendCalled { + t.Error("SendMedia was called despite Capabilities().Media == false") + } + if len(*calls) != 0 { + t.Errorf("api calls = %d, want 0 (capability check should short-circuit before any request)", len(*calls)) + } + + live.mu.Lock() + lines := strings.Join(live.toolLines, "\n") + live.mu.Unlock() + if !strings.Contains(lines, "https://example.com/v.mp4") { + t.Fatalf("fallback lines = %q, want it to contain the asset URL", lines) + } +} diff --git a/internal/channels/telegram/media.go b/internal/channels/telegram/media.go new file mode 100644 index 000000000..dabd04480 --- /dev/null +++ b/internal/channels/telegram/media.go @@ -0,0 +1,168 @@ +package telegram + +import ( + "context" + "errors" + "fmt" + + "github.com/go-telegram/bot" + "github.com/go-telegram/bot/models" + + "github.com/samcharles93/archie-core/internal/gateway" +) + +// telegramMediaSender delivers a MessageEvent's attachment through the +// media-specific Bot API methods (sendVideo, sendPhoto, ...) rather than +// sendMessage, which cannot carry a file at all. +// +// It captures the *bot.Bot at construction rather than reading the +// Gateway's shared field, matching telegramApprover: a sender belongs to +// the launch that built it, so a /restart abandons in-flight sends with +// the outgoing bot instance instead of silently redirecting them through +// the new one. That is the same lifetime rule the per-launch turns +// registry documents. +// +// Delivery is URL-only. A MediaAttachment.FileID identifies a file on the +// platform it was uploaded from and is meaningless as an outbound handle +// here, so only URL is accepted; uploading local bytes is a separate +// concern from routing a generated asset to a chat. +type telegramMediaSender struct { + bot *bot.Bot + chatID int64 + threadID int +} + +var ( + _ gateway.MediaSender = (*telegramMediaSender)(nil) + _ gateway.CapabilityReporter = (*telegramMediaSender)(nil) +) + +// NewMediaSender returns a MediaSender bound to one chat and to the bot +// instance of the launch that created it. Construct it per launch, from +// the same b that handled the update, never from a stored field. +func (g *Gateway) NewMediaSender(b *bot.Bot, chatID int64, threadID int) gateway.MediaSender { + return &telegramMediaSender{bot: b, chatID: chatID, threadID: threadID} +} + +// Capabilities reports Media support. Telegram implements every media +// kind MediaAttachment can describe, so this is unconditionally true. +func (s *telegramMediaSender) Capabilities() gateway.AdapterCapabilities { + return gateway.AdapterCapabilities{Media: true} +} + +// errNoMedia and errNoURL are the two ways an event can be undeliverable +// before any request is made. +var ( + errNoMedia = errors.New("message event carries no media attachment") + errNoURL = errors.New("media attachment has no URL") +) + +// SendMedia delivers the event's first attachment, captioned with the +// event text. Only the first is sent: a caption belongs to one file, and +// batching several into a media group is a distinct API with its own +// caption semantics. +func (s *telegramMediaSender) SendMedia(ctx context.Context, event gateway.MessageEvent) (gateway.SendResult, error) { + if len(event.Media) == 0 { + return invalidMedia(errNoMedia) + } + att := event.Media[0] + if att.URL == "" { + return invalidMedia(fmt.Errorf("%w (type %q)", errNoURL, att.Type)) + } + + msg, err := s.dispatch(ctx, att, event.Text) + if err != nil { + if errors.Is(err, errUnsupportedMediaType) { + return invalidMedia(err) + } + res := classifySendError(err) + res.Error = fmt.Errorf("send %s: %w", att.Type, err) + return res, res.Error + } + + id := "" + if msg != nil { + id = fmt.Sprintf("%d", msg.ID) + } + return gateway.SendResult{Success: true, MessageID: id}, nil +} + +var errUnsupportedMediaType = errors.New("unsupported media type") + +// dispatch routes an attachment to the Bot API method for its kind. The +// media type, not the MessageEvent type, decides: the event type describes +// the message while the attachment describes the file, and Telegram +// rejects a video sent through sendPhoto. +func (s *telegramMediaSender) dispatch(ctx context.Context, att gateway.MediaAttachment, caption string) (*models.Message, error) { + file := &models.InputFileString{Data: att.URL} + + switch att.Type { + case "video": + p := &bot.SendVideoParams{ChatID: s.chatID, Video: file, Caption: caption} + p.MessageThreadID = s.threadID + if att.Width != nil { + p.Width = *att.Width + } + if att.Height != nil { + p.Height = *att.Height + } + if att.Duration != nil { + p.Duration = *att.Duration + } + return s.bot.SendVideo(ctx, p) + case "image": + p := &bot.SendPhotoParams{ChatID: s.chatID, Photo: file, Caption: caption} + p.MessageThreadID = s.threadID + return s.bot.SendPhoto(ctx, p) + case "audio": + p := &bot.SendAudioParams{ChatID: s.chatID, Audio: file, Caption: caption} + p.MessageThreadID = s.threadID + if att.Duration != nil { + p.Duration = *att.Duration + } + return s.bot.SendAudio(ctx, p) + case "document": + p := &bot.SendDocumentParams{ChatID: s.chatID, Document: file, Caption: caption} + p.MessageThreadID = s.threadID + return s.bot.SendDocument(ctx, p) + default: + return nil, fmt.Errorf("%w %q", errUnsupportedMediaType, att.Type) + } +} + +// invalidMedia reports a failure that was detected before any request was +// made. Never retryable: resending an event that carries nothing, or names +// a type Telegram has no method for, fails identically every time. +func invalidMedia(err error) (gateway.SendResult, error) { + return gateway.SendResult{ + Success: false, + Retryable: false, + Error: err, + ErrorCode: "invalid_message", + }, err +} + +// classifySendError maps a Bot API failure onto SendResult's error +// vocabulary so a caller can decide on retry without inspecting +// Telegram-specific errors. +// +// The library reports API failures as sentinel errors (bot.ErrorBadRequest +// and friends), not as typed values, so these are errors.Is checks. A +// failure matching no sentinel is a transport error or a 5xx, both of +// which may yet succeed -- hence retryable, rather than defaulting to +// permanent and silently dropping a deliverable asset. +func classifySendError(err error) gateway.SendResult { + res := gateway.SendResult{Success: false, Error: err} + + switch { + case bot.IsTooManyRequestsError(err) || errors.Is(err, bot.ErrorTooManyRequests): + res.Retryable, res.ErrorCode = true, "rate_limited" + case errors.Is(err, bot.ErrorUnauthorized), errors.Is(err, bot.ErrorForbidden): + res.Retryable, res.ErrorCode = false, "auth" + case errors.Is(err, bot.ErrorBadRequest), errors.Is(err, bot.ErrorNotFound): + res.Retryable, res.ErrorCode = false, "invalid_message" + default: + res.Retryable, res.ErrorCode = true, "network" + } + return res +} diff --git a/internal/channels/telegram/media_test.go b/internal/channels/telegram/media_test.go new file mode 100644 index 000000000..66ef9a693 --- /dev/null +++ b/internal/channels/telegram/media_test.go @@ -0,0 +1,263 @@ +package telegram + +import ( + "context" + "log/slog" + "maps" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/go-telegram/bot" + + "github.com/samcharles93/archie-core/internal/gateway" +) + +// mediaAPI stands in for the Bot API, recording which sendX method was +// called and the form values it received. +type mediaAPI struct { + mu sync.Mutex + method string + form map[string]string + body string +} + +func newMediaAPI() (*mediaAPI, *httptest.Server) { + api := &mediaAPI{form: map[string]string{}, body: `{"ok":true,"result":{"message_id":77}}`} + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + api.mu.Lock() + parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/") + api.method = parts[len(parts)-1] + if err := r.ParseMultipartForm(1 << 20); err == nil { + for k, v := range r.Form { + if len(v) > 0 { + api.form[k] = v[0] + } + } + } + body := api.body + api.mu.Unlock() + + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(body)) + })) + return api, srv +} + +func (m *mediaAPI) called() (string, map[string]string) { + m.mu.Lock() + defer m.mu.Unlock() + form := make(map[string]string, len(m.form)) + maps.Copy(form, m.form) + return m.method, form +} + +func newTestMediaSender(t *testing.T, serverURL string, chatID int64, threadID int) gateway.MediaSender { + t.Helper() + b, err := bot.New("1:test", bot.WithServerURL(serverURL), bot.WithSkipGetMe()) + if err != nil { + t.Fatalf("new test bot: %v", err) + } + g := New("1:test", "", "", []int64{42}, slog.New(slog.DiscardHandler)) + return g.NewMediaSender(b, chatID, threadID) +} + +// Each media kind must reach its own Bot API method -- a video sent via +// sendPhoto is rejected by Telegram, and a document fallback would silently +// downgrade playback. +func TestSendMedia_RoutesByMediaType(t *testing.T) { + tests := []struct { + name string + mediaType string + msgType gateway.MessageType + wantMethod string + wantField string + }{ + {"video", "video", gateway.MsgVideo, "sendVideo", "video"}, + {"image", "image", gateway.MsgImage, "sendPhoto", "photo"}, + {"audio", "audio", gateway.MsgAudio, "sendAudio", "audio"}, + {"document", "document", gateway.MsgDocument, "sendDocument", "document"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + api, srv := newMediaAPI() + defer srv.Close() + + sender := newTestMediaSender(t, srv.URL, 555, 0) + res, err := sender.SendMedia(context.Background(), gateway.MessageEvent{ + Type: tt.msgType, + Text: "a caption", + Media: []gateway.MediaAttachment{{ + Type: tt.mediaType, + URL: "https://example.com/asset", + }}, + }) + if err != nil { + t.Fatalf("SendMedia: %v", err) + } + if !res.Success { + t.Fatalf("expected success, got %+v", res) + } + + method, form := api.called() + if method != tt.wantMethod { + t.Errorf("called %q, want %q", method, tt.wantMethod) + } + if form[tt.wantField] != "https://example.com/asset" { + t.Errorf("field %q = %q, want the asset URL", tt.wantField, form[tt.wantField]) + } + if form["caption"] != "a caption" { + t.Errorf("caption = %q, want %q", form["caption"], "a caption") + } + if form["chat_id"] != "555" { + t.Errorf("chat_id = %q, want the bound chat", form["chat_id"]) + } + }) + } +} + +// The sender is bound to a chat at construction, matching telegramApprover. +// A thread ID must survive to the API or replies land outside the topic. +func TestSendMedia_UsesBoundThread(t *testing.T) { + api, srv := newMediaAPI() + defer srv.Close() + + sender := newTestMediaSender(t, srv.URL, 555, 99) + if _, err := sender.SendMedia(context.Background(), gateway.MessageEvent{ + Type: gateway.MsgVideo, + Media: []gateway.MediaAttachment{{Type: "video", URL: "https://example.com/v.mp4"}}, + }); err != nil { + t.Fatalf("SendMedia: %v", err) + } + + _, form := api.called() + if form["message_thread_id"] != "99" { + t.Errorf("message_thread_id = %q, want 99", form["message_thread_id"]) + } +} + +// An event with no attachment must not reach the API at all: Telegram +// rejects an empty media field, and reporting success would leave the +// caller believing a video was delivered. +func TestSendMedia_NoAttachmentIsAnError(t *testing.T) { + api, srv := newMediaAPI() + defer srv.Close() + + sender := newTestMediaSender(t, srv.URL, 555, 0) + res, err := sender.SendMedia(context.Background(), gateway.MessageEvent{Type: gateway.MsgVideo}) + if err == nil { + t.Fatal("expected an error for an event carrying no media") + } + if res.Success { + t.Error("expected Success=false") + } + if res.Retryable { + t.Error("a missing attachment is not retryable") + } + if res.ErrorCode != "invalid_message" { + t.Errorf("ErrorCode = %q, want invalid_message", res.ErrorCode) + } + if method, _ := api.called(); method != "" { + t.Errorf("called the API (%q) despite having nothing to send", method) + } +} + +// An attachment with no URL cannot be sent: this sender is URL-only, and +// a FileID belongs to the platform it was uploaded from. +func TestSendMedia_MissingURLIsAnError(t *testing.T) { + _, srv := newMediaAPI() + defer srv.Close() + + sender := newTestMediaSender(t, srv.URL, 555, 0) + res, err := sender.SendMedia(context.Background(), gateway.MessageEvent{ + Type: gateway.MsgVideo, + Media: []gateway.MediaAttachment{{Type: "video"}}, + }) + if err == nil { + t.Fatal("expected an error for an attachment with no URL") + } + if res.ErrorCode != "invalid_message" { + t.Errorf("ErrorCode = %q, want invalid_message", res.ErrorCode) + } +} + +// An unroutable media type must be reported, not guessed at. +func TestSendMedia_UnknownTypeIsAnError(t *testing.T) { + _, srv := newMediaAPI() + defer srv.Close() + + sender := newTestMediaSender(t, srv.URL, 555, 0) + res, err := sender.SendMedia(context.Background(), gateway.MessageEvent{ + Type: gateway.MsgVideo, + Media: []gateway.MediaAttachment{{Type: "hologram", URL: "https://example.com/h"}}, + }) + if err == nil { + t.Fatal("expected an error for an unsupported media type") + } + if res.ErrorCode != "invalid_message" { + t.Errorf("ErrorCode = %q, want invalid_message", res.ErrorCode) + } +} + +// Telegram failures must be classified so callers can decide on retry, +// rather than every failure looking alike. +// +// The bot library branches on the JSON \`error_code\` field of the API +// response, not the HTTP status, so each stub has to carry the matching +// integer. +func TestSendMedia_ClassifiesAPIFailures(t *testing.T) { + tests := []struct { + name string + body string + wantCode string + wantRetryable bool + }{ + {"rate limited", `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`, "rate_limited", true}, + {"auth", `{"ok":false,"error_code":401,"description":"Unauthorized"}`, "auth", false}, + {"bad request", `{"ok":false,"error_code":400,"description":"wrong file identifier"}`, "invalid_message", false}, + {"server error", `{"ok":false,"error_code":500,"description":"boom"}`, "network", true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + api, srv := newMediaAPI() + defer srv.Close() + api.mu.Lock() + api.body = tt.body + api.mu.Unlock() + + sender := newTestMediaSender(t, srv.URL, 555, 0) + res, err := sender.SendMedia(context.Background(), gateway.MessageEvent{ + Type: gateway.MsgVideo, + Media: []gateway.MediaAttachment{{Type: "video", URL: "https://example.com/v.mp4"}}, + }) + if err == nil { + t.Fatal("expected an error") + } + if res.Success { + t.Error("expected Success=false") + } + if res.ErrorCode != tt.wantCode { + t.Errorf("ErrorCode = %q, want %q", res.ErrorCode, tt.wantCode) + } + if res.Retryable != tt.wantRetryable { + t.Errorf("Retryable = %v, want %v", res.Retryable, tt.wantRetryable) + } + }) + } +} + +// The capability must be reported, so a caller can check support without +// attempting a doomed send. +func TestMediaSender_ReportsMediaCapability(t *testing.T) { + _, srv := newMediaAPI() + defer srv.Close() + + sender := newTestMediaSender(t, srv.URL, 555, 0) + if caps := gateway.CapabilitiesOf(sender); !caps.Media { + t.Error("telegram media sender does not report the Media capability") + } +}