JavaRush /Java Blog /Random EN /Create a telegram bot using Spring Boot
Whiskels
Level 41
Москва

Create a telegram bot using Spring Boot

Published in the Random EN group
Hi all! At some point in your training, you want to move from solving problems to creating real projects that will form the basis of your portfolio. When I started to study on an internship (which I highly recommend to everyone), I received an offer to freelance to write a telegram bot. Due to my little knowledge, I wrote a rather simple bot ( the last commit before the migration to Spring ), which contained three threads:
  • message receiving thread;
  • thread for sending messages;
  • event scheduling thread (it checked for scheduled messages and updated cached data from JSON).
When writing this functionality, I largely relied on this article . Everything worked quite well, but the deeper I dived into Spring, the more I wanted to refactor everything in order to reduce the coherence of the program and improve the quality of the code. SonarLint (plugin for automatic code quality check) also tried to convince me all the time that having endless while loops is not very good. At some point, I made up my mind and rewrote everything, and now I want to share the knowledge gained in the process of refactoring with you. Let's start with the basics, and more specifically - with TelegramBots-Spring-Boot-Starter So, let's go! Let's create a bot that will say hello in response to any message. First we need to create a new Maven project. Let's add the necessary dependencies to pom.xml. Add Java and TelegramBots-Spring-Boot-Starter versions to properties. And we prescribe dependencies - here we will have the TelegramBots-Spring-Boot-Starter and Telegram API already mentioned above : Create a telegram bot using Spring Boot - 1The TelegramBots-Spring-Boot-Starter library includes Spring Boot and the Telegram API. Using it allows us to declare a bot in our code in a fairly simple way, and Spring itself will create a Bean and activate the bot. If you are interested in what is happening under the hood at this moment, then look at the source code of the library (in the development environment or on github ). We also add compilation options:Create a telegram bot using Spring Boot - 2 Don't forget to update all dependencies after filling 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: Create a telegram bot using Spring Boot - 3At this stage, let's add the credentials of our bot to application.yaml:
bot:
  name: CodeGymTelegramBot
  token: 22313424:AAF4gck4D8gDhq68E7k0UH8vlyQADhxQhYo
Hierarchical notation allows us to avoid repeating (bot.name, bot.token) and improve readability. If you have not created a bot yet, then you can start it by following the official instructions . If you don't want to show bot credentials in application.yaml (which is correct), use environment variables when deploying:
bot:
  name: ${BOT_NAME}
  token: ${BOT_TOKEN}
We fill 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 right, then we can run main and say hello to our bot. Create a telegram bot using Spring Boot - 4Ready! We have successfully written and launched a telegram bot that greets each incoming message. If this article was helpful to you, then the best thanks would be if you look into my repository and put an asterisk. There you will also find my version of the telegram bot, which has many interesting features:
  • storing users in the Postgres database;
  • authorization of access to commands based on user roles;
  • using custom annotations @BotCommand and @RequiredRoles to create message handlers and check user rights;
  • support for creating notification schedule.
If any of this functionality interests you, write in the comments, and I will try to either answer or write a detailed article on how to recreate it. PS This is my first post on CodeGym and I would love to dive into Spring JPA and @Scheduled annotations, but I thought it worth writing this tutorial on how to get a bot up and running using Spring Boot first. Several articles have already been written on bots, but the search did not return such a guide, so I decided to fill this niche :) I would also like to note Miroha - thanks for the UpdateHandler idea, I dragged it to myself :) PART 2 PART 3
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION