For reference the full code (please ignore my attempts for scheduling)
var config = require("./config.js");
var Twit = require('twit');
var TT = new Twit(config);
///dt.setDate(25);
//console.log(dt)
var d = new Date();
const d1 = new Date('December 12, 2020 00:00:00');
const d2 = new Date('December 12, 2020 00:00:00');
const d3 = new Date('December 12, 2020 00:00:00');
//const dt = new Date('December 24, 2020 00:00:00');
d1.setDate(25);
d2.setDate(26);
d3.setDate(27);
tweetIt();
setInterval(tweetIt, 86400000)
function tweetIt(){
var calc = d1.getDate() - d.getDate();
if (d < d1.getDate()) {
var tweet = calc + " days left until Christmas! Ho Ho Ho!"
}
else if(d == d1.getDate() && d < d2.getDate()) {
var tweet = "Today is Christmas! Ho Ho Ho! "
}
else if(d == d2.getDate() && d < d3.getDate()){
var tweet = "Today is Christmas! Ho Ho Ho! "
}
else { console.log(tweet);}
TT.post('statuses/update', {status: tweet}, tweeted);
function tweeted(err, data, response) {
if (err) {
console.log(err);
} else {
console.log('Success: ' + data.text);
//console.log(response);
}
};
}
I tried different ways of getting the Twitter status to actually send something. One of the things I tried doing was to set var tweet = { status: "Hello!"} or just var tweet = "Hello 2 " (as it is in the code). Also when I do console.log(tweet) it shows undefined and I can't figure out why it isn't reading any of the declared parameters.
Also for another reference - the code before this one (currently the one running on my server, and works perfectly fine) / code 2
var config = require("./config.js");
var Twit = require('twit');
var T = new Twit(config);
tweetIt();
setInterval(tweetIt, 86400000)
function tweetIt(){
var d = new Date();
var calc = 25 - d.getDate();
var tweet = calc + " days left until Christmas! Ho Ho Ho! ❄⛄🎄";
T.post('statuses/update', { status: tweet }, tweeted);
function tweeted(err, data, response) {
if (err) {
console.log(err);
} else {
console.log('Success: ' + data.text);
//console.log(response);
}
};
}
I can't understand why code 1 doesn't work, because I used code 2 as a template for code 1. Help is highly appreciated!
Edit: Please, keep in mind that I'm a beginner!
Related
I have been working on a personal project of user check In/Out time recorder. I created the multi user login and time recorder using JS. I faced an issue to record the time of each logged in user. The code I created is only able to record the time of single user. I used localStorage command to store time because it need to be displayed every users time data on admin page. I am using single JS file for login, user page recorder and also for admin page loader. Plz help me out if anyone has any solution. I can't use server based code right now. I only have to write this web-app code in html,css and javascript.
var users= [
{user : 'user1', pass: 'pass1'},
{user : 'user2', pass: 'pass2'},
{user : 'user3', pass: 'pass3'},
{user : 'admin', pass: 'admin'}
];
function login()
{
//login page
var username = document.getElementById('uname').value;
var password = document.getElementById('psw').value;
for (var i = 0; i < users.length; i++)
{
console.log('enter the loop');
console.log("current user: ", i+1);
if (username == users[i].user && password == users[i].pass)
{
window.location.href = 'user.html';
alert("Login Successful");
break;
}
else if (i == (users.length-1))
{
alert('Login failed! Try Again');
console.log(i,'-times wrong');
}
else if (username == users[3].user && password == users[3].pass)
{
console.log('admin login');
window.location.href = 'admin.html';
break;
}
else
{
console.log('else statement');
}
}
var userId = i;
console.log("current user: ", userId);
}
//Date & Time Display
setInterval(myTimer,1000);
function myTimer()
{
const d = new Date();
document.getElementById('date').innerHTML = d.toLocaleDateString();
document.getElementById('time').innerHTML = d.toLocaleTimeString();
}
let date = document.getElementById('date');
let time = document.getElementById('time');
let newDate = new Date();
let year = newDate.getFullYear();
let month = newDate.getMonth();
let todaysDate = newDate.getDate();
let hours = newDate.getHours();
let minutes = newDate.getMinutes();
let seconds = newDate.getSeconds();
var cal = {
data : null,
sMth : 0,
sYear : 0,
init : () => {
let newDate = new Date();
cal.sDay = newDate.getDate();
cal.sMth = newDate.getMonth();
cal.hour = newDate.getHours();
cal.minutes = newDate.getMinutes();
cal.date = document.getElementById('date');
cal.data = localStorage.getItem("cal-" + cal.sDay + "-" + cal.sMth);
if (cal.data == null)
{
localStorage.setItem("cal-" + cal.sDay + "-" + cal.sMth, "{}");
cal.data = {};
console.log("cal.data: null-",cal.data);
}
else
{
cal.data = JSON.parse(cal.data);
console.log("cal.data: JSON-",cal.data);
}
},
checkIn : () => {
cal.data[cal.sDay] = cal.hour + ":" + cal.minutes;
localStorage.setItem('cal-${cal.sDay}-${cal.sMth}',JSON.stringify(cal.data));
console.log('Time:', cal.data);
}
}
window.onload = cal.init;
Reference to the previous question to Filter Gmail body and paste in Spreadsheet
I had created below a google app script and set a trigger for after every 5 minutes:
function GetEmailsData(){
// SKIP TO OUT OF OFFICE HOURS AND DAYS
var nowH=new Date().getHours();
var nowD=new Date().getDay();
if (nowH>19||nowH<8||nowD==0) { return }
// START OPERATION
var Gmail = GmailApp;
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var MasterSheet = ss.getSheetByName("Master");
var index = 2;
var aa = 0; // count already update entries
var na = 0; // count not update entries
var lasttime = MasterSheet.getRange("Z1").getValue(); // in spreadsheet i record the last time of email scanned, so next trigger will search after that
Logger.log(lasttime);
var cdate = new Date();
var ctime = cdate.getTime();
var qDate = MasterSheet.getRange("Z1").getValue();
Logger.log("QDATE IS " + qDate);
//problem # 1: from filter is not working.
// SEARCH EMAIL
var query = 'from: email id, subject: email subject, after:' + Math.floor((qDate.getTime()) /1000);
var threadsNew = Gmail.search(query);
Logger.log(threadsNew.length);
//loop all emails
for(var n in threadsNew){
var thdNew = threadsNew[n];
var msgsNew = thdNew.getMessages();
var msgNew = msgsNew[msgsNew.length-1];
// GET ATTACHMENT
//var bodyNew = msgNew.getBody();
var plainbody = msgNew.getPlainBody();
var subject = msgNew.getSubject();
var Etime = msgNew.getDate();
//var attachments = msgNew.getAttachments();
//var attachment = attachments[0];
Logger.log(Etime);
Logger.log(subject);
//Logger.log(plainbody);
var tdata = plainbody.trim();
var data = parseEmail001(tdata);
//Logger.log(data);
// First Check Email Date
var newdate = new Date();
var dd = newdate.getDate();
var mm = newdate.getMonth() + 1;
var yyyy = newdate.getFullYear();
var cd = dd + "-" + mm + "-" + yyyy
//Logger.log(new Date());
//Logger.log(cd);
if (Etime.getDate() != dd) {return}
// first check current sheet exist or not
// DATE DECLARATION IS ABOVE
var itt = ss.getSheetByName(cd);
if (!itt) {
ss.insertSheet(cd);
var itt = ss.getSheetByName(cd);
var ms = ss.getSheetByName("Master");
var hlc = ms.getLastColumn();
var headings = ms.getRange(1,1,1,hlc).getValues();
itt.getRange(1,1,1,hlc).setValues(headings);
}
var MasterSheet = ss.getSheetByName(cd);
var mlr = MasterSheet.getLastRow();
var mlc = MasterSheet.getLastColumn();
//check data already updated or not
var NewDepositSlipNumber = Number(data[2]).toFixed(0);
//Logger.log(Number(data[2]).toFixed(0));
var olddata = MasterSheet.getDataRange().getValues();
//Logger.log(olddata[1][2]);
for(var i = 0; i<olddata.length;i++){
if(olddata[i][2] == NewDepositSlipNumber){
//Logger.log(i + 1);
var status = 'Already Update'
Logger.log(status);
break;
}
else{
var status = 'Not Update'
//Logger.log(status);
}
}
// count how many updated and how many not.
if(status == 'Not Update'){
na = na + 1;
}
else{
aa = aa + 1;
}
if(status == 'Not Update'){
MasterSheet.appendRow(data);
Logger.log("Data Updated");
}
}
//problem # 2: if conversation length are long, it is not reaching there
var lastscantime = threadsNew[0].getLastMessageDate();
var master = ss.getSheetByName("Master");
master.getRange("Z1").setValue(lastscantime);
Logger.log(lastscantime);
master.getRange("Z2").setValue(new Date());
Logger.log(new Date());
Logger.log("Total " + threadsNew.length + " found, out of which " + aa + " are already updated, while " + na + " are updated.");
}
function parseEmail001(message) {
var replaces = [
'Branch Code',
'Branch Name',
'Slip No',
'BL Number',
'Type Of Payment',
'Customer Name',
'Payer Bank',
'Payer Bank Branch',
'Transaction Type',
'Amount',
'Posting Date',
'Value Date'
];
return message.split('\n').slice(0, replaces.length)
.map((c,i) => c.replace(replaces[i], '').trim());
}
This script is working fine but I have two problems:
I placed three filters in query 1) from 2) subject 3) after
but sometimes it gives me emails that are from the same ID but different subject.
as per my observation, and I verified it by using debug mode if the conversation length is long I guess more than 30 it will not reach the end part of the script. it skipping my last step as I also marked it in the above script. and if conversation length is less it works smoothly.
explanation: in other words, from morning to evening it's working fine after every five minutes, but the next day it gets the problem, then I manually update my spreadsheet master sheet Z1 value as of today's date and time, then it works fine till tonight.
You might be reaching a script limitation. Possibly the custom function runtime.But it can be any, you should see an error if it didn't finish.
I have a website with multiple pages (http://www.europarl.europa.eu/sides/getDoc.do?type=PV&reference=20190131&secondRef=TOC&language=EN)
I crawled each page and got links with minutes in it. Each link with minutes has a date, after I created folders with Years and Months, I stuck with a store files from links.
The question is:
How can I download links in a month directory?
function crawlLink(link){
link = 'http://www.europarl.europa.eu'+link;
request(link, (error,response,
html) => {
if (!error && response.statusCode == 200) {
const $ = cheerio.load(html);
const docTitle = $('.doc_title' ) ;
var str = docTitle.html();
var date_str = str.replace(' - Brussels','').replace(' - Strasbourg', '');
var date = new Date(date_str);
console.log("created new dateobj", date);
var year = new Array('January','February', 'March' , 'April' , 'May' , 'June', 'July' ,'August','September','Oktober','November','December');
var mm = date.getMonth(); //January is 0
var yyyy = date.getFullYear();
var monthName = year[mm];
var yearDir = './data/'+yyyy;
if (!fs.existsSync(yearDir)){
fs.mkdirSync(yearDir);
}else{
console.log('yearDir exists');
}
var monthDir = yearDir+'/'+monthName;
if (!fs.existsSync(monthDir)){
fs.mkdirSync(monthDir);
}else{
console.log('monthDir exists');
}
console.log("wouhu everything is fine, get links and download them to monthDir");
let downloadLinks = [];
let $links = $('.doc_formats_box a');
$links.each(function(i, elem) {
downloadLinks.push({
title:$(this).text(),
link:$(this).attr('href')
});
});
console.log(downloadLinks);
`
I want to know if there's the possibiliy to know when an event in google calendar is created, I just have found how to create an event and take its info to create another I want to send the info of the event to a spreadsheed or any document
I just got this..
function createEvent() {
var calendarId = 'primary';
var eventSeries = CalendarApp.getDefaultCalendar().createEventSeries('Evento de prueba',
new Date('December 20 2014 10:00:00 AM -6'),
new Date('December 20 2014 10:30:00 AM -6'),
CalendarApp.newRecurrence().addWeeklyRule().
onlyOnWeekdays([CalendarApp.Weekday.SATURDAY]),
{ location: 'Tacos'});
Logger.log('EventSeriesID: ' + eventSeries.getId());
if (eventSeries.getTitle() == 'Evento de prueba'){
var calendarId2 = 'primary';
var event = CalendarApp.createEvent(eventSeries.getTitle(), eventSeries.getDateCreated(), new Date(eventSeries.getDateCreated() + 2),
{location : eventSeries.getLocation()});
}
}
I am not sure if you want this way or other way, but you can try for the following code.
function createEvent() {
try{
var calendarId = 'primary';
var eventSeries = CalendarApp.getDefaultCalendar().createEventSeries('My Events',
new Date('December 20 2014 12:00:00 PM'),
new Date('December 20 2014 03:30:00 PM'),
CalendarApp.newRecurrence().addWeeklyRule().onlyOnWeekdays([CalendarApp.Weekday.SATURDAY]),
{ location: 'Tacos'});
Logger.log('EventSeriesID: ' + eventSeries.getId());
if (eventSeries.getTitle() == 'My Events'){
var calendarId2 = 'primary';
var event = CalendarApp.createEvent(eventSeries.getTitle(), eventSeries.getDateCreated(), new Date(eventSeries.getDateCreated() + 2),
{location : eventSeries.getLocation()});
var ss_id = logEventData(event);
Logger.log(ss_id);
sendMail(ss_id);
}
}catch(error){
Logger.log(error.message);
}
}
function logEventData(event) {
var ss = SpreadsheetApp.create('calender-events-logs');
var eventDetails = [];
eventDetails.push(event.getTitle());
eventDetails.push(event.getDescription());
eventDetails.push(event.getCreators()[0]);
//You can get number of other details here if you want to.
ss.appendRow(eventDetails);
return ss.getId();
}
function sendMail(ss_id) {
var emailTo = 'Put your email id here';
var subject = 'Test';
var body = 'Test';
var pdf = DocsList.getFileById(ss_id).getAs('application/pdf').getBytes();
var attachment = {fileName:'CalendarEventLogs.pdf',content:pdf, mimeType:'application/pdf'};
// Send the freshly constructed email
MailApp.sendEmail(emailTo, subject, body, {attachments:[attachment]});
//MailApp.sendEmail(recipient, subject, body);
// Delete the dummy spreadsheet
deleteDummySheet(ss_id);
}
function deleteDummySheet(ss_id) {
DocsList.getFileById(ss_id).setTrashed(true);
}
I tried create markers by JSON parse from C #.I have a small problem about datetime compare in javascript.
var nowDate= new Date();
var LastTenMin= new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(),nowDate.getHours(),nowDate.getMinutes()- 10);
var Time1= data2.LastRecordTime;
var image2;
var status;
if (new Date(Time1) < new Date(LastTenMin)) {
image2 = '/Images/truckOnline.png';
status = "Truck is online."+"\n"+"Last seen:"+" "+Time1,
}
else {
image2 = '/Images/truckOffline.png';
status = "Truck is offline"+"\n"+"Last seen:"+" "+Time1,
}
else is not working ! There are truckOnline markers on google map.Where is my mistake ?
And LastRecordTime format like this in SQL : 04.12.2013 01:03:00
LastRecordTime=CONVERT(VARCHAR(10), [ReadTimeColumn], 104) + ' ' + CONVERT(VARCHAR(8), [ReadTimeColumn],108)
Mehmet,
Looks like you made a typo:
var LastTenMin= new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(),nowDate.getHours(),nowDate.getMinutes(),- 10);
Should be (note the comma):
var LastTenMin= new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(),nowDate.getHours(),nowDate.getMinutes() - 10);
Also you were trying to create a new date object from a date object, this is incorrect:
new Date(LastTenMin)
And here is a more complete solution:
var nowDate= new Date();
var Time1 = new Date("04/12/2013 01:03:00");
var LastTenMin= new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(), nowDate.getHours(), nowDate.getMinutes() - 10);
// Should return true
console.log(Time1 < LastTenMin);
// Change the year to a point in the future
Time1 = new Date("04/12/2014 01:03:00");
// Shold return false
console.log(Time1 < LastTenMin);
// So your original conditional should look like this:
if (Time1 < LastTenMin) {
image2 = '/Images/truckOnline.png';
status = "Truck is online."+"\n"+"Last seen:"+" "+Time1;
} else {
image2 = '/Images/truckOffline.png';
status = "Truck is offline"+"\n"+"Last seen:"+" "+Time1;
}
// And a more concise form:
var isOnline = !(Time1 < LastTenMin);
var image2 = isOnline ? '/Images/truckOnline.png' : '/Images/truckOffline.png';
var status = "Truck is " + (isOnline ? "Online" : "Offline") + "." + "\n" + "Last seen:" + " " + Time1
Here is the solution without comments:
var nowDate= new Date();
var Time1 = new Date(data2.LastRecordTime);
var LastTenMin= new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(), nowDate.getHours(), nowDate.getMinutes() - 10);
var isOnline = !(Time1 < LastTenMin);
var image2 = isOnline ? '/Images/truckOnline.png' : '/Images/truckOffline.png';
var status = "Truck is " + (isOnline ? "Online" : "Offline") + "." + "\n" + "Last seen:" + " " + Time1
My whole solution is assuming that the string contained in data2.LastRecordTime is in the format: "MM.DD.YYYY HH:MM:SS".
This is going to sound like a cop out, but I would switch to MomentJS so you get the following code:
var Time1 = moment("04/12/2013 01:03:00");
var lastTenMin = moment().subtract({minutes: 10});
if(Time1.isBefore(lastTenMin)){
image2 = '/Images/truckOnline.png';
status = "Truck is online."+"\n"+"Last seen:"+" "+Time1.local();
} else {
image2 = '/Images/truckOffline.png';
status = "Truck is offline"+"\n"+"Last seen:"+" "+Time1.local();
}
Remember, JavaScript has random off-by-one issues for the date and month (one is zero-based, the other is one-based). The problem most likely is in this line:
var LastTenMin= new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(),nowDate.getHours(),nowDate.getMinutes()- 10);
If you switch to MomentJS, these kind of problems will disappear. I have lost many hours fighting these same issues, so I understand!
P.S. Try out the calendar() formatting feature... it may be a good fit in your UI.
To compare dates with time in Javascript we need to pass them in Date object as "yyyy/mm/dd HH:mm" format for e.g. like "2014/05/19 23:20" . Then you can just compare them with > or < less then symbol according to your business rule. Please see given below code for more understanding.
$(function () {
$("input#Submit").click(function () {
var startDateTime = $("input[name='StartDateTime']").val();
var endDateTime = $("input[name='EndDateTime']").val();
var splitStartDate = startDateTime.split(' ');
var splitEndDate = endDateTime.split(' ');
var startDateArray = splitStartDate[0].split('/');
var endDateArray = splitEndDate[0].split('/');
var startDateTime = new Date(startDateArray[2] + '/ ' + startDateArray[1] + '/' + startDateArray[0] + ' ' + splitStartDate[1]);
var endDateTime = new Date(endDateArray[2] + '/ ' + endDateArray[1] + '/' + endDateArray[0] + ' ' + splitEndDate[1]);
if (startDateTime > endDateTime) {
$("#Error").text('Start date should be less than end date.');
}
else {
$("#Error").text('Success');
}
});
});
You can also see a working demo here
I solved by SQL.
I set a new colum for difference minute between now and ReadTime.
DifferenceMinute=DATEDIFF(MINUTE,ReadTime,GETDATE())
if(DifferenceMinute>10)
{
bla bla
}
else
{
bla bla
}