Botify 0.1.50

dotnet add package Botify --version 0.1.50
                    
NuGet\Install-Package Botify -Version 0.1.50
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Botify" Version="0.1.50" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Botify" Version="0.1.50" />
                    
Directory.Packages.props
<PackageReference Include="Botify" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Botify --version 0.1.50
                    
#r "nuget: Botify, 0.1.50"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Botify@0.1.50
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Botify&version=0.1.50
                    
Install as a Cake Addin
#tool nuget:?package=Botify&version=0.1.50
                    
Install as a Cake Tool

Botify 🚀

Botify — лёгкий C#-фреймворк для создания Telegram-ботов с интеграцией в Dependency Injection и удобной моделью атрибутов. Он позволяет быстро собирать ботов с обработкой команд, сообщений, callback-запросов, inline-query и платежных событий.

⚡ Особенности

  • Полная поддержка Dependency Injection через Microsoft.Extensions.DependencyInjection.
  • Простое добавление обработчиков команд, сообщений и callback-запросов.
  • Встроенная работа с Telegram.Bot API.
  • Кеширование данных и удобная работа с пользовательскими профилями.
  • Возможность интеграции с любыми базами данных через DbContext (например, PostgreSQL + EF Core).

📦 Установка

Через NuGet-источник проекта:

 dotnet add package Botify --source <папка_или_feed_с_Botify>

Если используется локальная сборка, можно подключить пакет из собственного feed или артефактов релиза.


🛠 Быстрый старт

public class Program
{
    static void Main(string[] args)
    {
        var builder = Host.CreateApplicationBuilder(args);

        var botToken = builder.Configuration["Telegram:BotToken"]
            ?? throw new InvalidOperationException("BotToken не указан");

        builder.Services.AddBotifyHandlers();
        builder.Services.AddBotify(options => {
            options.SetToken(botToken);
        });

        var host = builder.Build();
        host.Run();
    }
}

🧱 Основные концепции

Концепт Описание
CommandHandler Обработка команд вида /start, /help, /schedule.
CallbackHandler Обработка CallbackQuery от inline-кнопок.
MessageHandler Обработка входящих сообщений по regex-паттернам.
InlineHandler Обработка inline-запросов Telegram.
PaymentHandler Обработка платежных событий Telegram.
BotifyOptionsBuilder Конфигурация бота: токен, разделители, логирование, HTTP-параметры.

🔧 Примеры обработчиков

Команды

using Botify.Attributes;
using Telegram.Bot;
using Telegram.Bot.Types;

[CommandHandler]
public class CommandsHandler
{
    [Command("start", "Начать работу с ботом")]
    public async Task StartCommand(ITelegramBotClient client, Update update, CancellationToken ct)
    {
        if (update.Message == null)
            return;

        await client.SendMessage(update.Message.Chat.Id, "Привет! Я Botify-бот.", cancellationToken: ct);
    }
}

Callback-запросы

using Botify.Attributes;
using Telegram.Bot;
using Telegram.Bot.Types;

[CallbackHandler]
public class CallbacksHandler
{
    [Callback("change")]
    public async Task ChangeCallback(ITelegramBotClient client, Update update, CancellationToken ct)
    {
        if (update.CallbackQuery?.Message == null)
            return;

        await client.EditMessageText(
            update.CallbackQuery.Message.Chat.Id,
            update.CallbackQuery.Message.MessageId,
            "Изменено",
            cancellationToken: ct);
    }
}

Сообщения

using Botify.Attributes;
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;

[MessageHandler]
public class MessagesHandler
{
    [Message("^(привет|hello)$", MessageType.Text)]
    public async Task HelloMessage(ITelegramBotClient client, Update update, CancellationToken ct)
    {
        if (update.Message == null)
            return;

        await client.SendMessage(update.Message.Chat.Id, "Привет!", cancellationToken: ct);
    }

    [Message(".*")]
    public async Task FallbackMessage(ITelegramBotClient client, Update update, CancellationToken ct)
    {
        if (update.Message == null)
            return;

        await client.SendMessage(update.Message.Chat.Id, "Неизвестное сообщение.", cancellationToken: ct);
    }
}

Inline-запросы

using Botify.Attributes;
using Telegram.Bot;
using Telegram.Bot.Types;

[InlineHandler]
public class InlineSearchHandler
{
    [Inline("search")]
    public async Task Search(ITelegramBotClient client, Update update, CancellationToken ct)
    {
        if (update.InlineQuery == null)
            return;

        // обработка inline query
    }
}

Платежи

using Botify.Attributes;
using Telegram.Bot;
using Telegram.Bot.Types;

[PaymentHandler]
public class PaymentsHandler
{
    [PreCheckoutPayment]
    public Task PreCheckout(ITelegramBotClient client, Update update, CancellationToken ct)
    {
        // проверка заказа перед оплатой
        return Task.CompletedTask;
    }

    [SuccessfulPayment]
    public Task SuccessfulPayment(ITelegramBotClient client, Update update, CancellationToken ct)
    {
        // обработка успешной оплаты
        return Task.CompletedTask;
    }
}

⚙️ Конфигурация

BotifyOptionsBuilder позволяет настроить:

  • токен бота;
  • базовый URL Telegram API;
  • символ начала команды;
  • разделитель callback-данных;
  • разделитель inline-данных;
  • логирование;
  • пользовательский HttpClientHandler.

Пример:

builder.Services.AddBotify(options =>
{
    options.SetToken(botToken);
    options.SetBaseURL("https://api.telegram.org");
    options.UseLogger(logger, LogLevel.Information);
});

🗄 Работа с базой данных

Botify не ограничивает способ хранения данных. Можно использовать EF Core, Dapper или любой другой подход.

Пример с EF Core:

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseNpgsql(builder.Configuration.GetConnectionString("Postgres")));

🔗 Ссылки

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.1.50 90 5/17/2026
0.1.31 113 3/9/2026
0.1.5 96 5/17/2026
0.1.4 97 3/20/2026
0.1.3 97 3/9/2026
0.1.2 115 3/1/2026