Search code examples
javatelegramtelegram-bottelegram-webhook

How to get the list of all chat IDs in a given bot in Telegram?


I am creating a telegram bot using a CRON job so it will update with every interesting movie/series release, and I want it to send an update once every month.

You can view it in this GitHub Library

I have also seen other topics here in stackoverflow related. But, this kind of solution does not apply to my problem, or I think so at least, since I do not have to have updates from every chat that my bot will be into since it will be a newsletter bot.

Basically I have:

public void sendMessage(String message) {
        SendMessage messageSender = new SendMessage().setChatId(someId).setText(message);
        try {
            execute(messageSender);
        } catch (TelegramApiException e) {
            e.printStackTrace();
        }
    }

Which is fine to send one message if you already know the chatId you want to send the message to. But, I would like to have a function (or a REST endpoint) that returns the list of chetIds my bot is attached to so that I can go for something like:

List<Integer> chatIds = someMagicRESTendpointOrFunction();
chatIds.stream().forEach(message -> sendMessage(message));

Solution

  • You can not get all chatId's by Telegram API. See official docs.

    I think best solution there is to store all chatId's in database or file. You can get chatId from update variable from method public void onUpdateReceived(Update update) when user starts the bot or execute some actions:

    long chatId = update.hasMessage() 
               ? update.getMessage().getChat().getId() 
               : update.getCallbackQuery().getMessage().getChat().getId();
    

    Example of file-based id store:

    import java.io.*;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.nio.file.StandardOpenOption;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    
    public class FileUtil {
    
    private static final String FILE_NAME = "chatIds.txt";
    
    public static boolean writeChatId(long chatId) {
        try {
            Path path = Paths.get(FILE_NAME);
    
            List<Long> adminChatIds = getChatIds();
            if (adminChatIds.contains(chatId)) return true;
    
            Files.write(path, (String.valueOf(chatId) + System.lineSeparator()).getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        } catch (IOException e) {
            return false;
        }
        return true;
    }
    
    public static List<Long> getChatIds() {
        try {
            Path path = Paths.get(FILE_NAME);
            List<Long> result = new ArrayList<>();
    
            for (String line : Files.readAllLines(path)) {
                result.add(Long.valueOf(line));
            }
            return result;
        } catch (Exception e) {
            return Collections.emptyList();
        }
    }
    
    }