Bobby
Bobby

Reputation: 584

Can I launch a telegram bot from a Spring Boot application?

I try to create a bot from here https://github.com/rubenlagus/TelegramBots

It works as a simple application, but when I try to add Spring Boot it doesn't work. I suppose it is because Spring Boot launches Tomcat and telegram bot tries to send/recieve some http.

I don't get any errors (bot launches as @Component bean).

Is it even possible to connect this kind of bot and a Spring Boot app or at least a web application?

Upvotes: 4

Views: 11491

Answers (2)

daniele.dagostino
daniele.dagostino

Reputation: 43

As @Bobby said, you can try the

telegrambots-spring-boot-starter project

And also you can add the new telegrambots-extensions dependency which make you able to manage command bot.

So the code will be

@Component
public class Foo extends TelegramLongPollingCommandBot {

        @Override
        public void processNonCommandUpdate(Update update) {

Also you can manage the command in this way.

@Component
public class FooCommand extends DefaultBotCommand {
         
      @Override
      public void execute(AbsSender absSender, User user, Chat chat, Integer messageId, String[] arguments) {

You can register your TelegramLongPollingCommandBot within the SpringBoot class main, as below:

  @SpringBootApplication 
  public class TelegramBotConfiguration { 
       public static void main(String[] args)   {       
          ApiContextInitializer.init();
          TelegramBotsApi telegramBotsApi = new TelegramBotsApi();
          try {
            session = telegramBotsApi.registerBot(new Foo());
            
          } catch (TelegramApiException e) {
              log.error(e);
          }
          SpringApplication.run(TelegramBotConfiguration.class, args);
       }
  }

(https://github.com/rubenlagus/TelegramBots/tree/master/telegrambots-extensions)

Upvotes: 3

chmilevfa
chmilevfa

Reputation: 363

You can try to use telegrambots-spring-boot-starter from the same library.

Your main configuration should looks like:

@SpringBootApplication
public class YourApplicationMainClass {

    public static void main(String[] args) {
        ApiContextInitializer.init();

        SpringApplication.run(YourApplicationMainClass.class, args);
    }
}

And class of your bot:

// Standard Spring component annotation
@Component
public class YourBotName extends TelegramLongPollingBot {
    //Bot body.
}

A bit more information you can find here https://github.com/rubenlagus/TelegramBots/tree/master/telegrambots-spring-boot-starter

Upvotes: 12

Related Questions