问题
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