2
votes

I've written the following script:

function uploadImageToDiscord() {

  var link = "https://i.imgur.com/image.jpg";
  var img = UrlFetchApp.fetch(link).getBlob();

  var discordUrl = "https://discordapp.com/api/webhooks/mywebhook";

  var payload = {
    "file": img
  };

  var params = {
    headers: {
        "Content-Type": "multipart/form-data"
    },
    method: "post",
    payload: payload,
    muteHttpExceptions: true
  };

  var response = UrlFetchApp.fetch(discordUrl, params);

  Logger.log(response.getContentText());

}

However, GAS tells me that I'm trying to send an empty message. Can anyone help me?

Error Message

The error must be related to either the way of me trying to download the image:

var img = UrlFetchApp.fetch(link).getBlob();

or the way of how I define the payload for the multipart/form-data content:

 var payload = {
    "file": img
 };
1
Post exact error code,line number .. which line caused the error etc... - TheMaster
It's either the payload variable definition var payload = { "file": img }; or the way I try to GET the image UrlFetchApp.fetch(link).getBlob() that causes the error. The rest of the code should be correct, because with little changes I can send a simple text message just fine. But uploading a file is where I hit a wall. - Item

1 Answers

2
votes

How about this modification?

Modified script:

var params = {
  headers: {
      "Content-Type": "multipart/form-data"
  },
  method: "post",
  payload: payload,
  muteHttpExceptions: true
};
var params = {
  method: "post",
  payload: payload,
  muteHttpExceptions: true
};

Additional information:

For example, if you want to add the text to the file, please use the following request body.

var payload = {
  content: "sample text", // Added
  file: img
};
var params = {
  method: "post",
  payload: payload,
  muteHttpExceptions: true
};

Reference:

In my environment, I am using such request body. And it works fine. But if in your environment, it didn't work, please tell me. I would like to think of other solutions.