Telegram Bots Help

Lesson 9. Simple Spring Boot Bot

Hello! If you want to know how to code Telegram Bots on Java and Spring, this is it!

Install the library

You can install TelegramBots library with different methods:

<dependency> <groupId>org.telegram</groupId> <artifactId>telegrambots-springboot-longpolling-starter</artifactId> <version>7.10.0</version> </dependency> <dependency> <groupId>org.telegram</groupId> <artifactId>telegrambots-client</artifactId> <version>7.10.0</version> </dependency>
implementation 'org.telegram:telegrambots-springboot-longpolling-starter:7.10.0' implementation 'org.telegram:telegrambots-client:7.10.0'

If you don't like standard Maven Central Repository, see Jitpack steps here

Import the library .jar directly to your project. You can find it here, don't forget to fetch the latest version, it is usually a good idea.

Depending on the IDE you are using, the process to add a library is different, here is a video that may help with Intellij

Let's go to code!

We'll start writing a simple echo bot that will just echo any text message received.

Now, when you are in the project, create files MyAmazingBot.java and Main.java within the src directory. Open MyAmazingBot.java and let's write our actual bot:

import org.springframework.stereotype.Component; import org.telegram.telegrambots.client.okhttp.OkHttpTelegramClient; import org.telegram.telegrambots.longpolling.BotSession; import org.telegram.telegrambots.longpolling.interfaces.LongPollingUpdateConsumer; import org.telegram.telegrambots.longpolling.starter.AfterBotRegistration; import org.telegram.telegrambots.longpolling.starter.SpringLongPollingBot; import org.telegram.telegrambots.longpolling.util.LongPollingSingleThreadUpdateConsumer; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.generics.TelegramClient; public class MyAmazingBot implements SpringLongPollingBot, LongPollingSingleThreadUpdateConsumer { private final TelegramClient telegramClient; public MyAmazingBot() { telegramClient = new OkHttpTelegramClient(getBotToken()); } @Override public String getBotToken() { return "TOKEN"; } @Override public LongPollingUpdateConsumer getUpdatesConsumer() { return this; } @Override public void consume(Update update) { // TODO } }

Now, let's add the logic to process updates, consume(Update update) method is for us. When an update is received, it will call this method.

@Override public void consume(Update update) { // We check if the update has a message and the message has text if (update.hasMessage() && update.getMessage().hasText()) { // Set variables String message_text = update.getMessage().getText(); long chat_id = update.getMessage().getChatId(); SendMessage message = SendMessage // Create a message object .builder() .chatId(chat_id) .text(message_text) .build(); try { telegramClient.execute(message); // Sending our message object to user } catch (TelegramApiException e) { e.printStackTrace(); } } }

And last step here, we need to tell Spring Boot to create an instance on our bot, we can do it just adding the @Component annotation to it

@Component public class MyAmazingBot implements SpringLongPollingBot, LongPollingSingleThreadUpdateConsumer { // ... }

Our bot is now created! Let's save that file and go to Main.java. This file will be our Spring Boot application and will do all the magic for us.

We only need to add the @SpringBootApplication and tell Spring to start.

@SpringBootApplication public class Main { public static void main(String[] args) { SpringApplication.run(Main.class, args); } }

Here are all our files:

package org.telegram.telegrambots.tutorial.Lesson8.src; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Main class to start the Spring Boot application. */ @SpringBootApplication public class Main { public static void main(String[] args) { SpringApplication.run(Main.class, args); } }
package org.telegram.telegrambots.tutorial.Lesson8.src; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.telegram.telegrambots.client.okhttp.OkHttpTelegramClient; import org.telegram.telegrambots.longpolling.BotSession; import org.telegram.telegrambots.longpolling.interfaces.LongPollingUpdateConsumer; import org.telegram.telegrambots.longpolling.starter.AfterBotRegistration; import org.telegram.telegrambots.longpolling.starter.SpringLongPollingBot; import org.telegram.telegrambots.longpolling.util.LongPollingSingleThreadUpdateConsumer; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.generics.TelegramClient; @Component public class MyAmazingBot implements SpringLongPollingBot, LongPollingSingleThreadUpdateConsumer { private final TelegramClient telegramClient; public MyAmazingBot() { telegramClient = new OkHttpTelegramClient(getBotToken()); } @Override public String getBotToken() { return "TOKEN"; } @Override public LongPollingUpdateConsumer getUpdatesConsumer() { return this; } @Override public void consume(Update update) { // We check if the update has a message and the message has text if (update.hasMessage() && update.getMessage().hasText()) { // Set variables String message_text = update.getMessage().getText(); long chat_id = update.getMessage().getChatId(); SendMessage message = SendMessage // Create a message object .builder() .chatId(chat_id) .text(message_text) .build(); try { telegramClient.execute(message); // Sending our message object to user } catch (TelegramApiException e) { e.printStackTrace(); } } } @AfterBotRegistration public void afterRegistration(BotSession botSession) { System.out.println("Registered bot running state is: " + botSession.isRunning()); } }

Well done! Now we can pack our project into runnable .jar file and run it on our computer/server!

mvn package spring-boot:repackage

You can find all sources to this lesson in GitHub repository.

Now we can see our bot running:

Bot Spring

Well, that's all for now. Hope to see you soon! :)

Last modified: 23 November 2024