Hi all! At some point in your studies, you want to move from solving problems to creating real projects that will form the basis of your portfolio. When I started my internship (which I highly recommend to everyone), I received an offer to write a telegram bot as a freelancer. Due to my little knowledge, I wrote a fairly simple bot ( the last commit before migrating to Spring ), which contained three threads:
and Telegram API : The TelegramBots-Spring-Boot-Starter library includes Spring Boot and Telegram API. Using it allows us to declare a bot in our code in a fairly simple way, and Spring itself will create the Bean and activate the bot. If you are interested in what is happening under the hood at this moment, then look at the library sources (in the development environment or on Github ). We also add compilation parameters: Don’t forget to update all dependencies after filling out the pom! Let's create two classes - App and Bot, as well as an application.yaml file in the resources folder. The structure of my project looks like this: At this stage, let’s add the credentials of our bot to application.yaml:
- message receiving thread;
- message sending thread;
- event scheduling thread (it checked for scheduled messages and updated cached data from JSON).
bot:
name: JavaRushTelegramBot
token: 22313424:AAF4gck4D8gDhq68E7k0UH8vlyQADhxQhYo
Hierarchical notation allows us to avoid repetition (bot.name, bot.token) and improve readability. If you haven’t created a bot yet, you can create one by following the official instructions . If you don’t want to display the bot’s credentials in application.yaml (which is correct), use environment variables when deploying:
bot:
name: ${BOT_NAME}
token: ${BOT_TOKEN}
Filling out the Bot class:
package com.whiskels.telegram.bot;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
// Аннотация @Component необходима, чтобы наш класс распознавался Spring, How полноправный Bean
@Component
// Наследуемся от TelegramLongPollingBot - абстрактного класса Telegram API
public class Bot extends TelegramLongPollingBot {
// Аннотация @Value позволяет задавать meaning полю путем считывания из application.yaml
@Value("${bot.name}")
private String botUsername;
@Value("${bot.token}")
private String botToken;
/* Перегружаем метод интерфейса LongPollingBot
Теперь при получении messages наш бот будет отвечать сообщением Hi!
*/
@Override
public void onUpdateReceived(Update update) {
try {
execute(new SendMessage().setChatId(update.getMessage().getChatId())
.setText("Hi!"));
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
// Геттеры, которые необходимы для наследования от TelegramLongPollingBot
public String getBotUsername() {
return botUsername;
}
public String getBotToken() {
return botToken;
}
}
Fill in the App class:
package com.whiskels.telegram;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.telegram.telegrambots.ApiContextInitializer;
// Аннотация, которая объединяет в себя @Configuration, @EnableAutoConfiguration, @ComponentScan
@SpringBootApplication
public class App {
public static void main(String[] args) {
// Здесь code написан по заветам
// https://github.com/rubenlagus/TelegramBots/tree/master/telegrambots-spring-boot-starter
ApiContextInitializer.init();
SpringApplication.run(App.class, args);
}
}
If we did everything correctly, then we can run main and say hello to our bot. Ready! We have successfully written and launched a telegram bot that says hello to every incoming message. If this article was useful to you, then the best thanks would be if you look at my repository and leave a star. There you will also find my version of the telegram bot, which has many interesting features:
- storing users in a Postgres database;
- authorization of access to commands based on user roles;
- use of custom annotations @BotCommand and @RequiredRoles to create message handlers and check user rights;
- support for creating a notification schedule.
GO TO FULL VERSION