A Guide to Discord Bots

Time-based Events

If you are interested in executing a part of code in x seconds or each x seconds, see Timeouts/Intervals (Timers).
Here, we will talk about events happening at a specific date or time, and we will use the Moment package.
Install with: npm i moment.
With timezones support: npm i moment-timezone.
Documentation.

The basics

const moment = require('moment');

// Current time
// Example: April 25th, 02:06 PM
console.log('Current date and time: ' + moment().format('MMMM Do') + ', ' 
    + moment().format('hh:mm a');

// Current UTC time
// Example: April 25th, 12:06 AM
console.log('Current date and time (UTC): ' + moment().utc().format('MMMM Do') + ', '
    + moment().utc().format('hh:mm a');

// Tomorrow
// Example: April 26 2018
console.log('Tomorrow is: ' + moment().add(1, 'day').format('MMMM D YYYY');

// Yesterday
// Example: April 24 2018
console.log('Tomorrow is: ' + moment().substract(1, 'day').format('MMMM D YYYY');

// And much more

Date and time formatting.

Storing time objects

const moment = require('moment');

// seconds, minutes, hours, day, month, year
// .format() turns the time object into a string
var savedTime = moment.utc().format('ssmmHHDDMMYYYY');
fs.writeFileSync('file.txt', savedTime);

// First argument: the date to parse (a string)
// Second argument: the format it uses
var restoredTime = moment.utc(fs.readFileSync('file.txt'), 'ssmmHHDDMMYYYY');

Time differences

const moment = require('moment');

// For example, you can c
let diff = moment.utc().add(10, 'minutes').diff(moment.utc(), 'seconds');
console.log(diff); // 600 (seconds, = 10 minutes)


// Don't put this in the loop, or it will be endless
timeout = moment.utc().add(2, 'minutes');

var loop = setInterval(() => {
    let diff = timeout.diff(moment.utc(), 'seconds');
    console.log(diff);

    if (diff <= 0) {
        clearInterval(loop);
        console.log('2 minutes have elapsed');
    }
}, 1000);

results matching ""

    No results matching ""