Skip to main content
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

1

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
2

Configure bot token

Add your bot token to configuration. The recommended approach is using appsettings.json:
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.
3

Register handlers

Use the Handlers collection to register your update handlers:
builder.Handlers.AddHandler<StartCommandHandler>();
builder.Handlers.AddHandler<MessageHandler>();
4

Build and run

Build the host and start receiving updates:
var app = builder.Build();
await app.StartAsync();

Complete Example

Program.cs
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:
appsettings.json
{
  "ReceiverOptions": {
    "Offset": 0,
    "Limit": 100,
    "Timeout": 30,
    "AllowedUpdates": []
  }
}
Offset
int
default:"0"
Identifier of the first update to be returned
Limit
int
default:"100"
Maximum number of updates to be retrieved (1-100)
Timeout
int
default:"30"
Timeout in seconds for long polling
AllowedUpdates
string[]
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
int?
Maximum number of handlers that can execute concurrently. null = unlimited.
ExclusiveAwaitingHandlerRouting
bool
default:"false"
When true, awaiting handlers receive updates exclusively.
ExceptIntersectingCommandAliases
bool
default:"true"
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

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

Build docs developers (and LLMs) love