Apps Script bot for webhooks - google-apps-script

I'm looking to see if anyone has created a chatbot in google apps script to handle webhooks for hangouts? I have a bot created but I'm not sure on how to input the webhook url into the bots code so that the message can be deployed into the chat room.

I have not exactly created what you are looking for, however I believe the answer you are looking for can be found here. Basically there is an event whenever your bot enters a space. When that event is triggered you can add the space id to a list stored somewhere.(Spreadsheet , PropertiesService,etc)
Once the list is stored you can deploy your application as a web app. You can read more about web apps here but two things you need to know is google gives you a url to make web requests to, as well as pair of events called doGet (when someone makes a get request) and doPost (when someone makes a post request). You can create the function do post and get the parameters when your web app is posted to.
Finally upon receiving the post you can do a fetch call to the google api to post the message you just received from the request to all of the spaces you are in by doing a api fetch call to each ID.
Below will be code directly posted from the API in the first link.
// Example bot for Hangouts Chat that demonstrates bot-initiated messages
// by spamming the user every minute.
//
// This bot makes use of the Apps Script OAuth2 library at:
// https://github.com/googlesamples/apps-script-oauth2
//
// Follow the instructions there to add the library to your script.
// When added to a space, we store the space's ID in ScriptProperties.
function onAddToSpace(e) {
PropertiesService.getScriptProperties()
.setProperty(e.space.name, '');
return {
'text': 'Hi! I\'ll post a message here every minute. ' +
'Please remove me after testing or I\'ll keep spamming you!'
};
}
// When removed from a space, we remove the space's ID from ScriptProperties.
function onRemoveFromSpace(e) {
PropertiesService.getScriptProperties()
.deleteProperty(e.space.name);
}
// Add a trigger that invokes this function every minute via the
// "Edit > Current Project's Triggers" menu. When it runs, it will
// post in each space the bot was added to.
function onTrigger() {
var spaceIds = PropertiesService.getScriptProperties()
.getKeys();
var message = { 'text': 'Hi! It\'s now ' + (new Date()) };
for (var i = 0; i < spaceIds.length; ++i) {
postMessage(spaceIds[i], message);
}
}
var SCOPE = 'https://www.googleapis.com/auth/chat.bot';
// The values below are copied from the JSON file downloaded upon
// service account creation.
var SERVICE_ACCOUNT_PRIVATE_KEY = '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE
KEY-----\n';
var SERVICE_ACCOUNT_EMAIL = 'service-account#project-id.iam.gserviceaccount.com';
// Posts a message into the given space ID via the API, using
// service account authentication.
function postMessage(spaceId, message) {
var service = OAuth2.createService('chat')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setPrivateKey(SERVICE_ACCOUNT_PRIVATE_KEY)
.setClientId(SERVICE_ACCOUNT_EMAIL)
.setPropertyStore(PropertiesService.getUserProperties())
.setScope(SCOPE);
if (!service.hasAccess()) {
Logger.log('Authentication error: %s', service.getLastError());
return;
}
var url = 'https://chat.googleapis.com/v1/' + spaceId + '/messages';
UrlFetchApp.fetch(url, {
method: 'post',
headers: { 'Authorization': 'Bearer ' + service.getAccessToken() },
contentType: 'application/json',
payload: JSON.stringify(message),
});
}

Related

Google Ads API with Google Apps Script no access token received

I am trying to use Google Ads on Google Apps Script using this guide. I created client id and client secret on Google Console's API & Services.
Not too sure if this configuration is correct but the account is linked to Google Apps Script as I have pagespeed insights as well and there are some requests on the dashboard. I added https://www.googleapis.com/auth/drive as the scope. Again not too sure if I should add Google Ads to the scope. Lastly, got my refresh token from Google Auth playground. When I run the script above I got the following error:
Error: No access token received: {
"error": "invalid_client",
"error_description": "Unauthorized"
}
authenticate_ # test.gs:120
withRefreshToken # test.gs:144
initializeOAuthClient # test.gs:28
Honestly not too sure what I am doing wrong here so any help would be very much appreciated. Thank you.
Edit
Codes:
//From Google Console API & Services
var CLIENT_ID = '"MY_CLIENT_ID';
var CLIENT_SECRET = 'MY_CLIENT_SECRET';
//From Google Authplayground
var REFRESH_TOKEN = 'REFRESH_TOKEN';
// Enter scopes which should match scopes in File > Project properties
// For this project, e.g.: https://www.googleapis.com/auth/drive
var SCOPES = "https://www.googleapis.com/auth/adwords";
// Script ID taken from 'File > Project Properties'
var SCRIPT_ID = 'MY_SCRIPT_ID';
var authUrlFetch;
// Call this function just once, to initialize the OAuth client.
function initializeOAuthClient() {
if (typeof OAuth2 === 'undefined') {
var libUrl = 'https://developers.google.com/google-ads/scripts/docs/examples/oauth20-library';
throw Error('OAuth2 library not found. Please take a copy of the OAuth2 ' +
'library from ' + libUrl + ' and append to the bottom of this script.');
}
var tokenUrl = 'https://accounts.google.com/o/oauth2/token';
authUrlFetch = OAuth2.withRefreshToken(tokenUrl, CLIENT_ID, CLIENT_SECRET,
REFRESH_TOKEN, SCOPES);
}
/**
* Execute a remote function.
* #param {string} remoteFunctionName The name of the function to execute.
* #param {Object[]} functionParams An array of JSON objects to pass to the
* remote function.
* #return {?Object} The return value from the function.
*/
function executeRemoteFunction(remoteFunctionName, functionParams) {
var apiParams = {
'function': remoteFunctionName,
'parameters': functionParams
};
var httpOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
payload: JSON.stringify(apiParams)
};
var url = 'https://script.googleapis.com/v1/scripts/' + SCRIPT_ID + ':run';
var response = authUrlFetch.fetch(url, httpOptions);
var data = JSON.parse(response.getContentText());
// Retrieve the value that has been returned from the execution.
if (data.error) {
throw Error('There was an error: ' + response.getContentText());
}
return data.response.result;
}
// Paste in OAuth2 library here, from:
// https://developers.google.com/google-ads/scripts/docs/examples/oauth20-library
I have pasted the oauth2.0 library under the codes above.
Edit 2
I fixed the part of function initializeOAuthClient. It now shows execution complete, but when I try to run function executeRemoteFunction I am getting TypeError: Cannot read property 'fetch' of undefined. I am guessing I have to input remoteFunctionName and functionParams but where do I find them?

Google Sheets AddOn - AppScript & BigQuery Integration via Service Account

I have a Google Sheets workspace addon and recently did some work to integrate BigQuery. Essentially BigQuery hold a record of books each of which has an author, title etc and my Addon allows people to pull the books that they have read into their sheet. The first column in the sheet allows people to choose from all the authors in the DB, based on that selection the second column is populated with data from BigQuery with all books by that author etc etc. There is no need for my AddOn to access a user's BigQuery, they only access 'my' BgQuery.
This all works fine, but when I submitted my addon for approval I was told
Unfortunately, we cannot approve your request for the use of the following scopes
https://www.googleapis.com/auth/bigquery
We recommend using service accounts for this type of information exchange.
This seems fair and reading up on Service Accounts it seems a much better fit for my use case. I've gone through the process of creating the service accounts and downloaded my security details json file, however I just can't figure out how to actually query BigQuery from AppScript.
In my non-service account method I have the BigQuery Library installed in AppScript and basically run
var queryResults = BigQuery.Jobs.query(request, projectId);
I've been trying to work from an example at https://developers.google.com/datastudio/solution/blocks/using-service-accounts
function getOauthService() {
var serviceAccountKey = getServiceAccountCreds('SERVICE_ACCOUNT_KEY');// from private_key not private_key_id of JSON file
var serviceAccountEmail = getServiceAccountCreds('SERVICE_ACCOUNT_EMAIL');
return OAuth2.createService('RowLevelSecurity')
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setPrivateKey(serviceAccountKey)
.setIssuer(serviceAccountEmail)
.setPropertyStore(scriptProperties)
.setCache(CacheService.getScriptCache())
.setScope(['https://www.googleapis.com/auth/bigquery.readonly']);
}
function getData(request) {
var accessToken = getOauthService().getAccessToken();
var billingProjectId = getServiceAccountCreds('BILLING_PROJECT_ID');
// var email = Session.getEffectiveUser().getEmail();
// return cc
// .newBigQueryConfig()
// .setAccessToken(accessToken)
// .setBillingProjectId(billingProjectId)
// .setUseStandardSql(true)
// .setQuery(BASE_SQL)
// .addQueryParameter('email', bqTypes.STRING, email)
// .build();
}
I've commented out the code in the above which relates to
var cc = DataStudioApp.createCommunityConnector();
in the above tutorial since I'm not using DataStudio but I'm really not sure what to replace it with so I can query BigQuery with AppScript via a Service Account. Can anyone offer any advice?
Based on the advice from #TheAddonDepot in the comments above my revised code now looks like:
function getBigQueryService() {
return (
OAuth2.createService('BigQuery')
// Set the endpoint URL.
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
// Set the private key and issuer.
.setPrivateKey(JSON_CREDS.private_key) // from the json file downloaded when you create service account
.setIssuer(JSON_CREDS.client_email). // from the json file downloaded when you create service account
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getScriptProperties())
// Caching
.setCache(CacheService.getUserCache())
// Locking
.setLock(LockService.getUserLock())
// Set the scopes.
.setScope(['https://www.googleapis.com/auth/bigquery.readonly'])
// .setScope('https://www.googleapis.com/auth/bigquery')
)
}
function queryData(){
const bigQueryService = getBigQueryService()
if (!bigQueryService.hasAccess()) {
Logger.log("BQ ERROR IS "+ bigQueryService.getLastError())
}
//const projectId = bigqueryCredentials.project_id
var projectId = "<yourprojectid>"
let url = 'https://bigquery.googleapis.com/bigquery/v2/projects/<yourprojectid>/queries'; //projectID is taken from the security json file for the service account, although it doesn't seem to matter if you use the project code
const headers = {
Authorization: `Bearer ${bigQueryService.getAccessToken()}`,
'Content-Type': 'application/json',
}
var data = {query:"<your query>",useLegacySql:false};
const options = {
method: 'post',
headers,
//contentType: 'application/json',
payload: JSON.stringify(data),
muteHttpExceptions: true // on for debugging
}
try {
const response = UrlFetchApp.fetch(url, options)
const result = JSON.parse(response.getContentText())
Logger.log("here is result "+ JSON.stringify(result))
} catch (err) {
console.error(err)
}
}

how to send data from telegram bot inline keyboard to specific column in google spreadsheet?

I am not really familiar with the Telegram API and need to use JSON.
I want to create an inline keyboard that have options [yes/no] only.
Then, send it to a spreadsheet.
I managed to create the inline keyboard but nothing happens when I press it.
Is it possible to send data to a spreadsheet from the Telegram bot?
Code:
{"inline_keyboard":[[{"text":"yes","callback_data":"yes"}]]}
Yes, this is possible :)
You'd first need to setup a webhook for your telegram bot -
var telegramToken = 'Your-Telegram-Bot-Token-Goes-Here';
function setup() {
var method = 'setWebhook';
var payload = {
url: ScriptApp.getService().getUrl()
}
var options = {
'method' : 'post',
'contentType': 'application/json',
'payload' : JSON.stringify(payload)
};
var response = UrlFetchApp.fetch('https://api.telegram.org/bot' + telegramToken + '/' + method, options);
Logger.log(response);
}
and then setup a simple doPost(e) to capture incoming data from said webhook. You can refer some of the code from a bot that's i'd built here but please feel free to share more details with what you require so I could assist accordingly.

How to execute Google App script from external script

I am attempting to build a web app that will create a Google Doc from a template and populate it with user provided data. Using Google's quickstart example in the documentation, I can successfully authorize and access the Google Drive file system. Now I need to programmatically open a template Google Doc (or even create one from scratch) and add the data.
This is rather easily done using App Script's Document Service (the DocumentAppclass). So I can do something like:
function createDoc(contentArray) {
var doc = DocumentApp.create('Sample Document');
var body = doc.getBody();
var rowsData = contentArray; // data submitted with HTML form passed as arg
body.insertParagraph(0, doc.getName())
.setHeading(DocumentApp.ParagraphHeading.HEADING1);
table = body.appendTable(rowsData);
table.getRow(0).editAsText().setBold(true);
}
in a standalone App Script and successfully create the new Google Doc on Google Drive. I can't figure out how to execute this App Script from my external web app. Is there a way to do this or do I need to find a different way to create Google Docs (and add content) using just the Drive API?
EDIT:
here is the GET request from my web app:
var gurl = "https://script.google.com/macros/s/AKfycbwMHKzfZr1X06zP2iEB4E8Vh-U1vGahaLjXZA1tk49tBNf0xk4/exec";
$.get(
gurl,
{ name: "john", time: "2pm",},
function(data) {
console.log(data);
},
"jsonp"
)
and here is my doGet():
function doGet(e) {
var result = "";
var name = e.parameter.name;
Logger.log(name);
try {
result = "Hello " + name;
} catch (f) {
result = "Error: " + f.toString();
}
result = JSON.stringify({
"result": result
});
var doc = DocumentApp.create('ballz3');
var body = doc.getBody();
var rowsData = [['Plants', 'Animals'], ['Ficus', 'Goat'], ['Basil', 'Cat'], ['Moss', 'Frog']];
body.insertParagraph(0, doc.getName())
.setHeading(DocumentApp.ParagraphHeading.HEADING1);
table = body.appendTable(rowsData);
table.getRow(0).editAsText().setBold(true);
Logger.log('DOc Name: ' + doc.getName());
return ContentService
.createTextOutput(e.parameter.callback + "(" + result + ")")
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
In order to run a script from an external location like your web app you need to follow some set-up and use the Script API. The documentation provided below has a great example on how to run your scripts from outside.
Additionally, you can use the APIs directly, with services like OAuth to use the APIs directly in a way that can save you some time and make your code more simple. Using OAuth can provide you with simple API requests. To use it:
Go to the link provided below, select the desired scope (Drive for this example).
Exchange the authorization token for refresh/access tokens.
Proceed to configure the request. Here you can set all the parameters for the request, and even select from the existing operations the scope has available (“List possible operations” button).
The resulting request will look like the one below:
GET /drive/v3/files HTTP/1.1 Host: www.googleapis.com Content-length:
0 Authorization: Bearer [YOUR-TOKEN]
Beneath it you will see the server response to the request.
Documentation URL: https://developers.google.com/apps-script/api/how-tos/execute
OAuth Playground: https://developers.google.com/oauthplayground/

Google Apps Script Execution API - Calling app is Apps Script - Apps Script to Apps Script

I have two scripts in different domains, I would like to fetch data from one to the other.
I've found Script Execution API to be useful, however they don't provide any example GAS to GAS. https://developers.google.com/apps-script/guides/rest/quickstart/target-script
Any suggestion/guidance on how to accomplish such thing?
This answer might be helpful. what i have done is that created a cloud platform project and created two standalone project, one contains the calling script and other has the method you want to call and must be deployed as a API Executable.
IMPORTANT: Both these project must be associated with the Cloud Platform Project.
For associating the projects to Cloud Platform's project , in script editor do this, Resources --> Cloud Platform Project. You'll see the dialog box which has input box having placeholder Enter Project Number Here, here put the Cloud Platform's project number and do the same for other project as well.
Now as i have followed google's quick start tutorial for EXECUTION API. i have a target script (Script containing your method) as follows:
/**
* The function in this script will be called by the Apps Script Execution API.
*/
/**
* Return the set of folder names contained in the user's root folder as an
* object (with folder IDs as keys).
* #return {Object} A set of folder names keyed by folder ID.
*/
function getFoldersUnderRoot() {
var root = DriveApp.getRootFolder();
var folders = root.getFolders();
var folderSet = {};
while (folders.hasNext()) {
var folder = folders.next();
folderSet[folder.getId()] = folder.getName();
}
return folderSet;
}
NOTE: This script must be deployed as a API Executable. In project you must have enabled the Google Execution API.
Now the calling script,
function makeRequest(){
// DriveApp.getRootFolder();
var access_token=ScriptApp.getOAuthToken();
var url = "https://script.googleapis.com/v1/scripts/{YourScriptId}:run";
var headers = {
"Authorization": "Bearer "+access_token,
"Content-Type": "application/json"
};
var payload = {
'function': 'getFoldersUnderRoot',
devMode: true
};
var res = UrlFetchApp.fetch(url, {
method: "post",
headers: headers,
payload: JSON.stringify(payload),
muteHttpExceptions: true
});
Logger.log(res);
}
On first line inside function you can see i have commented out the Drive API call. I did that because the calling script and target script must have the same scope.
Yes you can use Execution API to fetch data from one domain to other. From the documentation, it consists of a single scripts resource, which has a single method, run, that makes calls to specific Apps Script functions.
The run method must be given the following information when called:
The ID of the script being called.
The name of the function within the script to execute.
The list of parameters the function requires (if any).
Here is an example from GitHub:
var script = google.script('v1');
var key = require('./creds.json');
var jwtClient = new google.auth.JWT(key.client_email, null, key.private_key, ['https://www.googleapis.com/auth/spreadsheets'], null);
jwtClient.authorize(function(err, tokens) {
if (err) {
console.log(err);
return;
}
script.scripts.run({
auth: jwtClient,
scriptId: 'script-id',
resource: {
function: 'test',
parameters: []
}
}, function(err, response) {
if (err) {
throw err;
}
console.log('response', response);
})
});
You can also check this related SO question on how to use Google Apps Script Execution API and Javascript to make the interaction between website and Google Drive.