A Java library that simplifies the creation of Telegram Bots
- Clone this repository with
git clone https://github.com/paxolo/croissant.git
- Build it with
mvn clean install
- Add the following code to your
pom.xml
:
<dependency>
<groupId>me.stefano</groupId>
<artifactId>croissant</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
Croissant uses annotations to simplify the creation of commands. In this example, we will create a simple 'hello' command that makes the bot print 'Hi there!' to the console when someone invokes it.
The @Command
annotation is used to specify the following properties:
- label, which must be specified
- aliases (optional), which defaults to an empty array of strings
- description (optional), which defaults to "Not available."
@Command("mycommand")
// @Command(value = "mycommand", aliases = { "mycmd" })
// @Command(value = "mycommand", description = "Example command.")
// @Command(value = "mycommand", aliases = { "mycmd" }, description = "Example command.")
public static class MyCommand implements CommandExecutor {
@Override
public void execute(Update update) {
System.out.println("Hi there!");
}
}
In order to tell the bot how to handle our commands, we need to create an instance of Croissant and use it to register them. To do that, you will need to edit the Bot class as follows:
- override the
onRegister()
method - create an instance of Croissant
- inside the
onUpdateReceived()
method, call thehandle()
method provided by the library
public class MyBot extends TelegramLongPollingBot {
private Croissant croissant;
// ...
@Override
public void onRegister() {
this.croissant = new Croissant();
}
@Override
public void onUpdateReceived(Update update) {
this.croissant.handle(update);
}
// ...
}
You can use the registerCommand()
method after creating an instance of the library to allow Croissant to handle commands.
public class MyBot extends TelegramLongPollingBot {
// ...
@Override
public void onRegister() {
this.croissant = new Croissant();
this.croissant.registerCommand(new MyCommand());
}
// ...
}
Some commands just don't belong in private chats, while others don't belong in groups.
The @CommandRetention
annotation allows you to specify the context in which a command is supposed to be used.
By default, commands can be used in both private and group chats. Let's edit the 'hello' command we created earlier so that it can only be executed in private chats.
@Command("mycommand")
@CommandRetention(CommandPolicy.PRIVATE)
// @CommandRetention(CommandPolicy.GROUPS)
public static class MyCommand implements CommandExecutor {
@Override
public void execute(Update update) {
System.out.println("Hi there!");
}
}