Google oAuth prob. Google Sign in is disabled - google-apps-script

I am using a script that checks if current active email is registered in our sheet later on we noticed that the script gives us an error called "Sign in with Google temporarily disabled for this app" we send a review for this concern with the google and this the reply. My question is how can I achieve this? what is the proper way to solve this .thnx
Here is my code.
function doGet() {
var HR_SprdSheet = SpreadsheetApp.openById("Awesome Sheet Link Here :D");
var HR_Sheet = HR_SprdSheet.getSheetByName("Email Registration");
var Email_Range = HR_Sheet.getRange("A3:A");
var Email_Values = Email_Range.getDisplayValues();
var Appl_Email = Session.getActiveUser().getEmail();
var message;
var notfound = HtmlService.createHtmlOutputFromFile("notfound.html");
var sample = HtmlService.createHtmlOutputFromFile("sample .html");
for (var i = 0; i < Email_Values.length; i++) {
if (Email_Values[i][0] == Appl_Email) {
message = 1;
break;
} else {
message = 0;
}
}
if (message == 1) {
return sample ;
} else {
Logger.log(1);
return notfound;
}
}
Here is the scopes

Related

How to list all emails a Google calendar was shared with?

I would like to get all emails a google Calendar was shared with.
It seems to me that Calendar.CalendarList.list will not give me required info
/**
* Lists the calendars shown in the user's calendar list.
*/
function listCalendars() {
var calendars;
var pageToken;
do {
calendars = Calendar.CalendarList.list({
maxResults: 100,
pageToken: pageToken
});
if (calendars.items && calendars.items.length > 0) {
for (var i = 0; i < calendars.items.length; i++) {
var calendar = calendars.items[i];
Logger.log('%s (ID: %s)', calendar.summary, calendar.id);
}
} else {
Logger.log('No calendars found.');
}
pageToken = calendars.nextPageToken;
} while (pageToken);
}
Calendar.Acl.get(calId, "user:"+user) looks promising but I do not know how go get the info I want. Someone could help?
Suggestion
Perhaps you can try this sample script below that was derived from this similar post.
Sample Script
function aclTest(){
calendarId = 'Calendar_ID';
calendars_acl_list = Calendar.Acl.list(calendarId);
for (var i = 0; i < calendars_acl_list.items.length; i++) {
var info = calendars_acl_list.items[i];
if(info.role != "owner" && !info.id.includes("domain")){
Logger.log(info.id);
}
}
}
Sample Test:
Sample Test Calendar
Apps Script result:

Google App Scripts / TwitterLib getting error Exception when trying to post a tweet

Trying to implement TwitterLib to send tweets from Google Sheets. I am using Google App Scripts, and the following code -
var sheet = SpreadsheetApp.getActive().getSheetByName('View');
var startRowNumber = 1;
var endRowNumber = sheet.getLastRow();
function sendTweets() {
var twitterKeys = {
TWITTER_CONSUMER_KEY: "xxxxxxxxxxxxxxxxxxx",
TWITTER_CONSUMER_SECRET: "xxxxxxxxxxxxxxxxxxx",
TWITTER_ACCESS_TOKEN: "xxxxxxxxxxxxxxxxxxx",
TWITTER_ACCESS_SECRET: "xxxxxxxxxxxxxxxxxxx"
}
var props = PropertiesService.getScriptProperties();
props.setProperties(twitterKeys);
var params = new Array(0);
var service = new Twitterlib.OAuth(props);
var quote;
var identifier;
for (var currentRowNumber = startRowNumber; currentRowNumber <= endRowNumber; currentRowNumber++) {
var row = sheet.getRange(currentRowNumber + ":" + currentRowNumber).getValues();
// check that the second column (Date) is equal to today
if (isToday(row[0][1])) {
quote = row[0][0];
identifier = currentRowNumber - 1;
if (!service.hasAccess()) {
console.log("Authentication Failed");
} else {
console.log("Authentication Successful");
var status = quote + "\n\n" + "#Quotes #Motivation";
try {
var response = service.sendTweet(status, params);
console.log(response);
} catch (e) { console.log(e) }
}
break;
}
}
}
function isToday(date) {
var today = new Date();
var dateFromRow = new Date(date);
return dateFromRow.getDate() == today.getDate() &&
dateFromRow.getMonth() == today.getMonth() &&
dateFromRow.getFullYear() == today.getFullYear()
}
I have signed up for Twitter DEV and have my API Key and Secret (CONSUMER_KEY and CONSUMER_SECRET above) and Access Token and Access Secret as well. I have turned on OAuth 1.0a, Read and write and Direct Message selected, and a Callback URI of (https://script.google.com/macros/s/YOUR_SCRIPT_ID/usercallback) - Replacing YOUR_SCRIPT_ID with the actual one I have.
I am seeing an Authentication Successful message in my Console, but seeing this error when running inside Apps Scripts IDE:
Send tweet failure. Error was: {"name":"Exception"}
Nothing more. I am not sure what else to check to see what I am doing wrong. Any help or resources to read over would greatly be appreciated! Thank you so much!
JJ

How do I resolve a "Exception: Service Error: Drive" for folder.addViewer();?

I am new to using Google Script and am trying to fix a pre-existing script. My organization uses a Google apps script to add and remove bulk viewers and editors to a folder. Every time I try and run the script, I get an error message saying
"Exception: Service Error: Drive"
# the line in the code which contains:
folder.addViewer();
what can I do to resolve this error?
For context, this is the section of code that line belongs to. userstoadd and editorstoadd are both variables.
function autoadd() {
var folder = DriveApp.getFolderById("folderid");
var usersheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('name');
var viewers = folder.getViewers();
var editors = folder.getEditors();
viewers = viewers.map(function(item) {
return
item.getEmail().toLowerCase();
}).sort();
editors = editors.map(function(item) {
return item.getEmail().toLowerCase();
}).sort();
viewers = viewers.concat(editors);
var userstoadd = usersheet.getRange('H2:H').getValues().filter(String).map(function(item) {
return item[0].toLowerCase();
});
var editorstoadd = usersheet.getRange('C2:C').getValues().filter(String).map(function(item) {
return item[0].toLowerCase();
});
for (var i = 0; i < userstoadd.length; i++) {
if (viewers.indexOf(userstoadd[i]) == -1 && editorstoadd.indexOf(userstoadd[i]) == -1) {
folder.addViewer(userstoadd[i]);
console.log(userstoadd[i]);
}
}
for (var i = 0; i < editorstoadd.length; i++) {
if (editors.indexOf(editorstoadd[i]) == -1) {
folder.addEditor(editorstoadd[i]);
console.log(editorstoadd[i]);
}
}
}

Is there a limit to how many G-Forms i can link to a singe google spreadshee?

I have a script that is designed to create about 120 forms and link them to a single spreadsheet where I will analyze the data. I don't have any issues with the script until my spreadsheet has about a dozen forms linked to it. Then I get an error saying the destination ID is invalid, after logging the id, and entering it manually into a url I see no issues with the ID....
var ssSummaryId = '******redacted*******';
var form = FormApp.create('RM#' + rmNumber).setDestination(FormApp.DestinationType.SPREADSHEET, ssSummaryId);
form.setDescription(valuesSummary[ii][2])
.setConfirmationMessage('Thanks for the update on room ' + rmNumber)
.setShowLinkToRespondAgain(false);
// form.setDestination(FormApp.DestinationType.SPREADSHEET, ssSummaryId);
var formId = form.getId();
var formUrl = form.getPublishedUrl();
EDIT I'm adding my complete script and some additional info, just in case someone wants to check my code out and point out all it rookie mistakes.
I'm using Google scripts to build a spreadsheet and then create 120 slightly altered Google forms that are linked to a single spreadsheet, all the responses are by design on separate sheets named "form responses n". I consistently hit a wall once I exceed 10 forms linked to one sheet. Note; in initial testing I remember having a spreadsheet with 46 forms (and therefore sheets) linked to it. As you can see in the code below, I have the app restart from where it's left off after every 5 forms are created, so I'm not getting any 'extended runtime errors". Just the error below, typically after the script runs twice from Google Scripts IDE.
I'm just finally getting the hand of basic javascript after years of using and modifying js in web developing. So I apologize in advanced for the poor code.
Failed to set response destination. Verify the destination ID and try again. (line 54, file "Code")
function spreadsheet_builder() {
var ssSummaryId = '<<REDACTED>>';
var ssFormDataId = '<<REDACTED>>';
var batchSize = 5;
var buildStatus = false;
var ssSummary = SpreadsheetApp.openById(ssSummaryId);
SpreadsheetApp.setActiveSpreadsheet(ssSummary);
if (ssSummary.getSheetByName('Summary') == null) {
var sheetSummary = ssSummary.getSheetByName('Sheet1');
} else {
var sheetSummary = ssSummary.getSheetByName('Summary');
}
var rangeSummary = sheetSummary.getDataRange();
var valuesSummary = rangeSummary.getValues();
buildStatus = get_last_position(valuesSummary, buildStatus); //either returns last position in array or 'true' if task is complete
if (buildStatus != true || buildStatus > 0) {
var formCreation = [];
var formData = get_form_data(ssFormDataId); // Get form questions from form Data ss, might be better to keep everything on the same sheet
batchSize = buildStatus + batchSize;
for ( var ii = buildStatus; ii < batchSize; ii++ ) {
if (valuesSummary[ii][1] != '') {
var formCreationReturn = form_builder(formData, valuesSummary, ii, ssSummaryId);
formCreation.push(formCreationReturn);
}
}
var aSum = [ssSummary, sheetSummary, rangeSummary];
final_storing_operation(formCreation, aSum, buildStatus);
}
if (sheetSummary.getName() != 'Summary') {
SpreadsheetApp.setActiveSpreadsheet(ssSummary);
sheetSummary.activate().setName('Summary');
sheetSummary.setFrozenColumns(3);
sheetSummary.setFrozenRows(1);
sheetSummary.hideColumns(1);
//var sSumIndex = sheetSummary.getIndex();
}
SpreadsheetApp.setActiveSpreadsheet(ssSummary);
sheetSummary.activate();
ssSummary.moveActiveSheet(1);
}
function form_builder(formData, valuesSummary, ii, ssSummaryId) {
var lastFormCreated = ii;
var rmNumber = valuesSummary[ii][1];
var form = FormApp.create('RM#' + rmNumber).setDestination(FormApp.DestinationType.SPREADSHEET, ssSummaryId);
form.setDescription(valuesSummary[ii][2])
.setConfirmationMessage('Thanks for the update on room ' + rmNumber)
.setShowLinkToRespondAgain(false);
// form.setDestination(FormApp.DestinationType.SPREADSHEET, ssSummaryId);
var formId = form.getId();
var formUrl = form.getPublishedUrl();
var sectionHeader = 'SECTION_HEADER'; //preformatted form question types.
var list = 'LIST';
var paragraphText = 'PARAGRAPH_TEXT';
for (var j = 1; j < formData.length; j++) { //top row is header
switch (formData[j][0]) {
case sectionHeader:
form.addSectionHeaderItem().setTitle(formData[j][1]);
break;
case list:
var item = form.addListItem();
item.setTitle(formData[j][1]).setHelpText(formData[j][2]);
item.setChoices([
item.createChoice(formData[j][3]),
item.createChoice(formData[j][4]),
item.createChoice(formData[j][5])
]);
break;
case paragraphText:
form.addParagraphTextItem().setTitle(formData[j][1]);
break;
default:
form.addSectionHeaderItem().setTitle('OOPS u\'don MESSED up');
break;
}
}
return [formId, formUrl, lastFormCreated, rmNumber];
}
function final_storing_operation(formCreation, aSum, buildStatus) {
SpreadsheetApp.setActiveSpreadsheet(aSum[0]);
aSum[1].activate();
var startRow = formCreation[0][2] + 1;
var newRange = aSum[1].getRange(startRow, 1, formCreation.length, 2); //row, clmn, rows, columns
var newValues = [];
for ( var ij = 0; ij < formCreation.length; ij++) {
var values = [formCreation[ij][0], "\=HYPERLINK(\"" + formCreation[ij][1] + "\", \"RM#" + formCreation[ij][3] + "\")"];
newValues.push(values);
}
newRange.setValues(newValues);
}
function get_last_position (valuesSummary, buildStatus) {
var rowPos = 1; // start at 1 to ignore headers
while (valuesSummary[rowPos][1] != '') {
if (valuesSummary[rowPos][0] == '') {
return rowPos;
}
rowPos++;
}
if(valuesSummary[rowPos][0] != '' && valuesSummary[rowPos][1] != '') {
buildStatus = true;
return buildStatus;
}
}
function get_form_data (ssFormDataId) {
var ssFormData = SpreadsheetApp.openById(ssFormDataId);
SpreadsheetApp.setActiveSpreadsheet(ssFormData);
var sheetFormData = ssFormData.getSheets()[0];
var rangeFormData = sheetFormData.getDataRange();
var valuesFormData = rangeFormData.getValues();
return valuesFormData;
}
As an alternative, you could create the forms, and intentionally not link them to a spreadsheet, then have some code that looped through every form, and extracted the data. You'd probably want to put the forms into their own folder.
Or, you'd need to build a form with Apps Script HTML Service, embed it into a Apps Script Gadget in a Google Site, and have everyone fill out the form from Sites.

How to get the URL of a page where a Google Script Gadget is embedded

I'm looking for a method that allows me to get the URL of the current page where a Google Script Gadget is embedded.
I tried using getActivePage() but that only returns my Google Site's home page. According to this issue: http://code.google.com/p/google-apps-script-issues/issues/detail?id=568 get active site and get active page is defective but that was in September 2011...
Here is my code:
var site = SitesApp.getActivePage();
Am I using getActivePage() incorrectly?
Thank you for your help in advance.
Edit 1 attempt:
var templates = site.getTemplates();
var template;
var names = '';
for (var i = 0; i < templates.length; i++) {
if (templates[i].getName() == 'profile') {
template = templates[i];
break;
}
}
if (template != null) {
var pageName = name;
Logger.log('Found: ' + pageName);
site.createPageFromTemplate(pageName, pageName, template);
}
else {
Logger.log('Not Found');
}
I created the following script
function doGet(e) {
var app = UiApp.createApplication();
var lbl = app.createTextArea();
lbl.setWidth('100%');
lbl.setHeight('100%');
var txt = SitesApp.getActivePage().getUrl();
lbl.setText(txt);
app.add(lbl);
return app;
}
and a couple of pages embedding the Google Script Gadget linked with this script. The script's output is the same as the URL in the internet browser address bar.
#LehanCoetzee code.
var templ = HtmlService.createTemplateFromFile('profile').evaluate();
site.createPageFromTemplate(name + ' ' + surname, name, templ);
'profile' is an html template I created through the apps script editor.
Edit 01:
I created a template page with a Gadget linked to my script above. The script's name is ProfileTemplate. Also I created a new page with the following script.
function doGet(e) {
var app = UiApp.createApplication();
var panel = app.createVerticalPanel();
var tb = app.createTextBox().setName('tb').setId('tb');
var btn = app.createButton().setText('Create').setId('btn');
var out = app.createTextArea().setId('out');
var handler = app.createServerHandler('onBtnClick');
handler.addCallbackElement(panel);
btn.addClickHandler(handler);
panel.add(tb);
panel.add(btn);
panel.add(out);
app.add(panel);
return app;
}
function onBtnClick(e) {
var app = UiApp.getActiveApplication();
var site = SitesApp.getActiveSite();
var out = app.getElementById('out');
var templates = site.getTemplates();
var template;
var names = '';
for (var i = 0; i < templates.length; i++) {
if (templates[i].getName() == 'profiletemplate') {
template = templates[i];
break;
}
}
if (template != null) {
var pageName = e.parameter.tb;
out.setText('Found: ' + pageName);
site.createPageFromTemplate(pageName, pageName, template);
}
else {
out.setText('Not Found');
}
return app;
}
If to open the new page, to type a text, for instance, test1 or test2, and click the Create button, then a new page from the template will be created. The templated page will have have an URL similar to https://sites.google.com/a/..../.../test1 for the text "test1" and the Gadget's output will contain this text.