TBotPlatform 2.4.3-beta1
dotnet add package TBotPlatform --version 2.4.3-beta1
NuGet\Install-Package TBotPlatform -Version 2.4.3-beta1
<PackageReference Include="TBotPlatform" Version="2.4.3-beta1" />
<PackageVersion Include="TBotPlatform" Version="2.4.3-beta1" />
<PackageReference Include="TBotPlatform" />
paket add TBotPlatform --version 2.4.3-beta1
#r "nuget: TBotPlatform, 2.4.3-beta1"
#:package TBotPlatform@2.4.3-beta1
#addin nuget:?package=TBotPlatform&version=2.4.3-beta1&prerelease
#tool nuget:?package=TBotPlatform&version=2.4.3-beta1&prerelease
TBotPlatform
A C# library that makes it easy to build Telegram bots.
TBotPlatform is built on top of Telegram.Bot and gives you additional control over your bot: a state machine, update routing, retries, rate limiting, logging, delayed-message queues, caching and distributed locks — capabilities that are hard or impossible to achieve with the raw Bot API.
Highlights
- State machine — model your bot flow as states activated via attributes (
[StateActivator],[StateInlineActivator],[AdminStateActivator], ...). - Multi-bot — run several bots in a single host using keyed services.
- Resilient HTTP pipeline — Polly retries (including
Retry-Afterhandling) plus request rate limiting; retries are not amplified on429and permanent4xxerrors are not retried. - SOCKS5 proxy — route all Telegram API traffic through a SOCKS5 proxy (RFC 1928) per bot, with optional username/password authentication, without affecting retries, rate limiting or caching.
- Caching — FusionCache with Redis or in-memory backends, fail-safe enabled, all extensions accept a
CancellationToken. - Delayed messages — schedule messages via a background queue.
- Distributed locks — built on FusionCache.
- Result pattern — typed, error-aware results instead of throwing exceptions everywhere.
- Logging — every Telegram call is traced with an operation id, request count and total elapsed time.
- Media, inline mode and payments — albums (
SendMediaGroup), in-place media and keyboard updates (EditMessageMedia,EditMessageReplyMarkup) instead of delete-and-resend, inline query answers and invoices. - Telegram helpers — HTML escaping and entity-aware conversion for
ParseMode.Html, chat member checks and WebAppinitDatavalidation.
Supported Platforms
Multi-targets .NET 8, .NET 9 and .NET 10.
Quick Start
Install the package:
dotnet add package TBotPlatformDefine a user, states and a menu, then wire everything up:
builder.Services .AddBotPlatform() .AddBot(new TBotSetting { BotName = "echo", Token = token }) .AddTelegramContext() .AddStates(Assembly.GetExecutingAssembly()) .AddReceivingHandler<EchoReceivingHandler>() .Build() .AddCache() .AddMemoryFusionCache() .Build() .AddFactories(Assembly.GetExecutingAssembly()) .AddHostedService() .Build();
See the samples folder for a complete runnable echo bot.
Telegram client options
TBotSetting exposes the native TelegramBotClientOptions knobs, so you do not have to configure the client yourself:
| Property | Description |
|---|---|
BaseUrl |
Legacy base URL of a local Bot API server; used only while Proxy.Url is empty. |
Proxy |
The local Bot API gateway (TBotSettingProxy): Url, ApiId / ApiHash from my.telegram.org sent as X-Telegram-Api-Id / X-Telegram-Api-Hash (required only for the first login), and the optional WebApiToken — the gateway's own bearer token (webApiToken), sent as Authorization: Bearer …. |
UseTestEnvironment |
Use the Telegram test environment. Not compatible with a local gateway (Proxy.Url / legacy BaseUrl): that combination throws InvalidOperationException, because the gateway does not support the /test URL suffix (REQ-TB-04). |
RetryCount / RetryThreshold |
Built-in retry count and the Retry-After threshold of TelegramBotClient. |
RequestTimeout |
Per-request timeout of the underlying HttpClient. |
ParseMode |
Parse mode used for outgoing messages (Html by default). |
WebhookUrl / WebhookSecretToken |
Switches the hosted service to webhook mode. |
UpdatePolicy |
Allowed UpdateTypes and update batch capacity. |
Updates are received through TelegramBotClientExtensions.ReceiveAsync with ReceiverOptions; polling errors and per-update errors are reported through IUpdateHandler (TelegramUpdateHandler) with typed ApiRequestException handling.
Local Bot API server
Set TBotSetting.Proxy.Url to route every request to a self-hosted Bot API gateway (for example tg-ws-proxy). Methods go to the gateway's own endpoint {Url}/bot{token}/{method} and file downloads to {Url}/file/bot{token}/{file_path} instead of https://api.telegram.org:
.AddBot(new TBotSetting
{
BotName = "echo",
Token = "<botId>:<secret>", // the full token, not only the secret part
Proxy = new TBotSettingProxy
{
Url = "http://localhost:8081", // the gateway service address
ApiId = apiId, // api_id from my.telegram.org
ApiHash = apiHash, // api_hash from my.telegram.org
WebApiToken = webApiToken, // optional gateway bearer token (webApiToken)
},
})
Proxy.ApiId and Proxy.ApiHash are required only for the first login, when the server creates the bot's auth_key. The headers are attached to every request and are harmless once the session exists.
Proxy.WebApiToken mirrors the gateway's own webApiToken setting (see the gateway's docs/web-api.md). When set, every request to the gateway carries Authorization: Bearer {token} — method calls and file downloads alike, because the header lives on the default request headers. It is only attached while a gateway address is configured, so the token never reaches https://api.telegram.org.
Behaviour you should know:
- A
401 login requiredresponse is retried exactly once, so a revoked or expired session re-logs in transparently. WithoutProxy.ApiId/Proxy.ApiHasha re-login is impossible and the error is surfaced as-is. - A local Bot API server answers HTTP
200even for Bot API errors ({ok:false,error_code,description}). The status is realigned witherror_code, so401,413,429and501reach you as a typedApiRequestExceptioncarrying the server'serror_codeanddescriptioninstead of a generic deserialization error.429is retried byTelegramBotClientitself (RetryCount/RetryThreshold), which is why Polly deliberately ignores it. - The bot token is masked in log output (
bot<id>:***). - Limits of the reference server:
30requests per second per bot (429) and20 MiBper upload (413). The default client limiter allows 29 requests per1000ms window per bot, just under that ceiling (HttpPolicy.TelegramRequestMilliSecondInterval). - Files are downloaded in two steps (
getFile, thenGET /file/bot{token}/{file_path});DownloadFileDatareports why a download failed —413(file larger than the server cache),404(evictedfile_path) or502(CDN-hosted file). - Methods the server does not implement answer
501(method '...' is not implemented). Only long polling (getUpdates) is supported:setWebhookis not implemented, so use polling mode with a local server. UseTestEnvironment = trueis rejected (InvalidOperationException) when a gateway address is configured — the/testsuffix is not supported by the gateway (REQ-TB-04).
Concepts
| Term | Description |
|---|---|
| State | A class that handles a request from a specific user. Selected by a state attribute. |
| State attribute | An attribute that maps a user command to a state. |
Interfaces
| Interface | Description |
|---|---|
IState |
State methods for handling a request. |
IStateFactory |
Helper factory; resolves a state by its attribute. |
IStateBindFactory |
Helper factory; works with bound states. |
IStateContextFactory |
Creates state contexts, invokes IState methods and refreshes the main (bottom) menu. |
IMenuButtonFactory |
Builds the main menu buttons. |
IStateContext |
Telegram API context: sending/editing messages, documents, the main menu, message buttons, photos, albums, inline answers and payments, with all necessary checks and validations. |
IStateContextMinimal |
Same as IStateContext, but works without a concrete state inside IStateContextFactory. |
ITelegramContext |
Context with queue and logging for Telegram: direct methods to send/edit messages, receive updates, etc. |
ITelegramContextLog |
Log context for ITelegramContext. |
ITelegramUpdateProcessor |
Processes single updates (webhook endpoint) or batches of updates (long polling). |
IMenuButton |
Builds the main (bottom) menu buttons. |
IStartReceivingHandler |
Handles incoming Telegram requests. |
IKeyInCache |
A cache item with a key. |
IDistributedLockFactory |
Distributed lock factory, based on FusionCache. |
IDelayQueue |
Queue for sending delayed messages. |
State attributes
| Attribute | Description |
|---|---|
StateActivatorBaseAttribute |
Base attribute holding all state-defining properties. |
StateActivatorAttribute |
For states that define the main (bottom) menu. |
StateInlineActivatorAttribute |
For states that define inline message buttons. |
AdminStateActivatorAttribute |
Admin variant of StateActivatorAttribute. |
AdminStateInlineActivatorAttribute |
Admin variant of StateInlineActivatorAttribute. |
Sending media, editing in place
// Send an album (2..10 files). The file count and payloads are validated
// (MediaGroupCountException / MediaGroupDataException).
await stateContext.SendMediaGroup(files, cancellationToken: cancellationToken);
// The same album pipeline can send videos or documents.
await stateContext.SendMediaGroup(files, MediaGroupType.Video, disableNotification: true, cancellationToken);
// Explicit entity markup instead of a parse mode: tg-emoji, custom emoji,
// spoilers and quotes survive a re-send without HTML/Markdown escaping.
await stateContext.SendTextMessageWithEntities(text, message.Entities, cancellationToken);
// Public link to the message that raised the update (channels and supergroups only, otherwise null).
var link = stateContext.GetMessageLink();
// Replace the keyboard of the message that raised the callback query
// (EditMessageReplyMarkup) instead of deleting and re-sending the message.
await stateContext.UpdateInlineMarkup(markupMassiveList, cancellationToken);
// Reply with reply parameters, link preview options and a message effect.
await stateContext.SendTextMessage(
text,
disableNotification: false,
replyParameters: new ReplyParameters { MessageId = messageId },
linkPreviewOptions: new LinkPreviewOptions { IsDisabled = true },
messageEffectId: null,
cancellationToken: cancellationToken);
When a callback message already contains a photo, SendOrUpdateTextMessage updates it in place through EditMessageMedia (caption, parse mode and keyboard are preserved) instead of deleting and re-sending it.
Inline mode and payments
IStateContext also exposes AnswerInlineQuery, AnswerWebAppQuery, AnswerPreCheckoutQuery, AnswerShippingQuery and SendInvoice.
Telegram and WebApp helpers
// HTML-safe output when ParseMode is Html.
var safeText = userText.ToEscapeHtml();
var html = message.ToTelegramHtml();
var plain = html.ToPlainText();
// Chat member checks.
if (chatMember.IsAdminOrCreator() && chatMember.IsInChat()) { /* ... */ }
// Validate Telegram WebApp initData (signature + optional auth_date freshness).
if (initData.TryValidateInitData(botToken, out var fields, TimeSpan.FromHours(1)))
{
// fields["user"], fields["auth_date"], ...
}
DI configuration
services
.AddBotPlatform()
.AddBot(telegramSettings)
.AddTelegramContext()
.AddStates(executingAssembly)
.AddReceivingHandler<StartReceivingHandler>()
.Build()
.AddCache()
.AddRedisFusionCache(redisConnectionString)
.AddHealthTags(tags)
.AddHealthName(redisHealthName)
.Build()
.Build()
.AddFactories(executingAssembly)
.AddHostedService()
.Build();
Several bots can share one host: call AddBot(...) per bot, then AddTelegramContext(), AddStates(...) and AddReceivingHandler<T>() for each of them. Every keyed registration (ITelegramContext, IStartReceivingHandler, state data) is isolated by TBotSetting.BotName, and each bot gets its own update receiver.
Use AddRedisFusionCache(connectionString) when the bots run in several instances: the user-state cache and distributed locks become shared, so a conversation is not split between replicas.
For webhook mode, set TBotSetting.WebhookUrl (and optionally WebhookSecretToken). The hosted service registers the webhook automatically. In your HTTP endpoint, validate the X-Telegram-Bot-Api-Secret-Token header, deserialize the request body to Update with JsonBotAPI.Options (snake_case naming) and pass it to ITelegramUpdateProcessor.ProcessUpdate. Return a non-2xx status only when you want Telegram to retry the delivery.
Testing and CI
dotnet test TBotPlatform.slnruns the NUnit test suite (net8.0).- Coverage is collected with
coverlet.collector:dotnet test TBotPlatform.Tests/TBotPlatform.Tests.csproj --collect:"XPlat Code Coverage". - GitHub Actions:
CIbuilds, tests and packs on every push and pull request;Publish to NuGetpacks and pushes onv*tags using theNUGET_API_KEYsecret.
Contacts
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. 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
- AspNetCore.HealthChecks.Redis (>= 9.0.0)
- Microsoft.Extensions.Caching.StackExchangeRedis (>= 11.0.0)
- Microsoft.Extensions.Http (>= 11.0.0)
- Microsoft.Extensions.Http.Polly (>= 11.0.0)
- Microsoft.IO.RecyclableMemoryStream (>= 4.0.1)
- Newtonsoft.Json (>= 13.0.4)
- RateLimiter (>= 2.2.0)
- Telegram.Bot (>= 22.10.5)
- ZiggyCreatures.FusionCache (>= 2.10.0)
- ZiggyCreatures.FusionCache.Serialization.NewtonsoftJson (>= 2.10.0)
-
net11.0
- AspNetCore.HealthChecks.Redis (>= 9.0.0)
- Microsoft.Extensions.Caching.StackExchangeRedis (>= 11.0.0)
- Microsoft.Extensions.Http (>= 11.0.0)
- Microsoft.Extensions.Http.Polly (>= 11.0.0)
- Microsoft.IO.RecyclableMemoryStream (>= 4.0.1)
- Newtonsoft.Json (>= 13.0.4)
- RateLimiter (>= 2.2.0)
- Telegram.Bot (>= 22.10.5)
- ZiggyCreatures.FusionCache (>= 2.10.0)
- ZiggyCreatures.FusionCache.Serialization.NewtonsoftJson (>= 2.10.0)
-
net9.0
- AspNetCore.HealthChecks.Redis (>= 9.0.0)
- Microsoft.Extensions.Caching.StackExchangeRedis (>= 11.0.0)
- Microsoft.Extensions.Http (>= 11.0.0)
- Microsoft.Extensions.Http.Polly (>= 11.0.0)
- Microsoft.IO.RecyclableMemoryStream (>= 4.0.1)
- Newtonsoft.Json (>= 13.0.4)
- RateLimiter (>= 2.2.0)
- Telegram.Bot (>= 22.10.5)
- ZiggyCreatures.FusionCache (>= 2.10.0)
- ZiggyCreatures.FusionCache.Serialization.NewtonsoftJson (>= 2.10.0)
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 | |
|---|---|---|---|
| 2.4.3-beta1 | 79 | 11/28/2026 | |
| 2.4.2 | 146 | 10/12/2026 | |
| 2.4.1 | 117 | 10/10/2026 | |
| 2.4.0 | 119 | 10/6/2026 | |
| 2.4.0-beta1 | 105 | 9/28/2026 | |
| 2.3.0 | 124 | 9/22/2026 | |
| 2.3.0-beta2 | 111 | 9/17/2026 | |
| 2.3.0-beta1 | 122 | 9/16/2026 | |
| 2.1.2 | 149 | 9/2/2026 | |
| 2.1.2-beta6 | 152 | 6/22/2026 | |
| 2.1.2-beta5 | 144 | 3/5/2026 | |
| 2.1.2-beta4 | 145 | 2/25/2026 | |
| 2.1.2-beta3 | 146 | 2/5/2026 | |
| 2.1.2-beta2 | 150 | 1/13/2026 | |
| 2.1.1 | 482 | 11/20/2025 | |
| 2.1.0 | 232 | 10/16/2025 | |
| 2.0.0 | 339 | 9/24/2025 |
See the release notes on GitHub: https://github.com/BolotnikovPS/TBotPlatform/releases