Send data to Influxdb using Google app script - google-apps-script

I'm trying to send the data to Influxdb using Google app script with the below code but I always run into Bad Request error. The same works when I send the data using the Influxdb API. Unable to figure out what am I missing here. Any suggestions would be appreciated.
function dataentry() {
var response;
var tags = {
"PROGRAM":"Migration"
}
var fields = {
"TESTED_BY": "Peter",
"RESULT":1,
"STATUS":"Fail"
}
var data = {"measurement":"testing","tags":tags,"time":,"fields":fields};
Logger.log(JSON.stringify(data));
var options = {
"method" : "post",
"muteHttpExceptions" : true,
"contentType": "application/json",
"payload" : JSON.stringify(data)
//"payload" : data
};
try {
response = UrlFetchApp.fetch('http://xx.xx.xx.xx:8086/write?db=mydbb', options);
Logger.log(response.getContentText());
}
catch(err) {
Logger.log(err);
}
}
Output: Exception: Bad request: http://xx.xx.xx.xx:8086/write?db=mydbb
Example of the Influxdb http write API -
curl -i -XPOST http://xx.xx.xx.xx:8086/write?db=mydbb --data-binary "testing,PROGRAM=Migration TESTED_BY=\"Peter\",STATUS=\"Fail\",RESULT=1"

Related

How to download media files in WhatsApp API which send users?

I am currently writing a chatbot for WhatsApp.
I use the 360dialog platform, which makes it possible to work with the WhatsApp Business API.
When the client sends a message, I see the following JSON object in the logs of my application:
{
"messages": [
{
"from": "77773336633",
"id": "ABGGd3c1cGY_Ago61ytHsZknvtLv",
"image": {
"id": "ffd23134-2dae-4fed-b5f8-0ce7867b6ddd",
"mime_type": "image/jpeg",
"sha256": "bd02100d961b5a1dbaae1dd645485ebbfeda77b44e82c015f1cf29b05654ccb9"
},
"timestamp": "1605703542",
"type": "image"
}
],
"contacts": [
{
"profile": {
"name": "Nurzhan Nogerbek"
},
"wa_id": "77773336633"
}
]
}
I can't find any information in the documentation about how to download this file.
In my case, I want to upload this image file that the client sends to my file storage.
Please tell me which URL method from the WhatsApp API is responsible for this mechanism?
P.S. At the same time, I can send files to clients. This information is available on the official documentation.
May be it will help, just try, take a look:-
const URL = `https://lookaside.fbsbx.com/whatsapp_business/attachments/?mid=1104480873777230&ext=1662705250&hash=ATuMx352sLrhKUegbQZSC8oLl3J5Vy3Z49lO4HwTUKWRYQ`;
const FROM = `video`;
const config = {
method: 'get',
url: URL, //PASS THE URL HERE, WHICH YOU RECEIVED WITH THE HELP OF MEDIA ID
headers: {
'Authorization': `Bearer ${token}`
},
responseType: 'arraybuffer'
};
axios(config)
.then(function (response) {
const ext = response.headers['content-type'].split("/")[1];
fs.writeFileSync(`${FROM}.${ext}`, response.data);
})
.catch(function (error) {
console.log(error);
});
It was very tricky because postman worked, but c# didn't work for me, and I spent two days trying to find the solution and finally did the following code, which works in C#:
using HttpClient _httpClient = new HttpClient();
Uri uri = new Uri(mediaUrl);
var fileName = $"{DateTime.Now.ToString("yyyyMMddhhmmss")}.jpeg";
string filePath = $"Files\\{fileName}";
// NOTE: to save bandwidth, request compressed content
_httpClient.DefaultRequestHeaders.AcceptEncoding.Clear();
_httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
_httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate"));
_httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("br"));
// NOTE: accept all languages
_httpClient.DefaultRequestHeaders.AcceptLanguage.Clear();
_httpClient.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("*"));
// NOTE: accept all media types
_httpClient.DefaultRequestHeaders.Accept.Clear();
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("image/jpeg"));
var productValue = new ProductInfoHeaderValue("ScraperBot", "1.0");
var commentValue = new ProductInfoHeaderValue("(+http://www.API.com/ScraperBot.html)");
_httpClient.DefaultRequestHeaders.UserAgent.Add(productValue);
_httpClient.DefaultRequestHeaders.UserAgent.Add(commentValue);
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", {WhatsApp_Access_Token});
HttpResponseMessage response = await _httpClient.GetAsync(uri);
response.EnsureSuccessStatusCode();
var mediaType = response?.Content?.Headers?.ContentType?.MediaType ?? string.Empty;
var imageBytes = await response.Content.ReadAsByteArrayAsync();
using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
fs.Write(imageBytes, 0, imageBytes.Length);
}
Here, {WhatsApp_Access_Token} is your Whatsapp API permanent token.
Ping me in a comment, please, if you have any issues or questions.
The official documentation has a session for this in https://developers.facebook.com/docs/whatsapp/api/media.
Basically you must make a GET request to download the media.
curl --request GET \
--url https://waba.360dialog.io/v1/media/{media id} \
--header 'D360-API-KEY: {your api token}'

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

Apps Script API returning 404 error for existing project. Error returned as HTML rather than JSON

I was attempting to run an Apps Script function using the Apps Script API. I set up the script in the console, and created an oauth client ID for the script. I configured the authorisation screen and deployed the script as API executable. I tested the api function calling in the same script but got a 404 error saying:
The Requested URL /v1/scripts/{{my_script_id}}:run was not found on this server.
The response came back as HTML. I also noticed that the script seems to make it's own client ID when it's called from the API.
I tried disabling and re-enabling the API which didn't work. I think it may be a problem with the calling application not being in the same project but I'm not sure how to do that as the Google documentation is unclear.
function trigger(){
var bogus = DriveApp.getRootFolder();
var argument = ["Value0", "Value1", "Value2", "Value3", "Value4", "Value5"];
// https://www.googleapis.com/auth/script.external_request
// https://www.googleapis.com/auth/spreadsheets
var postRequest = {
"Content-Type": "application/json",
"headers": { "Authorization" : "Bearer " + ScriptApp.getOAuthToken()},
"function": "setStatus",
"muteHttpExceptions": true,
"parameters": [argument],
"devMode": false
};
try{
var response = UrlFetchApp.fetch("https://script.googleapis.com/v1/scripts/{{my_script_id}}:run", postRequest);
Logger.log(response);
}catch(err){
Logger.log(err);
}
}
I expected some form of error in the form of JSON or maybe even for the function to run, what I got was a HTML document which displayed a 404 error when displayed.
You're not POSTing the request. Default .fetch method is GET.
Add this in postRequest object:
method: "POST",
payload is also missing from your postRequest.
Snippet:
var postRequest = {
"method":"POST", //added
"contentType": "application/json", //key changed
"headers": { "Authorization" : "Bearer " + ScriptApp.getOAuthToken()},
"muteHttpExceptions": true,
"payload": JSON.stringify({ //added
"function": "setStatus",
"parameters": argument, //removed []
"devMode": false
})
};
References:
UrlfetchApp
Script:run

GAS: Error when using UrlFetchApp

I am using the senotp serverside api to verify a number. When it is run using soap ui with the same content there's no error. But when I do it with UrlFetchApp it gives the error:
{"status":"error","response":{"code":"INVALID_REQUEST_BODY"}}
whereas the correct response should be:
{
"status": "success",
"response": {
"code": "OTP_SENT_SUCCESSFULLY",
"oneTimePassword": "34859"
}
}
The code I used is as foll0ws:
var payload =
{
"countryCode": "94",
"mobileNumber": "0766075555",
"getGeneratedOTP": true
};
var header=
{
"application-Key":"application_key_value"
};
var options =
{
"method" : "POST",
"headers":header,
"muteHttpExceptions": true,
"contentType":"application/json",
"payload" : payload
};
var request=UrlFetchApp.getRequest("https://sendotp.msg91.com/api/generateOTP", options)
Logger.log(request)
var response=UrlFetchApp.fetch("https://sendotp.msg91.com/api/generateOTP", options);
Logger.log(response);
I am not sure what is the problem here. Please help me debug it or let me know what is the problem with the code.
It seems as if using payload in GAS fetchService automatically results in contentType : application/x-www-form-urlencoded or contentType : multipart/form-data.
See documentention: https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#fetch(String,Object)
Unfortunately, I have not yet found a workaround.

How to send a JSON payload with UrlFetchApp service?

I'm trying to POST to a web service that is expecting to get JSON as payload using Google Apps Script. I'm using the following code:
var options =
{
"method" : "post",
"contentType" : "application/json",
"headers" : {
"Authorization" : "Basic <Base64 of user:password>"
},
"payload" : { "endDate": "2012-06-03" }
};
var response = UrlFetchApp.fetch("http://www.example.com/service/expecting/json", options);
On the server side I'm getting the following error:
WARN [facade.SettingsServlet] 04 Jun 2012 15:30:26 - Unable to parse request body: endDate=2012-06-03
net.liftweb.json.JsonParser$ParseException: unknown token e
I'm assuming that the server is expecting to get
{ "endDate": "2012-06-03" }
instead of
endDate=2012-06-03
but I don't know how to make the UrlFetchApp do it.
I do not understand the server side error but the 'payload' parameter must be a string as specified here: https://developers.google.com/apps-script/class_urlfetchapp?hl=fr-FR#fetch.
try:
var options =
{
"method" : "post",
"contentType" : "application/json",
"headers" : {
"Authorization" : "Basic <Base64 of user:password>"
},
"payload" : '{ "endDate": "2012-06-03" }'
};
If you set payload as a String, it will be passed directly (as a
UTF-8 string).
If you set payload as an Object, it will be sent like
an HTML form (which means either 'application/x-www-form-urlencoded' if the
fields are simple, or 'multipart/form-data' if the Object includes a
blob/file).
For your use case (the server is expecting to receive JSON), it sounds like Utilities.jsonStringify() is the way to go.
Something like this worked for me in a similar situation:
Instead of creating payload and adding to options, I built the parameters into a string to append to the URL:
var params = "id=2179853&price=62755";
then, I appended params to the url string:
var result = UrlFetchApp.getRequest(url + '?' + params, options);
So, my options was passed containing only the header.
For my project, this worked like a charm.
Here goes the code that should work with some important comments:
function testMe() {
var products_authkey = "------------";
try {
var url = "https://app.ecwid.com/api/v1/---------/product?id=----------&secure_auth_key=" + products_authkey;
//url= "http://requestb.in/----------"; // you can actually debug what you send out with PUTs or POSTs using Requestb.in service
var payload = {
id: "21798583", // id is necessary and should be a string, or it might be sent in scientific representation (with E)
price: 62755
};
payload = JSON.stringify(payload); // the payload needs to be sent as a string, so we need this
var options = {
method: "put",
contentType: "application/json", // contentType property was mistyped as ContentType - case matters
payload: payload
};
var result = UrlFetchApp.getRequest(url, options);
Logger.log(result) // a better way to debug
var result = UrlFetchApp.fetch(url, options); // works perfectly in my case
Logger.log(result)
} catch (e) {
Logger.log(e)
}
}