如何使用 Telegram Bot API 发送大文件?

big*_*awn 9 java telegram telegram-bot

Telegram bot 的发送文件大小限制为 50MB。

我需要发送大文件。有没有办法解决?

我知道这个项目https://github.com/pwrtelegram/pwrtelegram但我无法让它工作。

也许有人已经解决了这样的问题?

有一个选项可以通过 Telegram API 实现文件上传,然后通过file_id与 bot发送。

我使用库https://github.com/rubenlagus/TelegramBots用 Java 编写了一个机器人

更新

为了解决这个问题,我使用了电报 api,它对大文件有 1.5 GB 的限制。

我更喜欢 kotlogram - 具有良好文档的完美库https://github.com/badoualy/kotlogram

更新 2

我如何使用这个库的例子:

private void uploadToServer(TelegramClient telegramClient, TLInputPeerChannel tlInputPeerChannel, Path pathToFile, int partSize) {
    File file = pathToFile.toFile();
    long fileId = getRandomId();
    int totalParts = Math.toIntExact(file.length() / partSize + 1);
    int filePart = 0;
    int offset = filePart * partSize;
    try (InputStream is = new FileInputStream(file)) {

        byte[] buffer = new byte[partSize];
        int read;
        while ((read = is.read(buffer, offset, partSize)) != -1) {
            TLBytes bytes = new TLBytes(buffer, 0, read);
            TLBool tlBool = telegramClient.uploadSaveBigFilePart(fileId, filePart, totalParts, bytes);
            telegramClient.clearSentMessageList();
            filePart++;
        }
    } catch (Exception e) {
        log.error("Error uploading file to server", e);
    } finally {
        telegramClient.close();
    }
    sendToChannel(telegramClient, tlInputPeerChannel, "FILE_NAME.zip", fileId, totalParts)
}


private void sendToChannel(TelegramClient telegramClient, TLInputPeerChannel tlInputPeerChannel, String name, long fileId, int totalParts) {
    try {
        String mimeType = name.substring(name.indexOf(".") + 1);

        TLVector<TLAbsDocumentAttribute> attributes = new TLVector<>();
        attributes.add(new TLDocumentAttributeFilename(name));

        TLInputFileBig inputFileBig = new TLInputFileBig(fileId, totalParts, name);
        TLInputMediaUploadedDocument document = new TLInputMediaUploadedDocument(inputFileBig, mimeType, attributes, "", null);
        TLAbsUpdates tlAbsUpdates = telegramClient.messagesSendMedia(false, false, false,
                tlInputPeerChannel, null, document, getRandomId(), null);
    } catch (Exception e) {
        log.error("Error sending file by id into channel", e);
    } finally {
        telegramClient.close();
    }
}
Run Code Online (Sandbox Code Playgroud)

这里TelegramClient telegramClientTLInputPeerChannel tlInputPeerChannel您可以创建任意文件中写入。

不要复制粘贴,根据您的需要重写。

Dmi*_*rov 9

使用本地 Telegram Bot API 服务器,您可以发送文件大小限制为 2000Mb 的 InputStream,默认大小为 50Mb。


val*_*jon 7

如果您想通过电报机器人发送文件,您有三个选择

  1. 输入流(照片限制为10 MB ,其他文件限制为50 MB )
  2. 来自http url(Telegram 将下载并发送文件。照片最大大小为5 MB ,其他类型内容最大大小为20 MB。)
  3. 通过file_id发送缓存文件。(以这种方式发送的文件没有限制)

因此,我建议您预先存储 file_ids 并通过这些 id 发送文件(api 文档也推荐这样做)。