The Telegrator.Hosting package enables you to build Telegram bots as console applications using .NET’s Generic Host with long polling for receiving updates.
Installation
dotnet add package Telegrator.Hosting
Quick Start
Create the host builder
Use TelegramBotHost.CreateBuilder() to create a new host with default services and long polling: using Telegrator . Hosting ;
var builder = TelegramBotHost . CreateBuilder ();
This automatically:
Configures the .NET Generic Host
Registers default Telegrator services
Sets up long polling for receiving updates
Configure bot token
Add your bot token to configuration. The recommended approach is using appsettings.json: {
"TelegramBotClientOptions" : {
"Token" : "YOUR_BOT_TOKEN_HERE"
}
}
For production, store the token in environment variables or a secure configuration provider, not in source control.
Register handlers
Use the Handlers collection to register your update handlers: builder . Handlers . AddHandler < StartCommandHandler >();
builder . Handlers . AddHandler < MessageHandler >();
Build and run
Build the host and start receiving updates: var app = builder . Build ();
await app . StartAsync ();
Complete Example
using Telegrator . Hosting ;
using Telegrator . Sessions ;
using Telegram . Bot . Types ;
using Telegram . Bot ;
// Create host builder with default services and long polling
var builder = TelegramBotHost . CreateBuilder ();
// Register handlers
builder . Handlers . AddHandler < StartCommandHandler >();
builder . Handlers . AddHandler < EchoMessageHandler >();
// Build and run the host
var app = builder . Build ();
await app . StartAsync ();
// Handler examples
public class StartCommandHandler : IUpdateHandler
{
public UpdateType AllowedUpdates => UpdateType . Message ;
public async Task HandleUpdateAsync (
ITelegramBotClient client ,
Update update ,
CancellationToken ct )
{
if ( update . Message ? . Text == "/start" )
{
await client . SendMessage (
chatId : update . Message . Chat . Id ,
text : "Welcome! Send me a message." ,
cancellationToken : ct );
}
}
}
public class EchoMessageHandler : IUpdateHandler
{
public UpdateType AllowedUpdates => UpdateType . Message ;
public async Task HandleUpdateAsync (
ITelegramBotClient client ,
Update update ,
CancellationToken ct )
{
if ( update . Message ? . Text != null )
{
await client . SendMessage (
chatId : update . Message . Chat . Id ,
text : $"You said: { update . Message . Text } " ,
cancellationToken : ct );
}
}
}
Builder Methods
The TelegramBotHost class provides several static factory methods:
CreateBuilder()
Creates a builder with default configuration and services:
public static TelegramBotHostBuilder CreateBuilder ()
Automatically:
Adds console and debug logging
Registers Telegrator core services
Configures long polling receiver
CreateBuilder(settings)
Creates a builder with custom settings:
public static TelegramBotHostBuilder CreateBuilder (
TelegramBotHostBuilderSettings ? settings )
Example:
var settings = new TelegramBotHostBuilderSettings
{
ApplicationName = "MyTelegramBot" ,
EnvironmentName = "Production" ,
MaximumParallelWorkingHandlers = 10
};
var builder = TelegramBotHost . CreateBuilder ( settings );
CreateEmptyBuilder()
Creates a builder without any default services:
public static TelegramBotHostBuilder CreateEmptyBuilder ()
Use this only if you need full control over service registration. You’ll need to manually register all required services.
Configuration
Required Configuration
The bot token must be configured via TelegramBotClientOptions:
{
"TelegramBotClientOptions" : {
"Token" : "1234567890:ABCdefGHIjklMNOpqrsTUVwxyz"
}
}
Polling Configuration
Configure long polling behavior via ReceiverOptions:
{
"ReceiverOptions" : {
"Offset" : 0 ,
"Limit" : 100 ,
"Timeout" : 30 ,
"AllowedUpdates" : []
}
}
Identifier of the first update to be returned
Maximum number of updates to be retrieved (1-100)
Timeout in seconds for long polling
List of update types to receive. Empty array means all types.
Telegrator Options
Configure bot behavior via TelegratorOptions:
var settings = new TelegramBotHostBuilderSettings
{
MaximumParallelWorkingHandlers = 5 ,
ExclusiveAwaitingHandlerRouting = true ,
ExceptIntersectingCommandAliases = true
};
MaximumParallelWorkingHandlers
Maximum number of handlers that can execute concurrently. null = unlimited.
ExclusiveAwaitingHandlerRouting
When true, awaiting handlers receive updates exclusively.
ExceptIntersectingCommandAliases
When true, throws an exception if command aliases conflict.
Service Registration
The builder exposes an IServiceCollection for registering dependencies:
// Register custom services
builder . Services . AddSingleton < IDatabaseService , DatabaseService >();
builder . Services . AddHttpClient ();
builder . Services . AddMemoryCache ();
// Configure logging
builder . Logging . AddConsole ();
builder . Logging . SetMinimumLevel ( LogLevel . Debug );
// Access configuration
var token = builder . Configuration [ "TelegramBotClientOptions:Token" ];
Host Lifetime
The ITelegramBotHost interface extends IHost:
public interface ITelegramBotHost : IHost , ITelegratorBot
{
IServiceProvider Services { get ; }
IUpdateRouter UpdateRouter { get ; }
}
Starting the Host
Run Until Stopped
Manual Control
With Cancellation Token
var app = builder . Build ();
await app . RunAsync (); // Runs until Ctrl+C
Extension Methods
SetBotCommands
Automatically configure the bot’s command menu based on registered handlers:
var app = builder . Build ();
app . SetBotCommands (); // Syncs commands with Telegram
await app . RunAsync ();
AddLoggingAdapter
Integrate Telegrator’s internal logging with Microsoft.Extensions.Logging:
var app = builder . Build ();
app . AddLoggingAdapter ();
await app . RunAsync ();
Accessing Services
Retrieve registered services from the host:
var app = builder . Build ();
// Get Telegram client
var client = app . Services . GetRequiredService < ITelegramBotClient >();
// Get update router
var router = app . UpdateRouter ;
// Get custom services
var database = app . Services . GetRequiredService < IDatabaseService >();
Best Practices
Never hardcode tokens in source code. Use environment variables or secure configuration: export TelegramBotClientOptions__Token = "YOUR_TOKEN"
dotnet run
Or use User Secrets during development: dotnet user-secrets set "TelegramBotClientOptions:Token" "YOUR_TOKEN"
Handle cancellation tokens properly to ensure clean shutdown: var app = builder . Build ();
var cts = new CancellationTokenSource ();
Console . CancelKeyPress += ( s , e ) =>
{
e . Cancel = true ;
cts . Cancel ();
};
await app . RunAsync ( cts . Token );
Handler Registration Order
Register more specific handlers before generic ones: builder . Handlers . AddHandler < StartCommandHandler >(); // Specific
builder . Handlers . AddHandler < MessageHandler >(); // Generic
Configure logging to troubleshoot issues: builder . Logging . AddConsole ();
builder . Logging . SetMinimumLevel ( LogLevel . Debug );
var app = builder . Build ();
app . AddLoggingAdapter (); // Bridge Telegrator logs
Next Steps
Handlers Learn how to create update handlers
ASP.NET Core Deploy with webhooks using ASP.NET Core