我可以从 Spring 启动应用程序启动电报机器人吗?

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

我尝试从这里创建一个机器人 https://github.com/rubenlagus/TelegramBots

它作为一个简单的应用程序工作,但是当我尝试添加 Spring 引导时它不起作用。我想这是因为 Spring 启动启动 Tomcat 并且电报机器人试图 send/recieve 一些 http.

我没有收到任何错误(机器人作为 @Component bean 启动)。

甚至可以连接这种机器人和 Spring 启动应用程序或至少一个网络应用程序吗?

您可以尝试使用同一个库中的 telegrambots-spring-boot-starter

您的主要配置应如下所示:

@SpringBootApplication
public class YourApplicationMainClass {

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

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

你的机器人 class:

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

您可以在此处找到更多信息https://github.com/rubenlagus/TelegramBots/tree/master/telegrambots-spring-boot-starter

正如@Bobby 所说,您可以尝试

telegrambots-spring-boot-starter project

您还可以添加新的 telegrambots-extensions 依赖项,使您能够管理命令机器人。

所以代码将是

@Component
public class Foo extends TelegramLongPollingCommandBot {

        @Override
        public void processNonCommandUpdate(Update update) {

也可以通过这种方式管理命令

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

您可以在 SpringBoot class main 中注册您的 TelegramLongPollingCommandBot,如下所示:

  @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)