I have a spreadsheet with several payment dates and want to create a slackbot to post a message to Slack when the date in one specific column match today's date. I'm very new to coding and I'm using a code I found to send an email, but can't find nothing about posting it to Slack. Could someone give me a hand, please?
This is the code I'm using to send email:
function emailAlert() {
// today's date information
var today = new Date();
var todayMonth = today.getMonth() + 1;
var todayDay = today.getDate();
var todayYear = today.getFullYear();
// getting data from spreadsheet
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 100; // Number of rows to process
var dataRange = sheet.getRange(startRow, 1, numRows, 999);
var data = dataRange.getValues();
//looping through all of the rows
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var expireDateFormat = Utilities.formatDate(
new Date(row[6]),
'ET',
'yyyy/MM/dd'
);
// email information
var subject = '';
var message =
'Hello' +
'\n' +
'\n' +
'These are the due dates for today:' +
'\n' +
'\n' +
' ID number: ' +
row[0] +
'\n' +
' Name: ' +
row[1] +
'\n' +
' Due date: ' +
expireDateFormat;
//expiration date information
var expireDateMonth = new Date(row[6]).getMonth() + 1;
var expireDateDay = new Date(row[6]).getDate();
var expireDateYear = new Date(row[6]).getFullYear();
//checking for today
if (
expireDateYear === todayYear &&
expireDateMonth === todayMonth &&
expireDateDay === todayDay
)
{
var subject =
'Due date ' + row[1] + ' - ' + expireDateFormat;
MailApp.sendEmail('email address here', subject, message);
Logger.log('todayyyy!');
}
}
}
Here is a http post request shows how to send a post to Slack
POST https://slack.com/api/chat.postMessage
Content-type: application/json
Authorization: Bearer xoxb-your-token
{
"channel": "YOUR_CHANNEL_ID",
"text": "Hello world :tada:"
}
Chackout more information from : https://api.slack.com/messaging/sending
Related
function B2B() {
var summary = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Summary");
var subject = "B2B - Delivery Status on";
var recipient = "******#***.in";
var dataRange = summary.getRange('B2:AA49');
var data = dataRange.getValues();
summary.getRange(2, 2, 25, 25).getValue;
var body = "I just discovered Apps Script and it's so cool!" + data;
MailApp.sendEmail(recipient, subject, body);
}
Used this query which is working and mail is going but, selected data range is table which i am not getting in table format in the mail.
Try this
function B2B() {
var summary = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Summary");
var subject = "B2B - Delivery Status on";
var recipient = "******#***.in";
var dataRange = summary.getRange('B1:AA49');
var [headers, ...rows] = dataRange.getValues();
MailApp.sendEmail({
to: recipient,
subject: subject,
htmlBody: "I just discovered Apps Script and it's so cool!" + "<br><br>" + tableHTML([headers], rows)
})
}
function tableHTML(headers, data) {
var tableformat = 'cellspacing="2" cellpadding="2" border="1" style="width:100%;border-collapse:collapse;border:1px solid #ccc"';
var header = headers.map(h => '<tr><th>' + h.join('</th><th>') + '</th></tr>')
var rows = data.map(r => '<tr><td>' + r.join('</td><td>') + '</td></tr>')
return '<table ' + tableformat + ' >\n' + header.join('\n') + rows.join('\n') + '</table>'
}
you need htmlbody instead of body
tableHTML is a function that will tranform the data into a table
map
join
I have a table with 8 columns with dates. I need to track them if they are to expire, but for 3 of them I need to alert alert 3 months before and for the remaining columns, 6 months before.
I think that I am on the right track with the code below, but still not doing what it needs to be done.
I start with one month in the beginning. Can somebody help me?
function emailAlert() {
// today's date information
var today = new Date();
var todayMonth = today.getMonth() + 1;
var todayDay = today.getDate();
var todayYear = today.getFullYear();
var newToday = new Date()
var oneMonthFromToday = new Date(newToday.setMonth(newToday.getMonth()+1));
var oneMonthMonth = oneMonthFromToday.getMonth() + 1;
var oneMonthDay = oneMonthFromToday.getDate();
var oneMonthYear = oneMonthFromToday.getFullYear();
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2;
var numRows = 100;
var dataRange = sheet.getRange(startRow, 1, numRows, 999);
var data = dataRange.getValues();
//looping through all of the rows
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var expireDateFormat = Utilities.formatDate(
new Date(row[6]),
'ET',
'MM/dd/yyyy'
);
var subject = '';
var message = ' You have expiring pass. ' + '\n';
MailApp.sendEmail('lubomira.petkova88#gmail.com', subject, message);
}
It is not clear on your post but the code below assumed only 1 column needs to be checked. Feel free to adjust the conditions but this should be the main idea of your code.
Code:
function checkPasswordExpiry() {
// today's date information
var today = new Date();
today.setHours(0,0,0,0);
// 3 months before
var prev3Months = new Date();
prev3Months.setMonth(today.getMonth() - 3);
prev3Months.setHours(0,0,0,0);
// 6 months before
var prev6Months = new Date();
prev6Months.setMonth(today.getMonth() - 6);
prev6Months.setHours(0,0,0,0);
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2;
// get number of rows/columns in sheet instead of manually setting it
var numRows = sheet.getLastRow();
var numCols = sheet.getLastColumn();
var dataRange = sheet.getRange(startRow, 1, numRows, numCols);
var data = dataRange.getValues();
//looping through all of the rows
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var expireDateFormat = Utilities.formatDate(
new Date(row[6]),
'ET',
'MM/dd/yyyy'
);
var date = new Date(row[6]);
date.setHours(0,0,0,0);
var subject = 'Password Expiry';
var message = 'Hi ' + row[0] + ', \nYour password is expiring';
var email = 'lubomira.petkova88#gmail.com';
if(date.getTime() === prev6Months.getTime()) {
message += " in 6 months. ( " + expireDateFormat + " )";
MailApp.sendEmail(email, subject, message);
}
else if(date.getTime() === prev3Months.getTime()) {
message += " in 3 months. ( " + expireDateFormat + " )";
MailApp.sendEmail(email, subject, message);
}
else if(date.getTime() === today.getTime()) {
message += " today. ( " + expireDateFormat + " )";
MailApp.sendEmail(email, subject, message);
}
}
}
The code above does check column G whether it is already 6 months before today, 3 months before today or exactly the date. If you need to check multiple columns, just replace the conditions inside and it should still work.
Sample email:
Note that the code above should be triggered every day so it can check the data daily.
Code:
function createTimeDrivenTriggers() {
ScriptApp.newTrigger('checkPasswordExpiry')
.timeBased()
.everyDays(1)
.atHour(0)
.create();
}
Function createTimeDrivenTriggers needs to be run just once. Please see reference below.
Reference:
Time driven triggers
everyDays()
If I wasn't able to provide you the answer you are hoping for, I sincerely apologize. Feel free to comment below what are the changes that are needed to be done.
I am very new to this, so please bear with me. I am trying to get my code to look at each cell in a column, then compare that date to the current date, and if they match send an email. I am aware I will need a loop of some sort to get it to look through the column, but I haven't even gotten that far. I've tried every method I can find online to just get it to compare one cell to the date and send the email.
I tested the email function prior to adjusting it to compare the date, so I know that is working. Put something definitely isn't working...
function sendEmail() {
//Fetch the date
var removalDateRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Expirations").getRange("E2");
var removalDate = removalDateRange.getValue();
var currentDateRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Alerts").getRange("C2");
var currentDate = new Date();
var ui = SpreadsheetApp.getUi();
//Check Date
if (removalDate == currentDate) {
//Fetch the email address
var emailRange =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Alerts").getRange("B2");
var emailAddress = emailRange.getValue();
//Fetch Item Brand
var itemBrandRange =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Expirations").getRange("B2");
var itemBrand = itemBrandRange.getValue();
//Fetch Item Name
var itemNameRange =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Expirations").getRange("A2");
var itemName = itemNameRange.getValue();
//Fetch Item Location
var itemLocationRange =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Expirations").getRange("H2");
var itemLocation = itemLocationRange.getValue();
// Send Alert Email
var message = 'The ' + itemBrand + ' ' + itemName + ' in ' + itemLocation + ' will expire in 2 months. Please use and replace item.';
// Second Column
var subject = 'Pantry Alert';
MailApp.sendEmail(emailAddress, subject, message);
}
}
EDIT
Okay, I had it working late last night and even got it to loop through, and somehow I've broken it again. I've been looking at answers for hours trying to adjust things to make it work. What am I doing wrong?
function emailAlert() {
// today's date information
var today = new Date();
var todayMonth = today.getMonth() + 1;
var todayDay = today.getDate();
var todayYear = today.getFullYear();
// 2 months from now
var oneMonthFromToday = new Date(todayYear, todayMonth, todayDay);
var oneMonthMonth = oneMonthFromToday.getMonth() + 2;
var oneMonthDay = oneMonthFromToday.getDate();
var oneMonthYear = oneMonthFromToday.getYear();
// getting data from spreadsheet
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Exp");
var startRow = 2; // First row of data to process
var numRows = 500; // Number of rows to process
var dataRange = sheet.getRange(startRow, 1, numRows, 999);
var data = dataRange.getValues();
//looping through all of the rows
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var expireDateFormat = Utilities.formatDate(new Date(row[5]),
'ET',
'MM/dd/yyyy'
);
//email Information
var subject = 'Pantry Item Needs Attention!';
var message1 =
row[6] + ' ' + row[3] + ' of ' + row[2] + ' ' + row[1] + ' will expire on ' + expireDateFormat + '. Item can be found in ' + row[7]
+ '. Please Remove and Replace Item.' +
'\n' + 'Thanks Steve!';
var message2 =
row[6] + ' ' + row[3] + ' of ' + row[2] + ' ' + row[1] + ' will expire on ' + expireDateFormat + '. Item can be found in ' + row[7] +
'. Please ensure item has been replaced, removed from the pantry, and deleted from inventory.' +
'\n' + 'Thanks Steve!'
//expiration date information
var expireDateMonth = new Date(row[5]).getMonth() + 1;
var expireDateDay = new Date(row[5]).getDate();
var expireDateYear = new Date(row[5]).getYear();
//checking for today
if (
expireDateMonth === todayMonth &&
expireDateDay === todayDay &&
expireDateYear === todayYear
) {
ui.alert(message1);
}
}
}
Dates can be frustrating to work with, so consider doing the whole thing (loop, if then statement...) with an integer first and then returning to the date part if you're having trouble. That said, try adjusting the top of your code to look like the following:
var ss =SpreadsheetApp.getActiveSpreadsheet();
var removalDateVal = ss.getSheetByName("Expirations").getRange("E2").getValue();
var removalDate = new Date(removalDateVal);
var currentDateVal = ss.getSheetByName("Alerts").getRange("C2").getValue();
var currentDate = new Date(currentDateVal);
That will give you two date objects. But BEWARE! These dates contain time as well as calendar date so they may not equal each other even when they appear to. Use setHours() to zero out the date as seen below.
currentDate.setHours(0,0,0);
removalDate.setHours(0,0,0);
Other notes, it's best practice to set a variable for a spreadsheet and worksheet as shown by Google here. It makes the code much more readable.
I am very new to scripting and am struggling to write a script for our youth league program's apparel fundraiser. The script, when triggered by clicking an image, will send an email to all of the recipients on a list, add 'email sent' to status column 'I' in all of the rows that the email sent to...then whenever the script is run again, only send emails to the new rows of data that haven't been emailed yet.
The script that I have inserts email sent, but if the script is run again it doesn't pay attention to the status column 'I' and I get duplicate emails. I've used tutorial videos to get me this far, but now I'm stuck. I've tried to get help from similar questions, but I'm not experienced enough to modify it to fit my needs. Here is a copy of the google sheet, the 'Send Emails' sheet has the info the script is running from. UPDATED:
https://docs.google.com/spreadsheets/d/1MBVhLj1A7Z_cpYxs_s5ae11ykJvTmS16E0jW4tGsNU4/edit?usp=sharing
function sendOrderEmails() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.setActiveSheet(ss.getSheetByName("Send Emails"));
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2;
var dataRange = sheet.getRange("A2:I10");
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var rowData = data[i];
var emailAddress = rowData[0];
var recipient = rowData[1];
var message1 = rowData[2];
var parameter1 = rowData[3];
var message2 = rowData[4];
var message3 = rowData[5];
var parameter2 = rowData[6];
var message4 = rowData[7];
var emailSent = rowData[9];
var message = 'Hi ' + recipient + ',\n\n' + message1 + parameter1 + ' ' + message2 + ' ' + message3 + parameter2 + '. ' + message4 + '\n\n' + 'Tri-Valley Youth League Softball';
var subject = 'Order Reference Number ' + parameter2;
if (emailSent != "EMAIL_SENT" ) { // Prevents sending duplicates
MailApp.sendEmail(emailAddress, subject, message);
sheet.getRange(startRow + i, 9).setValue("EMAIL_SENT");
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}
Try this:
function sendOrderEmails() {
var ss=SpreadsheetApp.getActive();
var sheet=ss.getSheetByName("Send Emails");
var startRow=2;
var dataRange=sheet.getRange("A2:J10");//Include column 10 in the range
var data=dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var rowData = data[i];
var emailAddress = rowData[0];
var recipient = rowData[1];
var message1 = rowData[2];
var parameter1 = rowData[3];
var message2 = rowData[4];
var message3 = rowData[5];
var parameter2 = rowData[6];
var message4 = rowData[7];
var emailSent = rowData[8];//This is column 9
var message = 'Hi ' + recipient + ',\n\n' + message1 + parameter1 + ' ' + message2 + ' ' + message3 + parameter2 + '. ' + message4 + '\n\n' + 'Tri-Valley Youth League Softball';
var subject = 'Order Reference Number ' + parameter2;
if (emailSent != "EMAIL_SENT" ) {
MailApp.sendEmail(emailAddress, subject, message);
sheet.getRange(startRow + i, 9).setValue("EMAIL_SENT");
}
}
}
I did this so that you can see the difference row and columns and data indices.
function rowsColumnsAndIndices() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getActiveSheet();
var rg=sh.getRange(1,1,26,26);
var vA=rg.getValues();
for(var i=0;i<vA.length;i++) {
for(var j=0;j<vA[i].length;j++) {
vA[i][j]=Utilities.formatString('r: %s, c: %s\ni: %s,j: %s', i+1,j+1,i,j);
}
}
rg.setValues(vA);
}
I created a script earlier this year to create a calendar event from a spreadsheet line, putting it onto a shared family calendar and a secondary calendar of my own.
It was running fine earlier this year, but now instead of adding to the secondary calendars, it only adds to my default calendar, which I don't have coded into the script at all.
Did something change with the syntax of how to call a calendar by ID?
//push new events to calendar
function pushToCalendar() {
//spreadsheet variables
var book = SpreadsheetApp.getActiveSpreadsheet();
var now = new Date();
var currentYear = Utilities.formatDate(new Date(now.getTime()), 'America/Chicago', 'yyyy');
var currentSheet = ("Events" + " " + currentYear);
var sheet = book.getSheetByName(currentSheet);
var lastRow = sheet.getLastRow();
var lastCol = sheet.getLastColumn();
var range = sheet.getRange(2,1,lastRow,lastCol);
var values = range.getValues();
//calendar variables
var calendar = CalendarApp.getCalendarById('sample1#group.calendar.google.com');
var calendarShared = CalendarApp.getCalendarById('sample2#group.calendar.google.com');
var numValues = 0;
for (var i = 0; i < values.length; i++) {
//check to see if values 0,1,3,4,5,6 are filled out
if ((values[i][0]) && (values[i][1]) && (values[i][3]) && (values[i][4]) && (values[i][5]) && (values[i][6]))
{
//check if it's been entered before (values[i][8] = '')||(values[i][8] = null)
if (values[i][7].toString().toLowerCase() !== 'y') {
//create event https://developers.google.com/apps-script/class_calendarapp#createEvent
var newEventTitle = 'Game: ' + values[i][0] + ' - ' + values[i][1];
var newSharedTitle = 'Adam - Game: ' + values[i][0] + ' - ' + values[i][1];
var startDay = Utilities.formatDate(new Date(values[i][3]), 'America/Chicago', 'MMMM dd, yyyy');
var startTime = Utilities.formatDate(new Date(values[i][4]), 'America/Chicago', 'HH:mm');
var start = startDay + ' ' + startTime;
var endDay = Utilities.formatDate(new Date(values[i][5]), 'America/Chicago', 'MMMM dd, yyyy');
var endTime = Utilities.formatDate(new Date(values[i][6]), 'America/Chicago', 'HH:mm');
var end = endDay+ ' ' + endTime;
var details = values[i][9] + ' - $' + values[i][10] + '\n' + '\n' + 'Crew: ' + '\n' + values[i][14] + '\n' + values[i][15] + '\n' + values[i][16] + '\n' + '\n' +'Assessor:' + '\n' + values[i][17];
//new event on Secondary AND Shared Calendar
var newEvent = calendar.createEvent(newEventTitle, new Date(start), new Date(end), {location: values[i][13], description: details});
var newSharedEvent = calendarShared.createEvent(newSharedTitle, new Date(start), new Date(end), {location: values[i][13], description: details});
//get ID
var newEventId = newEvent.getId();
//mark as entered, enter ID
sheet.getRange(i+2,8).setValue('y');
sheet.getRange(i+2,9).setValue(newEventId);
}
else;
}
numValues++;
}
Thanks in advance for your help!
Try to create the event and after insert it into your calendar like this:
var event = {
summary:summary,
location: location,
description: '',
start: {dateTime: newdatestart.toISOString()},
end: {dateTime: newdateend.toISOString()},
attendees: [
{email: ''},{email: ''}],
// Red background. Use Calendar.Colors.get() for the full list.
colorId: 11
};
event = Calendar.Events.insert(event, calendarId);
I encountered this same problem with ID as well....apparently you need to get rid of #google.com part of the Event ID itself, and then get it as part of an array
.getId().split('#')[0];
just add this code and it worked like a charm for me