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