N
N
Nikita K2020-10-15 15:49:40
Java
Nikita K, 2020-10-15 15:49:40

How to send an image to a telegram bot in Java?

Here is my code:

public synchronized void getImg(Message message) throws IOException {

        Document document = message.getDocument();
        String file_id = document.getFileId();
        String file_name = document.getFileName();

        URL url = new URL("https://api.telegram.org/bot"+token+"/getFile?file_id="+file_id);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream()));
        String res = bufferedReader.readLine();

        JSONObject jResult = new JSONObject(res);
        JSONObject path = jResult.getJSONObject("result");
        String file_path = path.getString("file_path");

        URL download = new URL("https://api.telegram.org/file/bot" + token + "/" + file_path);
        FileOutputStream fileOutputStream = new FileOutputStream(upPath + file_name);
        System.out.println("Start upload");

        ReadableByteChannel rbc = Channels.newChannel(download.openStream());
        fileOutputStream.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        fileOutputStream.close();
        rbc.close();
        System.out.println("Uploaded");

    }


I throw an image into the bot, but it is not saved in the folder, what should I do?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question