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

Creating a telegram bot using Spring Boot

Published in the Random EN group
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:
  • message receiving thread;
  • message sending thread;
  • event scheduling thread (it checked for scheduled messages and updated cached data from JSON).
When writing this functionality, I relied heavily 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 (a plugin for automatically checking code quality) kept trying to convince me that it’s not very good to have endless while loops. At some point, I made up my mind and rewrote everything, and now I want to share the knowledge I gained during the refactoring process 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 register dependencies - here we will have the already mentioned above TelegramBots-Spring-Boot-Starter and Telegram API : Creating a telegram bot using Spring Boot - 1The 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: Creating a telegram bot using Spring Boot - 2 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: Creating a telegram bot using Spring Boot - 3At this stage, let’s add the credentials of our bot to application.yaml:
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. Creating a telegram bot using Spring Boot - 4Ready! 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.
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 article on JavaRush, and I would like to dive into the wilds of Spring JPA and @Scheduled annotations, but first I thought it would be worth writing this guide on how to generally build a bot using Spring Boot. Several articles have already been written on bots, but the search did not produce such a guide, so I decided to fill this niche :) I would also like to mention Miroha - thanks for the idea of ​​UpdateHandlers, I stole it for myself :) PART 2 PART 3
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION