-
Notifications
You must be signed in to change notification settings - Fork 0
How to create a custom listener?
tsziming edited this page Mar 7, 2022
·
1 revision
In TelegramBoilerplate custom listeners are inherited from Listener
type.
Listeners are stored in "Listeners" folder:
- Create a class named with "Listener" pattern and place it in "Listeners" folder or its subfolders:
namespace MyTelegramBot.Listeners {
public class MessageListener : Listener {}
}
- Add the constructor with
Bot
parameter:
namespace MyTelegramBot.Listeners {
public class MessageListener : Listener
{
public MessageListener(Bot bot):base(bot) {}
}
}
- Override
Validate()
method where you put your listener filters:
namespace MyTelegramBot.Listeners {
public class MessageListener : Listener
{
public MessageListener(Bot bot):base(bot) {}
public override bool Validate(Context context, CancellationToken cancellationToken)
{
if (context.Update.Type != UpdateType.Message) // listener filters all non-message updates
return false;
return true;
}
}
}
- Override
Handler()
method where you put your business logic:
namespace MyTelegramBot.Listeners {
public class MessageListener : Listener
{
public MessageListener(Bot bot):base(bot) {}
public override bool Validate(Context context, CancellationToken cancellationToken)
{
if (context.Update.Type != UpdateType.Message)
return false;
return true;
}
public override async Task Handler(Context context, CancellationToken cancellationToken)
{
// (Business logic) Listener increments message count for every call
var session = await GetSession(context.Update.Message);
session.Messages++;
await SaveChanges();
}
}
}
- Add the listener object to bot listeners array in
/Source/Bot.cs
constructor and passthis
as a parameter:
...
public Bot()
{
Listeners = new List<Listener> {
...
new MessageListener(this)
// TODO: Put more commands and other listeners.
};
}
...
- Complete! Now you can start your bot and test your new listener!