Twitter API: Count number of Tweets since 0:00am this morning? - javascript

Is there an API to count the number of Tweets since 0:00am this morning for a particular user? I have tried the following Javascript but the closest I can get to it is the total number of tweets for all time for that user.
$.getJSON("http://api.twitter.com/1/statuses/user_timeline/BarackObama.json?count=1&include_rts=1&callback=?", function(data) {
$("#twitter").html(data[0].user.statuses_count);
});

You can download the user timeline until you get tweets which were posted "yesterday" (i.e. before 0:00am). Once you get it, you just have to count tweets which were posted "today" (i.e. after 0:00am).
EDIT 1 : a pseudo JavaScript code for getting it
var howManyTweetsWerePostedToday = function () {
var timeline = downloadTimeline()
var lastTweet = timeline[timeline.length-1]
var now = new Date()
var today = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDay(), 0, 0, 0, 0) // Limit between today and yesterday
var lastTweetDate = new Date(lastTweet["created_at"])
while (lastTweetDate.getTime() >= today.getTime()) {
var lastTweetID = lastTweet["id_str"]
var earlierTweetsTimeline = downloadTimeline(max_id = lastTweetID)
timeline = timeline.concat(earlierTweetsTimeline.shift())
lastTweet = timeline[timeline.length-1]
lastTweetDate = new Date(lastTweet["created_at"])
}
return getNumberOfTweetsThatWerePostedTodayInTheTimeline(timeline)
}();
With downloadTimeline() which is a function calling the GET statuses/user_timelineTwitter API endpoint to get the timeline. See https://dev.twitter.com/docs/api/1/get/statuses/user_timeline for details about the endpoint, especially max_id which is the highest tweet ID that will be in the results.
created_at is the date when a tweet was posted. id_str is the ID of a tweet under a String form. See https://dev.twitter.com/docs/platform-objects/tweets for more details about tweets.

Related

Google Script cell value email notification by current date

I would like to send automated email notifications from my google spreadsheet if the value in column E is higher than 0. The spreadsheet looks like this. The problem is I cant figure out how to check only values for current days date and then post by email. My code looks like this
var failedOperationRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("notif").getRange("E2");
var failedOperation = failedOperationRange.getValue();
var ui = SpreadsheetApp.getUi();
// Check totals sales
if (failedOperation > 0){
// ui.alert('Failed operation occured!');
// Send Alert Email.
var message = failedOperation;
var subject = 'Your Google Spreadsheet Alert';
for(var i in TO) {
MailApp.sendEmail(TO[i], subject, message);
}
Get the value for the corresponding row in column 'H' and compare it with a javascript Date object.
If you need the current date in a string format you can use this:
var today = new Date();
today.toLocaleDateString(); // 3/26/2020
Then you send the email if the two conditions (failed operations > 0 and date = today) are satisfied.

How to get a timestamp based on a user's onclick event?

I'm creating an expense tracker application and wanted to get some insight on how to get and save a user's timestamp based on when they click the submit button.
let timestamp = new Date().getTime();
let todate = new Date(timestamp).getDate();
let tomonth = new Date(timestamp).getMonth() + 1;
let toyear = new Date(timestamp).getFullYear();
let original_date = tomonth + "/" + todate + "/" + toyear;
I understand the following code grabs the current date and formats it. If I were to just populate the DOM with original_date based on a click, then it'd work with today's date, but if I check it tomorrow, then it'll grab tomorrow's date. My current problem is, how would I go about saving the date based on a user's submit event without having it update to the current time.
Idea: Would having an event listener for the button be the way to go? Let's say:
function addTransaction(e) {
e.preventDefault();
let saveDate = original_date;
if (text.value.trim() === "" || amount.value.trim() === "") {
alert("Please add a description and amount of the transaction");
} else {
const transaction = {
id: generateID(),
text: text.value,
amount: +amount.value,
date: saveDate
};
transactions.push(transaction);
addTransactionDOM(transaction);
}
}
function addTransactionDOM(transaction) {
const sign = transaction.amount < 0 ? "-" : "+";
//creating new element
const item = document.createElement("li");
//Add class based on value
item.classList.add(transaction.amount < 0 ? "minus" : "plus");
item.innerHTML = `
${transaction.date}
${transaction.text}
${sign}${Math.abs(transaction.amount)}
`;
list.appendChild(item);
}
form.addEventListener("submit", addTransaction);
Would something like this work?
You can save in the browser localStorage the data you need to be retrieved later.
For example:
// Store data
localStorage.setItem('originalDateKey', original_date);
// Get data
var retrievedDate = localStorage.getItem('originalDateKey');
// Remove data
localStorage.removeItem('originalDateKey');
What you need is window.localStorage: localStorage documentation
window.localStorage.setItem(key, value) saves a string value to the user's local storage and can later be accessed with window.localStorage.getItem(key) where key is a unique string identifier.
Here's what I would do to achieve the desired result:
When the page is loaded, check if we have saved a previous date to localStorage
If saved date found, then load it from localStorage into the DOM
Set up a listener for the button which, saves the current date to localStorage (creating a new entry or overwriting the date that was there previously)
Here's some js flavored pseudo code:
// When site fully loaded, check for saved date and load into dom
window.addEventListener("load", function (event) {
const savedTimestamp = window.localStorage.getItem("savedDate");
// If savedTimestamp is null, then we have no previous saved date
if (savedTimestamp !== null) {
// Tip: we can reuse the date object instead of
// creating a new one every time here
const dateObj = new Date(savedTimestamp);
const todate = dateObj.getDate();
const tomonth = dateObj.getMonth() + 1;
const toyear = dateObj.getFullYear();
const savedDate = tomonth + "/" + todate + "/" + toyear;
// Show the saved date, just an example
// Put your code for showing the date here
showSavedDate(savedDate);
}
})
// ... rest of your code
function addTransaction(e) {
// ... omitting for brevity
let saveDate = original_date;
// ...
transactions.push(transaction);
addTransactionDOM(transaction);
// Save the current timestamp to local storage
window.localStorage.setItem("savedDate", saveDate);
}
// ... and so on
Make sure that saveDate is a string when you're saving it to localStorage, otherwise javascript will convert that to a string on its own and possibly screw things up.

Google Sheets Calendar

I would like some help in pulling certain data from a google form linked to a spreadsheet and set a certain value in the date of a certain employee. For example if he/she marked as Vacation Leave then the letter V will be marked under the Date. I have attached the link to my calendar to give an example, I have tried searching the net and this is my second time posting here.
I started the Code but I am stuck in actually finding the Cell for a certain date and inserting the letter.
https://docs.google.com/spreadsheets/d/1uFTR2_B7T0QBr7fTflByFffmmiszbNj_RaCvLEfYRCA/edit?usp=sharing
function setData(){
//Spreadsheets
var ss = SpreadsheetApp;
var data = ss.getActiveSpreadsheet().getSheetByName("Data");
var calendar = ss.getActiveSpreadsheet().getSheetByName("Calendar");
//Get last row / Individual Cells from Form
var lRow = data.getLastRow();
var lRowData = data.getRange(lRow,1,1,17).getValues();
var approval = data.getRange(lRow,17,1,1).getValue();
var leave = data.getRange(lRow,9,1,1).getValue();
var agentName = data.getRange(lRow, 5,1,1).getValue();
var dateBefore = data.getRange(lRow, 10,1,1).getValue();
var dateAfter = data.getRange(lRow, 11,1,1).getValue();
//Calander Variable Arrays
var allDates = calendar.getRange("LA1:NJ1").getValues();
var allNames = calendar.getRange("A4:A160").getValues();
for(var i = 0; i<allNames.length; i++){
if (approval === "Approved" && allNames[i][0] === agentName){
//Here I need it to insert the dates under the correct name and date with a value of V H S M U T.
};
};
};
You are building a spreadsheet-based Leave Calendar based on information from a form response. Based on your existing Calendar, you are having problems identifying the relevant leave dates, and then filling calendar cells to indicate proposed leave.
The problem is there are no fields in rows 1,2 or 3 of Calendar that have the same date format as the Start Date and End Date fields on Form. As a result, there's no easy way to search for a match of the form data fields.
The solution, in my view, is to change the format of the date fields in rows 2 and 3 and enable a search to be match.
Row 2
the existing format is "d" - day of the month (Numeric)
change the format to match the Form Start/End dates: "d-MMM-yyyy".
the font colour for this field can be used to "hide" these dates, and the column width reduced also.
Row 3
the existing format is "E" - day of the week (Name)
change the format to combine the existing formats of rows #2 and #3 - "E-d"
Aspects of the script
the form data is retrieved as getDisplayValues(). The purpose of this is to get the date as a string to facilitate the search.
Two sets of Calendar data are obtained
1) the dates row (Row#2)
2) the names column (Col #1). The Javascript map method is used to convert names from a 2D array to a 1D array. This creates an array that can be easily searched.
the Javascript indexOf method is used to find the Column match for the start and end dates, and to match the name in the Calendar Column (which yields the Row)
the script loops through the number of days leave to create a temporary array of "V" values.
using the row number and the start and end column numbers, a range can be defined on calendar and then updated from the values in the temporary array.
Presumably your function would be triggered by onFormSubmit(e).
Form data
Calendar - Before
Calendar - After
function so5871726503(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var form = ss.getSheetByName("Form");
var calendar = ss.getSheetByName("Calander");
//get form data
var formdataRange = form.getRange(6,1,1,9);// test data
var formData = formdataRange.getDisplayValues(); // display values to format date as string
//get the employee name, start date and end date
var formName = formData[0][1];
var formSD = formData[0][3];
var formED = formData[0][4];
// Logger.log("DEBUG: name = "+formName+", start date = "+formSD+", end date = "+formED);
//get Calendar variables
var calLR = calendar.getLastRow();
var calLC = calendar.getLastColumn();
var caldateStart = 9;
var calnameStart=4;
// get Calendar dates
var calDateRange = calendar.getRange(2,caldateStart,1,calLC-caldateStart+1);
var calDateValues = calDateRange.getDisplayValues();
// get Calendar names
var calNameRange = calendar.getRange(calnameStart,1,calLR-calnameStart+1);
var calNameValues = calNameRange.getValues();
var calNames = calNameValues.map(function(e){return e[0];});//[[e],[e],[e]]=>[e,e,e]
// there should be some error checking on indexof results = -1 in case there is a mismatch.
// find form start date in calender
var startdateresult = calDateValues[0].indexOf(formSD);
var startdateresultcol = startdateresult+caldateStart;
// Logger.log("DEBUG: start date result = "+startdateresult+", column = "+startdateresultcol);
// find form end date in calender
var enddateresult = calDateValues[0].indexOf(formED);
var enddateresultcol = enddateresult+caldateStart;
// Logger.log("DEBUG: end date result = "+enddateresult+", column = "+enddateresultcol);
// find form name in calender
var nameresult = calNames.indexOf(formName);
var nameresultrow = nameresult+calnameStart;
// Logger.log("DEBUG: name result = "+nameresult+", row = "+nameresultrow)
// calculate number of days leave
var daysleave = enddateresultcol-startdateresultcol+1
// Logger.log("DEBUG: days leave = "+daysleave)
// create array variable to hold leave data
var leave=[];
// loop to create data to fill Calendar
for (i=0;i<daysleave;i++){
leave.push("V");
}
// Logger.log(leave); // DEBUG
// build leave range
var calLeave = calendar.getRange(nameresultrow,startdateresultcol,1,daysleave);
//Logger.log(calLeave.getA1Notation()); //DEBUG
// Update the leave range
calLeave.setValues([leave]);
}

count how many data in array and increment javascript

I'm new in stackoverflow:
Here is my issue, i would like to count how many tickets by month a user has and push it in my array,
i did that:
for(j=0; j< data.data.tickets.length ;j++){
var requesterid = data.data.tickets[j].requester_id;
var created_at = data.data.tickets[j].created_at;
var today = new Date().toISOString().slice(0, 7);
if(created_at.includes(today)&& requesterid == cleartab[requesterid]['id']){total ++}
var arrayRef2 = cleartab[requesterid]['monthly'] || [];
cleartab[requesterid]['monthly'] = arrayRef2.concat([{"janvier":total}], [{"fevier":"fef"}]);
}
The problem is that it gave me wrong result.
Here is my array:
My array
If my question is not clear, i can re-explain or tell me if you need something more to answer it
I hope you can help me
My issue:
Some people should not have ticket the result is not the good one. I would like to be sure that it increment only one people when 1 ticket has been sent in the current month. For now, when someone send a ticket in the current month, every user got +1 ticket in the current month. But what i want is that: it increment only for one user, the user who sent the ticket. Is that clear ?
Based on my understanding of the problem, you could try as below:
for(j=0; j< data.data.tickets.length ;j++){
var requesterid = data.data.tickets[j].requester_id;
var created_at = data.data.tickets[j].created_at;
var today = new Date().toISOString().slice(0, 7);
// read the monthly for a given requestor or
// initialize the new array by setting the total
// to 0 "janvier:0
var arrayRef2 = cleartab[requesterid]['monthly'] ||
[{"janvier":0}, {"fevier":"fef"}];
if(created_at.includes(today) &&
requesterid == cleartab[requesterid]['id']){
// increment the total, very first time the value of
// arrayRef2[0].janvier will be zero, but in
// next iteration it will be always the previous value
arrayRef2[0].janvier++;
}
cleartab[requesterid]['monthly'] = arrayRef2;
}

Limit RSS Feed displayed by ZrssFeed by time

I'm using ZrssFeed to display an rss feed. I would like to limit it to only posts from the last 8 hours.
I tried adding the following block of code after ZRSS returns the feed:
// Add feeds
for (var i=0; i<feeds.entries.length; i++) {
// Get individual feed
var entry = feeds.entries[i];
feedcount = i;
// Format published date
var entryDate = new Date(entry.publishedDate);
var pubDate = entryDate.toLocaleDateString() + ' ' + entryDate.toLocaleTimeString();
var msPerDay = 8*60*60*1000; // 8 hours
var msPubDateTime = new Date(pubdate); // item date in ms
if (msNow.getTime() - entryDate.getTime() < msPerDay) //compare
{
// rest of plugin
This both doesn't work and seems to break the plugin altogether.
You may want to look at the jsDate script. It's great at handling all date-related JS issues.
http://www.datejs.com/

Categories