Giter Site home page Giter Site logo

viknsagit / telegram.bot.attributecommands Goto Github PK

View Code? Open in Web Editor NEW
1.0 1.0 0.0 32 KB

Library for creating commands for a telegram bot through attributes using Telegram.Bots

Home Page: https://www.nuget.org/packages/Telegram.Bot.AttributeCommands#readme-body-tab

License: MIT License

C# 100.00%

telegram.bot.attributecommands's Introduction

Telegram.Bot.AttributeCommands Library Documentation

The Telegram.Bot.AttributeCommands library offers a streamlined approach to managing and executing text, callback, and reply commands for a Telegram bot. By utilizing custom attributes to mark and categorize methods, this library simplifies the registration and processing of commands.

Table of Contents

Introduction

The Telegram.Bot.AttributeCommands library provides an elegant solution for managing and processing different command types within a Telegram bot. By using custom attributes, the library organizes text, callback, and reply commands, leading to a more organized and efficient command handling process.

Getting Started

Creating Command Classes

To start using the Telegram.Bot.AttributeCommands library, create a class to contain your command methods. These methods should be static and marked with the appropriate command attributes.

Registering Commands

Before utilizing the registered commands, instantiate the AttributeCommands class. Use the RegisterCommands method to register commands from your command class. This method combines the registration of text, callback, and reply commands.

Here's an example of registering commands:

using Telegram.Bot;
using Telegram.Bot.Types;

public class YourBotClass
{
    private readonly TelegramBotClient _botClient;
    private readonly AttributeCommands _commands;

    public YourBotClass(string botToken)
    {
        _botClient = new TelegramBotClient(botToken);
        _commands = new AttributeCommands();

        // Register your command classes
        _commands.RegisterCommands(typeof(TestCommands));
    }

    // Other bot handling methods here...
}

Handling Updates

When handling incoming updates in your bot's code, ensure that you invoke the appropriate command processing methods based on the command type received. This guarantees that registered methods with corresponding attributes are invoked correctly.

private async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
{
    switch (update)
    {
        case { Message: { } message }:
            {
                if (message.ReplyToMessage != null)
                    await BotOnReplyMessage(message, cts);
                else if (message.Text != null)
                    await BotOnMessageReceived(message, cts);
            }

            break;

        case { CallbackQuery: { } callbackQuery }:
            await BotOnCallbackQueryReceived(callbackQuery, cts);
            break;

        default:
            await UnknownUpdateHandlerAsync(update, cts);
            break;
    }
}

private async Task BotOnCallbackQueryReceived(CallbackQuery callbackQuery, CancellationTokenSource cts)
{
    try
    {
        await _commands.ProcessCommand(callbackQuery.Data!, new object[] { botClient, callbackQuery });
    }
    catch (CommandNotFoundException ex)
    {
        await botClient.SendTextMessageAsync(callbackQuery.Message!.Chat.Id, ex.Message);
    }
}

private async Task BotOnMessageReceived(Message message, CancellationTokenSource cts)
{
    try
    {
        await _commands.ProcessCommand(message.Text!, new object[] { botClient, message });
    }
    catch (CommandNotFoundException ex)
    {
        await botClient.SendTextMessageAsync(message.Chat.Id, ex.Message);
    }
}

private async Task BotOnReplyMessage(Message message, CancellationTokenSource cts)
{
    try
    {
        await _commands.ProcessCommand(message.ReplyToMessage!.Text!, new object[] { botClient, message });
    }
    catch (CommandNotFoundException ex)
    {
        await botClient.SendTextMessageAsync(message.Chat.Id, ex.Message);
    }
}

Usage

Attributes

The Telegram.Bot.AttributeCommands library includes three custom attributes to mark methods as different command types.

TextCommandAttribute

Use the TextCommandAttribute to identify methods as text commands for your Telegram bot.

[TextCommand("your_text_command")]
public static void YourTextCommandMethod(TelegramBotClient client, Update update)
{
    // Your text command logic here
}

CallbackCommandAttribute

Employ the CallbackCommandAttribute to mark methods as callback commands.

[CallbackCommand("your_callback_command")]
public static void YourCallbackCommandMethod(TelegramBotClient client, Update update)
{
    // Your callback command logic here
}

ReplyCommandAttribute

Utilize the ReplyCommandAttribute to indicate methods as reply commands.

[ReplyCommand("your_reply_command")]
public static void YourReplyCommandMethod(TelegramBotClient client, Update update)
{
    // Your reply command logic here
}

Exceptions

The Telegram.Bot.AttributeCommands library provides custom exceptions for error handling.

CommandNotFoundException

Thrown when attempting to process a non-existent command.

CommandExistsException

Thrown when trying to register a command with a duplicate name.

CommandArgumentsCountError

Thrown when the number of arguments provided does not match the expected count.

CommandBadArgumentType

Thrown when the type of an argument provided does not match the expected type.

Example

using Telegram.Bot;
using Telegram.Bot.Types;

public class TestCommands
{
    [TextCommand("start")]
    public static void StartCommand(TelegramBotClient client, Update update)
    {
        // Logic for the start text command
    }

    [CallbackCommand("button_click")]
    public static void ButtonClickCallback(TelegramBotClient client, Update update)
    {
        // Logic for the button click callback command
    }

    [ReplyCommand("thanks")]
    public static void ThankYouReply(TelegramBotClient client, Update update)
    {
        // Logic for the thank you reply command
    }
}

Processing Updates

When handling incoming updates in your bot's code, make sure to invoke the appropriate ProcessCommand method based on the command type received. This ensures that registered methods with corresponding attributes are invoked correctly.

Exception Handling

When using the Telegram.Bot.AttributeCommands library, handle exceptions to provide a smooth user experience. Catch CommandNotFoundException, CommandExistsException, CommandArgumentsCountError, and CommandBadArgumentType exceptions as needed.


This comprehensive documentation covers the Telegram.Bot.AttributeCommands library, including its custom attributes and exceptions. For more detailed information and usage scenarios, refer to the library's source code and comments.

Please note that this documentation is provided for informational purposes.

telegram.bot.attributecommands's People

Contributors

viknsagit avatar

Stargazers

 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.