redb.Route.Telegram
4.8.0
Prefix Reserved
dotnet add package redb.Route.Telegram --version 4.8.0
NuGet\Install-Package redb.Route.Telegram -Version 4.8.0
<PackageReference Include="redb.Route.Telegram" Version="4.8.0" />
<PackageVersion Include="redb.Route.Telegram" Version="4.8.0" />
<PackageReference Include="redb.Route.Telegram" />
paket add redb.Route.Telegram --version 4.8.0
#r "nuget: redb.Route.Telegram, 4.8.0"
#:package redb.Route.Telegram@4.8.0
#addin nuget:?package=redb.Route.Telegram&version=4.8.0
#tool nuget:?package=redb.Route.Telegram&version=4.8.0
redb.Route.Telegram
Telegram Bot transport for redb.Route.
Long-polling consumer, message / document / photo producer, webhook support, fluent DSL.
Installation
dotnet add package redb.Route.Telegram
Register in DI:
builder.Services.AddRedbRoute(route =>
{
route.Services.AddRedbRouteTelegram();
route.AddRouteBuilder<MyBotRoutes>();
});
Quick start — echo bot (long polling)
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. tokenis 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 readsIConfiguration, then context properties, then the OS environment when the context has noIConfiguration. 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).
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:
From(Tg.Receive(token))
.Threads(4) // 4 concurrent processing workers, one receiver
.Process(...);
See 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[].
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:
Streamorbyte[]— uploaded as a new file (usefileNamefor a sensible name).- HTTP(S) URL
string— passed to Telegram to fetch by URL. - To reuse an existing Telegram file, set header
telegram.fileIdor addbodyIsFileId=trueto the URI (then a string body is treated as afile_id). A plain string body without either of these is rejected with a clear error — the transport does not guess.
Fluent DSL
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:
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:
.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.
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<string>(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.
.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.
.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.
// 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)
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:
From(Tg.Receive(token))
.Choice()
.When(Header(TelegramHeaders.UpdateType).isEqualTo("CallbackQuery"))
.Process(async (e, ct) =>
{
var data = e.In.GetHeader<string>(TelegramHeaders.CallbackData);
// respond with AnswerCallbackQuery via injected ITelegramBotClient
})
...
.EndChoice();
Reply keyboard (keyboard shown below text input)
.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:
// 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:
From(Tg.Receive(token))
.Filter(Header(TelegramHeaders.MessageType).isEqualTo("WebAppData"))
.Process((e, ct) =>
{
var payload = e.In.GetHeader<string>(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
.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:
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) |
| 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.
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
Consumerspan 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
Producerspan per send,telegram.{mode} publish; an error when the send fails, the per-request timeout included, unless our own token cancelled it. RouteEngineOptions.EnableTelemetry = falseopens 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:
From(Tg.Receive(token))
.SpanTag("messaging.telegram.chat.id", Header(TelegramHeaders.ChatId), SpanTarget.Inbound)
...
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. net11.0 is compatible. |
-
net10.0
- JsonPath.Net (>= 2.2.0)
- JsonSchema.Net (>= 7.3.4)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 10.0.15)
- Microsoft.Extensions.Diagnostics.HealthChecks (>= 10.0.15)
- Microsoft.Extensions.Hosting.Abstractions (>= 10.0.15)
- Microsoft.Extensions.Logging.Abstractions (>= 10.0.15)
- Microsoft.Extensions.Options (>= 10.0.15)
- redb.Route (>= 4.8.0)
- Telegram.Bot (>= 22.10.3.3)
-
net11.0
- JsonPath.Net (>= 2.2.0)
- JsonSchema.Net (>= 7.3.4)
- Microsoft.Extensions.Diagnostics.HealthChecks (>= 10.0.15)
- redb.Route (>= 4.8.0)
- Telegram.Bot (>= 22.10.3.3)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 4.8.0 | 49 | 12/1/2026 |
| 4.7.8 | 98 | 11/30/2026 |
| 4.7.7 | 97 | 11/28/2026 |
| 4.7.6 | 101 | 11/26/2026 |
| 4.7.5 | 99 | 11/24/2026 |
| 4.7.2 | 134 | 11/13/2026 |
| 4.7.1 | 107 | 11/11/2026 |
| 4.7.0 | 112 | 11/7/2026 |
| 4.6.2 | 116 | 11/5/2026 |
| 4.6.1 | 157 | 11/4/2026 |
| 4.6.0 | 146 | 11/3/2026 |
| 4.5.1 | 219 | 10/30/2026 |
| 4.5.0 | 113 | 10/29/2026 |
| 4.4.2 | 111 | 10/23/2026 |
| 4.4.1 | 116 | 10/21/2026 |
| 4.3.0 | 116 | 10/14/2026 |
| 4.2.3 | 116 | 10/8/2026 |
| 4.2.2 | 120 | 10/5/2026 |
| 4.2.0 | 121 | 9/30/2026 |