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:
and Telegram API already mentioned above : The 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: 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: At this stage, let's add the credentials of our bot to application.yaml:
- message receiving thread;
- thread for sending messages;
- event scheduling thread (it checked for scheduled messages and updated cached data from JSON).
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. Ready! 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.
GO TO FULL VERSION