How to get notification from google drive sheet on edit? - google-drive-realtime-api

I want to send notification to third party application when someone make changes in document stored in google drive.
can someone please help me that how to bound script with any document and when someone make changes in that script should run and send notification to third party application.
I have tried the following code But it is not working.
function onEdit(event){
var sheet = event.source.getActiveSheet();
var editedRow = sheet.getActiveRange().getRowIndex();
var editedolumn = sheet.getActiveRange().getColumnIndex();
var values = sheet.getSheetValues(editedRow, editedolumn, 1, 6);
Logger.log(values);
getSession();
}
function getSession(){
var payload =
{
"username" : "username",
"password" : "password",
};
var options =
{
"method" : "post",
"payload" : payload,
"followRedirects" : false
};
var login = UrlFetchApp.fetch("https://abcd.service-now.com/nav_to.do?uri=login.do" , options);
Logger.log(login);
var sessionDetails = login.getAllHeaders()['Set-Cookie'];
Logger.log(sessionDetails);
sendHttpPost(sessionDetails);
}
function sendHttpPost(data) {
var payload = {"category" : "network","short_description" : "Test"};
var headers = {"Cookie" : data}
var url = 'https://abcd.service-now.com/api/now/table/incident';
var options = {'method': 'post','headers': headers,'payload': payload,'json': true};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response.getContentText());
}

To send notification to third party application when someone make changes in document stored in google drive
Based from this Google Drive Help Forum, this feature hasn't been added yet. However, you may set notifications in a spreadsheet to find out when there's some modifications done in your spreadsheet. To set notifications in a spreadsheet:
Open the spreadsheet where you want to set notifications.
Click Tools > Notification rules.
In the window that appears, select when and how often you want to
receive notifications.
Click Save.
And, to bound script with any document
You may find the complete guide in Scripts Bound to Google Sheets, Docs, or Forms documentation. As mentioned,
To create a bound script, open a Google Sheets, Docs, or Forms file, then select Tools > Script editor. To reopen the script in the future, do the same thing. Because bound scripts do not appear in Google Drive, that menu is the only way to find or open the script.

Related

Datastudio Community Connector - Add filter

I have a site with hundreds of members who would like to see activity relating to their products. We use datastudio at the moment, creating a report manually for a few who have asked.
We would like to be able to send out a single report that grabs the member details from the url and sets the report to that member. We followed the datastudio docs https://developers.google.com/datastudio/solution/viewers-cred-with-3p-credentials but it's not very clear
function getAuthType() {
var response = { type: 'NONE' };
return response;
}
function getConfig(request) {
var cc = DataStudioApp.createCommunityConnector();
var config = cc.getConfig();
config
.newTextInput()
.setId('token')
.setName('Enter user token')
.setAllowOverride(true);
config.setDateRangeRequired(false);
config.setIsSteppedConfig(false);
return config.build();
}
function getFields(request) {
var cc = DataStudioApp.createCommunityConnector();
var fields = cc.getFields();
var types = cc.FieldType;
fields.newDimension()
.setId('tokenValue')
.setType(types.TEXT);
return fields;
}
function getSchema(request) {
var fields = getFields(request).build();
return { schema: fields };
}
function getData(request) {
var token = request.configParams.token;
}
Has anyone set up a community connector that would allow multiple users to see a single report but only see what's specific to them?
I'm not sure if the token is being set property. It displays as the placeholder only. Is there a way to be sure what value my parameter is assigned?
We haven't got the the point of passing a url parameter. What we would like to do is pass the token value (Member details) to an existing filter. Is this possible in a community connector?
You can use the Filter by email address feature to filter your data based on the viewer's email address. This works out of the box and won't require you to build a custom connector.
Alternatively, if you do want to build a custom connector, follow this guide that seems more suitable for your use case.

Google App Script / Gmail add-on : How to display a window with text and buttons over Gmail?

I made a Google App script to answer automatically to my emails (a kind of clever email robot assistant). Nevertheless, I would like to check each answer made by the robot before sending.
So I would like to have a window over Gmail showing the user email and the robot answer, and two buttons "send" "skip". In this way, I could check the answer prepared by the robot and either send it or skip it (or potentially edit it).
How to display a window with text, editText and buttons over GMail from Google App Script ?
Thanks !
Regards.
You have to check Gmail Add-on : https://developers.google.com/gsuite/add-ons/gmail
For a first start you can check the codelab from Google, it will give you the code to set a first add-on in 5 minutes then you can adapt it to your needs : https://codelabs.developers.google.com/codelabs/apps-script-intro/
Stéphane
An easy solution would be to have the robot save the e-mail as 'draft'. That way, you can easily check the emails before manually sending them.
If you are still interested in creating the gmail add-on (which could display the original email, response, and buttons for sending or editing), you may be interested in building card-based interfaces. These will appear to the right of your Gmail web client, and will look like the following:
The code used to display such interface (with two buttons, one that automatically sends the email and another one that opens the editor on it) is the following:
function buildAddOn(e) {
// Activate temporary Gmail add-on scopes.
var accessToken = e.messageMetadata.accessToken;
GmailApp.setCurrentMessageAccessToken(accessToken);
return buildDraftCard(getNextDraft());
}
function buildDraftCard(draft) {
if (!draft) {
var header = CardService.newCardHeader().setTitle('Nothing to see here');
return CardService.newCardBuilder().setHeader(header).build();
} else {
var header = CardService.newCardHeader()
.setTitle(draft.getMessage().getSubject());
var section = CardService.newCardSection();
var messageViewer = CardService.newTextParagraph()
.setText(draft.getMessage().getBody());
var sendButton = CardService.newTextButton()
.setText('Send')
.setOnClickAction(CardService.newAction()
.setFunctionName('sendMessage')
.setParameters({'draftId': draft.getId()})
);
var editButton = CardService.newTextButton()
.setText('Edit')
.setOnClickAction(CardService.newAction()
.setFunctionName('editMessage')
.setParameters({'draftId': draft.getId()})
);
var buttonSet = CardService.newButtonSet()
.addButton(sendButton)
.addButton(editButton);
section.addWidget(messageViewer);
section.addWidget(buttonSet)
return CardService.newCardBuilder()
.setHeader(header)
.addSection(section)
.build();
}
}
function sendMessage(e) {
GmailApp.getDraft(e.parameters.draftId).send();
return CardService.newActionResponseBuilder().setNavigation(
CardService.newNavigation()
.popToRoot()
.updateCard(buildDraftCard(getNextDraft()))
).build();
}
function editMessage(e) {
var messageId = GmailApp.getDraft(e.parameters.draftId).getMessageId();
var link = "https://mail.google.com/mail/#all/" + messageId;
return CardService.newActionResponseBuilder().setOpenLink(
CardService.newOpenLink()
.setUrl(link)
.setOnClose(CardService.OnClose.RELOAD_ADD_ON)
).build();
}
function getNextDraft() {
return GmailApp.getDrafts().pop()
}
And the appsscript.json configuration is the following:
{
"oauthScopes": [
"https://www.googleapis.com/auth/gmail.addons.execute",
"https://mail.google.com/"
],
"gmail": {
"name": "Gmail Add-on Draft Autoresponse UI",
"logoUrl": "https://www.gstatic.com/images/icons/material/system/1x/label_googblue_24dp.png",
"contextualTriggers": [{
"unconditional": {
},
"onTriggerFunction": "buildAddOn"
}],
"openLinkUrlPrefixes": [
"https://mail.google.com/"
],
"primaryColor": "#4285F4",
"secondaryColor": "#4285F4"
}
}
Bear in mind however, that these interfaces at the moment still have some limitations. They can only be displayed whilst having a message open, and the HTML formatting of the email may look a bit off. You can find more information on how to test & run the code above by following this link.

Google apps script, openByURL returns missing file?

I've been trying to figure out why part of my Google App script doesn't work, but I've failed to come up with an answer.
The script is downloading an attachment, CSV, from an email in Gmail and stores in with a specific name in a specific folder - this works perfectly fine.
But then I want to edit the CSV, and this is where I run into problems.
var newFolderIterator = DriveApp.getFoldersByName(destinationFolderName)
var newFolderId, myFileName, myFileId
while(newFolderIterator.hasNext()) {
newFolderId = newFolderIterator.next().getId()
var newFileList = DriveApp.getFolderById(newFolderId).getFiles()
while(newFileList.hasNext()) {
myFileName = newFileList.next()
myFileId = myFileName.getId()
var myFileURL = myFileName.getUrl()
Logger.log(myFileName.getId() + " " + myFileName.getName()) //Logs the ID and Name
Logger.log(myFileURL) //Logs the URL
var ss = SpreadsheetApp.openById(myFileName.getId()) //Error, cannot find the ID (error message: perhaps it's missing?)
}
}
I've tried using the openByURL as well, with the same error message.
Probably really easy to fix, any hints and tips is appreciated.
Thanks
The problem here is you are uploading a CSV but attempting to open it with SpreadsheetApp. SpreadsheetApp can only open Google Sheets documents, and your CSV is not automatically converted.
The CSV must first be converted to a Google Sheets document before you can access it with SpreadsheetApp.
You may be able to do this on upload, but I haven't tried this personally. This question looks relevant:
How to automatically import data from uploaded CSV or XLS file into Google Sheets

using the googleapis library in dart to update a calendar and display it on a webpage

I am new to dart and I have been trying to figure out how to use the googleapis library to update a calendars events, then display the calendar/events on a webpage.
So far I have this code that I was hoping would just change the #text id's text to a list of events from the selected calendars ID:
import 'dart:html';
import 'package:googleapis/calendar/v3.dart';
import 'package:googleapis_auth/auth_io.dart';
final _credentials = new ServiceAccountCredentials.fromJson(r'''
{
"private_key_id": "myprivatekeyid",
"private_key": "myprivatekey",
"client_email": "myclientemail",
"client_id": "myclientid",
"type": "service_account"
}
''');
const _SCOPES = const [CalendarApi.CalendarScope];
void main() {
clientViaServiceAccount(_credentials, _SCOPES).then((http_client) {
var calendar = new CalendarApi(http_client);
String adminPanelCalendarId = 'mycalendarID';
var event = calendar.events;
var events = event.list(adminPanelCalendarId);
events.then((showEvents) {
querySelector("#text2").text = showEvents.toString();
});
});
}
But nothing displays on the webpage. I think I am misunderstanding how to use client-side and server-side code in dart... Do I break up the file into multiple files? How would I go about updating a calendar and displaying it on a web page with dart?
I'm familiar with the browser package, but this is the first time I have written anything with server-side libraries(googleapis uses dart:io so I assume it's server-side? I cannot run the code in dartium).
If anybody could point me in the right direction, or provide an example as to how this could be accomplished, I would really appreciate it!
What you might be looking for is the hybrid flow. This produces two items
access credentials (for client side API access)
authorization code (for server side API access using the user credentials)
From the documentation:
Use case: A web application might want to get consent for accessing data on behalf of a user. The client part is a dynamic webapp which wants to open a popup which asks the user for consent. The webapp might want to use the credentials to make API calls, but the server may want to have offline access to user data as well.
The page Google+ Sign-In for server-side apps describes how this flow works.
Using the following code you can display the events of a calendar associated with the logged account. In this example i used createImplicitBrowserFlow ( see the documentation at https://pub.dartlang.org/packages/googleapis_auth ) with id and key from Google Cloud Console Project.
import 'dart:html';
import 'package:googleapis/calendar/v3.dart';
import 'package:googleapis_auth/auth_browser.dart' as auth;
var id = new auth.ClientId("<yourID>", "<yourKey>");
var scopes = [CalendarApi.CalendarScope];
void main() {
auth.createImplicitBrowserFlow(id, scopes).then((auth.BrowserOAuth2Flow flow) {
flow.clientViaUserConsent().then((auth.AuthClient client) {
var calendar = new CalendarApi(client);
String adminPanelCalendarId = 'primary';
var event = calendar.events;
var events = event.list(adminPanelCalendarId);
events.then((showEvents) {
showEvents.items.forEach((Event ev) { print(ev.summary); });
querySelector("#text2").text = showEvents.toString();
});
client.close();
flow.close();
});
});
}

How to POST data to an online table without credentials

I have an HTML page that produces data (a table row). I want to store rows from all clients in an online table which can be accessed/downloaded (preferably by the owner alone, so anonymous clients can only add rows)
Possible solutions and encountered problems:
Google spreadsheet + google apps script - How to do a cross origin POST request?
Google fusion tables - How to add rows from anonymous clients? Is that possible?
Google app engine - possible, but seems too time consuming for this simple task.
I've found an answer on how to do cross domain POST, so I've managed to do what I want with apps script + spreadsheet:
Apps script:
function doPost(request) {
var ss = SpreadsheetApp.openById(id);
var sheet = ss.getSheets()[0];
if (request.parameters.row != null) {
sheet.appendRow(Utilities.jsonParse(request.parameters.row));
}
}
Client javascript (from https://stackoverflow.com/a/6169703/378594):
function crossDomainPost(paramsDict, url) {
// Add the iframe with a unique name
var iframe = document.createElement("iframe");
var uniqueString = "SOME_UNIQUE_STRING";
document.body.appendChild(iframe);
iframe.style.display = "none";
iframe.contentWindow.name = uniqueString;
// construct a form with hidden inputs, targeting the iframe
var form = document.createElement("form");
form.target = uniqueString;
form.action = url;
form.method = "POST";
// repeat for each parameter
for (i in paramsDict) {
var input = document.createElement("input");
input.type = "hidden";
input.name = i;
input.value = paramsDict[i];
form.appendChild(input);
}
document.body.appendChild(form);
form.submit();
}
crossDomainPost({'row': JSON.stringify([123, 123, 1211])}, serverURL);
Note that a similar scheme should work for Google fusion tables.

Resources