First of all, I don't have any coding knowledge/background, so I don't know if it is appropriate to ask for advices here, and also this is my first post here. I usually look for some codes on the internet that could find my needs, update it to fit my data and done.
So, right now I am setting a shared platform in my organization to allow people to register as either a presenter or participant of sharing sessions.
The session are all pre-created, and they have to pick in the list. After registering, the data are available in a spreadsheet and I have the code to add these registered person for the sessions.
However my issue is, they are added as guests of the event, but don't receive an invitation for this event. Here is the script:
function Presenterscalendar() {
var cal,i,iCalId,row,sheet,thisEvent,presenter,title,email;
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Presenters");
var dataRange = sheet.getRange("A2:G1000");
var data = dataRange.getValues();
cal = CalendarApp.getDefaultCalendar();
for (i in data) {
row = data[i];
presenter = row[1];
title = row[3];
tstart = row[2];
iCalId = row[4];
email = row[6];
thisEvent = cal.getEventSeriesById(iCalId);
if (thisEvent) {
thisEvent.setTitle(title);
thisEvent.setDescription('A session presented by '+presenter);
thisEvent.addGuest(email)
}
}
}
I looked for other script in order to send the invitations to all attendees of each session in the calendar:
function sendInvite(calendarId, eventId, email) {
var calendarId = 'test#test.com';
var vss = SpreadsheetApp.getActive();
var vS = vss.getSheetByName('Presenters');
var dataRange = vS.getRange("A2:H1000");
var data = dataRange.getValues();
for (i in data) {
row = data[i];
presenter = row[1];
title = row[3];
tstart = row[1];
iCalId = row[4];
mail = row[6];
var eventId = vS.getRange("e2:e1000").getValue();
var eid = eventId.split("#")[0]; // Added;
var event = Calendar.Events.get(calendarId, eid);
var attendees = event.attendees;
if(event.attendees) {
event.attendees.push({
email: email
});
} else {
event.attendees = new Array({email:email});
}
event = Calendar.Events.patch(event, calendarId, eid, {
sendupdates: "all"
});
}
}
This works if I just put a static email for ex ({email:"test#google.com"}), but when kept as is it says "missing attendees mail". Eventually, what I would like to is either:
The script to get all the events in the calendar and send the notifications to new attendees registered (update)
The script to get the data from the spreadsheet (where I have in 1 column the email of the attendee -1 row = 1 attendee-) and send the notification to new attendees
I did allow Calendar API for the script and the Google Cloud platform already.
I wonder if you could help me on this, I tried to replicate what I found on the internet, but my limited knowledge on coding doesn't allow me to go further...
Thanks a lot !
The optional query parameters for an event patch are case sensitive
Thus, you need to modify
sendupdates: "all"
to
sendUpdates: "all"
Related
Can i get this script to work from sheet id or sheet name
This script works when i use the active spreadsheet but i want it to get it from the spreadsheet name or the sheet id. If i add .getSheetByName("Test") to line 2 it returns "TypeError: Cannot read property 'getRange' of null"
i am running the script from the sheet named "test" and there is a value in cell a1
Thanks in advance for the help
function CheckPrice() {
var priceRange = SpreadsheetApp.getActiveSpreadsheet().getRange("A1").getValue();
var ui = SpreadsheetApp.getUi();
if (priceRange < 10){
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getRange("A2");
var emailAddress = emailRange.getValue();
var message = 'This is your Alert email!';
var subject = 'Your Google Spreadsheet Alert';
MailApp.sendEmail(emailAddress, subject, message);
}
} ```
Change twice SpreadsheetApp.getActiveSpreadsheet() to SpreadsheetApp.getActiveSpreadsheet().getSheetByName('mySheetName')
For instance
function CheckPrice() {
var priceRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Test').getRange("A1").getValue();
// get value from cell a1
var ui = SpreadsheetApp.getUi();
if (priceRange < 10){
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Test').getRange("A2");
// get email from cell a2
var emailAddress = emailRange.getValue();
// Send Alert Email.
var message = 'This is your Alert email!';
var subject = priceRange + " %up";
// adds cell value to subject
MailApp.sendEmail(emailAddress, subject, message); }
}
Like the title says, is there a way to get the highs and lows of a stock price during the day after a certain time? There's a way to get the days high and low over a period of time:
=GOOGLEFINANCE("AMZN","high","05/01/2020","05/10/2020","DAILY")
=GOOGLEFINANCE("AMZN","low","05/01/2020","05/10/2020","DAILY")
But what about during the day during a specific time period? For example from 9:12AM PST to 11:23AM PST?
Solution#3 : you can use Alpha Vantage by 2 ways, add-on GSheets or a custom function i.e. :
// mike steelson
var apikey = 'xxxxxxxxxxxxxx'
function getAllDataJSONv2(code) {
var url = 'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol='+code+'&interval=5min&apikey='+apikey
var data = JSON.parse(UrlFetchApp.fetch(url).getContentText())['Time Series (5min)']
var resultat = []
for (var elem in eval(data)){
resultat.push([elem,eval(data[elem]['1. open']),eval(data[elem]['2. high']),eval(data[elem]['3. low']),eval(data[elem]['4. close']),eval(data[elem]['5. volume'])])
}
return resultat
}
the apikey is free for up to 500 requests a day. https://rapidapi.com/alphavantage/api/alpha-vantage
no, not possible with GOOGLEFINANCE. you can get only the daily value which is usually from 16:00:00
your only other option is to find some website (which doesn't use JavaScript) that holds values you wish for and scrape it into google sheets
Solution1 : You can use Yahoo Finance to retrieve the information you want
function getHistoric(url){
var source = UrlFetchApp.fetch(url).getContentText()
var jsonString = source.match(/(?<=root.App.main = ).*(?=}}}})/g) + '}}}}'
var data = JSON.parse(jsonString).context.dispatcher.stores.HistoricalPriceStore.prices
var result = []
data.forEach(function(elem){
result.push([elem.date,elem.open,elem.high,elem.low,elem.close])
})
return result
}
https://docs.google.com/spreadsheets/d/1Kly5-Vu5jBfrl6xFljdICFJW369X-OCjB22z3Ouzt4Y/copy
Solution#2 : you can build your own data based on yahoo finance https://docs.google.com/spreadsheets/d/1QlqpPkIMjE8_jT6kNME1cLrMmQZ9cSzG-SR2Jjivvqo/edit?usp=sharing
//Mike Steelson
var histo = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('historic')
var code = histo.getRange('B1').getValue()
//put a trigger on historic
function historic(){
if (testDateHour()==true) {histo.appendRow([new Date(),marketPrice(code)])}
}
function marketPrice(code) {
var source = UrlFetchApp.fetch('https://finance.yahoo.com/quote/'+code).getContentText()
var data = JSON.parse(source.match(/(?<=root.App.main = ).*(?=}}}})/g) + '}}}}')
return data.context.dispatcher.stores.StreamDataStore.quoteData[code].regularMarketPrice.raw
}
function testDateHour(){
var d = new Date();
// not on sunday and saturday and between 10am and 4pm
if (d.getDay()!=0 && d.getDay()!=6 && d.getHours()>=10 && d.getHours()<=16) {return true}else{return false}
}
Configure your local settings (PST) + update if necessary the period when you want to retrieve the information. Then put the trigger (1min)
I'm trying to write a script where an automatic email is sent to a specific person upon edit of a cell and the cell equals "Done". However, I want the subject to be the first cell of the edited row. Cell that will contain "Done" is always going to be in the AA Column, and I want the subject to be the A column of the same row. Ex: AA3 was edited so subject is A3. I have spent hours sifting through tutorials and came up with this:
function checkValue() {
var sp = PropertiesService.getScriptProperties();
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Accts");
var valueToCheck = sheet.getRange("AA2:AA1000").getValue();
if (valueToCheck = 'Done') {
MailApp.sendEmail("a***a#gmail.com", activeCell.offset(-26,0).getValue(), Email.html);
}
}
Am I doing this entirely wrong or is there hope?
EDIT:
Now that it's resolved. I thought I'd share what my script ended up looking like. I added a UI and an option to execute using a menu option. Hope this helps someone else.
function onEdit(e)
{
var editRange = { // AA2:AA1000
top : 2,
bottom : 1000,
left : 27,
right : 27
};
// Exit if we're out of range
var thisRow = e.range.getRow();
if (thisRow < editRange.top || thisRow > editRange.bottom) return;
var thisCol = e.range.getColumn();
if (thisCol < editRange.left || thisCol > editRange.right) return;
var thisthang = e.value;
var doit = 'TRUE'
// We're in range; timestamp the edit
if(thisthang == doit)
{
doFinish();
}
else{return};
}
function onOpen()
{
var ui = SpreadsheetApp.getUi();
ui.createMenu('Finished')
.addItem('Finish', 'doFinish')
.addToUi();
}
function doFinish()
{
var cell = SpreadsheetApp.getActiveSheet().getActiveCell();
var row = cell.getRow();
var Campaign = getCampaignFromRow(row, 1);
var ui = SpreadsheetApp.getUi();
var response = ui.alert('Finish '+Campaign.name+'?', ui.ButtonSet.YES_NO);
if(response == ui.Button.YES)
{
handleFinish(row, Campaign);
}
if(response == ui.Button.NO)
{
SpreadsheetApp.getActiveSheet().getRange(row, 27).setValue('FALSE');
}
}
function getCampaignFromRow(row)
{
var values = SpreadsheetApp.getActiveSheet().getRange(row, 1).getValues();
var rec = values[0];
var Campaign =
{
Campaign_Name: rec[0]
};
Campaign.name = Campaign.Campaign_Name;
return Campaign;
}
function handleFinish(row, Campaign)
{
var templ = HtmlService
.createTemplateFromFile('Campaign-email');
templ.Campaign = Campaign;
var message = templ.evaluate().getContent();
MailApp.sendEmail({
to: "a***a#gmail.com",
subject: "A Campaign has been finished!",
htmlBody: message
});
SpreadsheetApp.getActiveSheet().getRange(row, 27).setValue('TRUE');
}
You are trying to trigger an email when the spreadsheet is edited on the "Accts" sheet, in Column "AA" and the value = "Done".
The best solution is to use an onEdit trigger and also make use of Event Objects. In the case, "a simple trigger cannot send an email" ref, so you will need to create an Installable Trigger.
The main differences to your script are:
- var valueToCheck = sheet.getRange("AA2:AA1000").getValue();
- a couple of things here.
- 1) you are trying to get all the values in the column, but you use the getValue (the method for a single cell) instead of getValues.
- 2) you could have defined the ActiveCell and just returned that value
- 3) though you tried to get the values for the entire column, your if statement is designed as though there is a single value rather than an array of values.
- 4) This demonstrates the benefit of the using the Event Objects. You can succinctly get the values of the edited cell and sheet.
- in your if comparison, you use "="; this is only used to assign a value. When comparing values you must use "==" or "===".
- To get the value of the "subject", the script uses the row number derived from the Event Objects; compared to the offset in your script - they are both acceptable. I used the getRange to demonstrate the alternative.
- your email body was defined as "Email.html", but this isn't declared. The answer uses a very simple body but could just as easily use another solution.
function so5967209001(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet()
// establish the values to be checked
var checkSheetname = "Accts"
var checkValue = "Done"
var checkColumn = 27; // column AA
// this will return the event objects
//Logger.log(JSON.stringify(e)); // DEBUG
// variables to use for checking
var editedrange = e.range;
var editedrow = editedrange.getRow();
var editedcolumn = editedrange.getColumn();
var editedsheet = editedrange.getSheet().getSheetName();
var editedvalue = e.value;
//Logger.log("DEBUG: row = "+editedrow+", column = "+editedcolumn+", sheet = "+editedsheet+", value"+editedvalue)
// test the sheet, the column and the value
if (editedsheet ==checkSheetname && editedcolumn==checkColumn && editedvalue == checkValue){
//Logger.log("DEBUG: this is a match");
var subject = sheet.getRange(editedrow,1).getValue(); // Column A of the edited row
//Logger.log("DEBUG: email subject = "+subject);
// build your own body
var body = "this is the body of the email"
// send the email
MailApp.sendEmail("ejb#tedbell.com.au", subject, body);
//Logger.log("DEBUG: mail sent")
}else{
//Logger.log("DEBUG: this isn't a match");
}
}
I'm trying to create an app script that you can type in the name and username of an individual and select various dates associated with their training. I'm nearly done with the project but one piece of script is giving me issues. What the script is supposed to do is take the User Name I've entered into the app and see if that value already exists in column L of the archive. If the value exists then it should return an alert with a YES_NO option and depending on what is selected it will either cancel the import or continue on and import the username to the sheet.
I've been trying to figure out this script for about 5 days and cannot figure it out. I've tried pretty much everything I can think of. Here's the code. The Username already exists in Cell L3 of the Archive.
function postApp(e)
{
var usern = e.parameter.userN;
var name1 = e.parameter.name;
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var tM = sheet.getSheetByName('Archive');
var tR = tM.getLastRow()-1;
var tC = tM.getLastColumn();
var tD = tM.getRange("L3").getValues();
if(tD == usern )
{
var ui = SpreadsheetApp.getUi(); // Same variations.
var result = ui.alert('Wait', 'The Username you are trying to use has already been archived. Would you still like to continue?', ui.ButtonSet.YES_NO);
// Process the user's response.
if (result == ui.Button.Yes) {
// User clicked "Yes".
SpreadsheetApp.getActiveSpreadsheet().toast('Error Report Has Been Updated', 'UPDATE ERRORS',3);
var date = new Date();
var d = Utilities.formatDate(date, Session.getScriptTimeZone(), 'M/d/yyyy');
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('SyNERGY');
var lR = s.getLastRow()+1;
var lC = s.getLastColumn();
var app = UiApp.getActiveApplication();
var name = e.parameter.name;
var user = e.parameter.userN;
var team = e.parameter.team;
var hire = e.parameter.hire;
////////////////////////////
// CREATE REPORT CARD
genReportCard(name, team, hire, app, user);
s.getRange(lR,12).setValue([[user]]).setNumberFormat(';;;');
s.getRange(lR,12).setValue(user.toString().toLowerCase());
s.getRange(lR,11).setValue('SyN');
///////////////////////////////////////////
///////////Close after complete////////////
var ui = SpreadsheetApp.getUi(); // Same variations.
var result = ui.alert("Specialist Created!");
var app = UiApp.getActiveApplication();
app.close();
return app;
}else {
// User clicked "No" or X in the title bar.
ui.alert('Import Canceled');
}
}else{
var date = new Date();
var d = Utilities.formatDate(date, Session.getScriptTimeZone(),
'M/d/yyyy');
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('SyNERGY');
var lR = s.getLastRow()+1;
var lC = s.getLastColumn();
var app = UiApp.getActiveApplication();
var name = e.parameter.name;
var user = e.parameter.userN;
var team = e.parameter.team;
var hire = e.parameter.hire;
////////////////////////////
// CREATE REPORT CARD
genReportCard(name, team, hire, app, user);
s.getRange(lR,12).setValue([[user]]).setNumberFormat(';;;');
s.getRange(lR,12).setValue(user.toString().toLowerCase());
s.getRange(lR,11).setValue('SyN');
///////////////////////////////////////////
///////////Close after complete////////////
var ui = SpreadsheetApp.getUi(); // Same variations.
var result = ui.alert("Specialist Created!");
var app = UiApp.getActiveApplication();
app.close();
return app;
}
}
This script Works as long as I am referencing One Cell so tM.getRange("L3").getValues(); Works. However, As soon as I change that to tM.getRange("L3:L").getValues(); it does not recognize the value exists within the range and returns the else portion of the code.
I have also tried a loop for the top section that is giving me issues but the same thing is happening. As soon as I try to find a value within the column rather than a specific cell it won't work. Here is what it looks like with the loop.
function postApp(e)
{
var usern = e.parameter.userN;
var name1 = e.parameter.name;
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var tM = sheet.getSheetByName('Archive');
var tR = tM.getLastRow()-1;
var tC = tM.getLastColumn();
var tD = tM.getDataRange().getValues();
for(var i = 0; i<tD.length; i++){
if(tD[i][11] == usern )
{
If anyone can figure out what i'm doing wrong or why it's not working as soon as I reference the entire column any help would be greatly appreciated.
Thanks!
I'm currently trying to fetch mailchimp data for the total amount of subscribers within a predefined auto updating segment within our subscriber list into Google sheets using the script editor. However, I must confess I'm not very knowledgeable in this area and have tried various ways of customizing this code with no luck. I have looked at Mailchimps documentation regarding this but still cannot seem to get this work.
function chimpSubscribers() {
var API_KEY = ''; // MailChimp API Key
var LIST_ID = ''; // MailChimp List ID
var SEGMENT_ID =''; //Mailchimp Segment ID
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Subscribers");
var dc = API_KEY.split('-')[1];
var api = 'https://'+ dc +'.api.mailchimp.com/3.0';
var memberList = '/lists/'+LIST_ID
var memberSegment = '/segments/'+SEGMENT_ID
var apiCall = function(endpoint){
options = {"headers": {"authorization": 'apikey '+API_KEY}};
apiResponseMembers = UrlFetchApp.fetch(api+endpoint,options);
json = JSON.parse(apiResponseMembers);
return json
}
var members = apiCall ("memberList", "memberSegment");
if (members) {
var d = new Date();
var member_count = members.stats.member_count;
var unsubscribe_count = members.stats.unsubscribe_count;
var open_rate = members.stats.open_rate;
var click_rate = members.stats.click_rate;
var report = [d, member_count, unsubscribe_count, open_rate, click_rate,];
Logger.log(report);
// Clear MailChimp data in Spreadsheet
sheet.clear();
// Append MailChimp data to Spreadsheet
sheet.appendRow(["Date", "Total Subscribers", "Unsubscribe Count", "Open Rate", "Click Rate"]);
sheet.appendRow(report);
}
}
Figured it out - for anyone else that may need it the code is as follows:
function chimpSubscribers() {
var API_KEY = ''; // MailChimp API Key
var LIST_ID = ''; // MailChimp List ID
var SEGMENT_ID = ''; // Mailchimp Segment ID
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Subscribers");
var dc = API_KEY.split('-')[1];
var api = 'https://'+ dc +'.api.mailchimp.com/3.0';
var memberList = '/lists/'+LIST_ID +'/segments/'+ SEGMENT_ID
options = {"headers": {"authorization": 'apikey '+API_KEY}};
var apiCall = function(endpoint){
apiResponseMembers = UrlFetchApp.fetch(api+endpoint,options);
json = JSON.parse(apiResponseMembers);
return json
}
var members = apiCall(memberList);
if (members) {
var d = new Date();
var member_count = members.member_count;
var report = [d,member_count,];
Logger.log(report);
// Clear MailChimp data in Spreadsheet
sheet.clear();
// Append MailChimp data to Spreadsheet
sheet.appendRow(["Date", "Total Subscribers"]);
sheet.appendRow(report);
}
}