I want to use Google Apps Script to integrate a Google Sheets with an API
This is the documentation from the API service:
curl --location --request POST 'https://apinew.socialhub.pro/api/sendMessage' \
--form 'api_token="SEU API_TOKEN AQUI"' \
--form 'phone="NUMERO DESTINO"' \
--form 'file=@"DIRETÓRIO DO ARQUIVO"' \
--form 'message="MENSAGEM"'
I have manage to create a script in Google App Script that works perfectly:
function send_message_teste(telephone,message) {
var url = "https://apinew.socialhub.pro/api/sendMessage";
telephone = telephone.toString();
let request = {
"api_token":"MY_TOKEN",
"phone":telephone,
"message":message
};
let resquest_body = JSON.stringify(request);
let config = {
muteHttpExceptions: true,
method: "post",
headers: {
"Content-Type": "application/json"
},
payload:resquest_body
};
let response = UrlFetchApp.fetch(url, config);
var data = JSON.parse(response.getContentText());
return response
}
My problem is that I can not make this work with a file. The API documentation has only the curl example. I have manage to translate this example to Google App Script, but I got stuck when trying to send a file through the API. Can anyone help me?
I believe your goal is as follows.
You want to convert the following curl command to Google Apps Script.
curl --location --request POST 'https://apinew.socialhub.pro/api/sendMessage' \
--form 'api_token="SEU API_TOKEN AQUI"' \
--form 'phone="NUMERO DESTINO"' \
--form 'file=@"DIRETÓRIO DO ARQUIVO"' \
--form 'message="MENSAGEM"'
I thought that when I saw your curl command, the request is multipart/form-data
. But, in your showing script, it seems that the value is sent ad JSON data. I thought that this might be the reason for your current issue. When this is reflected in a sample script, how about the following sample script?
Please set the file ID of your file on Google Drive to fileId
.
function send_message_teste(telephone,message) {
const fileId = "###"; // Please set your file ID of the file you want to upload.
var url = "https://apinew.socialhub.pro/api/sendMessage";
telephone = telephone.toString();
let request = {
"api_token": "MY_TOKEN",
"phone": telephone,
"message": message
};
const payload = { ...request, file: DriveApp.getFileById(fileId).getBlob() };
let config = { muteHttpExceptions: true, payload };
let response = UrlFetchApp.fetch(url, config);
var data = JSON.parse(response.getContentText());
return response;
}
payload
is included, the POST method is automatically used.I think that the request of this modified script is the same with the above curl command. But, if an error occurs, please confirm your values of request
and fileId
, again.
If the structure of multipart/form-data
of this modified script cannot be used in your API, this Google Apps Script library might be able to be used. Ref (Author: me)