Update Fusion Table From - google-apps-script

Hi Experts,
I was trying to update fusion table from google spreadsheet. I tried with the codes available in Google's documentation pages and some others also but seems to be broken.
Treads that I read
Thread 1,,,
Thread 2
Code that I tried:
Code 1
Every time am getting
Request failed for https://www.google.com/accounts/Client Login returned code 403
Please tell me how to update fusion table from google spreadsheet.
Thanks a lot,
Anees Hameed.

After repeated trails I was able to create code which read data from fusion table and write to logger console:
function GetData()
{
var FUSION_URL = 'https://www.googleapis.com/fusiontables/v1/query?';
var APIkey = 'key=AIzaSyDdZu1nYAxFa2Wm5DTVYwlAejxET5Wb8XE';
var query = 'sql=SELECT * FROM 1k6N_-P-wZ2ZMh8B_2Doym5oLsAJXdXHAqZO_H0I WHERE Ratings=7';
var options =
{
method : 'get',
};
var response = UrlFetchApp.fetch(FUSION_URL+"+query+"&"+APIkey, options);
Logger.log(response );
}
And then I tried to write data to sql tables using 'post' method, but it is not working.
function WriteData()
{
var FUSION_URL = 'https://www.googleapis.com/fusiontables/v1/query?';
var APIkey = 'key=AIzaSyDdZu1nYAxFa2Wm5DTVYwlAejxET5Wb8XE';
var query = 'sql=DELETE FROM 1k6N_-P-wZ2ZMh8B_2Doym5oLsAJXdXHAqZO_H0I WHERE Ratings=7';
var options =
{
method : 'post',
payload : query,
headers : {
key: APIkey
},
};
var responce = UrlFetchApp.fetch(FUSION_URL, options);
Logger.log(responce);
}

Related

UrlFetchApp returns no data from Wikidata SPARQL service

I'm trying to use Google Apps Script contained in a sheet to return XML from the Wikidata web service for SPARQL queries. I have a simple working SPARQL query and am using the URL-escaped https string, per the instructions in the Wikidata user guide.
Per the code below, I've tried UrlFetchApp.Fetch() both with and without the options parameter, but I always get an empty response. When I test the "simpleQry" url in my browser, it returns the correct xml file. I don't use web services very often, so I may be missing something obvious. Any help is greatly appreciated!
First I set the fetch options with JSON
//set http header values w/json
var headr = {
'Accept': 'application/sparql-results+xml'
};
//set options values w/json
var options = {
'method': 'get',
'header': headr
};
Then I submit the request:
simpleQry = "https://query.wikidata.org/sparql?query=select%20%3FpersonLabel%20%3FemployerLabel%20%3FworksLabel%0Awhere%20%7B%0A%20%20VALUES%20%3Fperson%20%7Bwd%3AQ112129152%7D%20.%0A%20%20%3Fperson%20wdt%3AP108%20%3Femployer%20.%0A%20%20%3Fperson%20wdt%3AP800%20%3Fworks%20.%0A%20%20SERVICE%20wikibase%3Alabel%20%7B%20bd%3AserviceParam%20wikibase%3Alanguage%20'%5BAUTO_LANGUAGE%5D%2Cen'.%20%7D%0A%20%20%7D";
var response = UrlFetchApp.fetch(simpleQry, options);
var dataAllxml = XmlService.parse(response.getContentText());
Process the results. This where the error gets uncovered. Length of content = 0.
var rows = [], data;
for (i = 0; i < dataAllxml.length; i++) {
data = dataAllxml[i];
rows.push([data.personLabel, data.employerLabel, data.worksLabel]); //
}
Modification points:
XmlService.parse(response.getContentText()) returns XML Object. By this, dataAllxml.length becomes undefined. By this, the for loop is not run. I think that this is the reason for your issue of Process the results. This where the error gets uncovered. Length of content = 0..
When this is reflected in your script, it becomes as follows.
Modified script:
function myFunction() {
var headr = {
'Accept': 'application/sparql-results+xml'
};
var options = {
'method': 'get',
'header': headr
};
var simpleQry = "https://query.wikidata.org/sparql?query=select%20%3FpersonLabel%20%3FemployerLabel%20%3FworksLabel%0Awhere%20%7B%0A%20%20VALUES%20%3Fperson%20%7Bwd%3AQ112129152%7D%20.%0A%20%20%3Fperson%20wdt%3AP108%20%3Femployer%20.%0A%20%20%3Fperson%20wdt%3AP800%20%3Fworks%20.%0A%20%20SERVICE%20wikibase%3Alabel%20%7B%20bd%3AserviceParam%20wikibase%3Alanguage%20'%5BAUTO_LANGUAGE%5D%2Cen'.%20%7D%0A%20%20%7D";
var response = UrlFetchApp.fetch(simpleQry, options);
var dataAllxml = XmlService.parse(response.getContentText());
// I modified below script.
var root = dataAllxml.getRootElement();
var ns = root.getNamespace();
var rows = root.getChild("results", ns).getChildren().map(e => e.getChildren().map(f => f.getValue().trim()));
console.log(rows);
}
Testing:
When this modified script is run, the following result is obtained.
[
["Ramona L. Pérez","San Diego State University","Good and bad death: exploring the perspectives of older Mexican Americans."],
["Ramona L. Pérez","San Diego State University","Diabetes Cultural Beliefs and Traditional Medicine Use Among Health Center Patients in Oaxaca, Mexico."],
["Ramona L. Pérez","San Diego State University","Exposure to smoking in soap operas and movies: smoking cessation and attempts to quit."]
]
References:
XML Service
map()

How to fix code 401 when auto filling google forms using google sheets scripts editor?

I am trying to develop a program that automatically fills out a google form using the data provided in google sheets.
This is my code.
function auto_data_entry() {
var formURL = "(URL of the form would be put here)";
var workbook = SpreadsheetApp.getActiveSpreadsheet();
var worksheet = workbook.getSheetByName("Sheet1");
var full_name = worksheet.getRange("A2").getValue();
var year = worksheet.getRange("B2").getValue();
var month = worksheet.getRange("C2").getValue();
var day = worksheet.getRange("D2").getValue();
var period = worksheet.getRange("E2").getValue();
var datamap =
{
"entry.1901360617": full_name,
"entry.43103907_year": year,
"entry.43103907_month": month,
"entry.43103907_day": day,
"entry.1047848587": period
};
var options =
{
"method": "post",
"payload": datamap
};
UrlFetchApp.fetch(formURL, options); //Line 27
}
However, it returns...
Exception: Request failed for https://docs.google.com returned code 401.
Truncated server response: <!DOCTYPE html><html lang="en"><head><meta name="description"
content="Web word processing, presentations and spreadsheets"><meta name="viewport" c...
(use muteHttpExceptions option to examine full response) (line 27, file "Code")
Is the problem that I am using a school owned google account or that there is an error with my code.
I am very lost and would appreciate it if someone could help out.
There is no need to use UrlFetchApp because you can use the Class FormResponse and the Class ItemResponse. This code will help you with your issue:
function autoDataEntry() {
// Get the desire form with its questions and create
// a response to later be submitted
var form = FormApp.openById("YOUR-FORM-ID");
var formResponse = form.createResponse();
var formQuestions = form.getItems();
var workbook = SpreadsheetApp.getActiveSpreadsheet();
var worksheet = workbook.getSheetByName("Sheet1");
// Get all the needed values in the second row
var answers = worksheet.getRange("A2:E2").getValues();
answers[0].forEach((answer, answerNumber) => {
// Get the question depending of its type
var question = getQuestion(formQuestions, answerNumber);
// Create the response to your question with the value obtained in the sheet
var formAnswer = question.createResponse(answer);
// Add the answer to the response
formResponse.withItemResponse(formAnswer);
});
// submit the form response
formResponse.submit();
}
What I did was to get the form where you want to send your response and the sheet where the answers are. Then I iterated through those answers to add them to the respective question, which would be added to the form response. When that process is finished, then you only need to submit the form response.
Edit
I modified my code by adding the following function and calling it inside the forEach in my autoDataEntry function:
// This function will return the question as the requiered type
function getQuestion(formQuestions, answerNumber){
var questionType = formQuestions[answerNumber].getType();
switch(questionType){
case FormApp.ItemType.TEXT:
return formQuestions[answerNumber].asTextItem();
case FormApp.ItemType.MULTIPLE_CHOICE:
return formQuestions[answerNumber].asMultipleChoiceItem();
case FormApp.ItemType.DATE:
return formQuestions[answerNumber].asDateItem();
}
}
In that way, you will get the proper question type as the situation requires as long you have set it as a condition in the switch statement. You can see all types in Enum ItemType.

getting active user name in Google sheets from external domain

I have a published web app:
function doGet(request) {
// DocumentApp.getActiveDocument();
SpreadsheetApp.getActive();
var about = Drive.About.get();
var user = about.name;
// Logger.log(Session.getActiveUser().getEmail());
return ContentService.createTextOutput(user);
}
... at this URL:
https://script.google.com/macros/s/AKfycbzTlhKJXrTAEPEba0l1KWqqzlkul2ntC-0iHi7_POj0wk7j3R6K/exec
Which produces the desired result the user's full name (after authorization to user's data is approved - subsequent running of the URL does not prompt for authentication or approval)
That is the data I want to retrieve from this App Script:
function Test3() {
var options = {
'method' : 'get',
'followRedirects' : true,
// 'validateHttpsCertificates' : 'true',
'muteHttpExceptions' : true,
'contentType' : 'null'
};
var url = "https://script.google.com/macros/s/AKfycbzTlhKJXrTAEPEba0l1KWqqzlkul2ntC-0iHi7_POj0wk7j3R6K/exec"
var response = UrlFetchApp.fetch(url, options);
// var response = test2() ;
// var myName = response.getContentText();
Browser.msgBox("[" + response + "]");
}
but I have not been able to get just that data. Instead I get an a page HTML text, which equates to a Google login page.
Again, just running the URL manually from a browser as any user results in the user name web page, so why when run from app script, it can't just retrieve the result of that page?
What am I missing? Surely I'm some simple syntax away from getting that data.

How to pull all user sharing activity using the Activity API inside App Script

I am new to Google API and got training wheels on for the App Script.
I need to know if there is a way to utilize the Activity API or any other inside App Script to pull sharing activity for all domain users.
Thanks in advance.
I got the following working for me but it is not showing me the "shared_externally" in particular, I need to use https://developers.google.com/admin-sdk/reports/v1/reference/activities/list api for all users on drive app, externally and internally shared filter.
function listShares() {
var userKey = 'all';
var applicationName = 'drive';
var optionalArgs = {
visibility: 'shared_externally'
};
var response = AdminReports.Activities.list(userKey, applicationName,
optionalArgs)
Logger.log(response);
}
My output is the same with or without the optionalArgs for shared_externally, can someone help with the proper syntax for the visibility arguments?
Ok I got it to work, yay.
function listShares() {
var userKey = 'all';
var applicationName = 'drive';
var optionalArgs = {
filters: 'visibility==shared_externally'
};
var response = AdminReports.Activities.list(userKey, applicationName,
optionalArgs)
Logger.log(response);}

Google Spreadsheet Script: UrlFetchApp upload string as file

I saw this SO thread to upload a file using UrlFetchApp.
Also I saw this SO thread to post a string as file in python requests (without having a file or creating a temp file).
I want to send a string as file in Google Spreadsheet Script, and based on the two threads above I think it should be possible to do it without creating a temp file in google drive.
My question is how in Google Spreadsheet Script I can pretend the string is coming from a file and pass it to UrlFetchApp?
Here is the base code I am working on:
var string = 'test';
var url = "https://api.telegram.org/.../sendDocument";
var chat_id = "12345";
var data = {'chat_id': chat_id,
'text':text} ;
var headers = { "Accept":"application/json",
"Content-Type":"application/json"
};
var options = { "method":"POST",
"headers": headers,
"payload" : payload
};
var response = UrlFetchApp.fetch(url, options);
Here is how I got it right to post a string as file:
var url = "https://api.telegram.org/.../sendDocument";
var blob = Utilities.newBlob('Test!', 'text/plain', 'report.txt');
var data = {
'chat_id' : '12345',
'document': blob
};
var options = {
'method' : 'POST',
'payload' : data,
};
UrlFetchApp.fetch(url, options);
Thanks to comment from #Jack Brown and google developer example for posting blobs (example titled: Make a POST request with form data.).