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