rubenlagus / TelegramBots

Java library to create bots using Telegram Bots API
https://telegram.me/JavaBotsApi
MIT License
4.77k stars 1.22k forks source link

How to send message from java or telegram scheduler? #816

Closed MainStar closed 4 years ago

MainStar commented 4 years ago

Hi, could you help please, how to create a scheduler which will send message to all chats (users) with java?

AndriiRomanenko commented 4 years ago

Hi! To create a scheduler you could create your application, basis on Spring Framework

TelegramBot has spring starter dependency

<dependency>
            <groupId>org.telegram</groupId>
            <artifactId>telegrambots-spring-boot-starter</artifactId>
            <version>4.9.1</version>
        </dependency>

Using Spring Framework you can create a scheduler, using this part of the code:

@Configuration
@EnableScheduling
public class Scheduler {

   @Scheduled(fixedDelay = 5000L)
  public void foo() {
   // your scheduler job code here
  }
}

Method foo() will do some job with delay of 5 seconds. You could configure on cron expression

Next what you need is a list of user's chat id. You could hold it in a file or in a database.

Class TelegramLongPollingBot has method execute, that take SendMessage object for sending messages to the users. All you need are the chat id of the user and text message, that you want to send. It can looks like this

public void sendMessage(Long chatId, String textMessage) {
        SendMessage message = new SendMessage()
                .setChatId(chatId)
                .setText(textMessage);
        try {
            execute(message);
        } catch (TelegramApiException e) {
            e.printStackTrace();
        }
    }
MainStar commented 4 years ago

Hi! Thanks a lot, It works! 👍