rubenlagus / TelegramBots

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

I get an error on step 2. "String uploadedFilePath = getFile(uploadedFile).getFilePath();" doesn't recognize getFile #703

Closed Dylan099 closed 4 years ago

Dylan099 commented 4 years ago

You should use getFile() method in order to accomplish this.

  1. Import below class import org.telegram.telegrambots.api.methods.GetFile;

  2. Do the following:

    String uploadedFileId = update.getMessage().getDocument().getFileId();
    GetFile uploadedFile = new GetFile();
    uploadedFile.setFileId(uploadedFileId);
    String uploadedFilePath = getFile(uploadedFile).getFilePath();

Having the filePath string, you can save your file using common java file utils. I have used the following method to do so: Add below dependency into your maven pom.xml file:

<dependency>
       <groupId>commons-io</groupId>
       <artifactId>commons-io</artifactId>
       <version>2.5</version>
</dependency>

Import below classes:

import org.apache.commons.io.FileUtils;
import java.io.File;
import java.net.URL;
import java.io.InputStream;

Do the following:

File localFile = new File("localPath/filename.doc");
InputStream is = new URL("https://api.telegram.org/file/bot"+ BotConfig.BOT_TOKEN+"/"+uploadedFilePath).openStream();
FileUtils.copyInputStreamToFile(is, localFile);

Originally posted by @pouraghajanOldAcc in https://github.com/rubenlagus/TelegramBots/issues/411#issuecomment-391891486

Chase22 commented 4 years ago

@rubenlagus this doesn't seem to be an issue by itself

m-tsybulskyi-git commented 4 years ago

@Dylan099 You need to use the execute method, and it will be working fine. execute(getFile)

    public void downloadFile(Document document,  String localFilePath) throws IOException, TelegramApiException {
        File file = getFilePath(document);

        java.io.File localFile = new java.io.File(localFilePath);
        InputStream is = new URL(file.getFileUrl(questionAnsweringBot.getBotToken())).openStream();
        FileUtils.copyInputStreamToFile(is, localFile);
    }

    public File getFilePath(Document document) throws TelegramApiException {
        GetFile getFile = new GetFile();
        getFile.setFileId(document.getFileId());
        File file = execute(getFile);
        return file;
    }