Skip to main content

Overview

MessageHandler is an abstract base class for handlers that process message updates. This handler is triggered when users send messages in chats and provides convenient methods for sending replies and responses.

Attribute

[MessageHandler(importance: 0)]
importance
int
default:"0"
The importance level of the handler. Higher values are executed first.

Base Class

public abstract class MessageHandler : AbstractUpdateHandler<Message>
Inherits from AbstractUpdateHandler<Message> with UpdateType.Message.

Properties

The following properties are inherited from AbstractUpdateHandler<Message>:
Container
IHandlerContainer<Message>
Handler container for the current update.
Client
ITelegramBotClient
Telegram Bot client associated with the current container.
Input
Message
Incoming message update.
HandlingUpdate
Update
The Telegram update being handled.
ExtraData
Dictionary<string, object>
Additional data associated with the handler execution.
CompletedFilters
CompletedFiltersList
List of successfully passed filters.
AwaitingProvider
IAwaitingProvider
Provider for awaiting asynchronous operations.

Methods

Execute

public abstract Task<Result> Execute(
    IHandlerContainer<Message> container,
    CancellationToken cancellation
)
Abstract method to implement your message handling logic.
container
IHandlerContainer<Message>
required
The handler container with message update data.
cancellation
CancellationToken
required
Cancellation token for the operation.
Returns: Task<Result> - A result indicating success, fault, or continuation.

Reply

protected async Task<Message> Reply(
    string text,
    ParseMode parseMode = ParseMode.None,
    ReplyMarkup? replyMarkup = null,
    LinkPreviewOptions? linkPreviewOptions = null,
    int? messageThreadId = null,
    IEnumerable<MessageEntity>? entities = null,
    bool disableNotification = false,
    bool protectContent = false,
    string? messageEffectId = null,
    string? businessConnectionId = null,
    bool allowPaidBroadcast = false,
    int? directMessageTopicId = null,
    SuggestedPostParameters? suggestedPostParameters = null,
    CancellationToken cancellationToken = default
)
Sends a reply message to the current message.
text
string
required
The text of the message to send.
parseMode
ParseMode
default:"ParseMode.None"
The parse mode for the message text (None, Markdown, HTML).
replyMarkup
ReplyMarkup
The reply markup for the message (keyboard, inline keyboard, etc.).
Options for link preview generation.
messageThreadId
int
The thread ID for forum topics.
disableNotification
bool
default:"false"
Whether to disable notification for the message.
protectContent
bool
default:"false"
Whether to protect the message content from forwarding.
Returns: Task<Message> - The sent message.

Response

protected async Task<Message> Response(
    string text,
    ParseMode parseMode = ParseMode.None,
    ReplyParameters? replyParameters = null,
    ReplyMarkup? replyMarkup = null,
    LinkPreviewOptions? linkPreviewOptions = null,
    int? messageThreadId = null,
    IEnumerable<MessageEntity>? entities = null,
    bool disableNotification = false,
    bool protectContent = false,
    string? messageEffectId = null,
    string? businessConnectionId = null,
    bool allowPaidBroadcast = false,
    int? directMessageTopicId = null,
    SuggestedPostParameters? suggestedPostParameters = null,
    CancellationToken cancellationToken = default
)
Sends a response message to the current chat (without replying to the specific message).
text
string
required
The text of the message to send.
parseMode
ParseMode
default:"ParseMode.None"
The parse mode for the message text.
replyParameters
ReplyParameters
The reply parameters for the message.
replyMarkup
ReplyMarkup
The reply markup for the message.
Returns: Task<Message> - The sent message.

Example

using Telegrator.Handlers;
using Telegrator.Filters;
using Telegram.Bot.Types.Enums;

[MessageHandler]
[TextFilter("hello")]
public class HelloHandler : MessageHandler
{
    public override async Task<Result> Execute(
        IHandlerContainer<Message> container,
        CancellationToken cancellation)
    {
        // Reply to the user's message
        await Reply(
            "Hello! How can I help you today?",
            parseMode: ParseMode.Html
        );

        return Result.Ok();
    }
}

BranchingMessageHandler

BranchingMessageHandler is a variant that supports multiple handler methods in a single class, each with its own filters.
public abstract class BranchingMessageHandler : BranchingUpdateHandler<Message>

Example

[MessageHandler]
public class MultiMessageHandler : BranchingMessageHandler
{
    [TextFilter("start")]
    public async Task<Result> HandleStart()
    {
        await Reply("Welcome! Let's get started.");
        return Result.Ok();
    }

    [TextFilter("help")]
    public async Task<Result> HandleHelp()
    {
        await Reply("Here are the available commands...");
        return Result.Ok();
    }
}

See Also

Build docs developers (and LLMs) love