Google Sheets activity sending to GA4 with App Script - google-apps-script

I have been trying to change my script that used to send to the old UA Google Analytics using the IMAGE() but with the new GA4 you have to send a POST. I tried to use the onOpen(e) with some of the code below but nothing seems to work even though I am not getting any errors. Does anyone know if it is possible to make a call [POST] with this information:
function onOpen(e) {
// Make a POST request with a JSON payload.
var data = {
"client_id": Utilities.getUuid(),
"user_id": "webuser",
"events": ["name", "cve_database"]
};
var options = {
'method' : 'post',
'contentType': 'application/json',
// Convert the JavaScript object to a JSON string.
'payload' : JSON.stringify(data)
};
var response = UrlFetchApp.fetch('https://www.google-analytics.com/mp/collect?api_secret=<ID-Here>&measurement_id=<GA4 Acc>', options);
Logger.log(response)
}
I tried to get it to update the Google Analytics information so that I can keep track of the users who view the page.

Related

Adding a doPost and doGet into google app script ("GAS") code

I am a total newbie when it comes to programming.
I have put a very simple switchbot script into google app script ("GAS") to make the switchbot bot do a press. While it can run when clicking on the "run" button in GAS, when sending a http post (i.e. via android's HTTP Shortcut app) to GAS, it connects but the action fails.
I do understand later that a doPost or doGet is required to run it when sending a post to the script from an external source, but after trying various methods with doPost and doGet, I still have no idea how to integrate it or where to put it into the code.
The code is below:
function main() {
var headers = {
"Authorization" : "SWITCHBOT_TOKEN_KEY",
"Content-type" : "application/json; charset=utf-8"
};
var data = {
"command" : "press",
"parameter" : "default",
"commandType": "command"
};
var options = {
'method' : 'post',
"headers" : headers,
muteHttpExceptions : true,
"payload" : JSON.stringify(data)
};
var deviceid = "INSERT_SWITCHBOT_DEVICEID";
var url1 = https://api.switch-bot.com/v1.0/devices/${deviceid}/commands;
var response = UrlFetchApp.fetch( url1, options );
var json = JSON.parse( response.getContentText() );
console.log( json )
}
Any assistance or lesson on how to do / understand this would be great!
Tried checking and looking at various codes with dePost and doGet and integrating it into the code but all seems not work.
While it connects to GAS via the deployed web app link, I am not able to get the actual script running. It simply logs it as failed in the GAS.

Sheets & Appscripts Hubspot POST Request with Authentication Token Problem

I've created a GAS app to provide better pipeline reporting from our Hubspot instance. So far the app works and I have successfully created a Sales Pipeline that shows up in Google sheets. I am trying to add a capability that requires a POST method to query Hubspot's CRM V3. I got it to work in Postman but cannot replicate it in GAS.
The error I get is "Authentication credentials not found." The headers print to the log so I assume they are being generated properly. My guess is that my access Token and payload are not being passed properly to the API during the request. Any help on the matter would be much appreciated.
function getConversions() {
// Prepare authentication to Hubspot
var service = getService();
var headers = {headers: {'Authorization': 'Bearer ' + service.getAccessToken()}};
Logger.log(headers);
var raw = JSON.stringify({"filterGroups":[{"filters":[{"propertyName":"hs_analytics_last_visit_timestamp","operator":"GT","value":"1561514165666"}]}],"limit":100,"after":0});
var options = {
'method' : 'post',
headers: headers,
'contentType': 'application/json',
// Convert the JavaScript object to a JSON string.
body : raw,
redirect: 'follow',
"muteHttpExceptions": true
};
var response = UrlFetchApp.fetch('https://api.hubapi.com/crm/v3/objects/contacts/search?', options);
var result = JSON.parse(response.getContentText());
Logger.log(result);
};
How about this modification?
Modification points:
When I checked the official document of Search of HubSpot API, I found the curl sample. When this sample is converted to Google Apps Script, I noticed several modification points in your script.
UrlFetchApp.fetch has no properties of body and redirect.
About followRedirects, the official document says as follows.
If false the fetch doesn't automatically follow HTTP redirects; it returns the original HTTP response. The default is true.
In your URL, https://api.hubapi.com/crm/v3/objects/contacts/search? is used. If you don't use the API key, how about modifying to https://api.hubapi.com/crm/v3/objects/contacts/search?
When above modification is reflected to your script, it becomes as follows.
Modified script:
Please modify as follows.
From:
var options = {
'method' : 'post',
headers: headers,
'contentType': 'application/json',
// Convert the JavaScript object to a JSON string.
body : raw,
redirect: 'follow',
"muteHttpExceptions": true
};
To:
var options = {
method : 'post',
headers: headers,
contentType: 'application/json',
payload : raw,
muteHttpExceptions: true
};
Note:
Above modification is required for your script. But I'm worry about the error of Authentication credentials not found.. In this modification, it supposes that your access token of service.getAccessToken() can be used for this request. When I saw the official document, the API key can be also used. If the access token cannot be used, how about using the API key? It's like below.
https://api.hubapi.com/crm/v3/objects/contacts/search?hapikey=YOUR_HUBSPOT_API_KEY
References:
Search of HubSpot API
fetch(url, params)
function getConversions() {
// Prepare authentication to Hubspot
var service = getService();
var headers = {headers: {'Authorization': 'Bearer ' + service.getAccessToken()}};
var url = 'https://api.hubapi.com/crm/v3/objects/contacts/search'
//Logger.log(headers);
var raw = {"filterGroups":[{"filters":[{"propertyName":"hs_analytics_last_visit_timestamp","operator":"GT","value":"1561514165666"}]}],"limit":100,"after":0};
var options = {
method : 'post',
contentType: "application/json",
// Convert the JavaScript object to a JSON string.
payload : JSON.stringify(raw),
muteHttpExceptions: true
};
var response = UrlFetchApp.fetch('https://api.hubapi.com/crm/v3/objects/contacts/search?hapikey=myapikey',options);
var result = JSON.parse(response.getContentText());
Logger.log(response)
Logger.log(result);
};

Fetch JSON object from GAS WebApp from another development GAS WebApp?

I have two different GAS projects Script1 and Script2.
Script1:
It is a development project with doPost() function. It uses the e.parameter or e.postData.contents to do something.
Script2:
It is a test script. It has also doPost() function. I want to transfer the doPost() e.parameter to Script1 by a post request. But the URLFetchApp success when I use the Current web app URL and ends in /exec. But I want to use the latest code and ends in /dev. Because of the Script1 is a development project and I can't update its version for a small change.
I tried this code. It not working
function myFunction() {
//var URL = "https://script.google.com/macros/s/xxxxxxxxxxxxxxxxxxxxxxxxxxx/exec";
var URL = "https://script.google.com/macros/s/xxxxxxxxxxxxxxxxxxxxxxxxxxxx/dev";
var data = {
'message' : "This is working"
}
var options = {
'method' : 'post',
'contentType': 'application/json',
'payload' : JSON.stringify(data)
};
var response = UrlFetchApp.fetch(URL, options);
}
I believe your goal as follows.
You want to access to Web Apps with the dev mode using Google Apps Script.
For this, How about this answer?
Modification points:
In order to access to the Web Apps with the dev mode, please use the access token. And in this sample, the scope of https://www.googleapis.com/auth/drive.readonly is used for the access token.
Modified script:
When your script is modified, please modify as follows.
function myFunction() {
//var URL = "https://script.google.com/macros/s/xxxxxxxxxxxxxxxxxxxxxxxxxxx/exec";
var URL = "https://script.google.com/macros/s/xxxxxxxxxxxxxxxxxxxxxxxxxxxx/dev";
var data = {
'message' : "This is working"
}
var options = {
'method' : 'post',
'contentType': 'application/json',
'payload' : JSON.stringify(data),
'headers': {'authorization': 'Bearer ' + ScriptApp.getOAuthToken()} // Added
};
var response = UrlFetchApp.fetch(URL, options);
}
// DriveApp.getFiles() // Added
Note:
The comment line of // DriveApp.getFiles() is used for automatically detecting the scope of https://www.googleapis.com/auth/drive.readonly by the script editor.
When the access token is used, even when Who has access to the app: is Only myself, the script works.
References:
Web Apps
Taking advantage of Web Apps with Google Apps Script

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.

Mandrill API to Google Sheets Script

I want to call the Mandrill API in order to have tagged template data populate in my google sheet labeled test, but I can't seem to get it working (spent hours I am a beginner). Below is my code
function mandrill() {
var from = "https://mandrillapp.com/api/1.0/tags/list.json";
var key = "*************";
var params = {
"return" :[
"time",
"sent",
"opens",
"clicks",
],
"sheet": "test"
}}
I followed the official docs but I can't seem to get it working. Any help at all would be greatly appreciated.
https://mandrillapp.com/api/docs/tags.JSON.html#method=all-time-series
The Apps Script reference specifies how to use the fetch() method to retrieve your request from Mandrill.
https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app
Please use
UrlFetchApp.fetch(url, options);
You need to JSON.stringify() the JSON request for the Mandrill /urls/list.json and pass it as a payload into the options of the fetch request. According to the documentation you provided, the correct JSON request is:
{
"key": "example key"
}
Subsequently, you can proceed your response and use it to populate the sheet. Please refer to:
https://developers.google.com/apps-script/reference/url-fetch/http-response
Then you need to parse the answer to JavaScript object, you need to parse it before accessing the content with the method getContentText(). You can then access the entries of interest and populate your sheet with it:
In summary, your code to retrieve the response from Mandrill should look like this:
function mandrill() {
var from = "https://mandrillapp.com/api/1.0/tags/list.json";
var params = {
"key": "*************"
};
var payload = JSON.stringify(params);
var options = {
'method': 'post',
'payload': payload,
'contentType' : 'application/json'
};
var response = UrlFetchApp.fetch(url, options);
var data = JSON.parse(response).getContentText());
var ss=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("test");
sheet.getRange("A1").setValue(data['sent'])
}