-
Notifications
You must be signed in to change notification settings - Fork 0
How to create a command?
tsziming edited this page Mar 7, 2022
·
1 revision
In TelegramBotBoilerplate commands are the classes that inherited from Command
type.
Command is a Listener
child, so it is also stored in "Listeners" folder:
- Create a class named with "Command" pattern and place it in "Listeners" folder or its subfolders:
namespace MyTelegramBot.Listeners {
public class StartCommand : Command {}
}
- Add the constructor with
Bot
parameter and its triggers (Names
property) array:
namespace MyTelegramBot.Listeners {
public class StartCommand : Command {
public StartCommand(Bot bot): base(bot) {
Names = new string[]{"/start", "/starting", "!start"};
}
}
}
- Override
Run()
orRunAsync()
methods where you put your business logic:
namespace MyTelegramBot.Listeners {
public class StartCommand : Command {
public StartCommand(Bot bot): base(bot) {
Names = new string[]{"/start", "/starting", "!start"};
}
public override string Run(Context context, CancellationToken cancellationToken)
{
// Here you put your business logic
return "Welcome! Press /help to see my functions.";
}
}
}
- Add the command object to bot listeners array in
/Source/Bot.cs
constructor and passthis
as a parameter:
...
public Bot()
{
Listeners = new List<Listener> {
new StartCommand(this),
new HelpCommand(this),
...
// TODO: Put more commands and other listeners.
};
}
...
- Complete! Now you can start your bot and test your new command!