| search |
|
|---|
Hello! If you want to know, how to code Telegram Bots on Java, you are on the right way!
Bot API is based on HTTP-requests, but in this book I will use Rubenlagus' library for Java.
You can install TelegramBots library with different methods:
- Using Maven:
<dependency>
<groupId>org.telegram</groupId>
<artifactId>telegrambots</artifactId>
<version>Latest</version>
</dependency>
In this tutorial I will use next machines:
- Ubuntu 16.04 Server with 1GB of RAM
- My home Windows 10 laptop with IntelliJ Idea pre-installed
Well, enough for words. Let's get down to buisness. In this lesson we will write simple bot that echoes everything we sent to him. Now, open IntelliJ Idea and create a new project. You can call it whatever you want. Then, dont forget to install TelegramBots library with preffered method. I think, that it is most easy to just download .jar from here
Now, when you are in the project, create files MyAmazingBot.java and Main.java within the src directory. Open MyAmazingBot.java and lets write our actual bot:
Remember! The class must extends
TelegramLongPollingBotand implement necessary methods
importorg.telegram.telegrambots.api.methods.send.SendMessage;
importorg.telegram.telegrambots.api.objects.Update;
importorg.telegram.telegrambots.bots.TelegramLongPollingBot;
importorg.telegram.telegrambots.exceptions.TelegramApiException;
publicclassMyAmazingBotextendsTelegramLongPollingBot {
@OverridepublicvoidonUpdateReceived(Updateupdate) {
// TODO
}
@OverridepublicStringgetBotUsername() {
// TODOreturnnull;
}
@OverridepublicStringgetBotToken() {
// TODOreturnnull;
}
}As you can understand, getBotUsername() and getBotToken() must return bot's username and bot's token, obtained from @BotFather. So now, our MyAmazingBot.java file will look like this:
importorg.telegram.telegrambots.api.methods.send.SendMessage;
importorg.telegram.telegrambots.api.objects.Update;
importorg.telegram.telegrambots.bots.TelegramLongPollingBot;
importorg.telegram.telegrambots.exceptions.TelegramApiException;
publicclassMyAmazingBotextendsTelegramLongPollingBot {
@OverridepublicvoidonUpdateReceived(Updateupdate) {
// TODO
}
@OverridepublicStringgetBotUsername() {
// Return bot username// If bot username is @MyAmazingBot, it must return 'MyAmazingBot'return"MyAmazingBot";
}
@OverridepublicStringgetBotToken() {
// Return bot token from BotFatherreturn"12345:qwertyuiopASDGFHKMK";
}
}Now, let's move on to the logic of our bot. As I said before, we want him to reply every text we send to him. onUpdateReceived(Update update) method is for us. When an update recieved, it will call this method.
@OverridepublicvoidonUpdateReceived(Updateupdate) {
// We check if the update has a message and the message has textif (update.hasMessage() && update.getMessage().hasText()) {
// Set variablesStringmessage_text = update.getMessage().getText();
longchat_id = update.getMessage().getChatId();
SendMessagemessage = newSendMessage() // Create a message object object
.setChatId(chat_id)
.setText(message_text);
try {
execute(message); // Sending our message object to user
} catch (TelegramApiExceptione) {
e.printStackTrace();
}
}
}Good! But how do I run the bot? Well, its a good question. Lets save that file and open Main.java. This file will instantiate TelegramBotsApi and register our new bot. It will look like this:
importorg.telegram.telegrambots.ApiContextInitializer;
importorg.telegram.telegrambots.TelegramBotsApi;
importorg.telegram.telegrambots.exceptions.TelegramApiException;
publicclassMain {
publicstaticvoidmain(String[] args) {
// TODO Initialize Api Context// TODO Instantiate Telegram Bots API// TODO Register our bot
}
}Now, lets initialize Api Context
importorg.telegram.telegrambots.ApiContextInitializer;
importorg.telegram.telegrambots.TelegramBotsApi;
importorg.telegram.telegrambots.exceptions.TelegramApiException;
publicclassMain {
publicstaticvoidmain(String[] args) {
// Initialize Api ContextApiContextInitializer.init();
// TODO Instantiate Telegram Bots API// TODO Register our bot
}
}Instantiate Telegram Bots API:
importorg.telegram.telegrambots.ApiContextInitializer;
importorg.telegram.telegrambots.TelegramBotsApi;
importorg.telegram.telegrambots.exceptions.TelegramApiException;
publicclassMain {
publicstaticvoidmain(String[] args) {
// Initialize Api ContextApiContextInitializer.init();
// Instantiate Telegram Bots APITelegramBotsApibotsApi = newTelegramBotsApi();
// TODO Register our bot
}
}And register our bot:
importorg.telegram.telegrambots.ApiContextInitializer;
importorg.telegram.telegrambots.TelegramBotsApi;
importorg.telegram.telegrambots.exceptions.TelegramApiException;
publicclassMain {
publicstaticvoidmain(String[] args) {
// Initialize Api ContextApiContextInitializer.init();
// Instantiate Telegram Bots APITelegramBotsApibotsApi = newTelegramBotsApi();
// Register our bottry {
botsApi.registerBot(newMyAmazingBot());
} catch (TelegramApiExceptione) {
e.printStackTrace();
}
}
}Here is all our files:
src/Main.java
importorg.telegram.telegrambots.ApiContextInitializer;
importorg.telegram.telegrambots.TelegramBotsApi;
importorg.telegram.telegrambots.exceptions.TelegramApiException;
publicclassMain {
publicstaticvoidmain(String[] args) {
// Initialize Api ContextApiContextInitializer.init();
// Instantiate Telegram Bots APITelegramBotsApibotsApi = newTelegramBotsApi();
// Register our bottry {
botsApi.registerBot(newMyAmazingBot());
} catch (TelegramApiExceptione) {
e.printStackTrace();
}
}
}
src/MyAmazingBot.java
importorg.telegram.telegrambots.api.methods.send.SendMessage;
importorg.telegram.telegrambots.api.objects.Update;
importorg.telegram.telegrambots.bots.TelegramLongPollingBot;
importorg.telegram.telegrambots.exceptions.TelegramApiException;
publicclassMyAmazingBotextendsTelegramLongPollingBot {
@OverridepublicvoidonUpdateReceived(Updateupdate) {
// We check if the update has a message and the message has textif (update.hasMessage() && update.getMessage().hasText()) {
// Set variablesStringmessage_text = update.getMessage().getText();
longchat_id = update.getMessage().getChatId();
SendMessagemessage = newSendMessage() // Create a message object object
.setChatId(chat_id)
.setText(message_text);
try {
execute(message); // Sending our message object to user
} catch (TelegramApiExceptione) {
e.printStackTrace();
}
}
}
@OverridepublicStringgetBotUsername() {
// Return bot username// If bot username is @MyAmazingBot, it must return 'MyAmazingBot'return"MyAmazingBot";
}
@OverridepublicStringgetBotToken() {
// Return bot token from BotFatherreturn"12345:qwertyuiopASDGFHKMK";
}
}Well done! Now we can pack our project into runnable .jar file and run it on our computer/server!
You can find all sources to this lesson in GitHub repository.
java -jar MyAmazingBot.jar
Now we can see our bot running:
Well, thats all for now. Hope to see you soon!:)
