I am hitting a Carrier limit when sending out requests to buy item's from sellers.
15-60 messages per minute and under 200 unique recipients a day
How can I stay within the following guidelines if I have 200-500 contacts in my spreadsheet for the script
function sendSms(to, body) {
var messages_url = "https://api.twilio.com/2010-04-01/Accounts/MYAPIKEY/Messages.json";
var payload = {
"To": to,
"Body" : body,
"From" : "+1PHONENUMBER"
};
var options = {
"method" : "post",
"payload" : payload
};
options.headers = {
"Authorization" : "Basic " + Utilities.base64Encode("MYAPIKEY:MYAUTHTOKEN")
};
UrlFetchApp.fetch(messages_url, options);
}
function sendAll() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2;
var numRows = sheet.getLastRow() - 1;
var dataRange = sheet.getRange(startRow, 1, numRows, 3); // Modified
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
if (row[2].toLowerCase() != "sent") { // Added
try {
response_data = sendSms(row[0], row[1]);
status = "sent";
} catch(err) {
Logger.log(err);
status = "error";
}
sheet.getRange(startRow + Number(i), 3).setValue(status);
}
}
}
Thank you any help!
This guarantees less than 15 per minute and if you put 200 recipients or less on sheets named for the days of the week (i.e. Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday). Actually you can name them anything you want and use the names over again within the same week as long as you have less that 200 recipients on any one sheet then you be limiting yourself to the maximum number per day.
function sendAll() {
var shA=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];//sheet names
var sheet = SpreadsheetApp.getActive().getSheetByName(shA[new Date().getDay()])
var startRow = 2;
var numRows = sheet.getLastRow() - 1;
var dataRange = sheet.getRange(startRow, 1, numRows, 3); // Modified
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
if (row[2].toLowerCase() != "sent") { // Added
try {
response_data = sendSms(row[0], row[1]);
status = "sent";
} catch(err) {
Logger.log(err);
status = "error";
}
sheet.getRange(startRow + Number(i), 3).setValue(status);
Utilities.sleep(4000);//4 seconds
}
}
}
Utilities.sleep()
Date().getDay()
Related
I am trying to write a javascript (Googlescript) to loop through a Google Sheet with Specific Tasks assigned to different users and grab all the rows assigned to "UserA" and send an email with the list of all the tasks assigned to userA. Then do the same with UserB
Tasks are not sorted by user.
Columns in the sheet in order are: Name, Description, Status, Owner, Due Date
I am able to send out Emails, with the information problem, the issue is that if you have X amount of Tasks assigned to you get X amount of emails. Which is a problem if you have 10+ tasks....
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("ITPM_Tasks");
var lastRow = sheet.getLastRow();
var startRow = 2; // First row of data to process
var numRows = lastRow - 1; // Number of rows to process
// Fetch the range of cells A:P
var dataRange = sheet.getRange(startRow, 1, numRows, 5);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var owner = row[3];
var status = row[2];
var desc = row[1];
var due = row[4];
var due_date = due.toDateString();
var message = 'Reminder: A task is assigned to you\n\n' + desc + '\nwith a due date of '
+ due_date + ' \n\nPlease complete and change status to completed or notify the ITPM Team \n\nThank You'
if (status != 'Complete') { // Prevents sending if status is not completed
var subject = 'Weekly Reminder: A task is assigned to you ';
MailApp.sendEmail(owner, subject, message);
SpreadsheetApp.flush();
}
}
}
Sending all the tasks for each person in one email
This version displays a basic a block of text in a dialog for each email so that I could test it without sending emails
function sendEmails() {
let s = '';
const sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");
const lastRow = sh.getLastRow();
const startRow = 2; // First row of data to process
const numRows = lastRow - 1; // Number of rows to process
const rg = sh.getRange(startRow, 1, numRows, 5);
const vs = rg.getValues();
let oners = {pA:[]};
vs.forEach((r,i) => {
let [name,desc,status,owner,due] = r;
if(status != 'Complete') {
if(!oners.hasOwnProperty(owner)) {
oners[owner]=[];
oners[owner].push(r);
oners.pA.push(owner)
} else {
oners[owner].push(r);
}
}
});
let subject = 'Weekly Reminder: The following tasks are assigned to you.';
oners.pA.forEach(p => {
let msg = `Tasks:\n`
msg += `Owner:${oners[p][0][3]}\n`;
msg += `Subject: ${subject}\n`
oners[p].forEach((r,i) => {
let [name,desc,status,owner,due] = r;
msg += `Task- ${i+1}\n`;
msg += `Desc:${desc}\n`;
msg += `Due Date: ${due.toDateString()}\n`
});
msg += `Please complete and change status to completed or notify the ITPM Team \nThank You\n`;
//MailApp.sendEmail(owner, subject, msg);
msg += `\n\n***********************************\n\n`;
s+=msg;
});
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(`<textarea cols="50" rows="12">${s}</textarea>`),'Simple Dialog')
}
This version should send emails. You may wish to doctor up the message a bit.
function sendEmails() {
let s = '';
const sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");
const lastRow = sh.getLastRow();
const startRow = 2; // First row of data to process
const numRows = lastRow - 1; // Number of rows to process
const rg = sh.getRange(startRow, 1, numRows, 5);
const vs = rg.getValues();
let oners = {pA:[]};
vs.forEach((r,i) => {
let [name,desc,status,owner,due] = r;
if(status != 'Complete') {
if(!oners.hasOwnProperty(owner)) {
oners[owner]=[];
oners[owner].push(r);
oners.pA.push(owner)
} else {
oners[owner].push(r);
}
}
});
let subject = 'Weekly Reminder: The following tasks are assigned to you.';
oners.pA.forEach(p => {
let msg = `Tasks:\n`
msg += `Owner:${oners[p][0][3]}\n`;
msg += `Subject: ${subject}\n`
oners[p].forEach((r,i) => {
let [name,desc,status,owner,due] = r;
msg += `Task- ${i+1}\n`;
msg += `Desc:${desc}\n`;
msg += `Due Date: ${due.toDateString()}\n`
});
msg += `Please complete and change status to completed or notify the ITPM Team \nThank You\n`;
MailApp.sendEmail(oners[p][0][3], subject, msg);
});
}
I'm trying to send texts on a time trigger on a google sheet using Twilio to send the texts. When I click the run button it works fine but when I set up a time trigger it says its in status it's completed but does not work. Also when I click on Executions I do get an error it says "Exception: Request failed for https://api.twilio.com returned code 400. Truncated server response: {"code": 21211, "message": "The 'To' number is not a valid phone number.", "more_info": "https://www.twilio.com/docs/errors/21211", "status": 400} (use muteHttpExceptions option to examine full response)"
I'm 100% new to Java and am learning about it any help would be great.
Here is my Code:
function RunThisToSendTexts() {
function sendSms(to, body) {
var messagesUrl = "https://api.twilio.com/2010-04-01/Accounts/AC9837381a431941024fc87xxxxxx/Messages.json";
var payload = {
"To": to,
"Body" : body,
"From" : "+197131999xx"
};
var options = {
"method" : "post",
"payload" : payload
};
options.headers = {
"Authorization" : "Basic " + Utilities.base64Encode("AC9837381a431941024fcxxxxxxx:22c7dec97dee0cef39exxxxxxx")
};
UrlFetchApp.fetch(messagesUrl, options);
}
function sendAll() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = sheet.getLastRow() - 1;
var dataRange = sheet.getRange(startRow, 1, numRows, 2)
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
try {
response_data = sendSms(row[0], row[1]);
status = "sent";
} catch(err) {
Logger.log(err);
status = "error";
}
sheet.getRange(startRow + Number(i), 3).setValue(status);
}
}
sendAll();
}
Try writing it like this:
function sendSms(to, body) {
var messagesUrl = "https://api.twilio.com/2010-04-01/Accounts/AC9837381a431941024fc87xxxxxx/Messages.json";
var payload = {
"To": to,
"Body" : body,
"From" : "+197131999xx"
};
var options = {
"method" : "post",
"payload" : payload
};
options.headers = {
"Authorization" : "Basic " + Utilities.base64Encode("AC9837381a431941024fcxxxxxxx:22c7dec97dee0cef39exxxxxxx")
};
UrlFetchApp.fetch(messagesUrl, options);
}
function sendAll() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = sheet.getLastRow() - 1;
var dataRange = sheet.getRange(startRow, 1, numRows, 2)
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
try {
response_data = sendSms(row[0], row[1]);
status = "sent";
} catch(err) {
Logger.log(err);
status = "error";
}
sheet.getRange(startRow + Number(i), 3).setValue(status);
}
}
And just run sendAll();
Try sendAll() this way:
function sendAll() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getActiveSheet();
const sr = 2;
const data = sh.getRange(sr, 1, sh.getLastRow() - sr + 1, sh.getLastColumn()).getValues();
var status = 'Error'
data.forEach((r, i) => {
sendSms(r[0], r[1]);
status = 'sent';
});
sh.getRange(i + sr, 3).setValue(status);
}
i need help raplacing dots with commas with this script;
function doPost(e) {
//Return if null
if( e == undefined ) {
console.log("no data");
return HtmlService.createHtmlOutput("need data");
}
//Parse the JSON data
var event = JSON.parse(e.postData.contents);
var data = event.data;
var price = event.data;
var at = event.data;
//Get the last row without data
var sheet = SpreadsheetApp.getActiveSheet();
var lastRow = Math.max(sheet.getLastRow(),1);
var column = sheet.getRange("C1:C");
var columnn = sheet.getRange("E1:E");
sheet.insertRowAfter(lastRow);
//Insert the data into the sheet
sheet.getRange(lastRow + 1, 1).setValue(event.price);
sheet.getRange(lastRow + 1, 2).setValue(event.at);
column.setNumberFormat("#");
columnn.setNumberFormat("#");
SpreadsheetApp.flush();
return HtmlService.createHtmlOutput("post request received");
}
price and at is coming as eg:347.7100 but i need it as 347,7100
Thanks!
Ciao you could try replace function like:
function doPost(e) {
//Return if null
if( e == undefined ) {
console.log("no data");
return HtmlService.createHtmlOutput("need data");
}
//Parse the JSON data
var event = JSON.parse(e.postData.contents);
var data = event.data;
var price = event.data.replace('.', ',');
var at = event.data.replace('.', ',');
//Get the last row without data
var sheet = SpreadsheetApp.getActiveSheet();
var lastRow = Math.max(sheet.getLastRow(),1);
var column = sheet.getRange("C1:C");
var columnn = sheet.getRange("E1:E");
sheet.insertRowAfter(lastRow);
//Insert the data into the sheet
sheet.getRange(lastRow + 1, 1).setValue(event.price);
sheet.getRange(lastRow + 1, 2).setValue(event.at);
column.setNumberFormat("#");
columnn.setNumberFormat("#");
SpreadsheetApp.flush();
return HtmlService.createHtmlOutput("post request received");
}
Note: replace works only with string. If at and/or price are not strings, you have to parse before apply replace like:
...
var price = String(event.data).replace('.', ',');
var at = String(event.data).replace('.', ',');
...
I have a google sheet which have 3 sheets, and I have 3 html form in total. Html don't run from google app script.
Here's the code I have to send from html from to google sheet. But it only can send to one sheet, I would to send to another sheet. It's a javascript for google app script, it's a .cs file. The code is from here https://medium.com/#dmccoy/how-to-submit-an-html-form-to-google-sheets-without-google-forms-b833952cc175
// original gist: https://gist.github.com/willpatera/ee41ae374d3c9839c2d6
function doGet(e){
return handleResponse(e);
}
// Enter sheet name where data is to be written below
var SHEET_NAME = "Sheet1";
var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service
function handleResponse(e) {
// shortly after my original solution Google announced the LockService[1]
// this prevents concurrent access overwritting data
// [1] http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html
// we want a public lock, one that locks for all invocations
var lock = LockService.getPublicLock();
lock.waitLock(30000); // wait 30 seconds before conceding defeat.
try {
// next set where we write the data - you could write to multiple/alternate destinations
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
// we'll assume header is in row 1 but you can override with header_row in GET/POST data
var headRow = e.parameter.header_row || 1;
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
var nextRow = sheet.getLastRow()+1; // get next row
var row = [];
// loop through the header columns
for (i in headers){
if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column
row.push(new Date());
} else { // else use header name to get data
row.push(e.parameter[headers[i]]);
}
}
// more efficient to set values as [][] array than individually
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
// return json success results
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
.setMimeType(ContentService.MimeType.JSON);
} catch(e){
// if error return this
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": e}))
.setMimeType(ContentService.MimeType.JSON);
} finally { //release lock
lock.releaseLock();
}
}
function setup() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
SCRIPT_PROP.setProperty("key", doc.getId());
}
I don't understand this part. I try to add in more variable and PropertiesService. And I can't get the result.
// Enter sheet name where data is to be written below
var SHEET_NAME = "Sheet1";
var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service
try {
// next set where we write the data - you could write to multiple/alternate destinations
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
function setup() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
SCRIPT_PROP.setProperty("key", doc.getId());
}
Here is the solution for your question. https://www.youtube.com/watch?v=V4JMjmwHPEg
I have made a tutorial on youtube you can check the link in the description of youtube for source code.
You have to create duplicate functions for every sheets you have in spreadsheet. Check below code which you need to add in spreadsheet .gs file. for further information you can check the youtube link provided.
// See front-end example at: http://codepen.io/notarazi/pen/yMqyXX
// Usage
// 1. Enter sheet name where data is to be written below
//var SHEET_NAME;
// 2. Run > setup
//
// 3. Publish > Deploy as web app
// - enter Project Version name and click 'Save New Version'
// - set security level and enable service (most likely execute as 'me' and access 'anyone, even anonymously)
//
// 4. Copy the 'Current web app URL' and post this in your form/script action
//
// 5. Insert column names on your destination sheet matching the parameter names of the data you are passing in (exactly matching case)
var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service
// If you don't want to expose either GET or POST methods you can comment out the appropriate function
function doGet(e){
return handleResponse(e);
}
function doPost(e){
return handleResponse(e);
}
function handleResponse(e) {
// shortly after my original solution Google announced the LockService[1]
// this prevents concurrent access overwritting data
// [1] http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html
// we want a public lock, one that locks for all invocations
var lock = LockService.getPublicLock();
lock.waitLock(30000); // wait 30 seconds before conceding defeat.
//Sheet1
try {
var action = e.parameter.action;
if (action == 'create') {
return create(e);
}
else if (action == 'retrieve') {
return retrieve(e);
}
else if (action == 'update') {
return update(e);
}
else if (action == 'delete') {
return del(e);
}
else if (action == 'findRowId'){
return findRowId(e.parameter.findstr);
}
} catch(e){
// if error return this
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": e}))
.setMimeType(ContentService.MimeType.JSON);
} finally { //release lock
lock.releaseLock();
}
//Sheet2
try {
var action = e.parameter.action;
if (action == 'create_1') {
return create_1(e);
}
else if (action == 'retrieve_1') {
return retrieve_1(e);
}
else if (action == 'update_1') {
return update_1(e);
}
else if (action == 'delete_1') {
return del_1(e);
}
else if (action == 'findRowId'){
return findRowId(e.parameter.findstr);
}
} catch(e){
// if error return this
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": e}))
.setMimeType(ContentService.MimeType.JSON);
} finally { //release lock
lock.releaseLock();
}
}
function getDataArr(headers, e){
var row = [];
// loop through the header columns
for (i in headers){
var d= new Date();
if (headers[i] == "tid"){ // special case if you include a unix Timestamp column
row.push(d.getTime());
}else if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column
row.push(new Date());
} else { // else use header name to get data
row.push(e.parameter[headers[i]]);
}
}
return row;
}
function create0(e){
// return json success results
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "row": 99}))
.setMimeType(ContentService.MimeType.JSON);
}
function findRowId(data) {
var SHEET_NAME = "Published Online";
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
//var column = sheet.getRange(column + ":" + column); // like A:A
var column = sheet.getRange(1,1,sheet.getLastRow(),1);
var values = column.getValues();
var data1=Number(data);
var row = 0;
var result = 0;
while ( values[row] && values[row][0] !== data ) {
row++;
}
if (values[row][0] === data)
result= row+1;
else
result = -1;
//result += data1;
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "values": result}))
.setMimeType(ContentService.MimeType.JSON);
}
function findInColumn(data) {
var SHEET_NAME = "Sheet1";
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
//var column = sheet.getRange(column + ":" + column); // like A:A
var column = sheet.getRange(1,1,sheet.getLastRow(),1);
var values = column.getValues();
//data=1490461629269;
var testdata = Number(data);
var row = 0;
while ( values[row] && values[row][0] !== testdata ) {
row++;
}
if (values[row][0] === testdata)
return row+1;
else
return -1;
// return ContentService
// .createTextOutput(JSON.stringify({"result":"success", "values": row}))
// .setMimeType(ContentService.MimeType.JSON);
}
function findInColumn_s2(data) {
var SHEET_NAME = "Sheet2";
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
//var column = sheet.getRange(column + ":" + column); // like A:A
var column = sheet.getRange(1,1,sheet.getLastRow(),1);
var values = column.getValues();
//data=1490461629269;
var testdata = Number(data);
var row = 0;
while ( values[row] && values[row][0] !== testdata ) {
row++;
}
if (values[row][0] === testdata)
return row+1;
else
return -1;
// return ContentService
// .createTextOutput(JSON.stringify({"result":"success", "values": row}))
// .setMimeType(ContentService.MimeType.JSON);
}
function findInRow(data) {
var SHEET_NAME = "Published Online";
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var rows = sheet.getDataRange.getValues();
for (var r=0; r<rows.length; r++) {
if ( rows[r].join("#").indexOf(data) !== -1 ) {
return r+1;
}
}
return -1;
}
/***********************************************************************************************************************************************************************************/
//SHEET 1 CREATE
function create(e) {
var SHEET_NAME = e.parameter.sheet_name || 'Sheet1';
// next set where we write the data - you could write to multiple/alternate destinations
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
// we'll assume header is in row 1 but you can override with header_row in GET/POST data
var headRow = e.parameter.header_row || 1;
var numColumns = sheet.getLastColumn();
var headers = sheet.getRange(1, 1, 1, numColumns).getValues()[0];
var nextRow = sheet.getLastRow()+1; // get next row
var row = getDataArr(headers, e);
// more efficient to set values as [][] array than individually
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
// return json success results
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
.setMimeType(ContentService.MimeType.JSON);
}
//SHEET 1 RETRIEVE
function retrieve(e) {
var SHEET_NAME = e.parameter.sheet_name || 'Sheet1';
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
var numRows = sheet.getLastRow();
var numColumns = sheet.getLastColumn();
var range = sheet.getRange(1, 1, numRows, numColumns);
var values = range.getValues();
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "values": values}))
.setMimeType(ContentService.MimeType.JSON);
}
//SHEET 1 UPDATE
function update(e) {
var SHEET_NAME = e.parameter.sheet_name || 'Sheet1';
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
var numColumns = sheet.getLastColumn();
var rowId = findInColumn(e.parameter.tid);
var headers = sheet.getRange(1, 1, 1, numColumns).getValues()[0];
var row = getDataArr(headers, e);
//var rowId = e.parameter.rowId;
var tid= row[0];
// more efficient to set values as [][] array than individually
sheet.getRange(rowId, 1, 1, numColumns).setValues([row]);
// return json success results
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "tid": tid}))
.setMimeType(ContentService.MimeType.JSON);
}
//SHEET 1 DELETE
function del(e) {
var SHEET_NAME = e.parameter.sheet_name || 'Sheet1';
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
var rowId = findInColumn(e.parameter.tid);
sheet.deleteRow(rowId);
// return json success results
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "rowId": rowId}))
.setMimeType(ContentService.MimeType.JSON);
}
/***********************************************************************************************************************************************************************************/
/***********************************************************************************************************************************************************************************/
//SHEET 2 CREATE
function create_1(e) {
var SHEET_NAME = e.parameter.sheet_name || 'Sheet2';
// next set where we write the data - you could write to multiple/alternate destinations
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
// we'll assume header is in row 1 but you can override with header_row in GET/POST data
var headRow = e.parameter.header_row || 1;
var numColumns = sheet.getLastColumn();
var headers = sheet.getRange(1, 1, 1, numColumns).getValues()[0];
var nextRow = sheet.getLastRow()+1; // get next row
var row = getDataArr(headers, e);
// more efficient to set values as [][] array than individually
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
// return json success results
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
.setMimeType(ContentService.MimeType.JSON);
}
//SHEET 2 RETRIEVE
function retrieve_1(e) {
var SHEET_NAME = e.parameter.sheet_name || 'Sheet2';
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
var numRows = sheet.getLastRow();
var numColumns = sheet.getLastColumn();
var range = sheet.getRange(1, 1, numRows, numColumns);
var values = range.getValues();
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "values": values}))
.setMimeType(ContentService.MimeType.JSON);
}
//SHEET 2 UPDATE
function update_1(e) {
var SHEET_NAME = e.parameter.sheet_name || 'Sheet2';
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
var numColumns = sheet.getLastColumn();
var rowId = findInColumn_s2(e.parameter.tid);
var headers = sheet.getRange(1, 1, 1, numColumns).getValues()[0];
var row = getDataArr(headers, e);
//var rowId = e.parameter.rowId;
var tid= row[0];
// more efficient to set values as [][] array than individually
sheet.getRange(rowId, 1, 1, numColumns).setValues([row]);
// return json success results
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "tid": tid}))
.setMimeType(ContentService.MimeType.JSON);
}
//SHEET 2 DELETE
function del_1(e) {
var SHEET_NAME = e.parameter.sheet_name || 'Sheet2';
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
var rowId = findInColumn_s2(e.parameter.tid);
sheet.deleteRow(rowId);
// return json success results
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "rowId": rowId}))
.setMimeType(ContentService.MimeType.JSON);
}
/***********************************************************************************************************************************************************************************/
//SETUP
function setup() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
SCRIPT_PROP.setProperty("key", doc.getId());
}
For getting the sheet that you exactly want, you can set another parameter in the Request parameters e.parameters. In each of your forms add a key/value pair defining the name of where you want the form to be submitted. For example:
For the first sheet
sheetName=Sheet1
For the second sheet
sheetName=Sheet2
If you are using a Get Request the URL would look like this:
https://script.google.com/a/your-domain/macros/s/your-id/exec?sheetName=Sheet1.
Then, you would only need to pass that value to the .getSheetByName() like this:
var sheet = doc.getSheetByName(e.parameters.sheetName);
I am using this function to pull information from coinmarketcap using their v2 api. The problem I am getting is that if a "website_slug" does not exist on coinmarketcap, I get an incorrect range width error instead of the function just putting xxx in the cell. This can be recreated by having a cell in column B that doesn't match a website_slug on cmc (https://api.coinmarketcap.com/v2/ticker/).
function getMarketCap(sheetname) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(sheetname);
var assets = [];
var idRange = sheet.getRange("B1:B");
var lastRow = getLastRowOfRange(idRange);
var cellRange = sheet.getRange(1, 2, lastRow).getValues();
var mcRange = sheet.getRange(1, 3, lastRow);
var mcValues = [];
for (var i = 0; i < cellRange.length; i++) {
assets[i] = cellRange[i];
}
var req = [];
for (var i = 0; i < 16; i++) {
req.push({
muteHttpExceptions: true,
method: "get",
url: "https://api.coinmarketcap.com/v2/ticker/?start=" + (i * 100 + 1),
});
}
var responses = UrlFetchApp.fetchAll(req);
var res = responses.filter(function(e){return e.getResponseCode() == 200}).map(function(e){return JSON.parse(e.getContentText())});
if (responses.length != res.length) Logger.log("%s errors occurred.", responses.length - res.length);
var mcValues = [];
assets.forEach(function(e, h) {
mcValues[h] = []
res.some(function(f) {
Object.keys(f.data).some(function(g) {
if (f.data[g].website_slug == e[0]) {
mcValues[h][0] = f.data[g].quotes.USD.market_cap;
return true;
}
});
if (mcValues[h][0]) return true;
});
if (!mcValues[h][0]) mcValues[h][0] = 'xxx';
});
mcRange.setValues(mcValues);
}