A package for effortlessly bootstrapping Telegram Bots in .NET WebAPI projects.
Supports both Polling and WebHook workflows with a unified interface and minimal configuration.
IServiceCollection.TgBotPlayUpdateHandlerBase, handling only the events you care about.Install the NuGet package:
dotnet add package TgBotPlay.WebAPI
Create a class that inherits from TgBotPlayUpdateHandlerBase and override only the update handlers you need:
public class MyBotHandler : TgBotPlayUpdateHandlerBase
{
public MyBotHandler(ILogger<MyBotHandler> logger) : base(logger) { }
protected async Task OnMessage(Message message)
{
// Handle incoming messages
}
protected async Task OnCallbackQuery(CallbackQuery query)
{
// Handle callback queries
}
}
Available handler methods include:
OnMessage(Message message)OnEditedMessage(Message message)OnChannelPost(Message message)OnEditedChannelPost(Message message)OnBusinessConnection(BusinessConnection connection)OnBusinessMessage(BusinessMessage message)OnEditedBusinessMessage(BusinessMessage message)OnDeletedBusinessMessages(DeletedBusinessMessages messages)OnMessageReaction(MessageReaction reaction)OnMessageReactionCount(MessageReactionCount reactionCount)OnInlineQuery(InlineQuery query)Program.cs or Startup.csbuilder.Services.AddTgBotPlay<MyBotHandler>(options => options
.WithToken("telegram bot token")
.AsPollingClient()
// Customize other options as needed
);
TgBotPlay automatically sets up controller endpoints for receiving updates:
POST TgBotPlay/ — Main webhook endpoint for Telegram updatesPOST TgBotPlay/HookUp — Start webhook servicePOST TgBotPlay/HookDown — Stop webhook serviceThe controller route and endpoint name can be customized using WithController(...) in options (Defaults to TgBotPlay).
.AsPollingClient().AsWebHookClient("<host name(ex. https://xyz.com)>")No other code changes are required!
WithController(string name, string template) — Customize controller name and route template.WithPollingInterval(double seconds = 5d) — Set polling interval in seconds.WithWebHookRefreshInterval(double minutes = 60d) — Set how often webhook is refreshed.SetDropPendingUpdates(bool dropPendingChanges = false) — Set how pending messages are processed when bot starts.You can simply add TgBotPlay Health Checks like this in your Program.cs or Startup.cs:
builder.Services.AddHealthChecks()
.AddTgBotPlayHealth();
builder.Services.AddTgBotPlay<MyBotHandler>(options => options
.WithToken("telegram bot token")
.AsWebHookClient("host name(ex. https://xyz.com)")
.WithController("TgBotPlay", "TgBotPlay/[action]")
.WithWebHookRefreshInterval(30) //minuets
);
builder.Services.AddTgBotPlay<MyBotHandler>(options => options
.WithToken("telegram bot token")
.AsPollingClient()
.WithPollingInterval(5) //seconds
);
main branch of This Repo(https://github.com/IPdotSetAF/TgBotPlay.WebAPI).