Bundle: redb-route / redb.Route.Telegram (redb.Route.Telegram.txt), 15 files Snapshot: development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt ==== Path: redb-route/redb.Route.Telegram/Extensions/ServiceCollectionExtensions.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Telegram/Extensions/ServiceCollectionExtensions.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Route.Core; using redb.Route.Extensions; namespace redb.Route.Telegram; /// /// Extension methods for registering the Telegram transport in a DI container. /// public static class ServiceCollectionExtensions { /// /// Registers so that telegram:// URIs are resolved. /// /// services.AddRedbRoute(route => /// { /// route.Services.AddRedbRouteTelegram(); /// route.AddRouteBuilder<MyTelegramRoutes>(); /// }); /// /// public static IServiceCollection AddRedbRouteTelegram(this IServiceCollection services) { services.AddSingleton(); // IRouteContextConfigurator is resolved by RouteHostedService at startup via // IEnumerable — this is the correct registration hook. services.AddSingleton(sp => new TelegramComponentConfigurator(sp)); return services; } } /// Registers into the route context at startup. internal sealed class TelegramComponentConfigurator(IServiceProvider sp) : IRouteContextConfigurator { public void Configure(RouteContext context) => context.AddComponent(sp.GetRequiredService()); } Path: redb-route/redb.Route.Telegram/Fluent/TelegramDsl.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Telegram/Fluent/TelegramDsl.cs ---- using System.Text; using Telegram.Bot.Types; using redb.Route.Abstractions; namespace redb.Route.Telegram.Fluent; /// /// Entry point for the Telegram fluent DSL. /// /// // Consumer (long polling) /// From(Tg.Receive(token)) /// /// // Producer (text message) /// .To(Tg.Send(token).ChatId(chatId).ParseMode("HTML")) /// /// // Producer (document) /// .To(Tg.Document(token).ChatId(chatId).FileName("report.pdf").Caption("Daily report")) /// /// public static class Tg { /// Creates a long-polling consumer endpoint. public static TgBuilder Receive(string token) => new TgBuilder("receive", token); /// Creates a long-polling consumer with expression token. public static TgBuilder Receive(IExpression token) => new TgBuilder("receive", token.ToTemplateString()); /// Creates a text message producer endpoint. public static TgBuilder Send(string token) => new TgBuilder("send", token); /// Creates a text message producer with expression token. public static TgBuilder Send(IExpression token) => new TgBuilder("send", token.ToTemplateString()); /// Creates a document producer endpoint (body must be Stream or byte[]). public static TgBuilder Document(string token) => new TgBuilder("document", token); /// Creates a document producer with expression token. public static TgBuilder Document(IExpression token) => new TgBuilder("document", token.ToTemplateString()); /// Creates a photo producer endpoint (body must be Stream or byte[]). public static TgBuilder Photo(string token) => new TgBuilder("photo", token); /// Creates a photo producer with expression token. public static TgBuilder Photo(IExpression token) => new TgBuilder("photo", token.ToTemplateString()); /// Answers a callback query (removes the loading spinner on an inline button). public static TgBuilder Answer(string token) => new TgBuilder("answer", token); /// Answers a callback query using an expression token. public static TgBuilder Answer(IExpression token) => new TgBuilder("answer", token.ToTemplateString()); /// Edits the text (and optionally markup) of an existing message. /// Requires header telegram.messageId at runtime. public static TgBuilder Edit(string token) => new TgBuilder("edit", token); /// Edits an existing message using an expression token. public static TgBuilder Edit(IExpression token) => new TgBuilder("edit", token.ToTemplateString()); /// Deletes a message. Requires headers telegram.chatId /// and telegram.messageId at runtime. public static TgBuilder Delete(string token) => new TgBuilder("delete", token); /// Deletes a message using an expression token. public static TgBuilder Delete(IExpression token) => new TgBuilder("delete", token.ToTemplateString()); /// /// Downloads a file the user sent; the bytes land in Out.Body as a byte[]. /// With no .FileId(...) it takes the attachment the consumer reported, which is /// what a voice / photo / document route wants. /// /// From("direct://voice") /// .To(Tg.Download(token)) // telegram.attachment.fileId → bytes /// .To("stt://local"); // bytes → text /// /// public static TgBuilder Download(string token) => new TgBuilder("download", token); /// Downloads a file using an expression token. public static TgBuilder Download(IExpression token) => new TgBuilder("download", token.ToTemplateString()); // ── Token-less overloads: the bot token comes from a registered // TelegramConnectionFactory via .ConnectionFactory("name") ────────────── /// Long-polling consumer; token supplied by .ConnectionFactory(name). public static TgBuilder Receive() => new TgBuilder("receive", string.Empty); /// Text message producer; token supplied by .ConnectionFactory(name). public static TgBuilder Send() => new TgBuilder("send", string.Empty); /// Document producer; token supplied by .ConnectionFactory(name). public static TgBuilder Document() => new TgBuilder("document", string.Empty); /// Photo producer; token supplied by .ConnectionFactory(name). public static TgBuilder Photo() => new TgBuilder("photo", string.Empty); /// Callback-answer producer; token supplied by .ConnectionFactory(name). public static TgBuilder Answer() => new TgBuilder("answer", string.Empty); /// Edit-message producer; token supplied by .ConnectionFactory(name). public static TgBuilder Edit() => new TgBuilder("edit", string.Empty); /// Delete-message producer; token supplied by .ConnectionFactory(name). public static TgBuilder Delete() => new TgBuilder("delete", string.Empty); /// File-download producer; token supplied by .ConnectionFactory(name). public static TgBuilder Download() => new TgBuilder("download", string.Empty); } /// /// Fluent builder for Telegram endpoint URIs. /// Builds a URI consumed by . /// Pattern mirrors KafkaDsl / RabbitMQ Rabbit builder. /// public sealed class TgBuilder { private readonly string _mode; private readonly string _token; private string? _chatId; private string? _parseMode; private string? _caption; private string? _fileName; private bool _disableNotification; private bool _bodyIsFileId; private string? _replyToMessageId; private string? _messageId; private bool _showAlert; private int? _sendTimeoutSeconds; private string? _fileId; private long? _maxDownloadBytes; private string? _connectionFactory; internal TgBuilder(string mode, string token) { _mode = mode; _token = token; } /// /// References a named from the route registry instead of /// putting the bot token in the URI. Use with the token-less mode overloads, e.g. /// Tg.Receive().ConnectionFactory("support-bot"). /// public TgBuilder ConnectionFactory(string name) { _connectionFactory = name; return this; } // ── Common ───────────────────────────────────────────────────────────────── /// Target chat ID (long) or @channelusername. public TgBuilder ChatId(long id) { _chatId = id.ToString(); return this; } /// Target chat ID from an expression (e.g. Header("telegram.chatId")). public TgBuilder ChatId(IExpression expr) { _chatId = expr.ToTemplateString(); return this; } /// Parse mode: "HTML", "Markdown", "MarkdownV2". Default: plain text. public TgBuilder ParseMode(string mode) { _parseMode = mode; return this; } /// Send silently (no sound notification). Default false. public TgBuilder DisableNotification(bool value = true) { _disableNotification = value; return this; } /// Reply to a specific message id (send/document/photo). public TgBuilder ReplyTo(long messageId) { _replyToMessageId = messageId.ToString(); return this; } /// Reply target from an expression, resolved per message /// (e.g. Header("myApp.threadRootId")). public TgBuilder ReplyTo(IExpression expr) { _replyToMessageId = expr.ToTemplateString(); return this; } /// /// Replies to the incoming message. Sugar for with the /// ${header.telegram.messageId} expression — the id the consumer put on the exchange. /// An explicit telegram.replyToMessageId header wins over this option. /// /// From(Tg.Receive(token)) /// .To(Tg.Send(token).ChatId(Header(TelegramHeaders.ChatId)).ReplyToIncoming()); /// /// public TgBuilder ReplyToIncoming() { _replyToMessageId = "${header." + TelegramHeaders.MessageId + "}"; return this; } /// Message to edit / delete, by id. public TgBuilder MessageId(long id) { _messageId = id.ToString(); return this; } /// Message to edit / delete, from an expression resolved per message /// (e.g. Header(TelegramHeaders.SentMessageId) to target the message just sent). public TgBuilder MessageId(IExpression expr) { _messageId = expr.ToTemplateString(); return this; } /// In answer mode, show the text as a modal alert instead of a toast. Default false. public TgBuilder ShowAlert(bool value = true) { _showAlert = value; return this; } // ── Document / photo ────────────────────────────────────────────────────── /// File name for document sends. public TgBuilder FileName(string name) { _fileName = name; return this; } /// File name from an expression (e.g. Header("telegram.fileName")). public TgBuilder FileName(IExpression expr) { _fileName = expr.ToTemplateString(); return this; } /// Caption for document/photo messages. public TgBuilder Caption(string text) { _caption = text; return this; } /// Caption from an expression. public TgBuilder Caption(IExpression expr) { _caption = expr.ToTemplateString(); return this; } /// Treat a string exchange body as a Telegram file_id (document/photo) instead of uploading. public TgBuilder BodyIsFileId(bool value = true) { _bodyIsFileId = value; return this; } // ── Download ────────────────────────────────────────────────────────────── /// Which file to download, by file_id. public TgBuilder FileId(string fileId) { _fileId = fileId; return this; } /// /// Which file to download, from an expression resolved per message — e.g. /// Header(TelegramHeaders.AttachmentFileId). Without this the producer takes the /// attachment header anyway; spell it out when a route downloads something other than /// "whatever the user just sent". /// public TgBuilder FileId(IExpression expr) { _fileId = expr.ToTemplateString(); return this; } /// /// Ceiling on a download, in bytes; 0 lifts it. Default 20 MiB — the Bot API's own /// limit on what a bot may download. /// public TgBuilder MaxDownloadBytes(long bytes) { _maxDownloadBytes = bytes; return this; } // ── Producer ────────────────────────────────────────────────────────────── /// Per-send timeout in seconds for producer calls (1–600). Default 120. Not used by receive. public TgBuilder Timeout(int seconds) { _sendTimeoutSeconds = seconds; return this; } // ── Build ───────────────────────────────────────────────────────────────── /// Builds the telegram:// URI string. public string Build() { var sb = new StringBuilder(); var sep = '?'; sb.Append("telegram://"); sb.Append(_mode); void Append(string key, string value) { sb.Append(sep); sb.Append(key); sb.Append('='); sb.Append(Uri.EscapeDataString(value)); sep = '&'; } void AppendIf(string key, string? value) { if (value != null) Append(key, value); } // A token-less builder relies on connectionFactory= supplying the credential. if (!string.IsNullOrEmpty(_token)) Append("token", _token); AppendIf("connectionFactory", _connectionFactory); AppendIf("chatId", _chatId); AppendIf("parseMode", _parseMode); AppendIf("caption", _caption); AppendIf("fileName", _fileName); AppendIf("replyToMessageId", _replyToMessageId); AppendIf("messageId", _messageId); AppendIf("fileId", _fileId); if (_maxDownloadBytes.HasValue) Append("maxDownloadBytes", _maxDownloadBytes.Value.ToString()); if (_disableNotification) Append("disableNotification", "true"); if (_bodyIsFileId) Append("bodyIsFileId", "true"); if (_showAlert) Append("showAlert", "true"); if (_sendTimeoutSeconds.HasValue) Append("sendTimeoutSeconds", _sendTimeoutSeconds.Value.ToString()); return sb.ToString(); } /// Allows passing TgBuilder directly to From() / To() without calling Build(). public static implicit operator string(TgBuilder builder) => builder.Build(); } /// /// Extension methods for using the Telegram webhook unpack pipeline inside a route DSL. /// public static class TelegramRouteExtensions { /// /// Deserializes a raw Telegram webhook JSON body into an object /// and populates all — equivalent to a long-polling /// exchange. /// /// From(Http.Listen("/tg/webhook")) /// .UnpackTelegramUpdate() /// .To("direct://tg-dispatch"); /// /// /// The current route definition. /// The route definition for chaining. public static IRouteDefinition UnpackTelegramUpdate(this IRouteDefinition route) => route .Unmarshal(typeof(TelegramUpdateSerializer), typeof(Update)) .Process(new TelegramUpdateUnpackProcessor()); /// /// Attaches an inline keyboard to the next produced message by setting the /// header. Sugar over /// SetHeader(TelegramHeaders.ReplyMarkup, TgKeyboard.Inline(build)). /// /// From(Tg.Receive(token)) /// .SetBody("Choose:") /// .WithInlineKeyboard(k => k /// .Row(r => r.Callback("✅ Yes", "act:yes").Callback("❌ No", "act:no"))) /// .To(Tg.Send(token).ChatId(Header(TelegramHeaders.ChatId))); /// /// /// The current route definition. /// Callback that builds the inline keyboard. /// The route definition for chaining. public static IRouteDefinition WithInlineKeyboard( this IRouteDefinition route, Action build) => route.SetHeader(TelegramHeaders.ReplyMarkup, TgKeyboard.Inline(build)); /// /// Attaches a reply keyboard (buttons below the input field) to the next produced /// message by setting the header. /// /// .WithReplyKeyboard(k => k /// .Row(r => r.Button("📋 Menu").Button("❓ Help")) /// .Resize().OneTime()) /// /// /// The current route definition. /// Callback that builds the reply keyboard. /// The route definition for chaining. public static IRouteDefinition WithReplyKeyboard( this IRouteDefinition route, Action build) => route.SetHeader(TelegramHeaders.ReplyMarkup, TgKeyboard.Reply(build)); /// /// Removes the current custom reply keyboard on the next produced message by setting the /// header to a ReplyKeyboardRemove. /// /// The current route definition. /// Remove the keyboard only for specific users (see Bot API docs). /// The route definition for chaining. public static IRouteDefinition WithoutKeyboard( this IRouteDefinition route, bool selective = false) => route.SetHeader(TelegramHeaders.ReplyMarkup, TgKeyboard.Remove(selective)); } Path: redb-route/redb.Route.Telegram/Fluent/TelegramKeyboard.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Telegram/Fluent/TelegramKeyboard.cs ---- using Telegram.Bot.Types; using Telegram.Bot.Types.ReplyMarkups; namespace redb.Route.Telegram.Fluent; /// /// Typed builders for Telegram reply markup (keyboards). /// /// The result is a Telegram.Bot markup object that is placed on the exchange /// under — the same header the producer reads. /// Use these factories to construct keyboards without referencing /// Telegram.Bot.Types.ReplyMarkups directly in route code. /// /// /// // Static keyboard via the route-extension sugar: /// From(Tg.Receive(token)) /// .SetBody("Choose:") /// .WithInlineKeyboard(k => k /// .Row(r => r.Callback("✅ Yes", "act:yes").Callback("❌ No", "act:no"))) /// .To(Tg.Send(token).ChatId(Header(TelegramHeaders.ChatId))); /// /// // Dynamic keyboard inside a processor: /// exchange.In.Headers[TelegramHeaders.ReplyMarkup] = TgKeyboard.Inline(k => /// { /// foreach (var o in orders) k.Row(r => r.Callback(o.Title, $"order:{o.Id}")); /// }); /// /// public static class TgKeyboard { /// Builds an inline keyboard (callback / URL / web-app buttons attached to the message). /// Callback that adds rows of buttons. public static InlineKeyboardMarkup Inline(Action build) { ArgumentNullException.ThrowIfNull(build); var builder = new InlineKeyboardBuilder(); build(builder); return builder.Build(); } /// Builds a reply keyboard (buttons shown below the text input). /// Callback that adds rows of buttons and configures options. public static ReplyKeyboardMarkup Reply(Action build) { ArgumentNullException.ThrowIfNull(build); var builder = new ReplyKeyboardBuilder(); build(builder); return builder.Build(); } /// Builds a markup that removes the current custom reply keyboard. /// Remove the keyboard only for specific users (see Bot API docs). public static ReplyKeyboardRemove Remove(bool selective = false) { var markup = new ReplyKeyboardRemove(); if (selective) markup.Selective = true; return markup; } } /// Fluent builder for an . public sealed class InlineKeyboardBuilder { private readonly List> _rows = new(); /// Adds a row of buttons. Empty rows are ignored. /// Callback that adds buttons to the row. public InlineKeyboardBuilder Row(Action build) { ArgumentNullException.ThrowIfNull(build); var row = new InlineRowBuilder(); build(row); if (row.Buttons.Count > 0) _rows.Add(row.Buttons); return this; } internal InlineKeyboardMarkup Build() => new(_rows); } /// Fluent builder for a single row of inline keyboard buttons. public sealed class InlineRowBuilder { private readonly List _buttons = new(); internal List Buttons => _buttons; /// Adds a callback button. The tap arrives as a CallbackQuery update carrying . public InlineRowBuilder Callback(string text, string data) { _buttons.Add(InlineKeyboardButton.WithCallbackData(text, data)); return this; } /// Adds a button that opens a URL. public InlineRowBuilder Url(string text, string url) { _buttons.Add(InlineKeyboardButton.WithUrl(text, url)); return this; } /// Adds a button that launches a Web App at . public InlineRowBuilder WebApp(string text, string url) { _buttons.Add(InlineKeyboardButton.WithWebApp(text, new WebAppInfo { Url = url })); return this; } /// Adds a button that prompts the user to pick a chat and switches to inline mode with . public InlineRowBuilder SwitchInlineQuery(string text, string query = "") { _buttons.Add(InlineKeyboardButton.WithSwitchInlineQuery(text, query)); return this; } /// Adds a button that switches to inline mode in the current chat with . public InlineRowBuilder SwitchInlineQueryCurrentChat(string text, string query = "") { _buttons.Add(InlineKeyboardButton.WithSwitchInlineQueryCurrentChat(text, query)); return this; } } /// Fluent builder for a . public sealed class ReplyKeyboardBuilder { private readonly List> _rows = new(); private bool _resize; private bool _oneTime; private bool _persistent; private bool _selective; private string? _placeholder; /// Adds a row of buttons. Empty rows are ignored. /// Callback that adds buttons to the row. public ReplyKeyboardBuilder Row(Action build) { ArgumentNullException.ThrowIfNull(build); var row = new ReplyRowBuilder(); build(row); if (row.Buttons.Count > 0) _rows.Add(row.Buttons); return this; } /// Resize the keyboard vertically to fit its buttons. public ReplyKeyboardBuilder Resize(bool value = true) { _resize = value; return this; } /// Hide the keyboard after the user taps a button. public ReplyKeyboardBuilder OneTime(bool value = true) { _oneTime = value; return this; } /// Keep the keyboard open until explicitly removed. public ReplyKeyboardBuilder Persistent(bool value = true) { _persistent = value; return this; } /// Show the keyboard only to specific users (see Bot API docs). public ReplyKeyboardBuilder Selective(bool value = true) { _selective = value; return this; } /// Placeholder text shown in the input field while the keyboard is active. public ReplyKeyboardBuilder Placeholder(string text) { _placeholder = text; return this; } internal ReplyKeyboardMarkup Build() { var markup = new ReplyKeyboardMarkup(_rows); if (_resize) markup.ResizeKeyboard = true; if (_oneTime) markup.OneTimeKeyboard = true; if (_persistent) markup.IsPersistent = true; if (_selective) markup.Selective = true; if (_placeholder is not null) markup.InputFieldPlaceholder = _placeholder; return markup; } } /// Fluent builder for a single row of reply keyboard buttons. public sealed class ReplyRowBuilder { private readonly List _buttons = new(); internal List Buttons => _buttons; /// Adds a plain text button; tapping it sends the text as a message. public ReplyRowBuilder Button(string text) { _buttons.Add(new KeyboardButton(text)); return this; } /// Adds a button that requests the user's phone number. public ReplyRowBuilder ContactButton(string text) { _buttons.Add(KeyboardButton.WithRequestContact(text)); return this; } /// Adds a button that requests the user's location. public ReplyRowBuilder LocationButton(string text) { _buttons.Add(KeyboardButton.WithRequestLocation(text)); return this; } /// Adds a button that launches a Web App at . public ReplyRowBuilder WebAppButton(string text, string url) { _buttons.Add(KeyboardButton.WithWebApp(text, new WebAppInfo { Url = url })); return this; } } Path: redb-route/redb.Route.Telegram/README.md Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Telegram/README.md ---- # redb.Route.Telegram Telegram Bot transport for [redb.Route](https://github.com/redbase-app/redb-route). Long-polling consumer, message / document / photo producer, webhook support, fluent DSL. --- ## Installation ```bash dotnet add package redb.Route.Telegram ``` Register in DI: ```csharp builder.Services.AddRedbRoute(route => { route.Services.AddRedbRouteTelegram(); route.AddRouteBuilder(); }); ``` --- ## Quick start — echo bot (long polling) ```csharp using redb.Route; using redb.Route.Telegram; using redb.Route.Telegram.Fluent; public class EchoBotRoutes : RouteBuilder { protected override void Configure() { From(Tg.Receive("${env:TELEGRAM_TOKEN}")) .Filter(Header(TelegramHeaders.MessageType).isEqualTo("Text")) .To(Tg.Send("${env:TELEGRAM_TOKEN}") .ChatId(Header(TelegramHeaders.ChatId))); } } ``` Set the environment variable and run — no other infrastructure needed. --- ## URI schemes | URI | Direction | Description | |---|---|---| | `telegram://receive?token=TOKEN` | Consumer | Long-polling; receives all update types | | `telegram://send?token=TOKEN&chatId=ID` | Producer | Sends a text message | | `telegram://document?token=TOKEN&chatId=ID` | Producer | Sends a file (body: `Stream` or `byte[]`) | | `telegram://photo?token=TOKEN&chatId=ID` | Producer | Sends a photo (body: `Stream` or `byte[]`) | | `telegram://answer?token=TOKEN` | Producer | Answers a callback query (removes button spinner) | | `telegram://edit?token=TOKEN&chatId=ID` | Producer | Edits text of an existing message | | `telegram://delete?token=TOKEN&chatId=ID` | Producer | Deletes a message | | `telegram://download?token=TOKEN` | Producer | Downloads a file the user sent (`getFile` + transfer); bytes land in `Out.Body` | All query parameters support `${...}` expressions. - **Per-message parameters** (`chatId`, `caption`, `fileName`, `parseMode`, …) support the full expression grammar — `${env:VAR}`, `${header.name}`, `${property.name}`, `${body}`, etc. They are resolved on every exchange. - **`token`** is resolved once at endpoint start (before any exchange exists), so only `${env:VAR}` is supported. Missing environment variables throw at startup instead of silently sending an unresolved literal to Telegram. - `${env:VAR}` is Telegram's own older spelling of an environment read. The general spelling, valid in any endpoint URI, is `{{TELEGRAM_TOKEN}}`: it reads `IConfiguration`, then context properties, then the OS environment when the context has no `IConfiguration`. Both work. ``` telegram://send?token=${env:TELEGRAM_TOKEN}&chatId=${header.telegram.chatId}&parseMode=HTML ``` ### Producer query parameters | Parameter | Type | Description | |---|---|---| | `token` | string | **Required.** Bot token from @BotFather | | `chatId` | string/long | Target chat ID or `@channelusername` | | `parseMode` | string | `HTML` \| `Markdown` \| `MarkdownV2` | | `caption` | string | Caption for document/photo | | `fileName` | string | File name when body is `Stream` | | `disableNotification` | bool | Send silently (default `false`) | | `replyToMessageId` | string | Message to reply to (`send`/`document`/`photo`). Constant id or a `${...}` expression resolved per message; `.ReplyToIncoming()` emits `${header.telegram.messageId}` | | `messageId` | string | Message to `edit`/`delete`. Constant id or a `${...}` expression, e.g. `${header.telegram.sentMessageId}` | | `showAlert` | bool | `answer` mode: show the text as a modal alert instead of a toast (default `false`) | | `bodyIsFileId` | bool | Treat string body as an existing Telegram `file_id` in `document`/`photo` mode (default `false`) | | `fileId` | string | Which file `download` fetches. Constant id or a `${...}` expression; without it the mode takes `telegram.attachment.fileId` | | `maxDownloadBytes` | long | Ceiling on a `download` (default `20971520` = 20 MiB, the Bot API's own limit; `0` lifts it) | | `sendTimeoutSeconds` | int | Per-send timeout, 1–600 (default `120`). Linked with the pipeline cancellation token. | ### Consumer query parameters | Parameter | Type | Description | |---|---|---| | `token` | string | **Required.** Bot token from @BotFather | The consumer has **no long-polling timeout knob** — the underlying `Telegram.Bot` receiver manages long-poll timing internally and exposes no public setting, so a fake option is not offered. To scale processing throughput use `.Threads(N)` on the route (see [Concurrency](#concurrency)). --- ## Delivery semantics (at-most-once) `Telegram.Bot`'s update receiver advances the update offset as soon as an update is **dispatched** to a handler — not after your route finishes processing it. There is therefore **no redelivery**: if a processor throws, the update is gone. The consumer reflects this honestly — a failing exchange is **logged as a drop** (`message dropped (at-most-once, no redelivery)`) and **not** rethrown, so one bad message never stalls the single update stream. If you need at-least-once, persist the update (e.g. to a queue) as the first route step and process from there. --- ## Rate limiting (HTTP 429) Telegram enforces flood limits and answers with HTTP 429 plus a `retry_after` hint. The producer honours it automatically: on 429 it waits `retry_after` seconds (clamped to 1–60 s) and retries, up to 3 attempts, respecting the pipeline cancellation token. This is mandatory — retrying a 429 immediately escalates to a temporary token ban. --- ## Concurrency The consumer runs a **single** update stream (Telegram delivers updates for a bot sequentially per long-poll connection; running two receivers on one token double-consumes and reorders). Starting a second consumer on the same token fails fast at startup. To parallelise **processing** without breaking ordering guarantees, use route threads: ```csharp From(Tg.Receive(token)) .Threads(4) // 4 concurrent processing workers, one receiver .Process(...); ``` See [CONCURRENCY.md](../CONCURRENCY.md) for the full model. --- ## Consumer headers After receiving an update, the consumer populates these headers on the exchange: ### All updates | Header | Type | Description | |---|---|---| | `telegram.updateId` | `long` | Unique update ID | | `telegram.updateType` | `string` | `Message`, `EditedMessage`, `CallbackQuery`, … | ### Message updates (`updateType` = Message / EditedMessage / ChannelPost / …) | Header | Type | Description | |---|---|---| | `telegram.messageId` | `int` | Message ID within the chat | | `telegram.messageType` | `string` | `Text`, `Photo`, `Document`, `Sticker`, … | | `telegram.text` | `string?` | Message text (omitted for non-text messages) | | `telegram.chatId` | `long` | Chat ID — use this to reply | | `telegram.chatType` | `string` | `Private`, `Group`, `Supergroup`, `Channel` | | `telegram.userId` | `long` | Sender user ID | | `telegram.firstName` | `string` | Sender first name | | `telegram.lastName` | `string?` | Sender last name (omitted if not set) | | `telegram.username` | `string?` | Sender `@username` without `@` (omitted if not set) | | `telegram.languageCode` | `string?` | Sender language code, e.g. `ru`, `en` | ### Attachments (any message carrying a file) Present only when the message has one; a plain text message gets none of them. | Header | Type | Description | |---|---|---| | `telegram.attachment.kind` | `string` | `voice`, `audio`, `videoNote`, `video`, `animation`, `document`, `photo`, `sticker` | | `telegram.attachment.fileId` | `string` | Telegram `file_id` — `telegram://download` takes it from here | | `telegram.attachment.mimeType` | `string?` | MIME type, when Telegram reports one | | `telegram.attachment.fileSize` | `long?` | Size in bytes, when reported | | `telegram.attachment.duration` | `int?` | Seconds — voice, audio, video, video note | | `telegram.attachment.fileName` | `string?` | Original name of a document or audio file | | `telegram.attachment.caption` | `string?` | Caption typed alongside the file | Photos arrive as a size ladder; the **largest** size is reported — downscaling is the caller's choice, not the connector's. ⚠️ **Not to be confused with the producer's `telegram.fileId`.** That one is an instruction to *send* an already-hosted file, and headers travel with the exchange: a route that consumed a voice note and then answered with a document would echo the user's own recording back at them if both sides read one key. The caption stays a header and does **not** become the body: promoting it would make a captioned photo indistinguishable from a typed command downstream. ### Callback query updates (`updateType` = CallbackQuery) | Header | Type | Description | |---|---|---| | `telegram.callbackQueryId` | `string` | Pass to `bot.AnswerCallbackQuery(...)` | | `telegram.callbackData` | `string?` | Data from the `InlineKeyboardButton` | | `telegram.chatId` | `long?` | Chat ID (omitted for inline messages) | | `telegram.userId` | `long` | User who tapped the button | | `telegram.firstName` | `string` | User first name | | `telegram.username` | `string?` | User `@username` (omitted if not set) | ### Mini App data (`messageType` = WebAppData) | Header | Type | Description | |---|---|---| | `telegram.webAppData` | `string` | Payload passed to `WebApp.sendData(...)` inside the mini app | | `telegram.webAppButtonText` | `string?` | Text of the reply-keyboard button that opened the mini app | Delivered as a regular message update, so all message headers above (`telegram.chatId`, `telegram.userId`, …) are present too — except `telegram.text`, which such a message does not carry. Exchange body = message text (or callback data for CallbackQuery, or the mini app payload for WebAppData). --- ## Producer headers Set these on the exchange before `.To(Tg.Send/...)` to control per-message behaviour: | Header | Type | Description | |---|---|---| | `telegram.chatId` | `long` / `string` | Overrides `chatId` option. Wins over the URI value. | | `telegram.parseMode` | `string` | Per-message `HTML` / `Markdown` / `MarkdownV2` override | | `telegram.disableNotification` | `bool` | Per-message silent send override | | `telegram.replyToMessageId` | `int` | Send the message as a reply | | `telegram.replyMarkup` | `InlineKeyboardMarkup` / `ReplyKeyboardMarkup` / `ReplyKeyboardRemove` | Inline / reply keyboard attached to the message | | `telegram.messageId` | `int` | Target for `edit` / `delete` modes. Wins over the `messageId` option | | `telegram.caption` | `string` | Per-message caption override for `document` / `photo` | | `telegram.showAlert` | `bool` | Per-message override for `showAlert` in `answer` mode | | `telegram.fileId` | `string` | The file this call is about: reuse an already-hosted file in `document` / `photo`, or name the one to fetch in `download` | | `telegram.fileName` | `string` | File name when body is `Stream` / `byte[]` | | `telegram.callbackQueryId` | `string` | Required for `answer` mode (set by consumer on `CallbackQuery`) | After a successful `send` / `document` / `photo` / `edit` the producer writes the resulting message id back to the exchange: | Header | Type | Description | |---|---|---| | `telegram.sentMessageId` | `int` | `Message.MessageId` returned by Telegram — use for follow-up `edit` / `delete` | --- ## Downloading what the user sent (`download`) The consumer reports an attachment (`telegram.attachment.fileId`) but never fetches it — a route that only wants to know a voice note arrived should not pay for the transfer. `telegram://download` is the second half: `getFile` plus the transfer, with the bytes on `Out.Body` as a `byte[]`. ```csharp From(Tg.Receive(token)) .Filter(e => e.In.Headers.ContainsKey(TelegramHeaders.AttachmentFileId)) .To(Tg.Download(token)) // attachment file_id → bytes .To("stt://local") // bytes → text (redb.Route.Llm) .To(Tg.Send(token).ChatId(Header(TelegramHeaders.ChatId))); ``` Which file it fetches, in priority order: the `telegram.fileId` header, then the `fileId` option (a constant or a `${...}` expression), then `telegram.attachment.fileId`, then a bare string body. The attachment header is the default rather than the override — the common case ("download what the user just sent") needs no configuration, and a route that names a file is still obeyed. Needs no `chatId`: like `answer`, this mode is addressed by an id of its own. Afterwards: | Header | Type | Description | |---|---|---| | `telegram.file.path` | `string` | Server-side path `getFile` reported, e.g. `voice/file_42.oga` | | `telegram.file.size` | `long` | Bytes actually downloaded (≠ `telegram.attachment.fileSize`, which is what the update claimed) | | `telegram.file.uniqueId` | `string` | `file_unique_id` — stable across bots and time; the id to deduplicate by | The download URL embeds the bot token, so it is built inside the client and never reaches the exchange: a header travels into logs, audits and dead letters. **Two ceilings, and both are needed.** `maxDownloadBytes` (default 20 MiB, the Bot API's own limit) is checked against the size `getFile` reports *before* the transfer, and again while reading. `file_size` is optional in the Bot API — trusting it alone would leave "how much memory does one message cost" to the sender. Bot downloads are capped at 20 MB by Telegram regardless of this option; above that `getFile` answers without a `file_path` and the producer says so. **Note on `edit` mode:** the Bot API's `editMessageText` does not accept `disable_notification`; editing a message never produces a notification, so the option and header are intentionally ignored in `edit` mode. **Body → file mapping for `document` / `photo`:** - `Stream` or `byte[]` — uploaded as a new file (use `fileName` for a sensible name). - HTTP(S) URL `string` — passed to Telegram to fetch by URL. - To reuse an existing Telegram file, set header `telegram.fileId` **or** add `bodyIsFileId=true` to the URI (then a string body is treated as a `file_id`). A plain string body without either of these is rejected with a clear error — the transport does not guess. --- ## Fluent DSL ```csharp using redb.Route.Telegram.Fluent; // Consumer (no timeout knob — use .Threads(N) on the route to scale processing) From(Tg.Receive(token)) // Text producer .To(Tg.Send(token).ChatId(chatId).ParseMode("HTML")) // Document producer — body must be Stream or byte[] .To(Tg.Document(token).ChatId(chatId).FileName("report.pdf").Caption("Daily report")) // Photo producer .To(Tg.Photo(token).ChatId(chatId).Caption("Screenshot")) // Reuse an existing Telegram file_id instead of uploading .To(Tg.Document(token).ChatId(chatId).BodyIsFileId()) // Download what the user sent — takes telegram.attachment.fileId with no configuration .To(Tg.Download(token)) .To(Tg.Download(token).FileId(Header(TelegramHeaders.AttachmentFileId)).MaxDownloadBytes(2_000_000)) // Tighter per-send timeout (default 120s) .To(Tg.Send(token).ChatId(chatId).Timeout(30)) // Reply to the incoming message (sugar for replyToMessageId=${header.telegram.messageId}) .To(Tg.Send(token).ChatId(chatId).ReplyToIncoming()) // Expressions are supported everywhere Tg.Send("${env:TELEGRAM_TOKEN}").ChatId(Header("telegram.chatId")) ``` --- ## Reply to a message To reply to the message that triggered the exchange, use `.ReplyToIncoming()` — sugar for `replyToMessageId=${header.telegram.messageId}`, the id the consumer put on the exchange: ```csharp From(Tg.Receive(token)) .To(Tg.Send(token).ChatId(Header(TelegramHeaders.ChatId)).ReplyToIncoming()) ``` `ReplyTo(...)` targets any message — a constant id or an expression resolved per message. The `telegram.replyToMessageId` header, when set, wins over the option: ```csharp .To(Tg.Send(token).ChatId(chatId).ReplyTo(Header("myApp.threadRootId"))) ``` If the expression resolves to nothing (e.g. `.ReplyToIncoming()` on an update without `telegram.messageId`), the message is sent unthreaded rather than failing. --- ## Answer a callback query Must be called after any inline button tap — otherwise the button shows an infinite spinner. ```csharp From(Tg.Receive(token)) .Filter(Header(TelegramHeaders.UpdateType).isEqualTo("CallbackQuery")) .SetBody("✅ Done") // optional toast text .To(Tg.Answer(token)) // clears the spinner .Process(e => e.In.Body = HandleAction( e.In.GetHeader(TelegramHeaders.CallbackData)!)) .To(Tg.Send(token).ChatId(Header(TelegramHeaders.ChatId))); // send follow-up ``` `Answer` reads `telegram.callbackQueryId` from headers (set automatically by the consumer). `.ShowAlert()` turns the toast into a modal alert. --- ## Edit a message Body = new text. The target comes from the `telegram.messageId` header or the `messageId=` option — e.g. `.MessageId(Header(TelegramHeaders.SentMessageId))` to edit the message just sent by an upstream step. ```csharp .SetBody("Updated text") .Process(e => { // optionally update the inline keyboard too e.In.Headers[TelegramHeaders.ReplyMarkup] = new InlineKeyboardMarkup( InlineKeyboardButton.WithCallbackData("🔄 Refresh", "action:refresh")); }) .To(Tg.Edit(token).ChatId(Header(TelegramHeaders.ChatId))) ``` --- ## Delete a message Target: `telegram.messageId` header or the `messageId=` option. ```csharp .To(Tg.Delete(token).ChatId(Header(TelegramHeaders.ChatId))) ``` --- ## Webhook Use `.UnpackTelegramUpdate()` to process Telegram webhook POSTs. The exchange headers are identical to the long-polling path — downstream routes work unchanged. ```csharp // Requires redb.Route.Http for Http.Listen(...) From(Http.Listen("/tg/webhook").InOut()) .Filter(Header("X-Telegram-Bot-Api-Secret-Token").isEqualTo(webhookSecret)) // the secret_token of setWebhook .UnpackTelegramUpdate() // deserialise JSON → Update + populate headers .To("direct://tg-dispatch"); // The same dispatcher handles both polling and webhook traffic From("direct://tg-dispatch") .Choice() .When(Header(TelegramHeaders.UpdateType).isEqualTo("Message")) .To("direct://handle-message") ... .EndChoice(); ``` --- ## Sending buttons (reply markup) Use the fluent keyboard builder — it constructs the markup for you and needs no `using Telegram.Bot.Types.ReplyMarkups` in your route code. Under the hood it just sets the `telegram.replyMarkup` header, so the raw-header approach (below) keeps working. ### Inline keyboard (callback buttons) ```csharp using redb.Route.Telegram.Fluent; From(Tg.Receive(token)) .SetBody("Choose an option:") .WithInlineKeyboard(k => k .Row(r => r.Callback("✅ Confirm", "action:confirm") .Callback("❌ Cancel", "action:cancel")) .Row(r => r.Callback("📊 Stats", "action:stats"))) .To(Tg.Send(token).ChatId(Header(TelegramHeaders.ChatId)).ParseMode("HTML")); ``` Inline row buttons: `Callback(text, data)`, `Url(text, url)`, `WebApp(text, url)`, `SwitchInlineQuery(text, query)`, `SwitchInlineQueryCurrentChat(text, query)`. Telegram delivers the user's tap as a `CallbackQuery` update — handle it on the consumer side: ```csharp From(Tg.Receive(token)) .Choice() .When(Header(TelegramHeaders.UpdateType).isEqualTo("CallbackQuery")) .Process(async (e, ct) => { var data = e.In.GetHeader(TelegramHeaders.CallbackData); // respond with AnswerCallbackQuery via injected ITelegramBotClient }) ... .EndChoice(); ``` ### Reply keyboard (keyboard shown below text input) ```csharp .WithReplyKeyboard(k => k .Row(r => r.Button("📋 Menu").Button("❓ Help")) .Resize() .OneTime()) ``` Reply row buttons: `Button(text)`, `ContactButton(text)`, `LocationButton(text)`, `WebAppButton(text, url)`. Keyboard options: `Resize()`, `OneTime()`, `Persistent()`, `Selective()`, `Placeholder(text)`. ### Mini Apps (Web Apps) A web app button opens your HTTPS page inside the Telegram client: ```csharp // inline — opens the mini app, cannot send data back to the bot .WithInlineKeyboard(k => k.Row(r => r.WebApp("🌟 Open", "https://app.example/"))) // reply keyboard — the mini app may call WebApp.sendData(...) .WithReplyKeyboard(k => k.Row(r => r.WebAppButton("🌟 Open", "https://app.example/"))) ``` `sendData` closes the mini app and delivers a message update with `telegram.messageType = "WebAppData"`; the payload lands in the body and in `telegram.webAppData`: ```csharp From(Tg.Receive(token)) .Filter(Header(TelegramHeaders.MessageType).isEqualTo("WebAppData")) .Process((e, ct) => { var payload = e.In.GetHeader(TelegramHeaders.WebAppData); // ... deserialise and handle return Task.CompletedTask; }) .SetBody("✅ Получено") .To(Tg.Send(token).ChatId(Header(TelegramHeaders.ChatId))); ``` `sendData` is one-way and limited to 4096 bytes — the mini app gets no response back. That is a Bot API property, not a connector limitation. ### Remove keyboard ```csharp .WithoutKeyboard() ``` ### Dynamic keyboards (built from runtime data) When rows depend on data available only at processing time, build the markup with `TgKeyboard.Inline(...)` / `TgKeyboard.Reply(...)` inside a `.Process(...)` step and assign it to the header directly: ```csharp using redb.Route.Telegram.Fluent; .Process((e, ct) => { e.In.Headers[TelegramHeaders.ReplyMarkup] = TgKeyboard.Inline(k => { foreach (var o in orders) k.Row(r => r.Callback(o.Title, $"order:{o.Id}")); }); return Task.CompletedTask; }) .To(Tg.Send(token).ChatId(Header(TelegramHeaders.ChatId))) ``` ### Raw header (still supported) The builder is optional. You can always set the `telegram.replyMarkup` header to a `Telegram.Bot` `InlineKeyboardMarkup` / `ReplyKeyboardMarkup` / `ReplyKeyboardRemove` instance yourself before the `.To(Tg.Send(...))` step. --- ## What is NOT included | Feature | Where to find it | |---|---| | Webhook HTTP server | `redb.Route.Http` — use `Http.Listen(...)` | | FSM / conversation state | Application layer — use your own state store | | At-least-once delivery / redelivery | Persist updates to a queue as the first route step (see [Delivery semantics](#delivery-semantics-at-most-once)) | | Batching | Not supported by Telegram Bot API — each message is a separate HTTP call | ## Named connection factory Keep credentials out of the route URI: register a factory in the context registry and reference it by name. A set-but-unknown name fails loud at startup — a typo can never silently fall back to inline URI parameters. ```csharp context.AddToRegistry("prod", new TelegramConnectionFactory { Token = secrets.BotToken, }); // telegram://bot?connectionFactory=prod ``` ## Tracing On the `redb.Route` activity source (`AddSource("redb.Route")`), with `messaging.system` = `telegram` and `redb.route.endpoint`: - **Consumer.** One `Consumer` span per routed update, `telegram.{type} receive`, with the chat type and message id. An update carries no trace context, so the span is a root, never a child of the activity the polling loop holds. A failed route marks it an error, whether the failure stays on the exchange or escapes it; our own stop does not. - **Producer.** One `Producer` span per send, `telegram.{mode} publish`; an error when the send fails, the per-request timeout included, unless our own token cancelled it. - `RouteEngineOptions.EnableTelemetry = false` opens neither span. The chat id identifies a person or a group, so neither span carries it, and neither do the log lines. A route that needs it in its traces adds it itself: ```csharp From(Tg.Receive(token)) .SpanTag("messaging.telegram.chat.id", Header(TelegramHeaders.ChatId), SpanTarget.Inbound) ... ``` Path: redb-route/redb.Route.Telegram/TelegramComponent.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Telegram/TelegramComponent.cs ---- using System.Collections.Concurrent; using System.Net; using Microsoft.Extensions.Logging; using Telegram.Bot; using redb.Route.Abstractions; using redb.Route.Extensions; using redb.Route.Core; namespace redb.Route.Telegram; /// /// Telegram Bot transport component for redb.Route. /// Scheme: telegram. /// /// URI format:
/// Consumer: telegram://receive?token=TOKEN&timeoutSeconds=30
/// Producer: telegram://send?token=TOKEN&chatId=123456&parseMode=HTML
/// Document: telegram://document?token=TOKEN&chatId=123456&fileName=report.pdf ///
/// /// Owns a per-token registry of instances with a /// dedicated per token. All consumers and producers /// targeting the same token share the same client — required by Telegram Bot API /// which allows only one getUpdates stream per token (HTTP 409 otherwise). /// The component disposes all owned instances on /// . /// ///
public sealed class TelegramComponent : ComponentBase { private readonly ConcurrentDictionary _clients = new(StringComparer.Ordinal); private readonly ConcurrentDictionary _consumerTokens = new(StringComparer.Ordinal); /// public override string Scheme => "telegram"; /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var options = new TelegramEndpointOptions(); options.BindFromUri(uri.RawParameters); // Resolve the named ConnectionFactory BEFORE Validate(): the factory may be the only // source of the bot token, and Validate() requires one. This is what lets a route // reference `connectionFactory=my-bot` and keep the token out of the URI entirely. if (!string.IsNullOrEmpty(options.ConnectionFactory)) { // A set-but-unknown name fails loud -- never a silent fallback to URI params. var factory = Context.GetRequiredFromRegistry(options.ConnectionFactory); factory.ApplyTo(options, uri); } options.Validate(); return new TelegramEndpoint(uri, this, options); } /// /// Returns the shared for , /// creating it on first use. ${env:VAR} expressions in the token are /// resolved via . /// public TelegramBotClient GetOrCreateClient(string rawToken) { ArgumentException.ThrowIfNullOrEmpty(rawToken); var resolved = TelegramEndpointOptions.ResolveTokenExpression(rawToken); var entry = _clients.GetOrAdd(resolved, static token => { // Own the HttpClient so we can dispose it on component shutdown. var http = BuildHttpClient(); var bot = new TelegramBotClient(token, http); return new ClientEntry(bot, http); }); return entry.Bot; } /// /// The shared HTTP transport of one bot: long polling and every producer send and download go /// through it. A getUpdates long poll is silent for up to ~50 s (Telegram caps the wait there); /// middleboxes (VPN tunnels, NAT, proxies) drop TLS connections that stay silent for about that /// long, which showed up as "The response ended prematurely" on nearly every poll through a /// sing-tun/xray tunnel (2026-09-04) — a retry storm in the log, and a message arriving in the /// gap waits for the next poll. HTTP/2 with PING frames while a request is in flight keeps the /// connection visibly alive (four consecutive 50-second polls completed with a ping every 15 s; /// without pings HTTP/1.1 lost every one). api.telegram.org speaks HTTP/2; on HTTP/1.1 the pings /// are simply not sent. /// internal static HttpClient BuildHttpClient() => new(new Http2UpgradeHandler(BuildHandler())) { // Must exceed the maximum long-polling duration (50s) plus a margin. Timeout = TimeSpan.FromSeconds(75), DefaultRequestVersion = HttpVersion.Version20, DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrLower, }; /// See . PooledConnectionLifetime mirrors Telegram.Bot's own default. internal static SocketsHttpHandler BuildHandler() => new() { PooledConnectionLifetime = TimeSpan.FromMinutes(3), KeepAlivePingDelay = TimeSpan.FromSeconds(15), KeepAlivePingTimeout = TimeSpan.FromSeconds(20), KeepAlivePingPolicy = HttpKeepAlivePingPolicy.WithActiveRequests, }; /// /// Reserves consumer ownership for within this /// component. Throws when a second consumer attempts to register the same /// token — Telegram Bot API only permits a single getUpdates stream /// per token, so a duplicate consumer would silently fail with HTTP 409. /// public void RegisterConsumer(string rawToken) { var resolved = TelegramEndpointOptions.ResolveTokenExpression(rawToken); if (!_consumerTokens.TryAdd(resolved, 0)) throw new InvalidOperationException( "Telegram: only one consumer per bot token is allowed within a RouteContext. " + "The Bot API returns HTTP 409 Conflict when two getUpdates streams run for the same token."); } /// Releases the consumer slot reserved by . public void UnregisterConsumer(string rawToken) { var resolved = TelegramEndpointOptions.ResolveTokenExpression(rawToken); _consumerTokens.TryRemove(resolved, out _); } /// public override ValueTask DisposeAsync() { foreach (var kv in _clients) { try { kv.Value.Http.Dispose(); } catch (Exception ex) { Logger?.LogWarning(ex, "Telegram: error disposing HttpClient for token"); } } _clients.Clear(); _consumerTokens.Clear(); return base.DisposeAsync(); } private readonly record struct ClientEntry(TelegramBotClient Bot, HttpClient Http); } /// /// Asks for HTTP/2 on every request that passes through. /// applies only to messages the client creates itself; Telegram.Bot builds its own /// s, which therefore start at HTTP/1.1 — and on HTTP/1.1 the /// keep-alive pings of are never sent (verified /// 2026-09-04: getMe through a client with DefaultRequestVersion 2.0 still went out as 1.1). /// HTTP/1.1 remains the fallback when the server does not offer h2. /// internal sealed class Http2UpgradeHandler(HttpMessageHandler inner) : DelegatingHandler(inner) { protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { request.Version = HttpVersion.Version20; request.VersionPolicy = HttpVersionPolicy.RequestVersionOrLower; return base.SendAsync(request, cancellationToken); } } Path: redb-route/redb.Route.Telegram/TelegramConnectionFactory.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Telegram/TelegramConnectionFactory.cs ---- using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Telegram; /// /// Named connection factory for Telegram. Register it in the route registry and reference it by /// name from the endpoint URI (connectionFactory=my-bot) so the bot token — a full account /// credential — never has to appear in the URI, and therefore can never reach logs, telemetry, /// or the Tsak dashboard. /// /// Example: /// /// context.AddToRegistry("support-bot", new TelegramConnectionFactory /// { /// Token = Environment.GetEnvironmentVariable("TELEGRAM_TOKEN")! /// }); /// /// // route carries no token at all: /// r.From("telegram://receive?connectionFactory=support-bot") /// /// /// public sealed class TelegramConnectionFactory { /// Bot token from @BotFather. Supports ${env:NAME} expressions. [Sensitive] public string Token { get; set; } = string.Empty; /// Per-send timeout in seconds for producer calls (default 120, range 1–600). public int SendTimeoutSeconds { get; set; } = 120; /// /// Copies this factory's settings onto the endpoint options, but only for parameters the /// endpoint URI did not set explicitly — an inline URI value always wins, so existing routes /// keep their behaviour. /// internal void ApplyTo(TelegramEndpointOptions options, EndpointUri uri) { var supplied = uri.RawParameters; if (!supplied.ContainsKey(nameof(options.Token))) options.Token = Token; if (!supplied.ContainsKey(nameof(options.SendTimeoutSeconds))) options.SendTimeoutSeconds = SendTimeoutSeconds; } } Path: redb-route/redb.Route.Telegram/TelegramConsumer.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Telegram/TelegramConsumer.cs ---- using System.Diagnostics; using Microsoft.Extensions.Logging; using Telegram.Bot; using Telegram.Bot.Exceptions; using Telegram.Bot.Polling; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; using TgMessage = Telegram.Bot.Types.Message; using RouteMessage = redb.Route.Core.Message; namespace redb.Route.Telegram; /// /// Telegram Bot long-polling consumer. /// Subscribes to bot.OnMessage and bot.OnUpdate events (Telegram.Bot v21+ API). /// Each received update is wrapped in an IExchange and passed to the processor pipeline. /// /// Long polling starts automatically when TelegramBotClient is created with a token. /// Cancelled when DrainableConsumer signals stop via pollCt. /// public sealed class TelegramConsumer : DrainableConsumer { private readonly TelegramEndpoint _endpoint; private readonly TelegramEndpointOptions _options; private TelegramComponent? _component; private TelegramBotClient? _bot; private TelegramBotClient.OnMessageHandler? _onMessageHandler; private TelegramBotClient.OnUpdateHandler? _onUpdateHandler; private TelegramBotClient.OnErrorHandler? _onErrorHandler; private readonly object _handlerLock = new(); private bool _handlersAttached; // Test seam: when false, RunAsync does not subscribe to the live bot (no network long-poll). // Tests drive updates via DeliverMessageForTest/DeliverUpdateForTest and errors via RaiseErrorForTest. internal bool AttachToLiveBot { get; set; } = true; // Test observability: set true when a fatal (401/409) polling error was handled. internal bool FatalPollingErrorDetected { get; private set; } /// protected override IEndpoint ConsumerEndpoint => _endpoint; /// protected override string ConsumerName => $"telegram:receive"; /// Creates a Telegram long-polling consumer. public TelegramConsumer(TelegramEndpoint endpoint, IProcessor processor, TelegramEndpointOptions options) : base(processor) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _options = options ?? throw new ArgumentNullException(nameof(options)); } /// /// /// Runs synchronously inside Start(). Resolving the shared client and reserving the /// single-consumer slot here (rather than in the background ) makes the /// duplicate-consumer guard fail fast: a second consumer for the same token throws to the caller /// of Start() instead of dying silently on a background task. /// protected override Task OnStarting(CancellationToken ct) { _component = _endpoint.Component as TelegramComponent ?? throw new InvalidOperationException( "Telegram consumer requires TelegramComponent as its owning component."); // Fail-fast: only one getUpdates stream per token is allowed (Bot API returns HTTP 409 otherwise). _component.RegisterConsumer(_options.Token); _bot = _component.GetOrCreateClient(_options.Token); return Task.CompletedTask; } /// /// /// Telegram.Bot v22 starts its single internal getUpdates loop when /// bot.OnMessage/bot.OnUpdate handlers are attached. The client is owned by /// and shared across consumers/producers with the same token. /// Handlers are detached in (step 1 of the drain sequence) so no /// new update inflates the in-flight count during the drain window. /// protected override async Task RunAsync(CancellationToken pollCt, CancellationToken processingCt) { var bot = _bot ?? throw new InvalidOperationException("Telegram consumer client was not initialised in OnStarting."); // Do NOT mutate bot.Timeout here. The HTTP timeout belongs to the shared HttpClient owned by // TelegramComponent (75s ceiling, covers the ~50s long-poll plus margin). Changing it here // would leak into producer sends that share the same client. _onErrorHandler = OnPollingError; _onMessageHandler = async (TgMessage msg, UpdateType type) => { if (processingCt.IsCancellationRequested) return; await HandleMessageAsync(msg, type, processingCt).ConfigureAwait(false); }; // OnUpdate catches everything: CallbackQuery, InlineQuery, etc. // All message-bearing update types are already handled via OnMessage — skip them // here to avoid double processing. _onUpdateHandler = async (Update update) => { if (processingCt.IsCancellationRequested) return; if (IsMessageBearing(update.Type)) return; await HandleUpdateAsync(update, processingCt).ConfigureAwait(false); }; if (AttachToLiveBot) AttachHandlers(bot); // Safety net for a Start()/Stop() race: if pollCt is already cancelled (or is cancelled while // this background task is still wiring up), detach immediately so nothing keeps polling. using var reg = pollCt.Register(DetachHandlers); Logger?.LogInformation( "Telegram long-polling started (sharedHttpTimeout={Http}s)", (int)bot.Timeout.TotalSeconds); // Block until pollCt is cancelled. Handlers do the work on the client's own polling thread. try { await Task.Delay(Timeout.Infinite, pollCt).ConfigureAwait(false); } catch (OperationCanceledException) { /* expected on stop */ } Logger?.LogInformation("Telegram long-polling stopped"); } /// /// /// Step 1 of 's stop sequence: detach the event handlers BEFORE the /// drain so the internal getUpdates loop stops delivering. Otherwise every update arriving during /// the drain window would increment the in-flight counter and the drain could never reach zero. /// protected override Task OnStopAccepting() { DetachHandlers(); return Task.CompletedTask; } /// protected override Task OnStopped() { DetachHandlers(); // idempotent safety net _component?.UnregisterConsumer(_options.Token); _bot = null; _component = null; _onMessageHandler = null; _onUpdateHandler = null; _onErrorHandler = null; return Task.CompletedTask; } // ── Handler attach / detach ─────────────────────────────────────────────── private void AttachHandlers(TelegramBotClient bot) { lock (_handlerLock) { if (_handlersAttached) return; if (_onErrorHandler is not null) bot.OnError += _onErrorHandler; if (_onMessageHandler is not null) bot.OnMessage += _onMessageHandler; if (_onUpdateHandler is not null) bot.OnUpdate += _onUpdateHandler; _handlersAttached = true; } } /// /// Detaches all handlers from the shared client, which stops its internal getUpdates loop once the /// handler lists are empty. Idempotent and safe to call from any thread (Stop hooks, the pollCt /// registration, or a fatal ). /// private void DetachHandlers() { lock (_handlerLock) { if (!_handlersAttached) return; var bot = _bot; if (bot is not null) { if (_onMessageHandler is not null) bot.OnMessage -= _onMessageHandler; if (_onUpdateHandler is not null) bot.OnUpdate -= _onUpdateHandler; if (_onErrorHandler is not null) bot.OnError -= _onErrorHandler; } _handlersAttached = false; } } /// /// Telegram.Bot polling / handler error callback. Fatal errors (401 revoked token, 409 conflicting /// webhook/second stream) detach the handlers to stop the loop — otherwise Telegram.Bot would retry /// getUpdates with no backoff and produce an API retry-storm plus a log flood. Transient /// errors are logged and left for Telegram.Bot's own retry. /// private Task OnPollingError(Exception ex, HandleErrorSource source) { if (IsFatal(ex)) { FatalPollingErrorDetected = true; Logger?.LogCritical(ex, "Telegram: fatal polling error ({Source}) — stopping the getUpdates stream to avoid a retry storm.", source); DetachHandlers(); } else { Logger?.LogError(ex, "Telegram transient polling error ({Source}); Telegram.Bot will retry.", source); } return Task.CompletedTask; } private static bool IsFatal(Exception ex) => ex is ApiRequestException { ErrorCode: 401 or 409 }; private static bool IsMessageBearing(UpdateType type) => type is UpdateType.Message or UpdateType.EditedMessage or UpdateType.ChannelPost or UpdateType.EditedChannelPost or UpdateType.BusinessMessage or UpdateType.EditedBusinessMessage; // ── Test seams (exercised by redb.Route.Tests.Telegram; no network) ─────── internal Task DeliverMessageForTest(TgMessage msg, UpdateType type, CancellationToken ct) => HandleMessageAsync(msg, type, ct); internal Task DeliverUpdateForTest(Update update, CancellationToken ct) => HandleUpdateAsync(update, ct); internal Task RaiseErrorForTest(Exception ex, HandleErrorSource source) => OnPollingError(ex, source); // ── Message handler ─────────────────────────────────────────────────────── private async Task HandleMessageAsync( TgMessage msg, UpdateType updateType, CancellationToken ct) { // An update carries no trace context: its span is a root, never a child of the activity the polling loop holds. using var span = StartReceiveSpan($"telegram.{updateType} receive", updateType.ToString()); if (span.Activity is { IsAllDataRequested: true } activity) { activity.SetTag("messaging.telegram.chat.type", msg.Chat.Type.ToString()); activity.SetTag("messaging.telegram.message.id", msg.MessageId); } var exchange = CreateMessageExchange(msg, updateType); IncrementInflight(); try { // Endpoint statistics (RecordMessageIn/Out/Error) are recorded by the // framework's StatisticsProcessor which wraps Processor. Matches the // Kafka/RabbitMQ pattern — no explicit Record* calls here. await Processor.Process(exchange, ct).ConfigureAwait(false); if (exchange.Exception is { } failure && !exchange.ExceptionHandled && (failure is not OperationCanceledException || !ct.IsCancellationRequested)) span.Activity.RecordFailure(failure); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { // Graceful shutdown mid-processing — not a message error. } catch (Exception ex) { // At-most-once: Telegram.Bot advances the update offset as soon as the update is dispatched, // so there is no redelivery. Route-level error handling (OnException / dead-letter) already // ran inside Processor.Process; anything reaching here is terminal. Log it as a dropped // message rather than re-throwing into the polling loop (which would only re-log the same error). span.Activity.RecordFailure(ex); Logger?.LogError(ex, "Telegram consumer: unhandled processor error for message {MessageId} — " + "message dropped (at-most-once, no redelivery).", msg.MessageId); } finally { await exchange.DisposeAsync().ConfigureAwait(false); DecrementInflight(); } } // ── Update handler (CallbackQuery, etc.) ────────────────────────────────── private async Task HandleUpdateAsync( Update update, CancellationToken ct) { var exchange = CreateUpdateExchange(update); if (exchange is null) return; using var span = StartReceiveSpan($"telegram.{update.Type} receive", update.Type.ToString()); if (span.Activity is { IsAllDataRequested: true } activity) { activity.SetTag("messaging.telegram.update.id", update.Id); if (update.CallbackQuery is { } cb) { activity.SetTag("messaging.telegram.callback_query.id", cb.Id); if (cb.Message?.Chat is { } chat) { activity.SetTag("messaging.telegram.chat.type", chat.Type.ToString()); } } } IncrementInflight(); try { await Processor.Process(exchange, ct).ConfigureAwait(false); if (exchange.Exception is { } failure && !exchange.ExceptionHandled && (failure is not OperationCanceledException || !ct.IsCancellationRequested)) span.Activity.RecordFailure(failure); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { // Graceful shutdown mid-processing — not a message error. } catch (Exception ex) { // At-most-once (see HandleMessageAsync): terminal error, message dropped, no redelivery. span.Activity.RecordFailure(ex); Logger?.LogError(ex, "Telegram consumer: unhandled processor error for update {UpdateId} — " + "message dropped (at-most-once, no redelivery).", update.Id); } finally { await exchange.DisposeAsync().ConfigureAwait(false); DecrementInflight(); } } /// The root span of one update; the Bot API carries no trace context. private TransportSpan StartReceiveSpan(string name, string destination) => RouteTelemetryExtensions.StartConsumerSpan( (_endpoint.Component as ComponentBase)?.Context, name, ActivityKind.Consumer, "messaging.system", "telegram", _endpoint.Uri.NormalizedKey, null, static (_, _) => null, destination: destination, operation: "receive"); // ── Exchange factories ──────────────────────────────────────────────────── private Exchange CreateMessageExchange(TgMessage msg, UpdateType updateType) { var routeMessage = new RouteMessage(); TelegramUpdateMapper.MapMessage(msg, updateType, routeMessage); var exchange = Exchange.Create(routeMessage, _endpoint.ScopeFactory); exchange.Pattern = ExchangePattern.InOnly; return exchange; } private Exchange? CreateUpdateExchange(Update update) { var routeMessage = new RouteMessage(); if (!TelegramUpdateMapper.MapUpdate(update, routeMessage)) { Logger?.LogDebug("Telegram consumer: skipping update type {Type}", update.Type); return null; } var exchange = Exchange.Create(routeMessage, _endpoint.ScopeFactory); exchange.Pattern = ExchangePattern.InOnly; return exchange; } } Path: redb-route/redb.Route.Telegram/TelegramEndpoint.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Telegram/TelegramEndpoint.cs ---- using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Telegram; /// /// Telegram Bot endpoint. /// Path segment determines the operation mode: /// "receive" — consumer (long polling) /// "send" — producer: text message /// "document" — producer: file/document (body must be Stream or byte[]) /// "photo" — producer: photo (body must be Stream or byte[]) /// "answer" — producer: answer a callback query (no chatId needed) /// "edit" — producer: edit an existing message /// "delete" — producer: delete a message /// "download" — producer: fetch a file the user sent (no chatId needed); /// the bytes land in Out.Body /// public sealed class TelegramEndpoint : EndpointBase { /// Mode parsed from URI path: receive | send | document | photo | answer | edit | delete | download. public string Mode { get; } /// Creates a Telegram endpoint. public TelegramEndpoint(EndpointUri uri, IComponent component, TelegramEndpointOptions options) : base(uri, component, options) { Mode = uri.Path.Trim('/').ToLowerInvariant() switch { "receive" => "receive", "send" => "send", "document" => "document", "photo" => "photo", "answer" => "answer", "edit" => "edit", "delete" => "delete", "download" => "download", var other => throw new ArgumentException( $"Unknown Telegram mode '{other}'. Expected: receive | send | document | photo | answer | edit | delete | download.", nameof(uri)) }; } /// public override IProducer CreateProducer() => new TelegramProducer(this, Options); /// public override IConsumer CreateConsumer(IProcessor processor) { if (Mode != "receive") throw new InvalidOperationException( $"Telegram endpoint '{Mode}' cannot be used as a consumer. " + $"Use 'telegram://receive?token=...' for long polling."); return new TelegramConsumer(this, processor, Options); } } Path: redb-route/redb.Route.Telegram/TelegramEndpointOptions.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Telegram/TelegramEndpointOptions.cs ---- using System.Text.RegularExpressions; using Telegram.Bot.Types.Enums; using redb.Route.Core; using TgParseMode = global::Telegram.Bot.Types.Enums.ParseMode; namespace redb.Route.Telegram; /// /// Typed options for . /// Bound from URI query parameters via reflection (EndpointOptions.BindFromUri). /// /// Consumer URI: telegram://receive?token=TOKEN /// Producer URI: telegram://send?token=TOKEN&chatId=123456&parseMode=HTML /// Document URI: telegram://document?token=TOKEN&chatId=123456&fileName=report.pdf /// public sealed class TelegramEndpointOptions : EndpointOptions { // ── Auth ────────────────────────────────────────────────────────────────── /// /// Bot token from @BotFather. /// Supports ${...} expressions: token=${env:TELEGRAM_TOKEN} /// [Sensitive] public string Token { get; set; } = string.Empty; /// /// Named from the route registry. Lets the bot token /// live in the registry instead of the endpoint URI, so it never reaches logs or dashboards. /// [RegistryReference(typeof(TelegramConnectionFactory))] public string? ConnectionFactory { get; set; } // ── Producer ────────────────────────────────────────────────────────────── /// /// Target chat ID or username (@channelusername). /// Supports expressions: chatId=${header.telegram.chatId} /// public string? ChatId { get; set; } /// /// Parse mode for message text: HTML, Markdown, MarkdownV2. /// Default: plain text (null). /// public string? ParseMode { get; set; } /// /// Send message silently (no notification sound). Default false. /// public bool DisableNotification { get; set; } /// /// Caption for document/photo messages. Supports expressions. /// public string? Caption { get; set; } /// /// File name for document sends (when body is Stream or byte[]). /// Required for mode=document if body is a Stream. /// Supports expressions: fileName=${header.telegram.fileName} /// public string? FileName { get; set; } /// /// When true, treats a string exchange body as a Telegram file_id /// in document/photo modes and reuses the file without re-uploading. /// Otherwise the body must be Stream, byte[], an HTTP(S) URL, /// or the telegram.fileId header must be set. Default false. /// public bool BodyIsFileId { get; set; } /// /// Message to reply to. Supports expressions, resolved per message: /// replyToMessageId=${header.telegram.messageId} replies to the incoming /// message (the fluent sugar .ReplyToIncoming() emits exactly that). /// An explicit telegram.replyToMessageId header wins over this option. /// Applies to send / document / photo modes. Default: no reply. /// public string? ReplyToMessageId { get; set; } /// /// Message to edit / delete. Supports expressions, resolved per message: /// messageId=${header.telegram.sentMessageId} targets the message just sent /// by an upstream producer step. An explicit telegram.messageId header wins. /// Applies to edit / delete modes. Default: header required. /// public string? MessageId { get; set; } /// /// In answer mode, show the text as a modal alert instead of a toast /// at the top of the chat. Default false. /// public bool ShowAlert { get; set; } // ── Download ────────────────────────────────────────────────────────────── /// /// Which file the download mode fetches. Supports expressions, resolved per /// message: fileId=${header.telegram.attachment.fileId} takes the attachment the /// consumer reported. An explicit telegram.fileId header wins over this option, /// and with neither set the producer falls back to the inbound attachment header — the /// case that needs no configuration at all. /// public string? FileId { get; set; } /// /// Ceiling on a download, in bytes. Default 20 MiB — the Bot API's own limit for /// what a bot may download, so the default refuses exactly what Telegram would refuse. /// /// Enforced BEFORE the transfer, against the size getFile reports, and again while /// reading: a downloaded file becomes a byte array in memory, and "how big can that get" /// must not be answerable only by the sender. Set 0 to lift the ceiling. /// /// public long MaxDownloadBytes { get; set; } = 20L * 1024 * 1024; /// /// Per-send timeout in seconds for producer calls (send / document / photo / edit / delete / answer). /// Default 120. Range 1–600. Independent from the long-polling HTTP ceiling so large uploads over /// a slow link are not capped by the consumer's poll timeout. /// public int SendTimeoutSeconds { get; set; } = 120; // ── Consumer ────────────────────────────────────────────────────────────── // // The Telegram Bot API allows a single getUpdates long-poll stream per token. Telegram.Bot manages // that loop internally (started when OnMessage/OnUpdate handlers are attached) and does NOT expose a // long-poll timeout knob for the event-based receiver, so there is deliberately no consumer // timeoutSeconds option — advertising one would be a silent no-op. Parallel processing is achieved // with the EIP `.Threads(N)` on the route, not a native concurrency option (see README / CONCURRENCY.md). /// public override void Validate() { if (string.IsNullOrWhiteSpace(Token)) throw new ArgumentException( "The 'token' parameter is required for Telegram endpoints.", nameof(Token)); if (SendTimeoutSeconds is < 1 or > 600) throw new ArgumentOutOfRangeException(nameof(SendTimeoutSeconds), SendTimeoutSeconds, "Telegram send timeout must be between 1 and 600 seconds."); if (MaxDownloadBytes < 0) throw new ArgumentOutOfRangeException(nameof(MaxDownloadBytes), MaxDownloadBytes, "Telegram maxDownloadBytes must be 0 (no ceiling) or a positive size."); if (!TryParseParseMode(ParseMode, out _)) throw new ArgumentException( $"Invalid parseMode '{ParseMode}'. Expected 'HTML', 'Markdown', 'MarkdownV2' or empty.", nameof(ParseMode)); // A constant message-id option must be a message id; expressions are resolved per message. ValidateMessageIdOption(ReplyToMessageId, "replyToMessageId", nameof(ReplyToMessageId)); ValidateMessageIdOption(MessageId, "messageId", nameof(MessageId)); } private static void ValidateMessageIdOption(string? value, string uriName, string paramName) { if (!string.IsNullOrWhiteSpace(value) && !value.Contains("${", StringComparison.Ordinal) && !long.TryParse(value, out _)) throw new ArgumentException( $"Invalid {uriName} '{value}'. Expected a message id or a ${{...}} expression.", paramName); } /// /// Maps a case-insensitive parse-mode string to . /// Empty / null maps to (plain text). /// Returns for an unrecognised value so callers can throw instead of /// silently downgrading to plain text. /// internal static bool TryParseParseMode(string? raw, out TgParseMode mode) { mode = TgParseMode.None; if (string.IsNullOrWhiteSpace(raw)) return true; switch (raw.Trim().ToLowerInvariant()) { case "html": mode = TgParseMode.Html; return true; case "markdown": mode = TgParseMode.Markdown; return true; case "markdownv2": mode = TgParseMode.MarkdownV2; return true; case "none": mode = TgParseMode.None; return true; default: return false; } } // Env-only expression matcher — exchange is unavailable at endpoint start, // so full ExpressionResolver cannot be used for connect-time resolution. private static readonly Regex EnvExpressionRegex = new(@"\$\{env:([^}]+)\}", RegexOptions.Compiled); /// /// Resolves ${env:NAME} expressions inside a token value at endpoint /// start (when no is available). Any /// literal without ${ is returned unchanged. /// Throws if a referenced variable /// is not set — keeps misconfiguration loud instead of silently sending an /// unresolved literal to Telegram (HTTP 401). /// public static string ResolveTokenExpression(string raw) { if (string.IsNullOrEmpty(raw) || !raw.Contains("${", StringComparison.Ordinal)) return raw; return EnvExpressionRegex.Replace(raw, m => { var name = m.Groups[1].Value; var value = Environment.GetEnvironmentVariable(name); if (string.IsNullOrEmpty(value)) throw new InvalidOperationException( $"Telegram: environment variable '{name}' referenced by token is not set."); return value; }); } } Path: redb-route/redb.Route.Telegram/TelegramHeaders.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Telegram/TelegramHeaders.cs ---- namespace redb.Route.Telegram; /// /// Header names written to IExchange by . /// Use these constants to read Telegram metadata inside route processors. /// public static class TelegramHeaders { // ── Update / common ─────────────────────────────────────────────────────── /// Update ID (long). Unique per bot, monotonically increasing. public const string UpdateId = "telegram.updateId"; /// Update type string: "Message", "EditedMessage", "CallbackQuery", etc. public const string UpdateType = "telegram.updateType"; // ── Message ─────────────────────────────────────────────────────────────── /// Telegram message ID (int) within the chat. public const string MessageId = "telegram.messageId"; /// Message type: "Text", "Photo", "Document", "Sticker", etc. public const string MessageType = "telegram.messageType"; /// Raw text of the message (null for non-text messages). public const string Text = "telegram.text"; /// Chat ID (long). Use this to reply via the producer. public const string ChatId = "telegram.chatId"; /// Chat type: "Private", "Group", "Supergroup", "Channel". public const string ChatType = "telegram.chatType"; // ── Sender ──────────────────────────────────────────────────────────────── /// Sender user ID (long). public const string UserId = "telegram.userId"; /// Sender first name. public const string FirstName = "telegram.firstName"; /// Sender last name (nullable). public const string LastName = "telegram.lastName"; /// Sender @username (nullable, without @). public const string Username = "telegram.username"; /// Sender language code, e.g. "ru", "en". public const string LanguageCode = "telegram.languageCode"; // ── Callback query ──────────────────────────────────────────────────────── /// Callback query ID — pass to bot.AnswerCallbackQuery(...). public const string CallbackQueryId = "telegram.callbackQueryId"; /// Callback data string set on the InlineKeyboardButton. public const string CallbackData = "telegram.callbackData"; // ── Web App (mini app) ──────────────────────────────────────────────────── /// /// Payload sent from a Telegram Mini App via WebApp.sendData(...). /// Present only on messages whose is "WebAppData", /// which Telegram delivers only for web app buttons opened from a reply keyboard /// (KeyboardButton.WithWebApp) — inline web app buttons cannot send data back. /// Also written to the exchange body, since such a message carries no text. /// public const string WebAppData = "telegram.webAppData"; /// Text of the reply-keyboard button that opened the mini app (nullable). public const string WebAppButtonText = "telegram.webAppButtonText"; // ── Producer controls ───────────────────────────────────────────────────── /// /// Reply markup to attach to a sent message. /// Set to an InlineKeyboardMarkup or ReplyKeyboardMarkup instance /// from the Telegram.Bot.Types.ReplyMarkups namespace. /// Used by send / document / photo / edit (inline only) modes. /// public const string ReplyMarkup = "telegram.replyMarkup"; /// /// Message ID to reply to in send / document / photo modes. /// Set to an int (or parseable string). When present, the sent message /// will appear as a reply to the referenced message in the chat. /// Wins over the replyToMessageId option. /// public const string ReplyToMessageId = "telegram.replyToMessageId"; /// /// Per-message override for /// in document/photo modes. /// public const string Caption = "telegram.caption"; /// /// Per-message override for in /// answer mode: show the text as a modal alert instead of a toast. /// Accepts bool or string parseable as bool. /// public const string ShowAlert = "telegram.showAlert"; /// /// Per-message override for . /// Values: "HTML", "Markdown", "MarkdownV2". Case-insensitive. /// public const string ParseMode = "telegram.parseMode"; /// /// Per-message override for . /// Accepts bool or string parseable as bool. /// public const string DisableNotification = "telegram.disableNotification"; /// /// Explicit Telegram file_id for the document/photo/download /// producer modes. /// /// On document/photo it means "send this file already hosted on /// Telegram instead of uploading the exchange body"; on download it names /// the file to fetch. Both readings are the same instruction — the file this /// producer call is about — which is why they share one key. /// /// public const string FileId = "telegram.fileId"; /// File name to use when the exchange body is a or byte[]. public const string FileName = "telegram.fileName"; // ── Inbound attachments (set by the consumer / webhook unpack) ──────────── // // Deliberately NOT reusing FileId above: that one is a *producer* instruction // ("send this already-hosted file"), and headers travel with the exchange. A route // that consumes a voice message and then sends a document would otherwise echo the // user's own file back at them — silently, because both sides read the same key. /// /// Kind of the attachment on an incoming message: voice, audio, /// videoNote, video, animation, document, photo, /// sticker. Absent when the message carries no file. /// /// Present alongside ; the pair is what a route needs to /// decide "this is a voice note" and then fetch it via getFile. /// /// public const string AttachmentKind = "telegram.attachment.kind"; /// /// Telegram file_id of the attachment on an incoming message. Pass it to /// getFile to obtain a download path. /// /// Photos arrive as a size ladder; the largest is reported, because a route that wants /// the picture wants the picture, and downscaling is the caller's choice. /// /// public const string AttachmentFileId = "telegram.attachment.fileId"; /// MIME type reported by Telegram for the attachment, when it sends one (nullable). public const string AttachmentMimeType = "telegram.attachment.mimeType"; /// Attachment size in bytes, when Telegram reports it (long, nullable). public const string AttachmentFileSize = "telegram.attachment.fileSize"; /// /// Duration in seconds for time-based attachments — voice, audio, video, video note /// (int, nullable). Lets a route reject a twenty-minute recording before /// downloading it. /// public const string AttachmentDuration = "telegram.attachment.duration"; /// Original file name of a document or audio attachment, when present (nullable). public const string AttachmentFileName = "telegram.attachment.fileName"; /// /// Caption typed alongside the attachment (nullable). Kept out of the exchange body on /// purpose: the body stays "what the user typed as a message", and silently promoting a /// caption to a body would make a captioned photo look like a text command. /// public const string AttachmentCaption = "telegram.attachment.caption"; // ── Producer results (set on the outgoing exchange after publish) ───────── /// /// Set by the producer after a successful send/document/photo/edit /// to the resulting (int). /// Allows downstream steps to edit or delete the message just produced without /// a separate round-trip. /// public const string SentMessageId = "telegram.sentMessageId"; /// /// Set by the download producer to the server-side path getFile reported /// (voice/file_42.oga). Useful for the extension — Telegram does not send a MIME /// type for every attachment kind, but it always names the file it stored. /// /// Deliberately NOT a URL: the download URL embeds the bot token, and a header travels /// with the exchange into logs, audits and dead letters. /// /// public const string FilePath = "telegram.file.path"; /// /// Set by the download producer to the number of bytes actually downloaded /// (long). Not the same as , which is what the /// update claimed before anything was fetched. /// public const string FileSize = "telegram.file.size"; /// /// Set by the download producer to the file's file_unique_id — stable /// across bots and over time, unlike file_id. The identifier to deduplicate or /// cache by; it cannot be used to download anything, which is exactly why it is safe /// to keep. /// public const string FileUniqueId = "telegram.file.uniqueId"; // ── Internal ────────────────────────────────────────────────────────────── /// Returns true if the key is a redb.Route.Telegram internal header. public static bool IsRedbHeader(string key) => key.StartsWith("telegram.", StringComparison.OrdinalIgnoreCase); } Path: redb-route/redb.Route.Telegram/TelegramProducer.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Telegram/TelegramProducer.cs ---- using System.Diagnostics; using System.Globalization; using Microsoft.Extensions.Logging; using Telegram.Bot; using Telegram.Bot.Exceptions; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.ReplyMarkups; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; using TgMessage = Telegram.Bot.Types.Message; namespace redb.Route.Telegram; /// /// Telegram Bot producer. /// Supported modes: send, document, photo, answer, edit, delete, download. /// /// ChatId is resolved (in priority order): /// 1. Header telegram.chatId on the exchange /// 2. Options.ChatId (from URI or DSL) /// /// The answer and download modes need no chatId: the first is addressed by /// callback query id, the second by file id. /// /// On successful send/document/photo/edit the resulting Message.MessageId /// is written back to the exchange as header ; /// download writes the bytes to Out.Body. /// public sealed class TelegramProducer : ConnectableProducer { private readonly TelegramEndpoint _endpoint; private readonly TelegramEndpointOptions _options; private ITelegramBotClient? _bot; private ITelegramBotClient? _testClient; /// protected override IEndpoint ProducerEndpoint => _endpoint; /// protected override string ProducerName => $"telegram:{_endpoint.Mode}"; /// Creates a Telegram producer. public TelegramProducer(TelegramEndpoint endpoint, TelegramEndpointOptions options) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _options = options ?? throw new ArgumentNullException(nameof(options)); } /// protected override Task ConnectAsync(CancellationToken ct) { // Test seam: a mock ITelegramBotClient injected via UseTestClient bypasses the component. if (_testClient is not null) { _bot = _testClient; return Task.CompletedTask; } // Client is owned and pooled by TelegramComponent (shared per resolved token). // Producer/consumer for the same token get the same instance. if (_endpoint.Component is not TelegramComponent component) throw new InvalidOperationException( "Telegram producer requires TelegramComponent as its owning component."); _bot = component.GetOrCreateClient(_options.Token); Logger?.LogInformation("Telegram producer connected (mode={Mode})", _endpoint.Mode); return Task.CompletedTask; } /// Test seam: inject a mock used instead of the component client. internal void UseTestClient(ITelegramBotClient bot) => _testClient = bot; /// protected override Task DisconnectAsync(CancellationToken ct) { // Ownership of the client (and its HttpClient) stays with TelegramComponent. // Releasing our reference is enough here. _bot = null; return Task.CompletedTask; } /// public override async Task Process(IExchange exchange, CancellationToken ct = default) { EnsureStarted(); // Capture the client locally: DisconnectAsync nulls _bot on Stop(), and a concurrent Process // must not dereference a null field (shutdown race). var bot = _bot ?? throw new InvalidOperationException( $"{ProducerName}: producer client is unavailable (stopped concurrently?)."); using var activity = RouteTelemetryExtensions.StartTransportSpan( (_endpoint.Component as ComponentBase)?.Context, $"telegram.{_endpoint.Mode} publish", ActivityKind.Producer, "messaging.system", "telegram", _endpoint.Uri.NormalizedKey, operation: "publish"); if (activity is { IsAllDataRequested: true }) activity.SetTag("messaging.telegram.mode", _endpoint.Mode); // Per-request timeout linked to the caller ct. Uses the dedicated producer send timeout // (SendTimeoutSeconds) — independent from the long-poll HTTP ceiling on the shared client, so a // large upload over a slow link is not capped at the ~50s long-poll window. using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct); cts.CancelAfter(TimeSpan.FromSeconds(_options.SendTimeoutSeconds)); var reqCt = cts.Token; try { // answer is addressed by callbackQueryId, download by fileId — neither needs a chat. if (_endpoint.Mode == "answer") { await AnswerCallbackQueryAsync(bot, exchange, activity, reqCt).ConfigureAwait(false); } else if (_endpoint.Mode == "download") { await DownloadFileAsync(bot, exchange, activity, reqCt).ConfigureAwait(false); } else { var chatId = ResolveChatId(exchange); switch (_endpoint.Mode) { case "document": await SendDocumentAsync(bot, exchange, chatId, reqCt).ConfigureAwait(false); break; case "photo": await SendPhotoAsync(bot, exchange, chatId, reqCt).ConfigureAwait(false); break; case "edit": await EditMessageAsync(bot, exchange, chatId, reqCt).ConfigureAwait(false); break; case "delete": await DeleteMessageAsync(bot, exchange, chatId, reqCt).ConfigureAwait(false); break; default: // "send" await SendMessageAsync(bot, exchange, chatId, reqCt).ConfigureAwait(false); break; } } // No RecordMessageOut: a routed .To() is counted by ToProcessor and a template send // by the ProducerTemplate - self-recording here doubled both (ownership audit). } catch (ApiRequestException ex) { activity.RecordFailure(ex); LogPublishDiagnostics(ex, exchange); throw; } catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested) { // Only our own token cancelling the send is a stop; the per-request timeout or any other failure marks the span. activity.RecordFailure(ex); throw; } } // ── Rate-limit (429) retry ──────────────────────────────────────────────── /// /// Telegram enforces per-chat/global flood limits and answers with HTTP 429 plus a /// retry_after hint. Bot API contract: wait that long and retry. Failing to wait (and /// letting the route retry immediately) escalates to a temporary token ban, so this is the one /// obligation a Telegram producer must implement. Retries are bounded and honour the request /// cancellation token; retry_after is clamped to [1, 60]s to avoid an unbounded stall. /// private async Task WithRateLimitRetryAsync(Func> action, CancellationToken ct) { const int maxRetries = 3; for (var attempt = 0; ; attempt++) { try { return await action(ct).ConfigureAwait(false); } catch (ApiRequestException ex) when (ex.ErrorCode == 429 && attempt < maxRetries) { var retryAfter = Math.Clamp(ex.Parameters?.RetryAfter ?? 1, 1, 60); Logger?.LogWarning( "Telegram: rate-limited (429) on mode={Mode}; waiting {RetryAfter}s before retry {Attempt}/{Max}.", _endpoint.Mode, retryAfter, attempt + 1, maxRetries); await Task.Delay(TimeSpan.FromSeconds(retryAfter), ct).ConfigureAwait(false); } } } private Task WithRateLimitRetryAsync(Func action, CancellationToken ct) => WithRateLimitRetryAsync(async c => { await action(c).ConfigureAwait(false); return null; }, ct); // ── Send modes ──────────────────────────────────────────────────────────── private async Task SendMessageAsync( ITelegramBotClient bot, IExchange exchange, ChatId chatId, CancellationToken ct) { var text = ResolveText(exchange); var parseMode = ResolveParseMode(exchange); var markup = ResolveReplyMarkup(exchange); var replyToId = ResolveReplyToMessageId(exchange); var disableNotification = ResolveDisableNotification(exchange); var replyParams = replyToId.HasValue ? new ReplyParameters { MessageId = replyToId.Value } : null; var result = await WithRateLimitRetryAsync(c => bot.SendMessage( chatId, text, parseMode: parseMode, replyMarkup: markup, replyParameters: replyParams, disableNotification: disableNotification, cancellationToken: c ), ct).ConfigureAwait(false); SetSentMessageId(exchange, result); Logger?.LogDebug("Telegram: sent message {MessageId}", result.MessageId); } private async Task SendDocumentAsync( ITelegramBotClient bot, IExchange exchange, ChatId chatId, CancellationToken ct) { var inputFile = ResolveInputFile(exchange); var caption = ResolveCaption(exchange); var parseMode = ResolveParseMode(exchange); var disableNotification = ResolveDisableNotification(exchange); var replyToId = ResolveReplyToMessageId(exchange); var replyParams = replyToId.HasValue ? new ReplyParameters { MessageId = replyToId.Value } : null; var result = await WithRateLimitRetryAsync(c => bot.SendDocument( chatId, inputFile, caption: caption, parseMode: parseMode, replyParameters: replyParams, replyMarkup: ResolveReplyMarkup(exchange), disableNotification: disableNotification, cancellationToken: c ), ct).ConfigureAwait(false); SetSentMessageId(exchange, result); Logger?.LogDebug("Telegram: sent document {MessageId}", result.MessageId); } private async Task SendPhotoAsync( ITelegramBotClient bot, IExchange exchange, ChatId chatId, CancellationToken ct) { var inputFile = ResolveInputFile(exchange); var caption = ResolveCaption(exchange); var parseMode = ResolveParseMode(exchange); var disableNotification = ResolveDisableNotification(exchange); var replyToId = ResolveReplyToMessageId(exchange); var replyParams = replyToId.HasValue ? new ReplyParameters { MessageId = replyToId.Value } : null; var result = await WithRateLimitRetryAsync(c => bot.SendPhoto( chatId, inputFile, caption: caption, parseMode: parseMode, replyParameters: replyParams, replyMarkup: ResolveReplyMarkup(exchange), disableNotification: disableNotification, cancellationToken: c ), ct).ConfigureAwait(false); SetSentMessageId(exchange, result); Logger?.LogDebug("Telegram: sent photo {MessageId}", result.MessageId); } private async Task AnswerCallbackQueryAsync( ITelegramBotClient bot, IExchange exchange, Activity? activity, CancellationToken ct) { if (!exchange.In.Headers.TryGetValue(TelegramHeaders.CallbackQueryId, out var v) || v is null) throw new InvalidOperationException( "Telegram answer: header 'telegram.callbackQueryId' is required. " + "Use Tg.Answer(token) after receiving a CallbackQuery update."); var callbackQueryId = v.ToString()!; // Optional notification text. Coerce non-string bodies rather than silently dropping them. var text = exchange.In.Body switch { null => null, string s => s, var other => BodyText.Of(other) }; activity?.SetTag("messaging.destination.name", callbackQueryId); activity?.SetTag("messaging.telegram.callback_query.id", callbackQueryId); await WithRateLimitRetryAsync( c => bot.AnswerCallbackQuery(callbackQueryId, text, showAlert: ResolveShowAlert(exchange), cancellationToken: c), ct) .ConfigureAwait(false); Logger?.LogDebug("Telegram: answered callback query {CallbackQueryId}", callbackQueryId); } /// /// The Telegram Bot API method editMessageText does not accept a /// disable_notification parameter — editing an existing message never /// triggers a notification. The DisableNotification option and the /// telegram.disableNotification header are intentionally ignored here. /// private async Task EditMessageAsync( ITelegramBotClient bot, IExchange exchange, ChatId chatId, CancellationToken ct) { var messageId = ResolveMessageId(exchange); var text = ResolveText(exchange); var parseMode = ResolveParseMode(exchange); // EditMessageText only accepts InlineKeyboardMarkup, not ReplyKeyboard. InlineKeyboardMarkup? markup = null; if (exchange.In.Headers.TryGetValue(TelegramHeaders.ReplyMarkup, out var v) && v is not null) { markup = v as InlineKeyboardMarkup ?? throw new InvalidOperationException( $"Telegram edit: header '{TelegramHeaders.ReplyMarkup}' must be an " + $"InlineKeyboardMarkup, but was '{v.GetType().Name}'."); } var result = await WithRateLimitRetryAsync(c => bot.EditMessageText( chatId, messageId, text, parseMode: parseMode, replyMarkup: markup, cancellationToken: c), ct) .ConfigureAwait(false); SetSentMessageId(exchange, result); Logger?.LogDebug("Telegram: edited message {MessageId}", messageId); } private async Task DeleteMessageAsync( ITelegramBotClient bot, IExchange exchange, ChatId chatId, CancellationToken ct) { var messageId = ResolveMessageId(exchange); await WithRateLimitRetryAsync( c => bot.DeleteMessage(chatId, messageId, cancellationToken: c), ct) .ConfigureAwait(false); Logger?.LogDebug("Telegram: deleted message {MessageId}", messageId); } // ── Download ────────────────────────────────────────────────────────────── /// /// Fetches a file the user sent and writes the bytes to Out.Body. /// /// Two calls, because the Bot API is two calls: getFile resolves a /// file_id to a server-side path valid for at least an hour, and the transfer /// itself is an ordinary download from that path. Neither is something a route should /// have to spell out — the consumer already reports telegram.attachment.fileId, /// and everything between that header and the bytes is transport. /// /// The download URL embeds the bot token, which is why it is built inside the /// client and never surfaces on the exchange: /// carries the path alone. /// private async Task DownloadFileAsync( ITelegramBotClient bot, IExchange exchange, Activity? activity, CancellationToken ct) { var fileId = ResolveDownloadFileId(exchange); var file = await WithRateLimitRetryAsync(c => bot.GetFile(fileId, c), ct).ConfigureAwait(false); if (string.IsNullOrEmpty(file.FilePath)) throw new InvalidOperationException( "Telegram download: getFile returned no file_path. The file is either expired or " + "too large for a bot to download (Bot API caps bot downloads at 20 MB)."); activity?.SetTag("messaging.destination.name", file.FilePath); activity?.SetTag("messaging.telegram.file.unique_id", file.FileUniqueId); // Cheap refusal first: when Telegram states the size up front there is no reason to // start a transfer that is going to be rejected at the end of it. var ceiling = _options.MaxDownloadBytes; if (ceiling > 0 && file.FileSize is { } declared && declared > ceiling) throw new InvalidOperationException( $"Telegram download: file is {declared} bytes, over the {ceiling}-byte ceiling " + $"(maxDownloadBytes). Reject oversized attachments before the download, or raise the option."); using var buffer = new CappedMemoryStream(ceiling); await WithRateLimitRetryAsync(async c => { // A 429 retry re-downloads from the start, so the buffer has to start from the // start too — otherwise the second attempt appends to the first one's bytes and // the route gets a file that is longer than any file Telegram holds. buffer.SetLength(0); await bot.DownloadFile(file.FilePath, buffer, c).ConfigureAwait(false); }, ct).ConfigureAwait(false); var bytes = buffer.ToArray(); exchange.Out ??= exchange.In.Clone(); exchange.Out.Body = bytes; exchange.Out.Headers[TelegramHeaders.FilePath] = file.FilePath; exchange.Out.Headers[TelegramHeaders.FileSize] = (long)bytes.Length; exchange.Out.Headers[TelegramHeaders.FileUniqueId] = file.FileUniqueId; activity?.SetTag("messaging.telegram.file.size", bytes.Length); Logger?.LogDebug( "Telegram: downloaded {Bytes} bytes from {FilePath}", bytes.Length, file.FilePath); } /// /// Which file download fetches, in priority order: the explicit producer /// instruction, then the option expression, then the attachment the consumer reported, /// then a bare string body. /// /// The attachment header is third and not first on purpose — it is the default, not the /// override, and a route that says which file it wants must be obeyed. It is present at /// all so that the common case ("download what the user just sent") needs no configuration. /// /// private string ResolveDownloadFileId(IExchange exchange) { if (exchange.In.Headers.TryGetValue(TelegramHeaders.FileId, out var explicitId) && explicitId is string id && !string.IsNullOrWhiteSpace(id)) return id; if (!string.IsNullOrWhiteSpace(_options.FileId)) { // An empty resolution means the referenced header is absent on this update — // fall through to the attachment rather than fail the exchange, the same way // ReplyToMessageId treats an unresolved expression. var resolved = _options.ResolveOption(_options.FileId, exchange); if (!string.IsNullOrWhiteSpace(resolved)) return resolved; } if (exchange.In.Headers.TryGetValue(TelegramHeaders.AttachmentFileId, out var attachment) && attachment is string attachmentId && !string.IsNullOrWhiteSpace(attachmentId)) return attachmentId; if (exchange.In.Body is string body && !string.IsNullOrWhiteSpace(body)) return body; throw new InvalidOperationException( $"Telegram download: no file id. Set header '{TelegramHeaders.FileId}', use " + $".FileId(...) in the fluent builder, or route an update that carries " + $"'{TelegramHeaders.AttachmentFileId}'."); } /// /// Buffer that refuses to grow past a ceiling. /// /// A downloaded file becomes an array in this process's memory, and file_size is /// optional in the Bot API — so the pre-flight check above can be skipped by an update /// that simply omits it. Trusting it alone would leave "how much memory does one message /// cost" to the sender. /// /// private sealed class CappedMemoryStream(long limit) : MemoryStream { /// public override void Write(byte[] buffer, int offset, int count) { Guard(count); base.Write(buffer, offset, count); } /// public override void Write(ReadOnlySpan buffer) { Guard(buffer.Length); base.Write(buffer); } /// public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { Guard(count); return base.WriteAsync(buffer, offset, count, cancellationToken); } /// public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) { Guard(buffer.Length); return base.WriteAsync(buffer, cancellationToken); } /// public override void WriteByte(byte value) { Guard(1); base.WriteByte(value); } private void Guard(int incoming) { if (limit > 0 && Length + incoming > limit) throw new InvalidOperationException( $"Telegram download: the transfer passed the {limit}-byte ceiling (maxDownloadBytes) " + "and was stopped. Telegram did not declare the size up front."); } } // ── Resolution helpers ──────────────────────────────────────────────────── private ChatId ResolveChatId(IExchange exchange) { // 1. Header set by consumer or upstream processor if (exchange.In.Headers.TryGetValue(TelegramHeaders.ChatId, out var headerValue) && headerValue is not null) { switch (headerValue) { case long l: return new ChatId(l); case int i: return new ChatId(i); case string s when long.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsed): return new ChatId(parsed); case string s: return new ChatId(s); // @channelusername } try { return new ChatId(Convert.ToInt64(headerValue, CultureInfo.InvariantCulture)); } catch (Exception ex) when (ex is FormatException or InvalidCastException or OverflowException) { throw new InvalidOperationException( $"Telegram producer: header '{TelegramHeaders.ChatId}' value '{headerValue}' " + "is not a valid chat id (expected long or '@channelusername').", ex); } } // 2. Options (from URI or DSL builder) if (!string.IsNullOrWhiteSpace(_options.ChatId)) { var resolved = _options.ResolveOption(_options.ChatId, exchange); if (string.IsNullOrWhiteSpace(resolved)) throw new InvalidOperationException( "Telegram producer: chatId expression resolved to an empty value. " + "Check that the header or environment variable referenced in ChatId is set."); if (long.TryParse(resolved, NumberStyles.Integer, CultureInfo.InvariantCulture, out var id)) return new ChatId(id); return new ChatId(resolved); // @channelusername } throw new InvalidOperationException( "Telegram producer: no chatId. Set header 'telegram.chatId' or use " + ".ChatId(...) in the fluent builder."); } private string ResolveText(IExchange exchange) { var body = exchange.In.Body; var text = body switch { string s => s, byte[] b => System.Text.Encoding.UTF8.GetString(b), null => null, _ => BodyText.Of(body) }; if (string.IsNullOrEmpty(text)) throw new InvalidOperationException( $"Telegram {_endpoint.Mode}: exchange.In.Body must contain non-empty text " + "(string or UTF-8 byte[]). Telegram rejects empty message text with HTTP 400."); return text; } private ParseMode ResolveParseMode(IExchange exchange) { // Header takes precedence over options for per-message overrides. string? raw = null; if (exchange.In.Headers.TryGetValue(TelegramHeaders.ParseMode, out var h) && h is not null) raw = h.ToString(); if (string.IsNullOrWhiteSpace(raw)) raw = _options.ParseMode; // Fail loud on a typo (e.g. "Markdwn") instead of silently downgrading to plain text and // shipping raw *bold* / markup to the user. if (!TelegramEndpointOptions.TryParseParseMode(raw, out var mode)) throw new InvalidOperationException( $"Telegram {_endpoint.Mode}: invalid parseMode '{raw}'. Expected HTML, Markdown, MarkdownV2 or empty."); return mode; } private bool ResolveDisableNotification(IExchange exchange) { if (exchange.In.Headers.TryGetValue(TelegramHeaders.DisableNotification, out var v) && v is not null) { return v switch { bool b => b, string s when bool.TryParse(s, out var parsed) => parsed, _ => _options.DisableNotification }; } return _options.DisableNotification; } private string? ResolveCaption(IExchange exchange) { // Header takes precedence over options for per-message overrides. if (exchange.In.Headers.TryGetValue(TelegramHeaders.Caption, out var h) && h is string s) return s; if (!string.IsNullOrWhiteSpace(_options.Caption)) return _options.ResolveOption(_options.Caption, exchange); return null; } private bool ResolveShowAlert(IExchange exchange) { if (exchange.In.Headers.TryGetValue(TelegramHeaders.ShowAlert, out var v) && v is not null) { return v switch { bool b => b, string s when bool.TryParse(s, out var parsed) => parsed, _ => _options.ShowAlert }; } return _options.ShowAlert; } private InputFile ResolveInputFile(IExchange exchange) { // 1. Explicit file_id header — reuse a file already hosted on Telegram. if (exchange.In.Headers.TryGetValue(TelegramHeaders.FileId, out var fileIdHeader) && fileIdHeader is string fileId && !string.IsNullOrWhiteSpace(fileId)) { return InputFile.FromFileId(fileId); } var body = exchange.In.Body; var fileName = ResolveFileName(exchange); switch (body) { case Stream s: return InputFile.FromStream(s, fileName ?? "file"); case byte[] bytes: return InputFile.FromStream(new MemoryStream(bytes), fileName ?? "file"); // URL string is checked before the file_id opt-in because URLs are always // preferred when they parse as absolute http(s). case string s when Uri.TryCreate(s, UriKind.Absolute, out var uri) && (uri.Scheme == "http" || uri.Scheme == "https"): return InputFile.FromUri(uri); // Explicit URI opt-in: bodyIsFileId=true treats the string body as a file_id. case string s when _options.BodyIsFileId: return InputFile.FromFileId(s); case string: throw new InvalidOperationException( $"Telegram {_endpoint.Mode}: string body is not a valid input. " + "Provide a Stream, byte[], or HTTP(S) URL. " + $"To reuse an existing Telegram file, set header '{TelegramHeaders.FileId}' " + "or add 'bodyIsFileId=true' to the URI."); default: throw new InvalidOperationException( $"Telegram {_endpoint.Mode}: unsupported body type '{body?.GetType().Name ?? "null"}'. " + "Expected Stream, byte[], HTTP(S) URL string, or 'telegram.fileId' header."); } } private string? ResolveFileName(IExchange exchange) { if (!string.IsNullOrWhiteSpace(_options.FileName)) return _options.ResolveOption(_options.FileName, exchange); if (exchange.In.Headers.TryGetValue(TelegramHeaders.FileName, out var h) && h is string s) return s; return null; } private static ReplyMarkup? ResolveReplyMarkup(IExchange exchange) { if (!exchange.In.Headers.TryGetValue(TelegramHeaders.ReplyMarkup, out var v) || v is null) return null; if (v is ReplyMarkup markup) return markup; throw new InvalidOperationException( $"Telegram: header '{TelegramHeaders.ReplyMarkup}' must be a Telegram.Bot ReplyMarkup " + $"(InlineKeyboardMarkup / ReplyKeyboardMarkup / ...), but was '{v.GetType().Name}'."); } private int? ResolveReplyToMessageId(IExchange exchange) { // Explicit header always wins (per-message override, same as chatId). if (exchange.In.Headers.TryGetValue(TelegramHeaders.ReplyToMessageId, out var v) && v is not null) return ToMessageId(v); if (!string.IsNullOrWhiteSpace(_options.ReplyToMessageId)) { var resolved = _options.ResolveOption(_options.ReplyToMessageId, exchange); // Empty resolution: the referenced header is absent on this update type // (e.g. .ReplyToIncoming() on an update without telegram.messageId) — // send unthreaded rather than fail the exchange. if (string.IsNullOrWhiteSpace(resolved)) return null; if (int.TryParse(resolved, NumberStyles.Integer, CultureInfo.InvariantCulture, out var id)) return id; throw new InvalidOperationException( $"Telegram {_endpoint.Mode}: replyToMessageId resolved to '{resolved}', " + "which is not a valid message id."); } return null; } private static int? ToMessageId(object v) => v switch { int i => i, long l => (int)l, string s when int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out var id) => id, _ => null }; private int ResolveMessageId(IExchange exchange) { // Explicit header always wins (per-message override, same as chatId). if (exchange.In.Headers.TryGetValue(TelegramHeaders.MessageId, out var v) && v is not null) return ToMessageId(v) ?? throw new InvalidOperationException( $"Telegram producer: cannot convert 'telegram.messageId' value '{v}' to int."); if (!string.IsNullOrWhiteSpace(_options.MessageId)) { var resolved = _options.ResolveOption(_options.MessageId, exchange); if (int.TryParse(resolved, NumberStyles.Integer, CultureInfo.InvariantCulture, out var id)) return id; throw new InvalidOperationException( $"Telegram {_endpoint.Mode}: messageId resolved to '{resolved}', " + "which is not a valid message id."); } throw new InvalidOperationException( "Telegram producer: no message id for edit/delete. Set header 'telegram.messageId' " + "or use .MessageId(...) in the fluent builder."); } private static void SetSentMessageId(IExchange exchange, TgMessage? result) { if (result is null) return; exchange.In.Headers[TelegramHeaders.SentMessageId] = result.MessageId; } private void LogPublishDiagnostics(ApiRequestException ex, IExchange exchange) { var body = exchange.In.Body; var bodySize = body switch { string s => s.Length, byte[] b => b.Length, Stream s when s.CanSeek => (int)Math.Min(int.MaxValue, s.Length), _ => -1 }; Logger?.LogError(ex, "Telegram publish failed: mode={Mode} parseMode={ParseMode} " + "bodySize={BodySize} errorCode={ErrorCode} retryAfter={RetryAfter}", _endpoint.Mode, _options.ParseMode ?? "None", bodySize, ex.ErrorCode, ex.Parameters?.RetryAfter); } } Path: redb-route/redb.Route.Telegram/TelegramUpdateMapper.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Telegram/TelegramUpdateMapper.cs ---- using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using redb.Route.Abstractions; using TgMessage = Telegram.Bot.Types.Message; namespace redb.Route.Telegram; /// /// Maps Telegram / objects to /// headers using the canonical constants. /// /// Shared between (long-polling) and /// (webhook) so both paths /// produce identical header semantics. /// /// public static class TelegramUpdateMapper { /// /// Populates body and headers from a Telegram message update. /// Call this when the update carries a payload. /// /// Telegram message. /// Update type (e.g. or EditedMessage). /// Route message to populate. public static void MapMessage(TgMessage msg, UpdateType updateType, IMessage message) { message.Body = msg.Text ?? string.Empty; message.Headers[TelegramHeaders.UpdateType] = updateType.ToString(); message.Headers[TelegramHeaders.MessageType] = msg.Type.ToString(); message.Headers[TelegramHeaders.MessageId] = msg.MessageId; AddIfNotNull(message.Headers, TelegramHeaders.Text, msg.Text); // Mini app payload (WebApp.sendData). Such a message has no Text, so the // data doubles as the exchange body — matching the "body = what the user sent" // contract of text messages and callback queries. if (msg.WebAppData is { } webApp) { message.Body = webApp.Data; message.Headers[TelegramHeaders.WebAppData] = webApp.Data; AddIfNotNull(message.Headers, TelegramHeaders.WebAppButtonText, webApp.ButtonText); } MapAttachment(msg, message); message.Headers[TelegramHeaders.ChatId] = msg.Chat.Id; message.Headers[TelegramHeaders.ChatType] = msg.Chat.Type.ToString(); if (msg.From is { } from) { message.Headers[TelegramHeaders.UserId] = from.Id; message.Headers[TelegramHeaders.FirstName] = from.FirstName; AddIfNotNull(message.Headers, TelegramHeaders.LastName, from.LastName); AddIfNotNull(message.Headers, TelegramHeaders.Username, from.Username); AddIfNotNull(message.Headers, TelegramHeaders.LanguageCode, from.LanguageCode); } } /// /// Populates body and headers from a generic . /// Returns when the update type is handled; /// for unrecognised / unsupported types (caller should skip the exchange). /// /// Telegram update. /// Route message to populate. /// if the update was mapped; to skip. public static bool MapUpdate(Update update, IMessage message) { message.Headers[TelegramHeaders.UpdateId] = update.Id; message.Headers[TelegramHeaders.UpdateType] = update.Type.ToString(); switch (update.Type) { // ── Message-bearing updates — delegate to MapMessage ────────────── case UpdateType.Message when update.Message is { } m: MapMessage(m, UpdateType.Message, message); return true; case UpdateType.EditedMessage when update.EditedMessage is { } m: MapMessage(m, UpdateType.EditedMessage, message); return true; case UpdateType.ChannelPost when update.ChannelPost is { } m: MapMessage(m, UpdateType.ChannelPost, message); return true; case UpdateType.EditedChannelPost when update.EditedChannelPost is { } m: MapMessage(m, UpdateType.EditedChannelPost, message); return true; // ── CallbackQuery ───────────────────────────────────────────────── case UpdateType.CallbackQuery when update.CallbackQuery is { } cb: message.Body = cb.Data ?? string.Empty; message.Headers[TelegramHeaders.CallbackQueryId] = cb.Id; message.Headers[TelegramHeaders.UserId] = cb.From.Id; message.Headers[TelegramHeaders.FirstName] = cb.From.FirstName; AddIfNotNull(message.Headers, TelegramHeaders.CallbackData, cb.Data); AddIfNotNull(message.Headers, TelegramHeaders.ChatId, cb.Message?.Chat.Id); AddIfNotNull(message.Headers, TelegramHeaders.Username, cb.From.Username); return true; default: return false; } } // ── Internal helpers ────────────────────────────────────────────────────── /// /// Exposes the attachment of an incoming message as headers: kind, file_id and /// whatever metadata Telegram sent with it. /// /// Without this a file-bearing update is unreachable: the body carries /// , which a voice note does not have, so a route could see /// that a recording arrived () but had no /// way to fetch it. The body is deliberately left alone — a caption stays a header, so a /// captioned photo is not mistaken for a typed command. /// /// private static void MapAttachment(TgMessage msg, IMessage message) { // Photo is a size ladder rather than a single file; the last entry is the largest. var photo = msg.Photo is { Length: > 0 } sizes ? sizes[^1] : null; var (kind, file) = msg switch { { Voice: { } voice } => ("voice", (FileBase)voice), { Audio: { } audio } => ("audio", audio), { VideoNote: { } note } => ("videoNote", note), { Video: { } video } => ("video", video), { Animation: { } animation } => ("animation", animation), { Document: { } document } => ("document", document), { Sticker: { } sticker } => ("sticker", sticker), _ when photo is not null => ("photo", photo), _ => (null, null), }; if (kind is null || file is null) return; message.Headers[TelegramHeaders.AttachmentKind] = kind; message.Headers[TelegramHeaders.AttachmentFileId] = file.FileId; AddIfNotNull(message.Headers, TelegramHeaders.AttachmentFileSize, file.FileSize); AddIfNotNull(message.Headers, TelegramHeaders.AttachmentCaption, msg.Caption); AddIfNotNull(message.Headers, TelegramHeaders.AttachmentMimeType, msg switch { { Voice: { } voice } => voice.MimeType, { Audio: { } audio } => audio.MimeType, { Video: { } video } => video.MimeType, { Animation: { } animation } => animation.MimeType, { Document: { } document } => document.MimeType, _ => null, }); AddIfNotNull(message.Headers, TelegramHeaders.AttachmentDuration, msg switch { { Voice: { } voice } => voice.Duration, { Audio: { } audio } => audio.Duration, { Video: { } video } => video.Duration, { Animation: { } animation } => animation.Duration, { VideoNote: { } note } => note.Duration, _ => (int?)null, }); AddIfNotNull(message.Headers, TelegramHeaders.AttachmentFileName, msg switch { { Audio: { } audio } => audio.FileName, { Video: { } video } => video.FileName, { Document: { } document } => document.FileName, _ => null, }); } private static void AddIfNotNull(IDictionary headers, string key, object? value) { if (value is not null) headers[key] = value; } } Path: redb-route/redb.Route.Telegram/TelegramUpdateSerializer.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Telegram/TelegramUpdateSerializer.cs ---- using System.Text.Json; using Telegram.Bot; using Telegram.Bot.Types; using redb.Route.Abstractions; namespace redb.Route.Telegram; /// /// Deserializes a Telegram from a raw JSON byte array received /// via webhook (HTTP POST from Telegram servers). /// /// Uses — the same /// that Telegram.Bot uses internally, ensuring correct handling of polymorphic /// fields (e.g. MaybeInaccessibleMessage). /// /// /// Serialization () is intentionally not supported: /// the Telegram Bot API is inbound-only in the webhook path. /// /// public sealed class TelegramUpdateSerializer : IMessageSerializer { /// public string ContentType => "application/json"; /// public byte[] Serialize(T value) => throw new NotSupportedException( $"{nameof(TelegramUpdateSerializer)} is receive-only. " + "Use Telegram.Bot client methods to send messages."); /// public T? Deserialize(byte[] data) { if (typeof(T) != typeof(Update)) throw new NotSupportedException( $"{nameof(TelegramUpdateSerializer)} only deserializes {nameof(Update)}. " + $"Requested type: {typeof(T).Name}"); return (T?)(object?)DeserializeUpdate(data); } /// public object? Deserialize(byte[] data, Type type) { if (type != typeof(Update)) throw new NotSupportedException( $"{nameof(TelegramUpdateSerializer)} only deserializes {nameof(Update)}. " + $"Requested type: {type.Name}"); return DeserializeUpdate(data); } // ── Internal ────────────────────────────────────────────────────────────── private static Update DeserializeUpdate(byte[] data) { var update = JsonSerializer.Deserialize(data, JsonBotAPI.Options); return update ?? throw new InvalidOperationException( "Telegram webhook: failed to deserialize Update — JSON body was null or empty."); } } Path: redb-route/redb.Route.Telegram/TelegramUpdateUnpackProcessor.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Telegram/TelegramUpdateUnpackProcessor.cs ---- using Telegram.Bot.Types; using redb.Route.Abstractions; namespace redb.Route.Telegram; /// /// Inline processor that unpacks a Telegram from the exchange body /// and populates on the inbound message. /// /// Use this after Unmarshal(TelegramUpdateSerializer, typeof(Update)) in a webhook route: /// /// From(Http.Listen("/tg/webhook")) /// .Unmarshal(new TelegramUpdateSerializer(), typeof(Update)) /// .Process(new TelegramUpdateUnpackProcessor()) /// .To("direct://tg-dispatch"); /// /// Or use the convenience extension: .UnpackTelegramUpdate(). /// /// /// After this processor runs the exchange has the same headers as a long-polling /// exchange, ensuring uniform downstream processing. /// /// public sealed class TelegramUpdateUnpackProcessor : IProcessor { /// public Task Process(IExchange exchange, CancellationToken ct = default) { if (exchange.In.Body is not Update update) throw new InvalidOperationException( $"TelegramUpdateUnpackProcessor expects an {nameof(Update)} in the exchange body, " + $"but found: {exchange.In.Body?.GetType().Name ?? "null"}. " + $"Ensure Unmarshal(new TelegramUpdateSerializer(), typeof(Update)) runs before this processor."); if (!TelegramUpdateMapper.MapUpdate(update, exchange.In)) throw new InvalidOperationException( $"TelegramUpdateUnpackProcessor: unsupported update type '{update.Type}'. " + "Add explicit handling or filter the route before this processor."); return Task.CompletedTask; } } Path: redb-route/redb.Route.Telegram/redb.Route.Telegram.csproj Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Telegram/redb.Route.Telegram.csproj ---- redb.Route.Telegram Telegram Bot transport for redb.Route ESB framework. Long-polling consumer + webhook unpack, and message/document/photo/edit/delete/answer/download producer with 429 rate-limit handling, parseMode, inline keyboards, attachment download and fluent DSL. Built on Telegram.Bot. esb;messaging;telegram;bot;chatops;redb README.md