I'm building a bot for Telegram to be able to users add to a spreadsheet "friends".
The idea is that when they start the bot they can simply write the name of the "friends" (e.g., #friend1 #friend2 #friend3), and they will be added to a new spreadsheet.
I'm writing in the Google Spreadsheet Script Editor.
Started to declare the variables, and set up the webhook.
var token = "token";
var url = "https://api.telegram.org/bot" + token;
var webAppUrl = "spreadhsheetURL"
var ssId = "spreadsheeID";
var myID = "$$$$$$$"
function getMe() {
var response = UrlFetchApp.fetch(url + "/getMe");
Logger.log(response.getContentText());
}
function getUpdates() {
var response = UrlFetchApp.fetch(url + "/getUpdates");
Logger.log(response.getContentText());
}
function setWebhook() {
var response = UrlFetchApp.fetch(url + "/setWebhook?url="+ webAppUrl);
Logger.log(response.getContentText());
}
function sendText(id, text) {
var response = UrlFetchApp.fetch(url + "/sendMessage?chat_id=" + id + "&text=" + encodeURIComponent(text));
Logger.log(response.getContentText());
}
function doGet(e){
return HtmlService.createHtmlOutput("Hello " + JSON.stringify(e));
}
All is functioning but when I tell BOT to ask the user if the wants to add new friends the program doesn't wait for the user to write and gives the "Error" of the last else.
function doPost(e){
try{
var contents = JSON.parse(e.postData.contents);
var text = contents.message.text;
var id = contents.message.from.id;
var name = contents.message.from.username;
sendText(id, "Hi " + name + " do you want to add more friends? (Yes/No)");
if(text == "Yes"){
sendText(id, "Add new friends (e.g., #friend1 #friend2 #friend3)).");
var sheetName = name;
var newText = text.split(" ").slice(1).join(" ");
//check if already exist the spreadshet
var sheet = ss.getSheetByName(sheetName) ? ss.getSheetByName(sheetName) : ss.insertSheet(sheetName);
// check the number of words (friends)
var str_len = newText.split(" ").length;
// Print friends per row
for (i=0; i<str_len; i++){
sheet.appendRow([new Date(), id, name, newText.split(" ")[i]]);
}
sendText(id,"The user " + newText + " was added to your list " + sheetName + " with success.");
}else{
if(text == "No"){
sendText(id, "Thank you.")
}else{
sendText(id, "Error.")
}
}
var ss = SpreadsheetApp.openById(ssId);
}catch(e){
sendText(myID, JSON.stringify(e,null,4));
}
}
Want to know if anyone could help me.
Thanks
The problem is that you are doing one delivery for two processes at once, and each process needs to be responded to at its own time, so you have to separate each response from each process.
You can use the reply_markup parameter with ForceReply for data input needs, which is available in almost all send methods.
A little improvement, modified version to solve the problem:
function doPost(e){
try {
var contents = JSON.parse(e.postData.contents);
var text = contents.message.text;
var id = contents.message.from.id;
var name = contents.message.from.username;
var answer = ["Yes","No"];
if ( text === "/start" ) {
sendText(id, "Hi " + name + " do you want to add more friends? (Yes/No)");
} else if ( answer.includes( text ) ) {
if ( text === "Yes" ) {
//force user to input
var dataForceReply = {
method: "post",
payload: {
method: "sendMessage",
chat_id: String( contents.message.chat.id ),
text: "Add new friends (e.g., #friend1 #friend2 #friend3))",
reply_markup: JSON.stringify({
"force_reply": true
})
}
};
UrlFetchApp.fetch( url + "/", dataForceReply );
} else sendText(id, "Thank you.");
//When the user provides feedback input
} else if ( (( contents || {} ).message || {}).reply_to_message ) {
//Make sure the user's answer is for the same question
if ( contents.message.reply_to_message.chat.id == contents.message.chat.id ) {
var ss = SpreadsheetApp.openById(ssId);
var sheetName = name;
var newText = text.split(" ").slice(1).join(" ");
//check if already exist the spreadshet
var sheet = ss.getSheetByName(sheetName) ? ss.getSheetByName(sheetName) : ss.insertSheet(sheetName);
//check the number of words (friends)
var str_len = newText.split(" ").length;
// Print friends per row
for (i=0; i<str_len; i++){
sheet.appendRow([new Date(), id, name, newText.split(" ")[i]]);
}
sendText(id,"The user " + newText + " was added to your list " + sheetName + " with success.");
} else sendText(id, "Error.");
}
} catch(e) {
sendText( myID, e );
}
}
Related
I have a google sheet with a dropdown menu. When the cell the drop down is in is equal to a certain string a pop up shows up on screen. You answer yes or no.
When you answer yes it sends the email. If you answer no it does not send the email and resets the cell to its previous state.
The issue I am having is that if you select no it does reset to the previous data, but it still sends the email regardless. Please help. I am fairly new and still learning.
UPDATE:
Please see the update below. The only var I had to fix was for rData, other than that the script works as intended now. Thank you so much for your time and input. This was a headache for some time.
function sendMailEdit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ui = SpreadsheetApp.getUi();
if (ss.getSheetName() == 'Project List' &
ss.getActiveCell().getColumn() == 3 &
ss.getActiveCell().getValue() == "_Complete") {
var alertPromptText = 'Are you sure you want to select Complete? ' +
'This action will notify all parties in the next process that this job is ready for fabrication.';
var promptResponse = ui.alert(alertPromptText, ui.ButtonSet.YES_NO);
if (promptResponse == ui.Button.YES) {
// CHECK START
// variable email needs to be fixed. It gets the column of values.
// it needs to be converted to a comma separated list of recepients
var email = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Email").getRange(1, 1, 100).getValues();
// CHECK END
var rData = e.source.getActiveSheet().getRange(e.range.rowStart,1,1,12).getValues();
sendEmail(email,rData);
} else { // For both 'No' and cancel response to pop-up
fix(e);
}
}
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
function sendEmail(email,rData) {
var first = 0;
var email = 1;
var emailTemp = HtmlService.createTemplateFromFile("send");
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Email");
var data = ws.getRange("A1:B" + ws.getLastRow()).getValues();
var lj = rData[0][1];
var j = rData[0][5];
var d = rData[0][3];
var p = rData[0][4];
var m = rData[0][7];
var desc = rData[0][11];
var now = new Date().toLocaleString("en-US");
var msg1 = "Laser Job Number: " + lj + " (" + now + ")" +
"\nProject Job Number: " + j +
"\nDesigner: " + d +
"\nDate Project was Submitted to Programming: " + p +
"\nMaterial used: " + m +
"\nDescription: " + desc;
var subject = "Project Ready for Fab";
Logger.log(msg1);
data.forEach(function(row){
emailTemp.fn = row[first];
emailTemp.msg = msg1;
emailTemp.j = j;
emailTemp.d = d;
emailTemp.lj = lj;
emailTemp.p = p;
emailTemp.m = m;
emailTemp.desc = desc;
//emailTemp.cart = cart;
const htmlMessage = emailTemp.evaluate().getContent();
GmailApp.sendEmail(row[email], subject, "Please open with an email client that supports HTML",
{htmlBody: htmlMessage});
return;
});
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
function fix(e) {
e.range.setNote(e.oldValue);
e.range.setValue(e.range.getNote());
e.range.clearNote();
}
You need to set a variable to capture the response to the pop-up.
And then compare the value of the variable for the go-no-go part of the script.
For example:
var response = ui.prompt('Alert', 'Are you sure you want to select Complete?', ui.ButtonSet.YES_NO);
And then
if (response.getSelectedButton() == ui.Button.YES) { ... }
More here in the documentation.
Update
Try the following script. You'll need to set the onEdit trigger to run the function SendMailEdit
Also, check the code for getting the list of email recepients. Not sure if it will work.
function sendMailEdit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ui = SpreadsheetApp.getUi();
if (ss.getSheetName() == 'Project List' &
ss.getActiveCell().getColumn() == 3 &
ss.getActiveCell().getValue() == "_Compvare") {
var alertPromptText = 'Are you sure you want to select Compvare? ' +
'This action will notify all parties in the next process that this job is ready for fabrication.';
var promptResponse = ui.alert(alertPromptText, ui.ButtonSet.YES_NO);
if (promptResponse.getSelectedButton() == ui.Button.YES) {
// CHECK START
// variable email needs to be fixed. It gets the column of values.
// it needs to be converted to a comma separated list of recepients
var email = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Email").getRange(1, 1, 100).getValues();
// CHECK END
var rData = ss.getRange(ss.getActiveCell().getRow(), 1, 1, 12).getValues();
sendEmail(email, rData);
} else { // For both 'No' and cancel response to pop-up
fix(e);
}
}
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
function sendEmail(email, rData) {
var lj = rData[0][1];
var j = rData[0][5];
var d = rData[0][3];
var p = rData[0][4];
var m = rData[0][7];
var desc = rData[0][11];
var now = new Date().toLocaleString("en-US");
var msg = "Laser Job Number: " + lj + " (" + now + ")" +
"\nProject Job Number: " + j +
"\nDesigner: " + d +
"\nDate Project was Submitted to Programming: " + p +
"\nMaterial used: " + m +
"\nDescription: " + desc;
Logger.log(msg);
GmailApp.sendEmail(email, "Project Ready for Fab", msg);
return;
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
function fix(e) {
e.range.setNote(e.oldValue);
e.range.setValue(e.range.getNote());
e.range.clearNote();
}
Well we have this google form and the details are being added to google sheet with custom g apps scripts. When the details have been appended to the google sheet log, it should send email. If I run the sendmail() manually, it works but when I call it inside onFormSubmit(), it's not working. What could have gone wrong?
function onFormSubmit(e) {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var templateLink = sheet.getSheetByName("Template Link").getRange(1, 1).getValue();
var logSheet = sheet.getSheetByName("Log");
var formResponsesSheet = sheet.getSheetByName("Form Responses 1");
var formResponsesHeader = formResponsesSheet.getRange(1, 2, 1, formResponsesSheet.getLastColumn() -1).getValues();
var newFileName = e.namedValues['Name'][0] + "-" + e.namedValues['Date'][0];
var populatedDocsFolder = DriveApp.getFolderById("1yTSd7W0U4Gcsm6CIw8NtD022F-MA7CPx");
var templateDocID = DocumentApp.openByUrl(templateLink).getId();
var newDocID = DriveApp.getFileById(templateDocID).makeCopy(newFileName, populatedDocsFolder).getId();
var newDocLink = DriveApp.getFileById(newDocID).getUrl();
var newDoc = DocumentApp.openById(newDocID);
var newDocBody = newDoc.getBody();
for (i = 0; i < formResponsesHeader[0].length; i++) {
var thisHeader = formResponsesHeader[0][i];
var thisValue = e.namedValues[thisHeader][0];
newDocBody.replaceText("<<" + thisHeader + ">>", thisValue);
}
//Log
var name = e.namedValues['Name'][0];
var email = e.namedValues['Email'][0];
var date = e.namedValues['Date'][0];
logSheet.appendRow([name,email,date,newDocID]);
//Trigger
ScriptApp.newTrigger("sendEmail").timeBased().after(15000).create();
//sendEmail();
}
function sendEmail() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var logSheet = sheet.getSheetByName("Log");
var logSheetData = logSheet.getDataRange().getDisplayValues();
var templateName = sheet.getSheetByName("Template Name").getRange(1, 1).getValue();
for (i = 1; i < logSheetData.length; i++) {
if (logSheetData[i][4] == "") {
//SEND EMAIL
var name = logSheetData[i][0];
var email = logSheetData[i][1];
var date = logSheetData[i][2];
var id = logSheetData[i][3];
var pdfName = templateName + "-" + name + "-" + date;
//PDF EMAIL
try{
var doc = DriveApp.getFileById(id);
var blob = doc.getBlob().getAs('application/pdf').setName(pdfName + ".pdf");
var subject = 'Document Created';
//GmailApp.sendEmail(email, subject, "This is just a test", {attachments: [blob]});
MailApp.sendEmail(email, subject, "", {attachments: [blob], name: pdfName});
}catch(err){
continue;
}
//Log Sheet Update
logSheet.getRange(i + 1, 5).setValue("Sent");
}
}
}
function onOpen() {
SpreadsheetApp.getUi().createMenu("Custom Menu")
.addItem("Build Form Submit Trigger", "formSubmitTrigger")
.addSeparator()
.addItem("Send Email", "sendEmail")
.addSeparator()
.addItem("Mismatch Check", "mismatchCheck")
.addToUi();
}
function formSubmitTrigger() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
ScriptApp.newTrigger("onFormSubmit").forSpreadsheet(sheet).onFormSubmit().create();
}
function mismatchCheck() {
var result = "";
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var templateLink = sheet.getSheetByName("Template Link").getRange(1, 1).getValue();
var formResponsesSheet = sheet.getSheetByName("Form Responses 1");
var formResponsesHeader = formResponsesSheet.getRange(1, 2, 1, formResponsesSheet.getLastColumn() -1).getValues();
var docBody = DocumentApp.openByUrl(templateLink).getBody().getText();
var matches = docBody.match(/<</g); var noOfLessThanMatches = matches.length;
var matches = docBody.match(/>>/g); var noOfMoreThanMatches = matches.length;
var lessThan = docBody.search(/<</g);
var moreThan = docBody.search(/>>/g);
Logger.log([noOfLessThanMatches,noOfMoreThanMatches]);
result += "<b>Less Than Signs:</b> " + noOfLessThanMatches + "<br>";
result += "<b>More Than Signs:</b> " + noOfMoreThanMatches + "<br>";
result += "<br><b>Doc to Form Check</b><br>";
var newDocBody = docBody;
var reverseArray = [];
for (i = 0; i < noOfLessThanMatches; i++) {
var lessThan = newDocBody.search(/<</g);
var moreThan = newDocBody.search(/>>/g);
var subString = newDocBody.substring(lessThan + 2,moreThan);
Logger.log(subString);
var indexOf = formResponsesHeader[0].indexOf(subString);
if (indexOf > -1) {
result += subString + " - FOUND<br>";
} else {
result += subString + " - NOT FOUND<br>";
}
reverseArray.push(subString);
newDocBody = newDocBody.replace("<<" + subString + ">>","XX")
}
result += "<br><b>Form to Doc Check</b><br>";
for (z = 0; z < formResponsesHeader[0].length; z++) {
var thisString = formResponsesHeader[0][z];
var indexOf = reverseArray.indexOf(thisString);
if (indexOf > -1) {
result += thisString + " - FOUND<br>";
} else {
result += thisString + " - NOT FOUND<br>";
}
}
Logger.log(result);
var htmlOutput = HtmlService
.createHtmlOutput('<p>' + result + '</p>')
.setWidth(400)
.setHeight(500);
SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'RESULT');
}
UPDATE: I have pasted the whole code instead above so you guys can see
You have to register onFormSubmit as the function that handles the form submit trigger. Have you registered the function "onFormSubmit" like this:
ScriptApp.newTrigger('onFormSubmit').forForm(form).onFormSubmit().create();
You might also want to check the registered triggers by clicking on Edit > Current project's trigger from your Apps Script project.
[Edit] Since the trigger is created properly, change the first the line of the trigger code from:
function onFormSubmit(e) {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
to this:
function onFormSubmit(e) {
var sheet = SpreadsheetApp.openById(e.source.getDestinationId());
I'm a beginner, so I'll try my best to explain what happends in the code and what I want to do. I've created a telegram bot and I want to save all the message log into google spreadsheets. I'm using Google App Scripts for this. The problem is that when I'm using the following code, only the messages that I write are saved into google sheets, it happends in the "doPost" function. What I want to do is to save also the messages I receive from the bot. I tried adding the same code the I used in "doPost" and worked into the function "sendText" but I'm still unable to save the messages that the bot sends. How can I do this? here's my code:
var token = "..."; // 1. FILL IN YOUR OWN TOKEN
var telegramUrl = "https://api.telegram.org/bot" + token;
var webAppUrl = "..."; // 2. FILL IN YOUR GOOGLE WEB APP ADDRESS
var ssId = "..."; // 3. FILL IN THE ID OF YOUR SPREADSHEET
var adminID = "..."; // 4. Fill in your own Telegram ID for debugging
// connect to bot
function getMe() {
var url = telegramUrl + "/getMe";
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function setWebhook() {
var url = telegramUrl + "/setWebhook?url=" + webAppUrl;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
// make the bot to send a message
function sendText(id,text) {
var url = telegramUrl + "/sendMessage?chat_id=" + id + "&text=" + encodeURIComponent(text);
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
try {
// this is where telegram works
var data = JSON.parse(response.getContentText());
var text = data.message.text;
var id = data.message.chat.id;
var name = data.message.chat.first_name + " " + data.message.chat.last_name;
var answer = "Hi " + name;
// sendText(id,answer);
SpreadsheetApp.openById(ssId).getSheets()[0].appendRow([new Date(),id,name,text,answer]);
if(/^#/.test(text)) {
var sheetName = text.slice(1).split(" ")[0];
var sheet = SpreadsheetApp.openById(ssId).getSheetByName(sheetName) ? SpreadsheetApp.openById(ssId).getSheetByName(sheetName) : SpreadsheetApp.openById(ssId).insertSheet(sheetName);
var newText = text.split(" ").slice(1).join(" ");
sheet.appendRow([new Date(),id,name,newText,answer]);
sendText(id,"your text '" + newText + "' is now added to the sheet '" + sheetName + "'");
}
} catch(e) {
sendText(adminID, JSON.stringify(e,null,4));
}
}
function doGet(e) {
return HtmlService.createHtmlOutput("Hi there");
}
// send a message from me to the bot
function doPost(e) {
try {
// this is where telegram works
var data = JSON.parse(e.postData.contents);
var text = data.message.text;
var id = data.message.chat.id;
var name = data.message.chat.first_name + " " + data.message.chat.last_name;
var answer = "Hi " + name;
// sendText(id,answer);
SpreadsheetApp.openById(ssId).getSheets()[0].appendRow([new Date(),id,name,text,answer]);
if(/^#/.test(text)) {
var sheetName = text.slice(1).split(" ")[0];
var sheet = SpreadsheetApp.openById(ssId).getSheetByName(sheetName) ? SpreadsheetApp.openById(ssId).getSheetByName(sheetName) : SpreadsheetApp.openById(ssId).insertSheet(sheetName);
var newText = text.split(" ").slice(1).join(" ");
sheet.appendRow([new Date(),id,name,newText,answer]);
sendText(id,"your text '" + newText + "' is now added to the sheet '" + sheetName + "'");
}
} catch(e) {
sendText(adminID, JSON.stringify(e,null,4));
}
}
Thank you.
Actual web page image that should come I am getting error:
"The script completed but did not return anything."
I have published new version of code but still getting the error after saving the code and error which is coming is "The script completed but did not return anything."
Code.gs
function doGet(e) {
var op = e.parameter.action;
var ss = SpreadsheetApp.openByUrl("some url");
var sheet = ss.getSheetByName("Sheet1");
if (op == "insert")
return insert_value(e, sheet);
//Make sure you are sending proper parameters
if (op == "read")
return read_value(e, ss);
if (op == "update")
return update_value(e, sheet);
if (op == "delete")
return delete_value(e, sheet);
}
//Recieve parameter and pass it to function to handle
function insert_value(request, sheet) {
var id = request.parameter.id;
var country = request.parameter.name;
var flag = 1;
var lr = sheet.getLastRow();
for (var i = 1; i <= lr; i++) {
var id1 = sheet.getRange(i, 2).getValue();
if (id1 == id) {
flag = 0;
var result = "Id already exist..";
}
}
//add new row with recieved parameter from client
if (flag == 1) {
var d = new Date();
var currentTime = d.toLocaleString();
var rowData = sheet.appendRow([currentTime, id, country]);
var result="Insertion successful";
}
result = JSON.stringify({
"result": result
});
return ContentService
.createTextOutput(request.parameter.callback + "(" + result + ")")
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
function read_value(request, ss) {
var output = ContentService.createTextOutput(),
data = {};
//Note : here sheet is sheet name , don't get confuse with other operation
var sheet = "sheet1";
data.records = readData_(ss, sheet);
var callback = request.parameters.callback;
if (callback === undefined) {
output.setContent(JSON.stringify(data));
} else {
output.setContent(callback + "(" + JSON.stringify(data) + ")");
}
output.setMimeType(ContentService.MimeType.JAVASCRIPT);
return output;
}
function readData_(ss, sheetname, properties) {
if (typeof properties == "undefined") {
properties = getHeaderRow_(ss, sheetname);
properties = properties.map(function(p) { return p.replace(/\s+/g, '_'); });
}
var rows = getDataRows_(ss, sheetname),
data = [];
for (var r = 0, l = rows.length; r < l; r++) {
var row = rows[r],
record = {};
for (var p in properties) {
record[properties[p]] = row[p];
}
data.push(record);
}
return data;
}
function getDataRows_(ss, sheetname) {
var sh = ss.getSheetByName(sheetname);
return sh.getRange(2, 1, sh.getLastRow() - 1, sh.getLastColumn()).getValues();
}
function getHeaderRow_(ss, sheetname) {
var sh = ss.getSheetByName(sheetname);
return sh.getRange(1, 1, 1, sh.getLastColumn()).getValues()[0];
}
//update function
function update_value(request, sheet) {
var output = ContentService.createTextOutput();
var id = request.parameter.id;
var flag = 0;
var country = request.parameter.name;
var lr = sheet.getLastRow();
for (var i = 1; i <= lr; i++) {
var rid = sheet.getRange(i, 2).getValue();
if (rid == id) {
sheet.getRange(i, 3).setValue(country);
var result = "value updated successfully";
flag = 1;
}
}
if (flag == 0)
var result="id not found";
result = JSON.stringify({
"result": result
});
return ContentService
.createTextOutput(request.parameter.callback + "(" + result + ")")
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
function delete_value(request,sheet) {
var output = ContentService.createTextOutput();
var id = request.parameter.id;
var country = request.parameter.name;
var flag = 0;
var lr = sheet.getLastRow();
for (var i = 1; i <= lr; i++) {
var rid = sheet.getRange(i, 2).getValue();
if (rid == id) {
sheet.deleteRow(i);
var result = "value deleted successfully";
flag = 1;
}
}
if(flag==0)
var result="id not found";
result = JSON.stringify({
"result": result
});
return ContentService
.createTextOutput(request.parameter.callback + "(" + result + ")")
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
HTML script section
<script>
var script_url = "apps script webapp url";
// Make an AJAX call to Google Script
function insert_value() {
$("#re").css("visibility","hidden");
document.getElementById("loader").style.visibility = "visible";
$('#mySpinner').addClass('spinner');
var id1 = $("#id").val();
var name = $("#name").val();
var url = script_url + "?callback=ctrlq&name=" + name + "&id=" + id1 + "&action=insert";
var request = jQuery.ajax({
crossDomain: true,
url: url ,
method: "GET",
dataType: "jsonp"
});
}
function update_value(){
$("#re").css("visibility","hidden");
document.getElementById("loader").style.visibility = "visible";
var id1 = $("#id").val();
var name = $("#name").val();
var url = script_url + "?callback=ctrlq&name=" + name + "&id=" + id1 + "&action=update";
var request = jQuery.ajax({
crossDomain: true,
url: url ,
method: "GET",
dataType: "jsonp"
});
}
function delete_value(){
$("#re").css("visibility","hidden");
document.getElementById("loader").style.visibility = "visible";
$('#mySpinner').addClass('spinner');
var id1 = $("#id").val();
var name = $("#name").val();
var url = script_url + "?callback=ctrlq&name=" + name + "&id=" + id1 + "&action=delete";
var request = jQuery.ajax({
crossDomain: true,
url: url ,
method: "GET",
dataType: "jsonp"
});
}
// print the returned data
function ctrlq(e) {
$("#re").html(e.result);
$("#re").css("visibility","visible");
read_value();
}
function read_value() {
// Other code here to process the result
}
</script>
HTML function calls:
<body>
<div align="center">
<h1>Operations .</h1>
<p>This is simple application<p>
<form >
ID
<input type = "text" name ="id" id="id">
Name
<input type = "text" name ="name" id="name">
</form>
<div id="loader"></div>
<p id="re"></p>
<input type = "button" id = "b1" onClick="insert_value()" value = "Insert"></input>
<input type="button" onclick="read_value()" value="Read" />
<input type="button" onclick="update_value()" value="Update" />
<input type="button" onclick="delete_value()" value="Delete" />
<div id="showData"></div>
</div>
</body>
<div align="center">
</div>
<html>
It should show web page for performing operation shown in screenshot
web page:
The error is correct - consider what happens when no parameters are given to your webapp function doGet. This scenario occurs when the webapp is visited via browser. To resolve this error, you must return something:
function doGet(e) {
console.log({event: e});
...
if (op)
return ContentService.createTextOutput("Unsupported operation");
else
return HtmlService.createHtmlOutputFromFile(...);
}
}
The default response will vary based on how your webapp is used - if you intend to use the webapp only as a crud backend vs. if you plan to have it host the web interface as well.
If the webapp is to host the interface as well, your HTML should use the built in client-server communication (google.script.run...) rather than jQuery.ajax. Review the Apps Script documentation in detail. This pattern will allow you to report and even handle errors in your server code execution.
I am trying to fetch the email ID of a user from the admin directory using his/her first name obtained from a spreadsheet, which simply checks if an email id exists in the directory and if yes shows his/her email id, here is my code:
function scanSsheet(){
var originalSpreadsheet = SpreadsheetApp.openById('xxxxxxxx-xxxxx-xxxxxxx-xxxx').getSheetByName("Form Responses 1");
var getRange = originalSpreadsheet.getDataRange();
var data = originalSpreadsheet.getDataRange().getValues();
for (var i = 1; i < data.length; i++) {
var volunteerFirstName = data[i][3];
var volunteerLastName = data[i][4];
Logger.log('****************Record No: ' + i + '****************');
Logger.log('volunteerFirstName: ' + data[i][3]);
Logger.log('volunteerLastName: ' + data[i][4]);
Logger.log('fetchUser is called');
var checkUser = fetchUser(volunteerFirstName);
if(checkUser){
Logger.log('Email exists');
}
else{
Logger.log('The user doesnot exist in the directory');
}
}
}
//Checks if the user exists in the directory or not and display email id if yes
function fetchUser(volunteerFirstName){
var isUser
try{
var email = AdminDirectory.Users.list({givenName: volunteerFirstName}); // This line should fetch email but it is not working
var user = AdminDirectory.Users.get(email);
Logger.log('email:' +email);
isUser = true;
} catch (e){
isUser = false;
}
return isUser;
}
As seen I have used var email = AdminDirectory.users.list({givenName: volunteerFirstName}) as seen in the code for which I followed G-suite's admin-sdk, but I am not able retrieve the email id, am I doing anything wrong here? Also, I am newbie to google-apps script, please ignore if its a stupid question.
I was able to retrieve it and a bunch of other details using users-list:
function scanSsheet(){
var originalSpreadsheet = SpreadsheetApp.openById('xxxxxxxx-xxxxx-xxxxxxx-xxxx').getSheetByName("Form Responses 1");
var getRange = originalSpreadsheet.getDataRange();
var data = originalSpreadsheet.getDataRange().getValues();
for (var i = 1; i < data.length; i++) {
var volunteerFirstName = data[i][3];
var volunteerLastName = data[i][4];
Logger.log('****************Record No: ' + i + '****************');
Logger.log('volunteerFirstName: ' + data[i][3]);
Logger.log('volunteerLastName: ' + data[i][4]);
Logger.log('fetchUser is called');
fetchUser(volunteerFirstName);
}
}
function fetchUser(volunteerFirstName){
var pageToken;
var membersList = AdminDirectory.Users.list({
domain: 'mydomain.com',
orderBy: 'email',
query: volunteerFirstName,
maxResults: 100,
pageToken: pageToken
});
Logger.log('membersList:' +membersList);
}
Thanks.