Trajano Roberto
Trajano Roberto

Reputation: 307

Telegram Bot API file access via Google Sheets Apps Script

How to transfer a local photo file to google drive using multipart/form-data?

I have copied local files to google drive, obtained the google drive file link but following code line hangs and an error comes up related to the html???

var response = UrlFetchApp.fetch(vUrlTelegram + "/sendPhoto?chat_id=" + chat_id + "&photo=" + photoUrl );

note: have obtained html string for a sample photo from the internet, and the following telegram bot google api javascript code works

function sendPhoto( chat_id, photoUrl ) {
var response = UrlFetchApp.fetch(vUrlTelegram + "/sendPhoto?chat_id=" + chat_id + "&photo=" + photoUrl );
console.log(response.getContentText());  

}

Telegram doco

Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. More info on Sending Files »

Upvotes: 3

Views: 1393

Answers (1)

Tanaike
Tanaike

Reputation: 201778

  • From your question, when the direct link of image in the internet is used for the following script, you can confirm that the script works.

      function sendPhoto( chat_id, photoUrl ) {
        var response = UrlFetchApp.fetch(vUrlTelegram + "/sendPhoto?chat_id=" + chat_id + "&photo=" + photoUrl );
        console.log(response.getContentText());
      }
    

From this situation, when you want to use the image file on Google Drive for above script, how about the following flow?

Flow:

  1. Publicly share the image file on Google Drive as Viewer of Anyone with the link.
  2. Use webContentLink of the image file as photoUrl.
    • In this case, when the file ID of the image file is used, webContentLink is as follows.

        https://drive.google.com/uc?export=download&id={fileId}
      

Sample script:

For example, When the image file is publicly shared and run UrlFetchApp.fetch and sharing image file is stopped, the script is as follows.

var fileId = "###"; // Please set the file ID of the image file.
var file = DriveApp.getFileById(fileId)

file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);  // Image file is publicly shared.

var photoUrl = "https://drive.google.com/uc?export=download&id=" + fileId;
var response = UrlFetchApp.fetch(vUrlTelegram + "/sendPhoto?chat_id=" + chat_id + "&photo=" + photoUrl );
console.log(response.getContentText());

// Utilities.sleep(2000); // I'm not sure whether this is required for this situation.
file.setSharing(DriveApp.Access.PRIVATE, DriveApp.Permission.NONE);  // Sharing image file is stopped.

References:

Upvotes: 3

Related Questions