google apps script that sends sms from spreadsheet data - javascript

I'm wondering if anyone has already put together a script that simply takes a phone number from a cell and sends a text message. Just the same as if it were an email address. Using the carriers email extension is not the solution I'm looking for but if someone has figured out how to programmatically figure out the carrier extension, add it to the phone number, then that would work too.
Example I'm using for sending an email
function inventory() {
var sheet = SpreadsheetApp.getActiveSheet()
var row = sheet.getActiveRange().getRowIndex()
var firstName = sheet.getRange(row, getColIndexByName("First Name")).getValue();
var lastName = sheet.getRange(row, getColIndexByName("Last Name")).getValue();
//var phone = sheet.getRange(row, getColIndexByName("Phone Number")).getValue();
var email = sheet.getRange(row, getColIndexByName("Email Address")).getValue();
var inventoryLinks = sheet.getRange(row, getColIndexByName("Inventory Links")).getValue();
//var userEmail = 'put email here';
var subject = "Your Inventory List";
var body = "Hello"
+ "\n\n" + "Please follow the supplied links below to see the listings that fit your profile."
+ "\n\n" + sheet.getRange(row, getColIndexByName("Inventory Links")).getValue();
MailApp.sendEmail(email, subject, body, {name:"Inventory List"});
}
function getColIndexByName(columnName) {
var sheet = SpreadsheetApp.getActiveSheet();
var numColumns = sheet.getLastColumn();
var row = sheet.getRange(1, 1, 1, numColumns).getValues();
for (i in row[0]) {
var name = row[0][i];
if (name == columnName) {
return parseInt(i) + 1;
}
}
return -1;
}
So I want to accomplish the same thing replacing the email address with a phone number
This is what I ended up with. Works Great!
function sendSMS() {
// Get account SID and auth token here:
// https://www.twilio.com/user/account
// Also, you have to buy a paid account to send SMS to any phone number. Otherwise you can only send to verified numbers
// So this script allows me to put my cursor in the row I want to send an SMS.
var sheet = SpreadsheetApp.getActiveSheet();
var row = sheet.getActiveRange().getRowIndex();
var phone = sheet.getRange(row, getColIndexByName("Phone")).getValue();
var inventoryLinks = sheet.getRange(row, getColIndexByName("Inventory Links")).getValue();
var sentSMS = sheet.getRange(row, getColIndexByName("Sent SMS")).getValue();
var comments = sheet.getRange(row, getColIndexByName("Comments")).getValue();
var activeUser = Session.getActiveUser().getEmail();
var extphone = "+1" + phone;
var body = "Click on the link/s to see current inventory. " + inventoryLinks;
var accountSid = "get it from your Twilio account";
var authToken = "get it from your Twilio account";
var url = "https://api.twilio.com/2010-04-01/Accounts/" + accountSid + "/SMS/Messages.json";
var options = {
method: "post",
headers: {
Authorization: "Basic " + Utilities.base64Encode(accountSid + ":" + authToken)
},
payload: {
// From is one of your Twilio phone numbers
From: "Put you Twilio number here",
To: extphone,
Body: body
}
};
sheet.getRange(row, getColIndexByName("Sent SMS")).setValue('Sent SMS').setComment(new Date() + activeUser);
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
}

Related

print Google Datasheets cell through a Telegram bot, print image taken form a cell as a link referal

I'm an Italian (sorry for bad English) system engineer but I accepted to help a friend so I had to achieve this goal.
He's trying to sponsor his products through Telegram but he's stingy and lazy and before investing wants to try something managed by a bot.
So I created the Telegram Bot, used his link of SpreadSheet, and tried to do this thing:
Column U is a link referral to an image and he wants to display that image, column B must be compared with a string and if it's the same then print the column A(integer), F(integer), L(string), J opens a chat with #someone if it's not the same than go to the next line.
As a newbie I past many time reading online and trying to find the way, but I've just reached this:
var token ="myToken";;
var telegramUrl = "https://api.telegram.org/bot" + token;
var webAppUrl = "https://script.google.com/macros/s/myLinkReferal/exec";
var ssId = "MyssId";
var ui = SpreadsheetApp.getUi();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var rangeData = sheet.getDataRange();
var lastColumn = rangeData.getLastColumn();
var lastRow = rangeData.getLastRow();
var searchRange = sheet.getRange(2,2, lastRow-1, lastColumn-1);
function getMe() {
var url = telegramAPI + "/getMe";
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function setWebhook() {
var url = telegramAPI + "/setWebhook?url=" + webAppAPI;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function sendText(id,text) {
var url = telegramAPI + "/sendMessage?chat_id=" + id + "&text=" + text;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function doPost(e) {
Logger.log(e);
for(i = 1; i < lastColumn; i++){
for (j = 1; j < lastRow ; j++){
var cell = searchRange.getCell(1,i).getValue();
if (cell === "DISPONIBILE"){
****visualize a photo taken form a link in datasheet cell Ux
print string taken from Ax
print string taken from Ax**
link to chat with #someone**
}else j=lastRow;
};
};
var text = data.message.text;
var what = data.message.text.split("-")[0]
var who = data.message.text.split("-")[1]
var response = "Hi " + name + ", this quote has been added to your database: " + text;
sendText(id,response);
SpreadsheetApp.openById(ssId).getSheets()[1].appendRow([text,response,what,who]);
}

Trigger WhatsApp message when someone from google sheets

Is it possible to automatically send WhatsApp messages if someone fills my google form,currently storing data into a google sheet. In this form, users fill in their Name and phone number. I want to automatically send them a welcome message when they fill the form. I have successfully sent a welcome email in a similar google form with the help of App Script.
This is what I did in case of email:
function sendMail() {
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("CRM").activate()
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lr = ss.getLastRow();
var quotaLeft = MailApp.getRemainingDailyQuota();
// Logger.log(quotaLeft)
if((lr-1) > quotaLeft){
Browser.msgBox("You have only " + quotaLeft + " E-mail left, mails were not sent")
} else{
for(var i=2; i<=lr;i++){
var currentEmail = ss.getRange(i, 1).getValue();
var currentSub = ss.getRange(i, 3).getValue();
var currentName = ss.getRange(i, 2).getValue();
var templateText = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Templates").getRange(i, 2).getValue();
var name = templateText.replace("{name}", currentName);
MailApp.sendEmail(currentEmail, currentSub, name)
}
Browser.msgBox("Welcome emails sent")
}
}
It's possible if you use twillo. Try the below code
function sampletTextMessage(){
var ACCOUNT_SID = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
var ACCOUNT_TOKEN = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
var options = {
"method" : "post",
'headers' : {
"Authorization" : "Basic " + Utilities.base64Encode(ACCOUNT_SID + ":" + ACCOUNT_TOKEN),
},
'payload' :{
'Body' : 'Your Twilio code is 1238432',
'To' : 'whatsapp:+91XXXXXXXXX3',
'From': 'whatsapp:+1XXXXXXXXX6',
},
'muteHttpExceptions' : true
};
var url="https://api.twilio.com/2010-04-01/Accounts/" + ACCOUNT_SID + "/Messages.json";
var response = UrlFetchApp.fetch(url,options);
Logger.log(response);
}
Register in https://panel.rapiwha.com/landing/login.php. Link your number and get the API Key.
Put the below code in your sheet
Install a Trigger "On Form Submit"
//
//
function onFormSubmit(e) {
var today=new Date();
var shtname = e.source.getActiveSheet().getName();
switch (shtname) {
case "SaleOrder":
var resp = e.source.getActiveSheet().getRange(e.range.rowStart,1, e.range.rowStart,4 ).getValues();
//name is the first question
//mobile no is second question (with country code, without + sign)
var api_key="xxxxxx"; //from rapiwah
var wup = "Dear " +resp[0][1]+" Thank you for contacting us. We will get back yo you soon";
var formurl2= 'https://panel.rapiwha.com/send_message.php?apikey='+api_key+'&number=' + resp[0][2] +'&text='+wup;
var formurl3 = formurl2.replace(/#/g, "");
var formurl4 = formurl3.replace(/,/g, "");
var formurl = formurl4.replace(/ /g, "%20");
var response = UrlFetchApp.fetch(formurl);
break;
//
default:
break;
}
}

Send Email based on column value = yes

I have a Google Sheet where the Email & Name columns are auto-fill based on user submitted form. Also, I have 2 more columns where one column contain the list of giveaway code and another column is to act as an approval to send the email.
So for now I manage to create a button where when click it will send all emails with the giveaway code.
Now,
How can I only send the email to the user that only has a value "y" in the Status column?
Also, after sending the emails, the value "y" will changed to "d"? So that later, if I use the function again, it will only sending to the new users.
This is the sheet example https://docs.google.com/spreadsheets/d/1KkShktBnJoW9TmIzNsAuAJb6XslBrMwJGEJu7xeF1fk/edit?usp=sharing
This is the code
function sendArticleCountEmails() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.setActiveSheet(ss.getSheetByName("Test1"));
var sheet = SpreadsheetApp.getActiveSheet();
var dataRange = sheet.getRange("A2:E1000");
var data = dataRange.getValues();
for (i in data) {
var rowData = data[i];
var emailAddress = rowData[1];
var timeStamp = rowData[0];
var recipient = rowData[2];
var code = rowData[3];
var status = rowData[4];
var message = 'Dear ' + recipient + ',\n\n' + 'The giveaway code is ' + code;
var subject = 'Here is your giveaway code!';
MailApp.sendEmail(emailAddress, subject, message);
}
}
/**
* The event handler triggered when opening the spreadsheet.
* #param {Event} e The onOpen event.
*/
function onOpen(e) {
var spreadsheet = SpreadsheetApp.getActive();
var menuItems = [
{name: 'Send Emails', functionName: 'sendArticleCountEmails'}
];
spreadsheet.addMenu('Send Emails', menuItems);
}
Just add an if statement like this:
function sendArticleCountEmails() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.setActiveSheet(ss.getSheetByName("Test1"));
var sheet = SpreadsheetApp.getActiveSheet();
var dataRange = sheet.getRange("A2:E1000");
var data = dataRange.getValues();
for (i in data) {
var rowData = data[i];
var emailAddress = rowData[1];
var timeStamp = rowData[0];
var recipient = rowData[2];
var code = rowData[3];
var status = rowData[4];
var message = 'Dear ' + recipient + ',\n\n' + 'The giveaway code is ' + code;
var subject = 'Here is your giveaway code!';
if (status == "y") {
MailApp.sendEmail(emailAddress, subject, message);
var actualRow = parseInt(i)+2;
sheet.getRange(actualRow,5).setValue("d");
}
}
}

Google Sheets email once based on cell values

This script works, except it sends multiple emails, This script check Column F for any value above 0 then sends an email.Column F is where i manually enter data. Trying to get it to only send one email and put a "Email Sent" in column H. Then check if column H has a "Email Sent" if so don't send email again.
Here Is what my sheet looks like
https://docs.google.com/spreadsheets/d/1o5jKMDECIFozrwAQx6EDvPL1NkoMQ1nbpkd6AdS9ULk/edit?usp=sharing
function sendEmails() {
var sSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses"); //get the sheet "Form Responses"
var data = sSheet.getRange(2, 1, sSheet.getLastRow(),sSheet.getLastColumn()).getValues(); //get the values of your table, without the header
var lastRow = sSheet.getLastRow();//gets the last row of entered data
var yourColumn = "H";//set your column
var yourFunction = ("Email Sent");//whatever function or formula or data you want,just don't forget to use lastRow do do the row number
sSheet.getRange(yourColumn+lastRow).setValue(yourFunction);
for (var i = 0; i < data.length; i++) { // For each element of your tab
var row = data[i];
if(row[5] > 0) { // If the person have got at least 1 report outstanding (column E)
var body = "Good day "+ row[0] + " you have " + row[5] + " Internal Audit reports outstanding.";
GmailApp.sendEmail(row[1],"Outstanding Internal Audit Reports", body); // Sending a mail to alert
}
}
}
Try This:
function sendEmailsToTechs() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName("Form Responses");
//var sh=ss.getActiveSheet();
var rg=sh.getDataRange();
var data=rg.getValues();
var hRange=sh.getRange(2,8,sh.getLastRow(),1);
var hValues=hRange.getValues();
for (var i=1;i<data.length;i++){
var row = data[i];
if(row[5] && row[7]!='Email Sent') {
var body = "Good day "+ row[0] + " you have " + row[5] + " Internal Audit reports outstanding.";
GmailApp.sendEmail(row[1],"Outstanding Internal Audit Reports", body);
//Logger.log(body);
hValues[i-1][0]='Email Sent';
}
}
hRange.setValues(hValues);//Puts the values into the spreadsheet all at one time.
}

Add encryption to converted Google sheet to PDF

Is it possible to encrypt a converted google sheet into PDF before sending it as an attachment in an email ?
This is my current code: It hides the sheet I don't need to be converted and converting the other sheet into PDF. What I would like to achieve here is for the converted PDF to be password encrypted because it contains some personal information.
function myFunction() {
Utilities.sleep(200);
var sheet=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 1");
var pdfsheet=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");
sheet.hideSheet();
var substringsubject = pdfsheet.getRange("B4:B4").getValues();
var substringnname = pdfsheet.getRange("B3:B3").getValues();
var substringidnum = pdfsheet.getRange("B7:B7").getValues();
var startRow =9; // First row of data to process B9:B9
var numRows =1; // Number of rows to process
// Fetch the range of cells B9:B9
var dataRange = pdfsheet.getRange(startRow, 1, numRows, 2)
// 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 email = row[1];
var emailcc = row[2];
// Subject of email message
var subject = "USER ACCOUNT DETAILS " + substringsubject + " " + substringidnum + "";
var ss= SpreadsheetApp.getActiveSpreadsheet();
// Email Body can be HTML too
var body = '<body>' + ' Hi ' + substringnname +',<br><br>' +
'Please see attached file for your account details.</p>' +
//'<p> Click here to go to google.<p>'
'</body>'
var pdf = DriveApp.getFileById(ss.getId()).getAs("application/pdf");
pdf.setName(substringsubject+" "+substringidnum+" .pdf");
// If allowed to send emails, send the email with the PDF attachment
MailApp.sendEmail({
to:email,
cc:emailcc,
subject:subject,
htmlBody:body,
attachments:[pdf]
});
sheet.showSheet();
}
}
Thank you.
You can't protect your PDF directly from Apps script. See this previous SO question.

Categories