Handlers are the core building blocks of your Telegrator bot. Each handler processes specific types of Telegram updates and encapsulates a discrete piece of bot functionality.
Command handlers process messages that start with / (e.g., /start, /help).
1
Create command handler class
Inherit from CommandHandler and use [CommandHandler] with [CommandAllias]:
using Telegrator.Handlers;using Telegrator.Annotations;using Telegram.Bot.Types;using Telegram.Bot.Types.Enums;[CommandHandler][CommandAllias("start", "hello")][ChatType(ChatType.Private)]public class StartCommandHandler : CommandHandler{ public override async Task<Result> Execute( IHandlerContainer<Message> container, CancellationToken cancellation) { await Response( "Welcome to the bot! Use /help to see available commands.", cancellationToken: cancellation); return Result.Ok(); }}
2
Access command arguments
Command handlers provide properties to access command arguments:
[CommandHandler][CommandAllias("greet")]public class GreetCommandHandler : CommandHandler{ public override async Task<Result> Execute( IHandlerContainer<Message> container, CancellationToken cancellation) { // Get command arguments as array string[] args = Arguments; // Get full arguments string string argsString = ArgumentsString; // Get the command that was used string command = ReceivedCommand; if (args.Length > 0) { await Reply($"Hello, {args[0]}!", cancellationToken: cancellation); } else { await Reply("Hello! Please provide a name.", cancellationToken: cancellation); } return Result.Ok(); }}
The ReceivedCommand property returns the command without the / prefix and bot username.
For example, /start@mybot returns "start".
Handlers with higher importance values are evaluated first. If multiple handlers match an update,
the one with the highest importance will execute. Use Priority to control the order among handlers
with the same importance level.