r/GoogleAppsScript • u/bdeskin • Jan 18 '21
Resolved Adding a Timestamp With Google Apps Script When Adding a Spreadsheet Row from Slack
I want to send information from Slack into a new row in a Google Sheet and include a timestamp indicating when that row was added.
Following Slack instructions on how to Send Information into a Google Sheet I have successfully added a row, but do not see how to send a timestamp along with it.
I found a Google Apps script from this Stackoverflow page to add a timestamp when a cell is edited:
function onEdit() {
var s = SpreadsheetApp.getActiveSheet();
if( s.getName() == "Sheet1" ) { //checks that we're on the correct sheet
var r = s.getActiveCell();
if( r.getColumn() == 1 ) { //checks the column
var nextCell = r.offset(0, 1);
if( nextCell.getValue() === '' ) //is empty?
nextCell.setValue(new Date());
}
}
}The script adds a timestamp when I manually enter data into the Google spreadsheet, but when I add a new row from Slack, no timestamp appears.
This Stackoverflow post is about a similar issue. It explains that there's a difference between pasting and editing, so I think my problem is related. But I still don't understand what exact changes to make in the script above, and I wasn't able to implement the corrected script on that page successfully either.
Can someone help me either
tweak the script above so it will work when I'm adding a row from Slack; or
figure out another way to send a timestamp from Slack as part of that row of data?
1
u/mobile-thinker Jan 19 '21
OnEdit won’t fire when another script runs (the Slack connector).
I don’t know Slack - but are you able to create a new field in the Slack form that has a variable containing the current time? You may need to raise this in a Slack forum, because this can’t be resolved in gSheets.
You could get a time that was roughly correct by running a timed trigger that finds all rows without a time stamp and applies a time stamp. Make this run once per minute and you’ve got something crude.
1
1
u/imthenachoman Jan 19 '21
So this is a hack but it works well enough. One disclaimer is that it won't be accurate down to the exact second.
Create a 2nd sheet in your spreadsheet
Early on in your Slack workflow, write `=now()` to a cell in this 2nd sheet
Before you write the real data you want to write to your 1st sheet, read the value of the cell you wrote in the above step
Use that value when writing the real data you want to write
I hope that makes sense?
2
1
1
u/lordph8 Jan 18 '21
Change onEdit to onChange.