Build your first Telegram bot with Telegrator in minutes
This guide will walk you through creating a fully functional Telegram bot using Telegrator. You’ll learn the fundamental concepts and have a working bot by the end.
using Telegram.Bot.Types;using Telegram.Bot.Types.Enums;using Telegrator.Handlers;using Telegrator.Annotations;[CommandHandler][CommandAlias("start", "hello")][ChatType(ChatType.Private)]public class StartCommandHandler : CommandHandler{ public override async Task<Result> Execute( IAbstractHandlerContainer<Message> container, CancellationToken cancellation) { string username = Input.From?.FirstName ?? "friend"; await Response($"Hello, {username}! Welcome to my bot!", cancellationToken: cancellation); return Result.Ok(); }}
The [CommandHandler] attribute marks this class as a command handler, while [CommandAlias] specifies which commands trigger it (both /start and /hello will work).
using Telegrator;// Create bot client with your token from BotFathervar bot = new TelegratorClient("YOUR_BOT_TOKEN_HERE");// Register handlersbot.Handlers.AddHandler<StartCommandHandler>();bot.Handlers.AddHandler<EchoHandler>();// Start receiving updatesConsole.WriteLine("Bot is starting...");bot.StartReceiving();// Keep the application runningConsole.WriteLine("Bot is running. Press any key to stop.");Console.ReadKey();
using Telegram.Bot.Types;using Telegram.Bot.Types.Enums;using Telegrator.Handlers;using Telegrator.Annotations;namespace MyHostedBot.Handlers;[CommandHandler][CommandAlias("start")][ChatType(ChatType.Private)]public class StartCommandHandler : CommandHandler{ public override async Task<Result> Execute( IAbstractHandlerContainer<Message> container, CancellationToken cancellation) { string message = $""" Welcome to my bot! Available commands: /start - Show this message /help - Get help /echo [text] - Echo your message """; await Response(message, cancellationToken: cancellation); return Result.Ok(); }}
Create Handlers/HelpCommandHandler.cs:
Handlers/HelpCommandHandler.cs
using Telegram.Bot.Types;using Telegrator.Handlers;using Telegrator.Annotations;namespace MyHostedBot.Handlers;[CommandHandler][CommandAlias("help")]public class HelpCommandHandler : CommandHandler{ public override async Task<Result> Execute( IAbstractHandlerContainer<Message> container, CancellationToken cancellation) { await Response( "This bot demonstrates Telegrator framework features. Try sending me a message!", cancellationToken: cancellation ); return Result.Ok(); }}
Create Handlers/EchoCommandHandler.cs:
Handlers/EchoCommandHandler.cs
using Telegram.Bot.Types;using Telegrator.Handlers;using Telegrator.Annotations;namespace MyHostedBot.Handlers;[CommandHandler][CommandAlias("echo")]public class EchoCommandHandler : CommandHandler{ public override async Task<Result> Execute( IAbstractHandlerContainer<Message> container, CancellationToken cancellation) { if (string.IsNullOrWhiteSpace(ArgumentsString)) { await Response("Usage: /echo <text>", cancellationToken: cancellation); } else { await Response($"Echo: {ArgumentsString}", cancellationToken: cancellation); } return Result.Ok(); }}
The ArgumentsString property in CommandHandler provides everything after the command, while Arguments gives you an array of individual arguments.
using Telegrator.Hosting;// Create builder with settingsTelegramBotHostBuilder builder = TelegramBotHost.CreateBuilder( new TelegramBotHostBuilderSettings() { Args = args, ExceptIntersectingCommandAliases = true });// Automatically discover and register all handlers in the assemblybuilder.Handlers.CollectHandlersAssemblyWide();// Optional: Register custom services// builder.Services.AddSingleton<IMyService, MyService>();// Build the hostTelegramBotHost telegramBot = builder.Build();// Set bot commands in Telegram UItelegramBot.SetBotCommands();// Add logging adapter to connect Telegrator logs with Microsoft.Extensions.LoggingtelegramBot.AddLoggingAdapter();// Run the botConsole.WriteLine("Bot is starting...");telegramBot.Run();
The CollectHandlersAssemblyWide() method automatically discovers and registers all handlers in your assembly. You can also register handlers individually using builder.Handlers.AddHandler<T>().
using Telegrator.Hosting;using Telegrator.Hosting.Web;// Create web host builderTelegramBotWebHostBuilder builder = TelegramBotWebHost.CreateBuilder( new TelegramBotWebOptions() { Args = args, ExceptIntersectingCommandAliases = true });// Register handlersbuilder.Handlers.CollectHandlersAssemblyWide();// Optional: Add your services// builder.Services.AddSingleton<IMyService, MyService>();// Build and configureTelegramBotWebHost telegramBot = builder.Build();telegramBot.SetBotCommands();telegramBot.AddLoggingAdapter();// Run the web applicationConsole.WriteLine("Web bot is starting...");telegramBot.Run();
Handlers execute based on their importance level. You can control execution order:
[CommandHandler(importance: 10)] // Higher importance = executes first[CommandAlias("admin")]public class AdminCommandHandler : CommandHandler{ // This handler will execute before handlers with lower importance}[MessageHandler(importance: 0)] // Default importancepublic class GeneralMessageHandler : MessageHandler{ // This handler executes after high-importance handlers}
The importance parameter in handler attributes controls execution order. Higher values execute first. Default is 0 for messages and 1 for commands.
Filters control when handlers execute. Combine multiple filters for precise control:
using Telegram.Bot.Types.Enums;using Telegrator.Handlers;using Telegrator.Annotations;[CommandHandler][CommandAlias("admin")][ChatType(ChatType.Private)] // Only in private chats[SenderId(123456789)] // Only for specific userpublic class AdminCommandHandler : CommandHandler{ public override async Task<Result> Execute( IAbstractHandlerContainer<Message> container, CancellationToken cancellation) { await Response("Admin panel loading...", cancellationToken: cancellation); return Result.Ok(); }}
Common filter attributes:
[ChatType(ChatType.Private)] - Filter by chat type
[SenderId(id)] - Filter by sender ID
[ChatId(id)] - Filter by chat ID
[TextContains("word")] - Filter messages containing text
// Response - sends a new message to the chatawait Response("Hello!");// Reply - replies to the message that triggered the handlerawait Reply("Hello!"); // Shows as a reply in Telegram
// Success - handler completed successfully, stop routingreturn Result.Ok();// Error - handler encountered an error, stop routingreturn Result.Fault();// Continue - let the router continue to other handlersreturn Result.Next();// Chain - continue only to handlers of specific typereturn Result.Next<CommandHandler>();
Explore the GitHub repository for more examples and the complete source code!