spring

Building a Telegram bot using Spring Boot

In the ever-evolving realm of modern communication, Telegram has emerged as a platform for personal messaging and an environment for creating interactive and intelligent bots. These bots serve different purposes, from automating tasks to providing real-time information. In this guide, we delve into the exploration of integrating Telegram bot development with Spring Boot. From setting up a Spring Boot project to integrating it with the Telegram Bot API, we’ll cover the aspects that empower us to build interactive and responsive bots to meet our specific needs.

1. Overview of the Telegram Bot

Telegram bots are automated entities designed to engage with users and offer a diverse range of services on the Telegram messaging platform. These bots leverage the Telegram Bot API, offering developers a toolkit to create smart, interactive, and responsive applications.

Below are some key aspects surrounding Telegram bots.

1.1 BotFather

The creation of Telegram bots involves interacting with BotFather, a specialized bot on Telegram designed to help developers generate unique API tokens for their respective bots. BotFather assists developers by guiding them through the process of creating a bot, providing configuration details along the way.

1.2 Flexible Capabilities

Telegram bots are versatile and capable of performing various tasks. They can deliver real-time updates, answer queries, automate processes, and even engage in interactive conversations. The flexibility of bot functionalities renders them suitable for a variety of applications.

1.3 Bot API Features

The Telegram Bot API provides a comprehensive set of features. Developers can send messages, and multimedia content, manage user commands, establish custom keyboards, and execute inline queries. This API empowers developers to design bots that go beyond basic messaging.

1.4 User Engagement and Interaction

Telegram bots enable two-way communication. Initiating conversations, issuing commands, and receiving responses from bots are all actions that users can take. This interactive nature fosters engaging user experiences and creates possibilities for businesses, communities, and individuals to engage with their audience.

1.5 Security and Privacy Considerations

Telegram prioritizes security, and developers must adhere to best practices when creating bots. Ensuring the secure handling of user data, employing HTTPS, and safeguarding API tokens are critical aspects of responsible bot development.

1.6 Technology Stacks

Various programming languages and frameworks can be employed for Telegram bot development. This includes Java with Spring Boot, Python with Flask or Django, Node.js with Telegraf, and others.

2. Prerequisites

Before delving into the code, let’s ensure that we have the necessary tools and accounts set up:

  1. Telegram Account: A Telegram account to create a bot.
  2. Telegram Bot Token
  3. Java Development Kit (JDK): Install and use the latest version of the JDK on your machine.
  4. An IDE of your choice: In this Project, Netbeans 17 is used.

3. Create a new Spring Boot Project

We will use the Spring Initializer to generate a fresh Spring Boot project. Navigate to https://start.spring.io/ and configure the following parameters:

  • Project: Maven
  • Language: Java
  • Spring Boot: 2.7.17
  • Group: com.jcg
  • Artifact: quotegenerator
  • Description: Demo project for Telegram Quote Generator Bot
  • Packaging: Jar
  • Dependencies: Add Spring Web

Click the Generate button, download the zip file, and extract it. Fig 1.0 shows the Spring boot initialzr configuration screenshot.

Fig 1.0 Spring boot initialzr configuration
Fig 1.0 Spring boot initialzr configuration

4. Set Up Telegram Bot

4.1 Use Case (Random Quote Generator)

We will develop a simple Spring Boot application with a scheduled task that sends random quotes using the Telegram Bot API. The application would consist of a service class that would encapsulate the logic for selecting and providing a random quote from a predefined collection in our application.

4.2 Create a Telegram Bot

  • Obtain a token for your Telegram bot by utilizing the BotFather at https://core.telegram.org/bots#botfather
  • Start a chat with BotFather and click on the /newbot command link to create a new bot.
  • Follow the instructions to choose a name and username for your bot.
  • Upon completion, BotFather will provide you with a token. You have to save this token as it will be required later for authenticating your bot.

4.3 Add Telegram Bot API Dependencies to Spring Boot Project

Now, within the Spring Boot project, let’s update the project by adding the following dependencies to our pom.xml file for the Telegram Bot API:


    <dependency>
        <groupId>org.telegram</groupId>
        <artifactId>telegrambots</artifactId>
        <version>5.2.0</version> <!-- Use the latest version available -->
    </dependency>

4.4 Implementing the Telegram Bot in Spring Boot

First, let’s create a simple service class called QuoteService.java to generate some random quotes. The class should look like the code example listed below:

@Service
public class QuoteService {

    private static final List quotes = new ArrayList();

    static {
        quotes.add("Success is not final, failure is not fatal: It is the courage to continue that counts. - Winston Churchill");
        quotes.add(" In three words I can sum up everything I've learned about life: it goes on. - Robert Frost");
        quotes.add("Life is what happens when you're busy making other plans. - John Lennon");
        quotes.add("The only way to do great work is to love what you do. - Steve Jobs");
        quotes.add("The future belongs to those who believe in the beauty of their dreams. - Eleanor Roosevelt");
    }

    public String getRandomQuote() {
        Random random = new Random();
        return quotes.get(random.nextInt(quotes.size()));
    }

}

In the code listing above, we use a simple ArrayList for demonstration purposes. In the code, a list of quotes stored in a List<String> quotes. The data source could be a database or an external API. We can add as many quotes as we want to this list. Also, we create a method getRandomQuote that uses the java.util.Random class to generate a different random quote from the list each time it is called.

Next, we create a class to handle Telegram bot functionality and name it TelegramBot.java. This class extends the TelegramLongPollingBot class and implements the required methods as shown below:

@Service
public class TelegramBot extends TelegramLongPollingBot {
    
    @Value("${telegram.bot.token}")
    private String token;

    @Value("${telegram.bot.chatId}")
    private Long chatId;
    
    @Value("${telegram.bot.username}")
    private String username;

    public Long getChatId() {
        return chatId;
    }
    
    @Override
    public void onUpdateReceived(Update update) {
        // Handle incoming updates if needed
    }

    @Override
    public String getBotUsername() {     
        return username; // Replace with your bot's username     
    }

    @Override
    public String getBotToken() {    
        return token; // Replace with the token obtained from BotFather   
    }
    
}

Next, we update the application.properties file in our application with the following content:

telegram.bot.token=your_bot_token
telegram.bot.chatId=your_chatID
telegram.bot.username=your_bot_user_name

The application.properties file simplifies the management of configuration settings in a Spring Boot application and allows us to externalize configuration from our code. Let us understand the contents of the application.properties file used in this application.

  • telegram.bot.token= specifies your Telegram bot’s username.
  • telegram.bot.chatId= specifies your Telegram bot’s token.
  • telegram.bot.username= specifies the chat ID where you want to send messages.

Remember to replace the placeholder values with your actual bot details. To manually get your chat ID, forward a message from the chat to the get_id_bot on Telegram. The get_id_bot will reply with the chat ID.

Next, we create a class QuoteGeneratorTelegramBot.java to send the random quotes at fixed intervals. The contents of this Class should look like this:

@Service
public class QuoteGeneratorTelegramBot {

    private final TelegramBot telegramBot;
    private final QuoteService quoteGenerator;
    

    @Autowired
    public QuoteGeneratorTelegramBot(TelegramBot telegramBot, QuoteService quoteGenerator) {
        this.telegramBot = telegramBot;
        this.quoteGenerator = quoteGenerator;
    }

    // Scheduled task that sends random quotes at fixed intervals
    @Scheduled(fixedRate = 60000) // Adjust the interval as needed (e.g., 60000 ms = 1 minute)
    public void sendScheduledQuote() {

        // Get a random quote from the generator
        String randomQuote = quoteGenerator.getRandomQuote();

        // The chat ID where you want to send the quote
        long chatId = telegramBot.getChatId(); 

        try {
            telegramBot.execute(new SendMessage(String.valueOf(chatId), randomQuote));
        } catch (TelegramApiException e) {
            e.printStackTrace();
        }
    }
}

The example code above is responsible for sending the random quotes and contains the following fields, annotations, and methods as explained below:

  • the QuoteGeneratorTelegramBot class is annotated with @Service, and it’s injected with the TelegramBot and QuoteService service class using the @Autowired annotation. This allows us to access the values in our service class.
  • The @Scheduled annotation is applied to the sendScheduledQuote method. In this example, the fixedRate attribute is set to 60000, indicating that the sendScheduledQuote method should be executed every 1 minute (60000ms = 1 minute). We can adjust the time interval as required by the application.
  • Inside the sendScheduledQuote method, we use the quoteGenerator which is an instance of the QuoteService class to get a random quote.
  • long chatId = telegramBot.getChatId() : This line calls the getChatId method on the telegramBot instance to retrieve the chat ID. The chat ID is used to specify the destination of the message, indicating which chat will receive the message.
  • telegramBot.execute(new SendMessage(String.valueOf(chatId), randomQuote)) : This line of code is enclosed in a try-catch block. It sends a message using the telegramBot instance. It creates a new SendMessage object with the chat ID and the random quote and then executes it. If there’s an exception (e.g., TelegramApiException), it prints the stack trace.

Next, we have to enable scheduling in our Main application class like this:

@SpringBootApplication
@EnableScheduling
public class QuotegeneratorApplication {

    public static void main(String[] args) {
        SpringApplication.run(QuotegeneratorApplication.class, args);

    }

}

In the code above, we added the @EnableScheduling annotation on our main Spring Boot application class to enable scheduling support in the application. This allows the use of the @Scheduled annotation on the sendScheduledQuote method.

5. Run the Spring Boot Application

Now, if we run our Spring Boot application, our Telegram bot will send a random quote to the specified chat every minute as shown in the screenshot below:

Fig 2: Screenshot of the Random Quote Generator bot
Fig 2: Screenshot of the Random Quote Generator bot

6. Further Exploration and Customization

To explore additional customization, we can consider the following aspects:

  • Persistent Storage: Integrate a persistent storage mechanism to store the random quotes or some user data. This could involve using a database like MySQL, or PostgreSQL, or an embedded database like H2, depending on our requirements.
  • Logging and Monitoring: Integrate logging mechanisms to keep track of bot activities. Additionally, consider incorporating monitoring tools or services to gain insights into your bot’s performance and user interactions.
  • Localization and Internationalization: If your bot is intended for a global audience, implement localization and internationalization features to support multiple languages. Telegram allows you to send messages in different languages based on user preferences.
  • User Authentication and Authorization: Implement user authentication and authorization mechanisms to control access to certain bot functionalities.

7. Conclusion

In this article, we’ve delved into the steps involved in creating a Telegram bot and connecting it with a Spring Boot API. Building a Telegram bot using Spring Boot provides a flexible foundation for developing interactive and automated communication tools. Leveraging the power of the Spring framework, along with the Telegram API, allows us to integrate our applications with Telegram’s messaging platform.

Through the implementation steps outlined above, including setting up the Telegram bot, configuring a Spring Boot project, and utilizing the @Scheduled annotation for periodic tasks, we can create feature-rich bots that deliver dynamic content.

8. Download the Source Code

This was a tutorial on Building a Telegram bot using Spring Boot.

Download
You can download the full source code of this example here: Building a Telegram bot using Spring Boot

Omozegie Aziegbe

Omos holds a Master degree in Information Engineering with Network Management from the Robert Gordon University, Aberdeen. Omos is currently a freelance web/application developer who is currently focused on developing Java enterprise applications with the Jakarta EE framework.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button