How to upload an image to Discord using Google Apps Script and a Discord Webhook?

爷,独闯天下 提交于 2020-08-08 10:13:35

问题


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:


How about this modification?

Modified script:

From:
var params = {
  headers: {
      "Content-Type": "multipart/form-data"
  },
  method: "post",
  payload: payload,
  muteHttpExceptions: true
};
To:
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:

  • Webhook Resource

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.



来源:https://stackoverflow.com/questions/52509999/how-to-upload-an-image-to-discord-using-google-apps-script-and-a-discord-webhook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!