Read Google Spreadsheets conditonal format information - google-sheets-api

I wish to read google spreadsheets conditional format information with script. I do it as below:
function readConditionalFormatInfo() {
var url = "https://sheets.googleapis.com/v4/spreadsheets/spreadsheetId?fields=sheets(properties(title,sheetId),conditionalFormats)"
var response = UrlFetchApp.fetch(url)
Logger.log(response)
}
But error happen:
Request failed for https://sheets.googleapis.com/v4/spreadsheets/spreadsheetId?fields=sheets(properties(title,sheetId),conditionalFormats) returned code 403. Truncated server response: { "error": { "code": 403, "message": "The request is missing a valid API key.", "status": "PERMISSION_DENIED" } } (use muteHttpExceptions option to examine full response) (line 214, file "Code")
Maybe I should not run REST API in GAS but I don't know how to do it in script!
Appreciate if anyone can help!

Something like below:
function readConditionalFormat() {
var sheet = SpreadsheetApp.getActive().getActiveSheet();
var rules = sheet.getConditionalFormatRules();
if (rules != null) {
for (var i=0;i<rules.length;i++) {
var rule = rules[i].getBooleanCondition()
var criteria = rule.getCriteriaType()
var value = rule.getCriteriaValues()
var bakcolor = rule.getBackground()
Logger.log(criteria+ " -> " + value + ":" + bakcolor);
}
} else {
Logger.log('Conditional Format rule null')
}
}

Related

Hangouts Chat Bot "The caller does not have permission", PERMISSION_DENIED

I created a chat bot using the JAVA Api, based on the sample code from the documentation,
the Bot uses a service account.
The Bot works fine in one Room, but when I try to use it with a new Room I am experiencing an error.
After adding the Bot to the new Room and trying to post a message I receive
{ "code" : 403, "errors" : [ { "domain" : "global", "message" : "The caller does not have permission", "reason" : "forbidden" } ], "message" : "The caller does not have permission", "status" : "PERMISSION_DENIED" }
Is there any additional step necessary after adding the Bot to a room before posting messages ?
Any help with this problem would be greatly appreciated!
Code used:
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = new JacksonFactory();
HangoutsChat.Builder builder = new HangoutsChat.Builder(httpTransport, jsonFactory, credentials);
builder.setApplicationName(bot);
HangoutsChat service = builder.build();
ListSpacesResponse response = service.spaces().list().execute();
// Look for space Space _space = null;
while (response.getSpaces() != null && _space == null) {
for(Space s : response.getSpaces()) {
if(s.getDisplayName().equals(space)) {
_space = s;
}
}
if (_space == null && response.getNextPageToken() != null && !response.getNextPageToken().isEmpty()) {
String pageToken = response.getNextPageToken();
response = service.spaces().list().setPageToken(pageToken).execute();
} else {
break;
}
}
if(_space != null) {
Message m = new Message();
byte[] data = {0x0A};
m.setText(text.replace("\\r", "").replace("\\n", new String(data)));
Message r = service.spaces().messages().create(_space.getName(), m).setThreadKey(thread).execute();
Element el = new Element("message");
el.setAttribute("space", r.getSpace().getDisplayName());
el.setAttribute("text", r.getText());
el.setAttribute("thread", r.getThread().getName());
outNode.addContent(el);
} else {
throw new Exception("SendHangouts failed " + "Space " + space + " not found");
}

How to get weight data from Google fitness api?

Existing script for step count works perfectly and I can get the data from Google Fit
// see step count example at https://developers.google.com/fit/scenarios/read-daily-
step-total
function getSteps() {
var start = new Date();
start.setHours(0,0,0,0);
start.setDate(start.getDate()-1);
var end = new Date();
end.setHours(23,59,59,999);
end.setDate(end.getDate()-1);
var fitService = getFitService();
var request = {
"aggregateBy": [{
"dataTypeName": "com.google.step_count.delta",
"dataSourceId": "derived:com.google.step_count.delta:com.google.android.gms:estimated_steps"
}],
"bucketByTime": { "durationMillis": 86400000 },
"startTimeMillis": start.getTime(),
"endTimeMillis": end.getTime()
};
var response = UrlFetchApp.fetch('https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate', {
headers: {
Authorization: 'Bearer ' + fitService.getAccessToken()
},
'method' : 'post',
'contentType' : 'application/json',
'payload' : JSON.stringify(request, null, 2)
});
var json = JSON.parse(response.getContentText());
var steps = json.bucket[0].dataset[0].point[0].value[0].intVal;
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Weight');
sheet.appendRow([start, steps]);
}
Now I am trying to change this code to get by changing below 2 lines
"dataTypeName": "com.google.weight.summary",
"derived:com.google.step_count.delta:com.google.android.gms:merge_weight"
But I get an error at the response statement. Get an error stating
Request failed for https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate returned code 400. Truncated server response: { "error": { "errors": [ { "domain": "global", "reason": "invalidArgument", "message": "datasource not found: derived:<?> (use muteHttpExceptions option to examine full response) (line 39, file "Code")
Could not find what to define for the FetchURL to get the weight data. I coul dnot find any examples on getting weight.
As mentioned earlier the code works perfectly fine to get step count.
Any help is appreciated.
Solved: There was a typo in my dataSourceId. It should have been as below
"dataSourceId": "derived:com.google.weight:com.google.android.gms:merge_weight"
And when getting the weight data, we need to use fpVal instead of intVal
var steps = json.bucket[0].dataset[0].point[0].value[0].fpVal;
Thanks to Robert who provided the original script on his blog and also pointed out my mistake.
Link to blog article is here
https://ithoughthecamewithyou.com/post/export-google-fit-daily-steps-to-a-google-sheet

Display dynamic data with JSON API Jquery

I've been reading about Javascript for 2 days now and I'm still confused. I'm familiar with HTML and CSS. My goal is to display a dynamic value on my website. The data will be from an API call using JSON.
The URL i'm using displays info like this
{
"error" : 0,
"error_message" : "-",
"amount" : 35.63000
}
What I want to do is take the "amount" variable and display it on my website. So far I have managed to jumble a bunch of code together that barely makes sense to me. I'm probably using all the wrong syntax so I will continue to try and figure this out myself. All this does it displays a static variable in "div1". What is the best way to convert the variable from the API call to show instead.
$.getJSON('https://www.amdoren.com/api/currency.php?api_key=jbqe5fH8AykJTFbnyR7Hf3d2n3KVQR&from=USD&to=THB&amount=1', function(data) {
//data is the JSON string
});
////
var $items = $('#amount')
var obj = {}
$items.each(function() {
obj[this.id] = $(this).val();
})
var json = JSON.stringify(obj);
///
var obj = [ {
"error": 0,
"error_message": "-",
"amount": 35.60000 ///THIS IS OBVIOUSLY STATIC...
}]
var tbl = $("<table/>").attr("id", "mytable");
$("#div1").append(tbl);
for (var i = 0; i < obj.length; i++) {
var tr = "<tr>";
var td3 = "<td>" + obj[i]["amount"] + "</td></tr>";
$("#mytable").append(tr + td3);
}

QuickBlox create user issue (bad request) without any error message

I want to create an user using the rest API. Rest API returns an error (bad request), when I made the request. There are not any other error messages.
JSON:
Required Parameters : login, password, email
http://quickblox.com/developers/Users#API_User_Sign_Up
{
"user":
{
"login":"user123456",
"password":"User11#2015",
"email":"xxx#ccc.com.tr",
"blob_id":null,
"external_user_id":null,
"facebook_id":null,
"twitter_id":null,
"full_name":null,
"phone":null,
"website":null,
"custom_data":null,
"tag_list":null
}
}
Rest API Result:
Response Status Code : BadRequest.
Response Content is empty. No error message.
I do not understand the error. Can you help me?
Code :
public NotificationUser CreateUser(string token, NotificationUser notificationUser)
{
var user = new QuickbloxUser()
{
email = notificationUser.Email,
password = notificationUser.Password,
login = notificationUser.Login
};
var jsonBody = JsonConvert.SerializeObject(user);
var request = new RestRequest("users.json", Method.POST);
request.AddHeader("QB-Token", token);
request.AddParameter("user", jsonBody);
var response = _restClient.Execute<RootUser<QuickbloxUserResponse>>(request);
if (response.StatusCode == HttpStatusCode.OK)
{
notificationUser.Id = response.Data.user.id;
notificationUser.Email = response.Data.user.email;
notificationUser.Login = response.Data.user.login;
return notificationUser;
}
return null;
}

Uploaded image on parse.com gives 403 error

I am trying to upload image to parse.com using REST API, and associating to an object as shown in docs
I am getting the fileUrl from phonegap / appgyver-supersonic camera api.
The Image is uploaded successfully and also associated successfully to the "receipt" object but accessing the url gives 403 error.
How do I access the URL and view the uploaded image, I get a white page (with broken image icon) and 403 error.
File :
http://files.parsetfss.com/68087456-8a5a-403a-820f-13912d2c0911/tfss-5d0edbdb-730b-4cd6-a44f-f0ce1e2ab120-pic.jpg
My receipt class has public write/read access.
Here is my code :
$scope.send = function(fileURL, mimeType){
function win(r) {
$scope.textvar = r;
var response = JSON.parse(r.response);
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
var req = {
method: 'POST',
url: 'https://api.parse.com/1/classes/receipt',
headers: {
'X-Parse-Application-Id':'XXXXXXXXXXXXX',
'X-Parse-REST-API-Key':'XXXXXXXXXXXXXXXX',
"Content-Type": "application/json"
},
data: {"name": "user_receipts",
"images": {
"name": response.name,
"__type" : "File"
}
}
}
$http(req).success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log("image association success ");
console.log(data);
console.log(headers);
console.log(status);
console.log(config);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
function fail(error) {
console.log("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
console.log("upload error http-code " + error.http_status);
}
var uri = encodeURI("https://api.parse.com/1/files/pic.jpg");
var options = new FileUploadOptions();
options.fileKey="data-binary";
options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1);
options.mimeType=mimeType;
var headers = {"X-Parse-Application-Id": "XXXXXXXXXXXXXXXXX",
"X-Parse-REST-API-Key":"XXXXXXXXXXXXXXXX",
"Content-Type":"image/jpeg"};
options.headers = headers;
var ft = new FileTransfer();
ft.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable) {
console.log("length : "+progressEvent.loaded/progressEvent.total);
} else {
console.log("loaded : "+progressEvent.loaded);
}
};
ft.upload(fileURL, uri, win, fail, options);
};
I have wasted 5 days on this already, Please Help.
I am no expert in either appgyver / phonegap or parse.com