【问题标题】:How to get the list of all chat IDs in a given bot in Telegram?如何在 Telegram 中获取给定机器人中所有聊天 ID 的列表?
【发布时间】:2019-04-02 21:46:51
【问题描述】:

我正在使用 CRON 作业创建一个电报机器人,因此它会随着每部有趣的电影/连续剧的发布而更新,我希望它每月发送一次更新。

您可以在这个GitHub Library查看它

我还在 stackoverflow related 中看到了其他主题。 但是,这种解决方案不适用于我的问题,或者至少我认为如此,因为我不必从我的机器人将要进入的每个聊天中获取更新,因为它将是一个新闻通讯机器人。

基本上我有:

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

如果您已经知道要将消息发送到的 chatId,那么发送一条消息就可以了。但是,我想要一个函数(或 REST 端点),它返回我的机器人所连接的 chetIds 列表,以便我可以执行以下操作:

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

【问题讨论】:

    标签: java telegram telegram-bot telegram-webhook


    【解决方案1】:

    您无法通过 Telegram API 获取所有 chatId。见official docs

    我认为最好的解决方案是将所有 chatId 存储在数据库或文件中。 当用户启动机器人或执行某些操作时,您可以从方法public void onUpdateReceived(Update update) 中的update 变量中获取chatId:

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

    基于文件的 id 存储示例:

    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();
        }
    }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-21
      • 2023-03-24
      • 2020-04-14
      • 1970-01-01
      • 1970-01-01
      • 2019-10-01
      • 2016-08-12
      • 1970-01-01
      • 2018-05-29
      相关资源
      最近更新 更多