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; }); } }