
Security News
npm ‘is’ Package Hijacked in Expanding Supply Chain Attack
The ongoing npm phishing campaign escalates as attackers hijack the popular 'is' package, embedding malware in multiple versions.
TelegramUpdater is feature-rich super customizable framework library for building telegram bots in c#.
ReadNext
.Update
and inner update, Updater
itself and more. This can enable you to have,
use or create a lot of extension methods on them.Let's get started with this package and learn how to implement some of above features.
The package is available inside Nuget.
TelegramUpdater uses Telegram.Bot: .NET Client for Telegram Bot API package as an C# wrapper over Telegram bot api.
Documentations can be found at Here.
A very minimal yet working example of TelegramUpdater usage is something like this.
using TelegramUpdater;
using TelegramUpdater.UpdateContainer;
using TelegramUpdater.UpdateContainer.UpdateContainers;
var updater = new Updater("YOUR_BOT_TOKEN")
.AddDefaultExceptionHandler()
.QuickStartCommandReply("Hello there!");
await updater.Start();
This setups Updater
with your bot token, adds a default exception handler that logs errors,
a (singleton) update handler that works on /start
command on private chats
and finally starts up the updater.
Updater can automatically collect your handlers as statics methods like example below
var updater = new Updater("YOUR_BOT_TOKEN")
.AddDefaultExceptionHandler()
.CollectHandlingCallbacks();
await updater.Start();
partial class Program
{
[Command("start"), Private]
[HandlerCallback(UpdateType.Message)]
public static async Task Start(IContainer<Message> container)
{
await container.Response("Hello World");
}
}
This should work the same as before. (Filters are applied as attributes)
[!WARNING] If you add scoped handlers but your
Updater
without having access to the DI (IServiceProvider
), the updater will still try to make an instance of you scoped handler if its filters passes, by its parameterless constructor.
If your project is a worker service or anything that has HostBuilder and DI (dependency injection) in it, you can setup updater like this.
var builder = Host.CreateApplicationBuilder(args);
// this will collect updater options like BotToken, AllowedUpdates and ...
// from configuration section "TelegramUpdater". in this example from appsettings.json
builder.AddTelegramUpdater(
(builder) => builder
// Modify the actual updater
.Execute(updater => updater
// Collects static methods marked with `HandlerCallback` attribute.
.CollectHandlingCallbacks())
// Collect scoped handlers located for example at UpdateHandlers/Messages for messages.
.CollectHandlers()
.AddDefaultExceptionHandler());
var host = builder.Build();
await host.RunAsync();
The configuration are automatically figured out if they're exists somewhere like in appsettings.json
.
You can add them like this:
{
...
"TelegramUpdater": {
"BotToken": "",
"AllowedUpdates": [ "Message", "CallbackQuery" ]
},
...
}
[!NOTE] Updater can and will figure out
AllowedUpdates
if not specified by looking into you registered handlers.
For singleton handlers it's just like before, but if your going to use scoped handlers, put them into the right place as mentioned in the example.
For example create a file at UpdateHandlers/Messages
like UpdateHandlers/Messages/Start.cs
The Start.cs
should look like this:
using TelegramUpdater.FilterAttributes.Attributes;
using TelegramUpdater.UpdateContainer;
using TelegramUpdater.UpdateContainer.UpdateContainers;
using TelegramUpdater.UpdateHandlers.Scoped.ReadyToUse;
namespace GettingStarted.UpdateHandlers.Messages;
[Command("start"), Private]
internal class Start : MessageHandler
{
protected override async Task HandleAsync(MessageContainer container)
{
await container.Response("Hello World");
}
}
Watch out for name space where the MessageHandler
came from, it must be ...Scoped.ReadyToUse
not Singleton
.
And the filters are now applied on class.
The handler will be automatically collected by the updater if you call CollectHandlers
.
An now you can use your IFancyService
which is available in DI right into Start
's constructor.
Instead of using HandleAsync(MessageContainer container)
, you use a more contextual overload like this:
HandleAsync(
MessageContainer input,
IServiceScope? scope,
CancellationToken cancellationToken)
But remember not to override both! (The one with less parameters will be ignored).
Instead using scoped handlers as classes you can also create your handlers Minimally!
// This is a minimal handler
updater.Handle(
UpdateType.Message,
async (IContainer<Message> container, IFancyService service) =>
{
// Do something with the container and service
},
ReadyFilters.OnCommand("command"))
Controller handlers are scoped handlers where you're not restricted to a single HandleAsync
method.
This enables you to reuse filters and injected services for different but related handling logics.
If you want a method to recognize as a controller's action, you need to add the HandlerAction
attribute to it.
You can apply filters to the action methods as well as the controller it self to further filter the action methods.
If you need an extra service inside your action method, you need to mark them with
[ResolveService]
attribute (Not to mess with big boy's [FromServices]
). This will resolve the service from DI and inject it into your action method.
You can have access to the IContainer<T>
inside your actions if needed.
[Command("about")]
internal class About(IFancyOverallService overallService) : MessageControllerHandler
{
[HandlerAction]
[ChatType(ChatTypeFlags.Private)]
public async Task Private([ResolveService] IFancyService service)
{
// Do something with your service or overallService.
await Response($"This's what you need to know about me: ");
}
[HandlerAction]
[ChatType(ChatTypeFlags.Group | ChatTypeFlags.SuperGroup)]
public async Task Group(IContainer<Message> container)
{
// Do something with your overallService.
await container.Response(
"Theses are private talks!",
replyMarkup: new InlineKeyboardMarkup(aboutButton));
}
}
[!TIP] There are other attributes like
[ExtraData]
,[CommandArg]
or[RegexMatchingGroup]
that can be used on actions parameter to have access to extra data based on filters (See PlayGround About, Update or InsertSeen handlers).
[!NOTE] Typically Methods like
updater.Handle(...)
refers to a singleton handler andupdater.AddHandler(...)
orupdater.Add...Handler
refer to an scoped handler. Minimal handlers are actually singleton handlers but you can use DI inside them.
[Command("about"), Private]
[HandlerCallback(UpdateType.Message)]
public static async Task AboutCommand(IContainer<Message> container)
{
var message = await container.Response("Wanna know more about me?! Answer right now!",
replyMarkup: new InlineKeyboardMarkup([[
InlineKeyboardButton.WithCallbackData("Yes"),
InlineKeyboardButton.WithCallbackData("No")]]));
// Wait for short coming answer right here
var answer = await container.ChannelButtonClick(TimeSpan.FromSeconds(5), new(@"Yes|No"));
switch (answer)
{
case { Update.Data: { } data }:
{
// User did answer
if (data == "Yes")
await answer.Edit("Well me too :)");
else
await answer.Edit("Traitor!");
await answer.Answer();
break;
}
default:
{
// Likely timed out.
await message.Edit("Slow");
break;
}
}
}
Extension methods return containerized results.
[!CAUTION] The package is still in preview and the API may change in the future (for sure). It's actually changing right now, so be careful when using it.
Examples inside /Examples folder are up to date with latest package changes and are good start points to begin.
IServiceCollection
, IConfiguration
s can be used by the updater (This's preferred to the console app as you can use scoped handlers)The package has also some extension packages:
If you think this package worths it, then help and contribute. It will be always appreciated!
FAQs
Unknown package
We found that telegramupdater demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
The ongoing npm phishing campaign escalates as attackers hijack the popular 'is' package, embedding malware in multiple versions.
Security News
A critical flaw in the popular npm form-data package could allow HTTP parameter pollution, affecting millions of projects until patched versions are adopted.
Security News
Bun 1.2.19 introduces isolated installs for smoother monorepo workflows, along with performance boosts, new tooling, and key compatibility fixes.