{"id":33242448,"url":"https://github.com/k-paul-acct/minimal-telegram-bot","last_synced_at":"2025-11-16T20:04:39.368Z","repository":{"id":247471671,"uuid":"763757888","full_name":"k-paul-acct/minimal-telegram-bot","owner":"k-paul-acct","description":"Minimal Telegram Bot is a modern .NET framework for building Telegram Bots using simple and concise syntax inspired by ASP.NET Core Minimal APIs.","archived":false,"fork":false,"pushed_at":"2025-01-05T17:44:29.000Z","size":320,"stargazers_count":33,"open_issues_count":0,"forks_count":4,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-11-09T06:19:51.799Z","etag":null,"topics":["bot","dotnet","framework","telegram"],"latest_commit_sha":null,"homepage":"https://k-paul-acct.github.io/minimal-telegram-bot/","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/k-paul-acct.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":".github/CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":".github/CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-02-26T21:36:48.000Z","updated_at":"2025-10-16T14:13:51.000Z","dependencies_parsed_at":"2024-11-04T07:25:45.776Z","dependency_job_id":"8d20cd19-b484-42bf-8687-ac512bebf616","html_url":"https://github.com/k-paul-acct/minimal-telegram-bot","commit_stats":null,"previous_names":["k-paul-acct/telegram-bot-framework"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/k-paul-acct/minimal-telegram-bot","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/k-paul-acct%2Fminimal-telegram-bot","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/k-paul-acct%2Fminimal-telegram-bot/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/k-paul-acct%2Fminimal-telegram-bot/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/k-paul-acct%2Fminimal-telegram-bot/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/k-paul-acct","download_url":"https://codeload.github.com/k-paul-acct/minimal-telegram-bot/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/k-paul-acct%2Fminimal-telegram-bot/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":284767943,"owners_count":27060132,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-11-16T02:00:05.974Z","response_time":65,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bot","dotnet","framework","telegram"],"created_at":"2025-11-16T20:04:38.779Z","updated_at":"2025-11-16T20:04:39.358Z","avatar_url":"https://github.com/k-paul-acct.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cimg alt=\"\" src=\"./logo/package-icon.png\" width=\"96\"/\u003e\n\n# Welcome to the Minimal Telegram Bot project\n\n[![latest version](https://img.shields.io/nuget/v/MinimalTelegramBot)](https://www.nuget.org/packages/MinimalTelegramBot)\n[![Telegram Bot API](https://img.shields.io/badge/Telegram_Bot_API-8.2-blue)](https://core.telegram.org/bots/api#january-1-2025)\n\nMinimal Telegram Bot is a modern .NET framework for building Telegram Bots using simple and concise syntax inspired by\nASP.NET Core Minimal APIs.\n\nJoin the project's [Telegram channel](https://t.me/minimal_telegram_bot_channel) to stay tuned or ask for help in the\nproject's [Telegram group](https://t.me/minimal_telegram_bot_group).\n\n## Intentions\nThe development of a Minimal Telegram Bot project was started as an attempt to solve the problem with the lack of a\nsingle convenient solution for Telegram bot development on the .NET platform.\n\nA great community-approved Telegram Bot API wrapper already exists in .NET. However, creating bots for more complex\ncases using only a bare-bones wrapper soon becomes cumbersome and unsupportable. Existing solutions that solve such a\nproblem were made very focused on the specific author's problem and not fit well to wider scope of demands,\nand some of the solutions are abandoned as of today.\n\nWith some experience in development and other languages, I developed a proof of concept where writing\nbots was made way easier, hiding unnecessary boilerplate details. The developer and consumer of this project now only\nneed to focus on their tasks, write the code that is needed here and now to solve the business tasks and not worry\nabout the rest.\n\n## Considerations\nDetailed documentation is still in progress with framework's public APIs so some changes are possible in the future.\nThe project roadmap includes considerations for changing the policy of support and updates as well as the communication\npractices with the audience if it gains enough audience.\n\nAt the moment, this framework already has enough features and customization mechanisms to use in real projects.\nFuture plans are to create more public API methods for user convenience, tailor the API and provide full documentation.\n\n## Features\n- Support for the latest Telegram Bot API version, receiving fast updates thanks to\n  [Telegram.Bot](https://github.com/TelegramBots/Telegram.Bot), the most popular .NET Client for\n  [Telegram Bot API](https://core.telegram.org/bots/api)\n\n### Framework features\n- Fully parallel Telegram updates handling\n- Pipeline ([middleware](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware)) building just like in\n  ASP.NET Core\n- Powerful and customizable updates handling and filtering similar to\n  [ASP.NET Core Minimal APIs](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis)\n- Integration of [dependency injection](https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection),\n  configuration and logging from ASP.NET Core\n\n### Extensions\n- Support for the Finite State Machine concept for Telegram bots using StateMachine extension packages\n  with various persistence models and extendable configuration.\n- Built-in bot localization features using Localization extension packages\n\n### Getting updates from Telegram\n- Support [getting updates](https://core.telegram.org/bots/faq#how-do-i-get-updates) via both webhook and polling\n- Provides direct [responses](https://core.telegram.org/bots/faq#how-can-i-make-requests-in-response-to-updates) to\n  webhook requests\n\n## Getting started\n### Prerequisites\nThis project is using .NET 8 for now, so be sure to [install](https://dotnet.microsoft.com/en-us/download/dotnet/8.0)\nthe appropriate version of .NET, and that's all you need to start developing. Note that this does not restrict you\nfrom using newer versions of .NET.\n\n### New project\nStart by creating an \"Empty\" ASP.NET Core application using the command line:\n```sh\ndotnet new web -n MyBot -f net9.0\n```\nOr create a new ASP.NET Core web application in your IDE, and choose \"Empty\" for the project template.\n\n### Installation\nMinimal Telegram Bot library is available on [NuGet](https://www.nuget.org/packages/MinimalTelegramBot) so you can\ninstall the library using NuGet package manager in your IDE:\n```sh\ndotnet add package MinimalTelegramBot\n```\nIn addition, you can add some extension packages that provide Localization and State Machine features:\n```sh\ndotnet add package MinimalTelegramBot.Localization\ndotnet add package MinimalTelegramBot.StateMachine\n```\n\n## Usage\n### Basic setup\nIn your `Program.cs` you can use following basic setup:\n```csharp\nusing MinimalTelegramBot.Builder;\nusing MinimalTelegramBot.Handling;\n\nvar builder = BotApplication.CreateBuilder(args);\nvar bot = builder.Build();\n\nbot.HandleCommand(\"/start\", () =\u003e \"Hello, World!\");\n\nbot.Run();\n```\nIn the code above we are creating `BotApplication` using builder just like in web applications. When the `bot` instance\nare set up and ready for handling configuration, we call `HandleCommand()` with specified `/start` command and return\n`Hello, World!` message as a result.\n\nBy default, [polling](https://core.telegram.org/bots/faq#how-do-i-get-updates) method for getting updates from Telegram\nis used because it's faster to start development with polling method and polling requires less effort to configure.\nBot token is specified in configuration with `\"BotToken\"` key. For local development you can set your bot token using\n[dotnet user-secrets](https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets) tool:\n```sh\ndotnet user-secrets init\ndotnet user-secrets set \"BotToken\" \"your bot token\"\n```\nIn other environments you can use `.env` files or just set bot token in `appsettings.json`:\n```json\n{\n  \"Logging\": {\n    \"LogLevel\": {\n      \"Default\": \"Information\",\n      \"Microsoft.AspNetCore\": \"Warning\"\n    }\n  },\n  \"AllowedHosts\": \"*\",\n  \"BotToken\": \"your bot token\"\n}\n```\n\u003e Ensure that your bot token is not included in version control to prevent unauthorized access to your bot.\n\nIf you have any trouble with telegram bot token or [BotFather](https://t.me/botfather), read the\n[official tutorial](https://core.telegram.org/bots/tutorial#obtain-your-bot-token).\n\nWhen all configuration is complete, just run program with `dotnet run` or via IDE's interface and test your bot.\n\n## Advanced handling examples\n### Localizer usage\nLocalization is essential when creating bots for users across multiple regions.\nHere, the localizer service allows you to retrieve messages dynamically based on the user's locale.\nHow to add localizer in bot app with single locale before building the bot app:\n```csharp\nbuilder.Services.AddSingleLocale(\n    new Locale(\"en\"),\n    locale =\u003e locale.EnrichFromFile(\"Localization/en.yaml\"));\n```\nHow to use localizer services after building bot app:\n```csharp\nbot.UseLocalization();\n```\nTo use different languages, you need to implement `IUserLocaleProvider` interface,\nin that way you provide the context for resolving user's locale.\nYou can find more details about adding localization and different languages in the\n[code samples](./src/UsageExample/Program.cs).\n\nThe command below uses localizer to respond to the `/start` command with a `\"HelloText\"` message retrieved and\na dynamically generated keyboard based on the user's locale from method `MenuKeyboard()`.\n[See more](https://telegrambots.github.io/book/2/reply-markup.html) on keyboards.\n```csharp\nbot.HandleCommand(\"/start\", (ILocalizer localizer) =\u003e\n{\n    var helloText = localizer[\"HelloText\"];\n    var keyboard = MenuKeyboard(localizer);\n    return Results.Message(helloText, keyboard);\n});\n```\n\n### Callback data handling\nThis handler handles callback data `\"Photo\"` and responses with photo and description.\n\nHere, general `Handle()` method is used with `FilterCallbackData()` filter.\n\nNote, `wwwroot` folder comes from ASP.NET Core static file serving.\n```csharp\nbot.Handle(() =\u003e\n        Results.Photo(\"wwwroot/cat.jpeg\", \"Little cat\"))\n    .FilterCallbackData(x =\u003e x == \"Photo\");\n```\n\n### Parameter parsing\nThis example handles the `/add` command by parsing user input into `AddCommandModel` and responding with a sum\nof two parsed numbers or error message, depending on the input's validity.\nExample: `/add 1.3 5.7` outputs `7`.\nAttribute `[UseFormatProvider]` allows culture-specific number parsing like comma- or point-based decimal separator.\n```csharp\nbot.HandleCommand(\"/add\", (\n    [UseFormatProvider] AddCommandModel model,\n    ILocalizer localizer) =\u003e\n{\n    return model.IsError\n        ? localizer[\"ParsingError\"]\n        : localizer[\"AddCommandTemplate\", model.Result];\n});\n```\nHere example of `AddCommandModel` class, note that implementing an interface `ICommandParser`.\nThis interface is essential for ensuring that command will be parsed.\n```csharp\npublic class AddCommandModel : ICommandParser\u003cAddCommandModel\u003e\n{\n    public double A { get; set; }\n    public double B { get; set; }\n    public bool IsError { get; set; }\n    public double Result =\u003e A + B;\n\n    public static AddCommandModel Parse(\n        string command,\n        IFormatProvider? formatProvider = null)\n    {\n        var parts = command.Split(' ');\n\n        if (parts.Length \u003c 3 ||\n            !double.TryParse(parts[1], formatProvider, out var a) ||\n            !double.TryParse(parts[2], formatProvider, out var b))\n        {\n            return new AddCommandModel { IsError = true, };\n        }\n\n        return new AddCommandModel { A = a, B = b, };\n    }\n}\n```\nCallback data parsing is also supported using a similar API.\n\n### Dependency injection and keyed services\nIn this example, we handle commands that retrieve data from a specific service registered in DI container with a key.\nThe `NameService` is used here to provide different names depending on the command.\nBy using the `FromKeyedServices` attribute, we dynamically inject the appropriate service into the handler based on the\ncommand.\n\n`FromKeyedServices`\n[attribute](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection#keyed-services) allows you\nto dynamically inject services registered with specific keys, such as `FirstName`, or `LastName` in this example.\n\nStandard dependency injection techniques are also supported, handling context is a scope.\n```csharp\nbot.HandleCommand(\"/firstname\",\n    ([FromKeyedServices(\"FirstName\")] NameService nameService) =\u003e\n        nameService.Name);\n\nbot.HandleCommand(\"/lastname\",\n    ([FromKeyedServices(\"LastName\")] NameService nameService) =\u003e\n        nameService.Name);\n```\n\n### Async weather service example\nThis example demonstrates how to handle complex interactions asynchronously,\nusing a weather service to fetch real-time data.\n\nHere, general `Handle()` method is used with `FilterCallbackData()` filter.\n\nNote, here `string messageText` directly injected from incoming message, and\nhandler catches all messages by using `FilterUpdateType(UpdateType.Message)` filter.\n```csharp\nbot.Handle(async (string messageText, WeatherService weatherService) =\u003e\n{\n    var weather = await weatherService.GetWeather();\n    var keyboard = new InlineKeyboardMarkup(InlineKeyboardButton.WithCallbackData(\"Hello\", \"Hello\"));\n    return ($\"Hello, {messageText}, weather is {weather}\", keyboard);\n}).FilterUpdateType(UpdateType.Message);\n```\n\n### Error handling\nThis example shows default error handling. Command `/throw` randomly decides to throw an exception\nand default error handling mechanism gracefully caches an exception and logs it preventing bot app from unexpected\nshutdown. If no error occurs, the bot responds with message 'Ok'.\n```csharp\nbot.HandleCommand(\"/throw\", () =\u003e\n{\n    if (Random.Shared.Next(0, 2) == 0)\n    {\n        throw new Exception(\"Error\");\n    }\n\n    return Results.Message(\"Ok\");\n});\n```\nIf you need custom error handling, you can wrap bot app execution pipeline (middleware) in your own middleware\nlike this:\n```csharp\nbot.Use(async (context, next) =\u003e\n{\n    try\n    {\n        await next(context);\n    }\n    catch (Exception ex)\n    {\n        // Custom exception handling.\n    }\n});\n```\nEnsure that this middleware is placed before other handlers in the pipeline.\n\n## More advanced use-cases\nIf you need examples of more complex use-cases and features, you can check code example\n[here](https://github.com/k-paul-acct/minimal-telegram-bot/blob/main/src/UsageExample.Nuget/Program.cs) or ask any\nquestion in [Telegram group](https://t.me/minimal_telegram_bot_group).\n\n## Additional resources\nCheck out some resources that can help you develop good bots:\n- [Code samples](./src)\n- Localization extension [NuGet package](https://www.nuget.org/packages/MinimalTelegramBot.Localization)\n- StateMachine extension [NuGet package](https://www.nuget.org/packages/MinimalTelegramBot.StateMachine)\n- Telegram.Bot API wrapper [GitHub](https://github.com/TelegramBots/Telegram.Bot)\n- Telegram.Bot API wrapper [documentation](https://telegrambots.github.io/book/)\n- Telegram.Bot [group](https://t.me/joinchat/B35YY0QbLfd034CFnvCtCA)\n- Project's [Telegram channel](https://t.me/minimal_telegram_bot_channel)\n- Project's [Telegram group](https://t.me/minimal_telegram_bot_group)\n\n## Updates\n\nCurrently, the best way to be up to date is using the latest NuGet package versions.\nThere are plans for major feature updates or breaking changes announcements in\n[Telegram channel](https://t.me/minimal_telegram_bot_channel) but keep in mind that the project is still under active\ndevelopment and is in its pre-1.0.0 version stage.\n\n## Contributing and feedback\n\nI welcome community pull requests for bug fixes, enhancements, and documentation.\nSee [How to contribute](./.github/CONTRIBUTING.md) for more information.\n\nIf you have a specific question about using this project, I encourage you to ask it on\n[Telegram group](https://t.me/minimal_telegram_bot_group).\nIf you encounter a bug or would like to request a feature, submit a GitHub issue.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fk-paul-acct%2Fminimal-telegram-bot","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fk-paul-acct%2Fminimal-telegram-bot","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fk-paul-acct%2Fminimal-telegram-bot/lists"}