首页 > 解决方案 > 我无法将收到的来自电报机器人的照片保存到像字节数组这样的数据库中

问题描述

我正在尝试将收到的照片从电报机器人保存到字节数组并存储在数据库中。

我的代码:

public void onUpdateReceived(Update update) {
    this.responseText = "Kerakli bo'limni tanlang:";

    if (update.hasMessage() && update.getMessage().hasPhoto()) {
        
        this.chatId = update.getMessage().getChatId();
        SendMessage sendMessage = new SendMessage();

        List<org.telegram.telegrambots.meta.api.objects.PhotoSize> photo = update.getMessage().getPhoto();

        GetFile getFile = new GetFile();

        getFile.setFileId(update.getMessage().getPhoto().get(0).getFileId());

        File file = getFileRequest(getFile);

        InputStream inputStream = new FileInputStream(file);
    }
}

标签: spring-boottelegram-bot

解决方案


当您收到更新时,它包含带有file_id. 使用该 file_id 来定位file_path.

更新可能包含也可能不包含file_path或为空file_path。所以,你需要先得到它。

用于getFile获取文件文件信息如下。例如,file_id 是AgACAgUAAxkBAAIC

WebClient webClient = new WebClient();
string result = webClient.DownloadString("https://api.telegram.org/<botToken>/getFile?file_id=AgACAgUAAxkBAAIC");

调用上面的代码,你会得到这样的结果:

{"ok":true,"result":{"file_id":"AgACAgUAAxkBAAIC","file_unique_id":"AQADWaw","file_size":1266,"file_path":"photos/file_0.jpg"}}

现在,file_path如下所示传递它以将其转换为字节数组:

webClient = new WebClient();
byte[] bytes = webClient.DownloadData("https://api.telegram.org/file/<botToken>/photos/file_0.jpg");

这是使用 WebClient 的 C# 示例。我在这里没有使用任何电报机器人库。根据您的要求,这只是为了您的帮助。


推荐阅读