botmaker API post JSON google sheet script - json

I have google sheet with data that I need to send using WhatsApp, so I have the API of Botmaker. They give a cURL and JSON data but I do not know how to use the cURL and JSON to do the post usen a google scrip function.
This is the cURL:
curl
- X POST
--header 'Content-Type: multipart/form-data'
--header 'Accept: application/json'
--header 'access-token: myAccessToken'
-F chatPlatform=whatsapp
-F chatChannelNumber=############
-F platformContactId=############
-F mediaType=document
This is the Request URL of the API: 'https://go.botmaker.com/api/v1.0/message/binary/v3'
This is the Response Body:
no content
This the Response Code:
401
Response Headers:
{
"accept": "[application/json, application/xml, text/plain]",
"access-control-allow-credentials": "true",
"access-control-allow-headers": "bearer-token,access-token,Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin",
"access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS, HEAD",
"access-control-allow-origin": "https://go.botmaker.com",
"alt-svc": "h3=\":443\"; ma=2592000,h3-29=\":443\"; ma=2592000",
"cache-control": "must-revalidate,no-cache,no-store",
"content-length": "0",
"content-security-policy": "default-src 'self'",
"date": "Sat, 11 Jun 2022 22:52:02 GMT",
"permissions-policy": "geolocation=(self \"https://go.botmaker.com\"), microphone=()",
"reason-phrase": "Cannot authenticate user with received tokens after applying [access-token] and accessToken [null]",
"referrer-policy": "no-referrer",
"server": "Botmaker",
"strict-transport-security": "max-age=31536000; includeSubDomains",
"via": "1.1 google",
"x-content-type-options": "nosniff",
"x-frame-options": "DENY"
}
I understand that I need to use the UrlFetchApp.fetch
Someone can help me to create

I found the way, here is how it works for me:
var userNumber = '123456789012' // to: cellular phone number
const waNumber = '123456789012'; // from: cellular phone
const accessToken = 'faketoken'; // use you token
// send a template
var url = 'https://go.botmaker.com/api/v1.0/intent/v2';
var headers = {
'Content-Type': 'application/json' ,
'Accept': 'application/json' ,
'access-token': accessToken
};
var dataJson = {
"chatPlatform": "whatsapp",
"chatChannelNumber": waNumber,
"platformContactId": userNumber,
"ruleNameOrId": "template_name" // the name of the template
};
var payload = JSON.stringify(dataJson);
var options = {
'method': 'POST',
'headers': headers,
'payload': payload
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);

Related

How to turn Postman API's request into Apps Script code?

I'm currently using Postman to do an API post request from a CRM software called Intercom.
I followed the below documentation to do this:
https://developers.intercom.com/intercom-api-reference/v0/reference/creating-an-export-job
My purpose is to create a script via Google Apps Script to automate the API request.
I need to give the following elements:
Method: Post
URL: https://api.intercom.io/export/content/data
Headers: Authorization : Bearer 123456789, Accept : application/json, Content-Type: application/json
Body: "created_at_after": 1654041600, "created_at_before": 1656547200 (this is the date in Unix Timestamp)
The only parameter that will change is the body ("created_at_after" and "created_at_before"). Everything else will remain the same.
Below is the script I've created, that currently does not work.
Any help on how to fix this would be appreciated. I'm quite a beginner programmer so apologies in advance if the problem is quite obvious.
function exportjob() {
var url = 'https://api.intercom.io/export/content/data';
var options = {
"Method": "post",
"Headers": {
"Authorization": "Bearer 123456789",
"Accept": "application/json",
"Content-Type": "application/json"
},
"Body": {
"created_at_after": 1654041600,
"created_at_before": 1656547200}
}
var response = UrlFetchApp.fetch(url, options);
}
From your showing document, I believe your goal is as follows.
You want to convert the following curl command to Google Apps Script.
curl https://api.intercom.io/export/content/data \
-X POST \
-H 'Authorization:Bearer <Your access token>' \
-H 'Accept: application/json' \
-H 'Content-Type: application/json' -d '
{
"created_at_after": 1527811200,
"created_at_before": 1530316800
}'
Modification points:
At params of fetch(url, params) of Class UrlFetchApp, there are no properties of Method, Headers, Body.
In your situation, it seems that it is required to be sent the data as the string. And, by the content type of application/json, the data is parsed at the server side.
When these points are reflected in your script, how about the following modification?
Modified script:
function exportjob() {
var url = 'https://api.intercom.io/export/content/data';
var options = {
"method": "post",
"headers": {
"Authorization": "Bearer 123456789",
"Accept": "application/json",
},
"contentType": "application/json",
"payload": JSON.stringify({
"created_at_after": 1654041600,
"created_at_before": 1656547200
})
}
var response = UrlFetchApp.fetch(url, options);
console.log(response.getContentText())
}
Note:
If an error occurs for the request, please confirm your access token and the data again. And, please provide the error message.
Reference:
fetch(url, params)

API access works in curl but UrlFetchApp returns 400 Bad Request

I'm trying to access my Home Assistant API and it works fine using curl, but not in Google Apps Script using UrlFetchApp. Using curl works fine:
curl -X GET -H "Authorization: Bearer longFunkyCodeLikeThisiJ9.eyJpc3Mijk5fQ.0Fpw8I" -H "Content-Type: application/json" https://mydevice.duckdns.org:8123/api/states/sensor.my_special_sensor
Google Apps Script returns a 400 Bad Request error.
var HOME_ASSISTANT_TOKEN = "longFunkyCodeLikeThisiJ9.eyJpc3Mijk5fQ.0Fpw8I"
var HOME_ASSISTANT_URL = "https://mydevice.duckdns.org:8123/api/"
function testTemp() {
console.log(getDeviceParameters('sensor.my_special_sensor'));
}
function getDeviceParameters(id) {
var url = HOME_ASSISTANT_URL + "states/" + id;
Logger.log(url);
var bearer = "Bearer " + HOME_ASSISTANT_TOKEN;
var headers = {
"Authorization": bearer,
"Content-Type": 'application/json',
};
var params = {
method: 'get',
headers: headers
};
return UrlFetchApp.fetch(url, params ).getContentText();
}
What am I doing wrong?
It seems Google Apps Script may be blocking port 8123. The script functions by using by instead using your nabu casa url which operates out of port 80.
Just change the HOME_ASSISTANT_URL value to https://[yourspecialcode].ui.nabu.casa/api/

GAS: Error 401 while connecting to an API

I'm trying to connect to Cloud Waitress API, a solution for restaurants,
Documentation: https://apidocs.cloudwaitress.com/#orderpromos
It's documentation gives an example on how to connect to the API:
curl https://api.cloudwaitress.com/v1/orders \
-X POST \
-H "Content-Type: application/json" \
-H "Authorization: YOUR_API_KEY" \
-d `
{
"restaurant_id": "xxxxxxx",
"limit": 10,
"page": 1,
"sort": { "created": -1 },
}
I tried to create a Script in GAS to get the information back to a Spreadsheet.
Based on this question:
How curl maps onto Google App Script URLFetchApp
I have changed my code as follows:
function getAuthHeader(){
var apiKey = "SOME-API-KEY";
var authHeader = Utilities.base64Encode(apiKey);
return {
headers: {Authorization: authHeader}
}
}
function GetOrders(){
var url = "https://api.cloudwaitress.com/v1/orders";
var data = {
"restaurant_id":"SOME-RESTAURANT-ID",
"limit": 10,
"page": 1,
"sort": { "created": 1 }
};
var result = goPost(url ,data);
}
function goPost(url,data){
var options = {
'method' : 'post',
'payload' : data,
'headers': getAuthHeader()['headers']
};
var response;
try{
response = JSON.parse(UrlFetchApp.fetch(url,options).getContentText());
}catch(err){
Logger.log(err);
}
return response;
}
Right now the new error that I'm getting is:
Exception: Request failed for https://api.cloudwaitress.com returned
code 401. Truncated server response: {"outcome":1,"message":"Invalid
Authentication"} (use muteHttpExceptions option to examine full
response)
Which I believe is quite a progress since I was getting an 500 error before.
I have asked the cloudwaitress team their assistance, however I wonder if there is something else I can try.
How about this modification?
Modification points:
At your sample curl, "Content-Type: application/json" is used, and the JSON object is converted to the string.
The thread you refered uses the basic authorization like -u testtoken123:. By this, Utilities.base64Encode is required be used. But in your sample curl, the API key is directly used.
I thought that this might be the reason of the error message.
When above points are reflected to your script, it becomes as follows.
Modified script:
From:
var options = {
'method' : 'post',
'payload' : data,
'headers': getAuthHeader()['headers']
};
To:
var apiKey = "SOME-API-KEY";
var options = {
'method' : 'post',
'payload' : JSON.stringify(data),
'headers': {Authorization: apiKey},
'contentType': "application/json",
};
In this case, getAuthHeader() is not used.
Note:
The request of this modified script is the same with your sample curl command. But in this modified script, it supposes that your apiKey and data can be used for this API. Please be careful this.
Reference:
Class UrlFetchApp

UrlFetchApp Token Authorization

I am trying to fetch a URL using GScript's UrlFetchApp. The URL requires Token API Key to be passed in request header.
url = 'https://freshsales.io/search?q=abc';
var options = {
'method' : 'get',
'headers':{
'Authorization': "Token token=XYZ"
}
};
var response = UrlFetchApp.fetch(url, options);
This does not fetch me the expected response, as pasted below:
Freshsales
window.NREUM||(NREUM={});NREUM.info={"beacon":"bam.nr-data.net","errorBeacon":"bam.nr-data.net","licenseKey":"","applicationID":"33348835,33348834","transactionName":"e11YEBQJXVlXER1LUllAVQxJFVRUQABaF0RdU0QHDg==","queueTime":1,"applicationTime":30,"agent":""}
(window.NREUM||(NREUM={})).loader_config={xpid:"VQcDVl5UDxADV1JWDwkEUw==",licenseKey:"",applicationID:"33348835"};window.NREUM||(NREUM={}),__nr_require=function(t,n,e){function
r(e){if(!n[e]){var
o=n[e]={exports:{}};t[e][0].call(o.exports,function(n){var
o=t[e][1][n];return r(o||n)},o,o.exports)}return
n[e].exports}if("function"==typeof __nr_require)return
__nr_require;for(var o=0;o0&&(p-=1)}),s.on("internal-error",function(t){i("ierr",[t,c.now(),!0])})},{}],3:[function(t,n,e){t("loader").features.ins=!0},{}],4:[function(t,n,e){function
r(t){}if(window.performance&&window.performance.timing&&window.performance.getEntriesByType){var
o=t("ee"),i=t("handle"),a=t(9),s=t(8),c="learResourceTimings",f="addEventListener",u="resourcetimingbufferfull",d="bstResource",l="resource",p="-start",h="-end",m="fn"+p,w="fn"+h,v="bstTimer",g="pushState",y=t("loader");y.features.stn=!0,t(7),"addEventListener"in window&&t(5);var x=NREUM.o.EV;o.on(m,function(t,n){var e=t[0];e
instanceof x&&(this.bstStart=y.now())}),o.on(w,function(t,n){var
e=t[0];e instanceof
x&&i("bst",[e,n,this.bstStart,y.now()])}),a.on(m,function(t,n,e){this.bstStart=y.now(),this.bstType=e}),a.on(w,function(t,n){i(v,[n,this.bstStart,y.now(),this.bstType])}),s.on(m,function(){this.bstStart=y.now()}),s.on(w,function(t,n){i(v,[n,this.bstStart,y.now(),"requestAnimationFrame"])}),o.on(g+p,function(t){this.time=y.now(),this.startPath=location.pathname+location.hash}),o.on(g+h,function(t){i("bstHist",[location.pathname+location.hash,this.startPath,this.time])}),f
in
window.performance&&(window.performance["c"+c]?window.performancef:window.performancef),documentf,documentf,documentf}},{}],5:[function(t,n,e){function
r(t){for(var
n=t;n&&!n.hasOwnProperty(u);)n=Object.getPrototypeOf(n);n&&o(n)}function
o(t){s.inPlace(t,[u,d],"-",i)}function i(t,n){return t[1]}var
a=t("ee").get("events"),s=t("wrap-function")(a,!0),c=t("gos"),f=XMLHttpRequest,u="addEventListener",d="removeEventListener";n.exports=a,"getPrototypeOf"in
Object?(r(document),r(window),r(f.prototype)):f.prototype.hasOwnProperty(u)&&(o(window),o(f.prototype)),a.on(u+"-start",function(t,n){var
e=t[1],r=c(e,"nr#wrapped",function(){function
t(){if("function"==typeof e.handleEvent)return
e.handleEvent.apply(e,arguments)}var n={object:t,"function":e}[typeof
e];return
n?s(n,"fn-",null,n.name||"anonymous"):e});this.wrapped=t[1]=r}),a.on(d+"-start",function(t){t[1]=this.wrapped||t[1]})},{}],6:[function(t,n,e){function
r(t,n,e){var r=t[n];"function"==typeof r&&(t[n]=function(){var
t=i(arguments),n={};o.emit(e+"before-start",[t],n);var
a;n[m]&&n[m].dt&&(a=n[m].dt);var s=r.apply(this,t);return
o.emit(e+"start",[t,a],s),s.then(function(t){return
o.emit(e+"end",[null,t],s),t},function(t){throw
o.emit(e+"end",[t],s),t})})}var
o=t("ee").get("fetch"),i=t(22),a=t(21);n.exports=o;var
s=window,c="fetch-",f=c+"body-",u=["arrayBuffer","blob","json","text","formData"],d=s.Request,l=s.Response,p=s.fetch,h="prototype",m="nr#context";d&&l&&p&&(a(u,function(t,n){r(d[h],n,f),r(l[h],n,f)}),r(s,"fetch",c),o.on(c+"end",function(t,n){var
e=this;if(n){var
r=n.headers.get("content-length");null!==r&&(e.rxSize=r),o.emit(c+"done",[null,n],e)}else
o.emit(c+"done",[t],e)}))},{}],7:[function(t,n,e){var
r=t("ee").get("history"),o=t("wrap-function")(r);n.exports=r;var
i=window.history&&window.history.constructor&&window.history.constructor.prototype,a=window.history;i&&i.pushState&&i.replaceState&&(a=i),o.inPlace(a,["pushState","replaceState"],"-")},{}],8:[function(t,n,e){var
r=t("ee").get("raf"),o=t("wrap-function")(r),i="equestAnimationFrame";n.exports=r,o.inPlace(window,["r"+i,"mozR"+i,"webkitR"+i,"msR"+i],"raf-"),r.on("raf-start",function(t){t[0]=o(t[0],"fn-")})},{}],9:[function(t,n,e){function
r(t,n,e){t[0]=a(t[0],"fn-",null,e)}function
o(t,n,e){this.method=e,this.timerDuration=isNaN(t[1])?0:+t[1],t[0]=a(t[0],"fn-",this,e)}var
i=t("ee").get("timer"),a=t("wrap-function")(i),s="setTimeout",c="setInterval",f="clearTimeout",u="-start",d="-";n.exports=i,a.inPlace(window,[s,"setImmediate"],s+d),a.inPlace(window,[c],c+d),a.inPlace(window,[f,"clearImmediate"],f+d),i.on(c+u,r),i.on(s+u,o)},{}],10:[function(t,n,e){function
r(t,n){d.inPlace(n,["onreadystatechange"],"fn-",s)}function o(){var
t=this,n=u.context(t);t.readyState>3&&!n.resolved&&(n.resolved=!0,u.emit("xhr-resolved",[],t)),d.inPlace(t,g,"fn-",s)}function
i(t){y.push(t),h&&(b?b.then(a):w?w(a):(E=-E,O.data=E))}function
a(){for(var t=0;t
I tested the same via python (code below) and it works perfectly.
url = "https://freshsales.io/search?q=abe"
payload = {}
headers = {
'Authorization': 'Token token=XYZ'
}
response = requests.request("GET", url, headers=headers, data = payload)
Response from Python code:
[
{
"id": "1000705745",
"name": "MKnight",
"email": "mknight#xxx.gov",
"owner": {
"id": 1000002014,
"name": "Tim"
},
"updated_at": "2020-02-13T04:57:29Z",
"primary_sales_account_name": "City of XYZ",
"type": "contact"
} ]
Any thoughts on what i may be missing here ?
Add the contentType that you can accept to force the returned content type from the server:
headers:{
Accept: "application/json",
Authorization: "Token token=XYZ"
}

Can not create folder using multipart

I always get:
Missing end boundary in multipart body.
API Sandbox doesn't help. It is possible to create folder there.
The request is:
curl https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart -d #/home/payload -H 'Authorization: Bearer mytoken' -H 'Content-Type: multipart/boundary; boundary=RubyApiClientUpload'
The payload is:
--RubyApiClientUpload
Content-Type: application/json
{ "mimeType":"application/vnd.google-apps.folder", "name":"newfolder", "parents":["0AMtAREF....."] }
--RubyApiClientUpload
--RubyApiClientUpload--
You're using the wrong API call. A folder has no content, so you create it by POSTing to the URL in https://developers.google.com/drive/v3/reference/files/create
You can easily test it at https://developers.google.com/drive/v3/reference/files/create#try-it where you should see
POST https://www.googleapis.com/drive/v3/files?key={YOUR_API_KEY}
{
"mimeType": "application/vnd.google-apps.folder",
"name": "test folder"
}
This code works for me.
const body = JSON.stringify({
name: "Super folder!!!",
mimeType: "application/vnd.google-apps.folder"
});
const headers = new Headers();
headers.append("Authorization", `Bearer ${accessToken}`);
headers.append("Content-Type", "application/json");
headers.append("Content-Length", body.length);
fetch(
"https://www.googleapis.com/drive/v3/files", {
method: "POST",
headers,
body
});