Thursday, September 14, 2023
HomeJavaProducing a Telegram Crawler with Springtime Boot

Producing a Telegram Crawler with Springtime Boot

1. Intro

In this tutorial, we’ll develop a Telegram Crawler utilizing Springtime Boot.

A Telegram crawler is an automatic program that runs within the Telegram messaging system It uses the Telegram Crawler API to communicate with customers and also do numerous jobs. We’ll utilize a Java collection rather than connecting with the API straight. Robots aid us reply to individual commands, supply info, and also do computerized activities.

We’ll begin by establishing a new crawler and after that take place to explain exactly how to utilize the Java collection to apply straightforward activities.

2. Producing a Telegram Crawler

Initially, we require to develop a brand-new crawler on the Telegram system. We do it straight utilizing the Telegram messaging application and also looking for the BotFather in the search bar. As soon as open, we’ll kind the / newbot command to develop the crawler and also comply with BotFather’s directions. It’ll request for the username we intend to appoint to the crawler, which requires to finish with a crawler according to Telegram’s plan:

Over, the BotFather produced a token that we should conserve someplace risk-free to utilize later on to configure our application.

3. Establishing the Application

2nd, we should have a Springtime Boot job where we intend to incorporate the Telegram Crawler. We are mosting likely to change the pom.xml documents and also consist of the telegrambots-spring-boot-starter and also the telegrambots-abilities collection:

<< reliance>>.
<< groupId>> org.telegram<.
<< artifactId>> telegrambots-spring-boot-starter<.
<< variation>> 6.7.0<.
<< reliance>>.
<< groupId>> org.telegram<.
<< artifactId>> telegrambots-abilities<.
<< variation>> 6.7.0<.

Under the hood, the AbilityBot utilizes webhooks to interact with Telegrams APIs, however we do not require to bother with that. Actually, the collection carries out all the user interfaces offered by the Telegram Crawler API

Currently, we can execute our crawler.

4. Describing the PizzaBot

We'll apply an easy crawler replicating a pizza store to show utilizing the collection with Springtime Boot. Furthermore, we'll have a predefined collection of communications with the crawler:

Pizzabot Interaction diagram

In other words, we'll begin by asking the individual for their name. After that, we'll trigger him to choose a Pizza or a beverage. When it comes to beverages, we'll show a message stating we do not offer beverages. Or else, we'll ask for the garnishes of the pizza. After choosing the readily available garnishes, we'll validate if the individual intends to buy once more. In this situation, we'll duplicate the circulation. Additionally, we'll thank them and also shut the conversation with a closing message.

5. Set up and also Register the PizzaBot

Allow's begin by setting up an AbilityBot for our brand-new PizzaShop:

public course PizzaBot prolongs AbilityBot {
exclusive last ResponseHandler responseHandler;
public PizzaBot( Atmosphere env) {
incredibly( env.getProperty(" botToken"), "baeldungbot");
responseHandler = brand-new ResponseHandler( quiet, db);
public lengthy creatorId() {
return 1L;

We checked out the botToken residential or commercial property infused as an atmosphere variable inside the fitter. We should maintain the token risk-free and also not press it right into the codebase In this instance, we export it to our atmosphere prior to running the application. Additionally, we might specify it inside the residential properties documents. Furthermore, we should supply a special creatorId that explains our crawler.

Likewise, we are prolonging the AbilityBot course which lowers the boilerplate code and also supplies generally made use of devices such as state equipments via ReplyFlow Nonetheless, we'll just utilize the ingrained data source and also handle the state clearly inside ResponseHandler:

 public course ResponseHandler {
exclusive last SilentSender sender;
exclusive last Map<< Long, UserState> > chatStates;

public ResponseHandler( SilentSender sender, DBContext db) {
this.sender = sender;
chatStates = db.getMap( Constants.CHAT _ STATES);


5.1. Springtime Boot 3 Compatibility Problem

When utilizing variation 3 of Springtime Boot, the collection does not immediately set up the crawler when proclaimed as @Component As a result, we should initialize it by hand inside our primary application course:

 TelegramBotsApi botsApi = brand-new TelegramBotsApi( DefaultBotSession.class);
botsApi.registerBot( ctx.getBean(" pizzaBot", TelegramLongPollingBot.class));

We develop a brand-new circumstances of the TelegramBotsApi and after that supply the pizzaBot element circumstances from the Springtime Application context

6. Carrying Out the PizzaBot

The Telegram API is substantial and also can come to be recurring to apply brand-new commands. Subsequently, we utilize capacities to streamline the procedure of establishing brand-new capacities. We must think about completion individual, the essential problems, and also the implementation procedure when developing the communication circulation.

In our PizzaBot, we'll utilize simply a solitary capability that'll / begin the discussion with the crawler:

 public Capacity startBot() {
return Capacity
. home builder()
. name(" begin")
. details( Constants.START _ SUMMARY)
. region( CUSTOMER)
. personal privacy( PUBLIC)
. activity( ctx -> > responseHandler.replyToStart( ctx.chatId()))
. develop();.

We utilize the home builder pattern to develop the Capacity Initially, we specify the name of the Capacity, which coincides as the command of the Capacity. Second, we supply a summary string of this brand-new Capacity. This'll be useful when we run the / commands command to obtain our crawler's capacities. Third, we specify the region and also personal privacy of the crawler. Lastly, we specify what activity we should take upon getting the command. For this instance, we'll onward the id of the conversation to the ResponseHandler course. Complying with the layout from the representation over, we'll request for the name of the individual and also wait inside a map with its preliminary state:

 public gap replyToStart( lengthy chatId) {
SendMessage message = brand-new SendMessage();.
message.setChatId( chatId);.
message.setText( START_TEXT);.
sender.execute( message);.
chatStates.put( chatId, AWAITING_NAME);.

In this approach, we develop a SendMessage command and also perform it utilizing the sender After that, we established the conversation state to AWAITING_NAME, signalling we are awaiting the individual's name:

 exclusive gap replyToName( lengthy chatId, Message message) {
promptWithKeyboardForState( chatId, "Hey there" + message.getText() + ". What would certainly you such as to have?",.

After the individual enters their name, we send them a ReplyKeyboardMarkup that motivates them with 2 alternatives:

 public fixed ReplyKeyboard getPizzaToppingsKeyboard() {
KeyboardRow row = brand-new KeyboardRow();.
row.add(" Margherita");.
row.add(" Pepperoni");.
return brand-new ReplyKeyboardMarkup( List.of( row));.

This'll conceal the key-board and also show the individual a user interface with 2 switches:

PizzaBot Button menu Currently, the individual can choose a pizza or beverage that our pizza store does not supply. Telegram sends out a sms message with a feedback when choosing any one of both alternatives.

For all the eco-friendly diamond-shaped components in the representation over, we comply with a comparable procedure. As a result, we will not duplicate it right here. Rather, allow's concentrate on managing the reaction to the switches.

7. Managing the Replies From the Individual

For all the inbound messages and also the present state of the conversation, we take care of the reaction in different ways inside our PizzaBot course:

 public Reply replyToButtons() {
BiConsumer<< BaseAbilityBot, Update> > activity = (abilityBot, upd) -> > responseHandler.replyToButtons( getChatId( upd), upd.getMessage());.
return Reply.of( activity, Flag.TEXT, upd -> > responseHandler.userIsActive( getChatId( upd)));.

The. replyToButtons() obtains all the MESSAGE responds and also forwards them to the ResponseHandler in addition to the chatId and also the inbound Message things. After that, inside the ResponseHandler the replyToButtons() approach determines exactly how to refine the message:

 public gap replyToButtons( lengthy chatId, Message message) {
if (message.getText(). equalsIgnoreCase("/ quit")) {
stopChat( chatId);.

button (chatStates.get( chatId)) {
situation AWAITING_NAME -> > replyToName( chatId, message);.
situation FOOD_DRINK_SELECTION -> > replyToFoodDrinkSelection( chatId, message);.
situation PIZZA_TOPPINGS -> > replyToPizzaToppings( chatId, message);.
situation AWAITING_CONFIRMATION -> > replyToOrder( chatId, message);.
default -> > unexpectedMessage( chatId);.

Inside the button, we inspect the present standing of the conversation and also respond to the individual appropriately. For instance, when the present state for the individual is FOOD_DRINK_SELECTION, we refine the reaction and also transfer to the following state when the individual faucets on the alternative pizza:

 exclusive gap replyToFoodDrinkSelection( lengthy chatId, Message message) {
SendMessage sendMessage = brand-new SendMessage();.
sendMessage.setChatId( chatId);.
if (" beverage". equalsIgnoreCase( message.getText())) {
sendMessage.setText(" We do not offer drinks.nBring your very own beverage!!:-RRB-");.
sendMessage.setReplyMarkup( KeyboardFactory.getPizzaOrDrinkKeyboard());.
sender.execute( sendMessage);.
} else if (" pizza". equalsIgnoreCase( message.getText())) {
sendMessage.setText(" We like Pizza in here.nSelect the garnishes!");.
sendMessage.setReplyMarkup( KeyboardFactory.getPizzaToppingsKeyboard());.
sender.execute( sendMessage);.
chatStates.put( chatId, UserState.PIZZA _ GARNISHES);.
} else {
sendMessage.setText(" We do not offer" + message.getText() + ". Please choose from the alternatives listed below.");.
sendMessage.setReplyMarkup( KeyboardFactory.getPizzaOrDrinkKeyboard());.
sender.execute( sendMessage);.

In addition, within. replyToButtons(), we quickly inspect if the individual sent out the / quit command. Because situation, we quit the conversation and also get rid of the chatId from the chatStates map:

 exclusive gap stopChat( lengthy chatId) {
SendMessage sendMessage = brand-new SendMessage();.
sendMessage.setChatId( chatId);.
sendMessage.setText(" Thanks for your order. See you soon!nPress/ begin to buy once more");.
chatStates.remove( chatId);.
sendMessage.setReplyMarkup( brand-new ReplyKeyboardRemove( real));.
sender.execute( sendMessage);.

This eliminates the individual's state from the data source. To communicate once more, the individual has to compose the / begin command.

8. Verdict

In this tutorial, we went over executing a Telegram crawler utilizing Springtime Boot.

Initially, we produced a brand-new crawler on the Telegram system utilizing BotFather. Second, we established our Springtime Boot job and also clarified the capability of our PizzaBot and also exactly how it engages with customers. After that, we carried out the PizzaBot utilizing capacities to streamline establishing brand-new commands. Lastly, we managed the replies from customers and also offered suitable reactions based upon the conversation state.

As constantly, the resource code of this write-up is readily available over on GitHub


Most Popular

Recent Comments