diff --git a/.eslintrc.json b/.eslintrc.json index d7fd563..64963a2 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -1,18 +1,24 @@ { - "env": { - "es6": true, - "node": true - }, - "extends": "google", - "rules": { - "require-jsdoc": ["error", { - "require": { - "FunctionDeclaration": false, - "MethodDefinition": false, - "ClassDeclaration": false - } - }], - "max-len": ["error", 100], - "error": 0 - } + "env": { + "es6": true, + "node": true + }, + "extends": "airbnb", + "plugins": [ + "react", + "jsx-a11y", + "import" + ], + "rules": { + "comma-dangle": [ + "error", + { + "arrays": "ignore", + "objects": "ignore", + "imports": "ignore", + "exports": "ignore", + "functions": "ignore" + } + ] + } } \ No newline at end of file diff --git a/README.md b/README.md index de346d2..ef7881e 100644 --- a/README.md +++ b/README.md @@ -1,74 +1,81 @@ # Wengy-ven -BOT de Bienvenida a nuevos integrantes del grupo [ngVenezuela OFF-TOPIC](https://telegram.me/ngvenezuela) -en Telegram. +> BOT de Bienvenida a nuevos integrantes del grupo [ngVenezuela](https://t.me/ngvenezuela) +en Telegram. Desarrollado con NodeJS y el API de Telegram. -## Comenzando +## Prerequisitos -Clonamos el proyecto con el comando: `git clone git@github.com:ngVenezuela/wengy-ven.git` +Antes de comenzar a trabajar con nuestro BOT, es necesario cumplir con los siguientes requisitos: -### Prerequisitos +- [Node v6.0 o superior](https://nodejs.org/en/) -Para poder tener un bot, es necesario crearlo, y obtener un token para el mismo, las -instrucciones las puedes consultar aquí: [¿Cómo creo un bot?](https://core.telegram.org/bots#3-how-do-i-create-a-bot). -Este bot nos va a servir para hacer nuestros desarrollos y/o pruebas. + Esta versión es necesaria debido a la compatibilidad de ES6, la cual no tiene gran soporte en [versiones anteriores](http://node.green/). -Luego de creado el bot, lo agregamos a un grupo: -[Agregar bot a un grupo](images/add-bot-to-group.jpg) -Y ya automáticamente quedará escuchando cualquier comando +- [Crear un BOT el Telegram](https://core.telegram.org/bots#3-how-do-i-create-a-bot) -Lo otro que debemos hacer es tener instalado una versión de [NodeJS](https://nodejs.org/en/) mayor a la v6.0, debido -a la compatibilidad de ES6 no tiene un gran soporte en [versiones anteriores](http://node.green/). + Para poder tener un bot, es necesario crearlo y así obtener un **Token** para el mismo. Este bot nos va a hacer posible nuestros desarrollos y/o pruebas. -### Instalando +- [Agregar el BOT a un grupo](https://raw.githubusercontent.com/ngVenezuela/wengy-ven/master/images/add-bot-to-group.jpg) -Instalamos todas las dependencias del proyecto con el comando: `npm install` + Luego de haber creado el BOT, lo agregamos a un grupo para que así escuche cualquier comando. + + +## Installación + +Para comenzar a trabajar en nuestro BOT, abrimos nuestra _terminal_ y ejecutamos los siguientes comandos: + +```bash +# Clonamos el proyecto. +$ git clone git@github.com:ngVenezuela/wengy-ven.git + +# Accedemos al directorio donde se clonó nuestro proyecto. +$ cd wengy-ven + +# Instalamos todas las dependencias del proyecto. +$ npm install +``` Por último creamos un archivo en el directorio `config/` llamado `config.js` con el formato -que tiene el archivo `config.sample.js`. En este nuevo archivo colocaremos nuestros token que -pudimos obtener durante la sección de Prerequisitos. +que tiene el archivo `config.sample.js`. En este nuevo archivo colocaremos el [Token](https://core.telegram.org/bots#3-how-do-i-create-a-bot) que +pudimos obtener previamente. ## Corriendo los tests -Corriendo pruebas: -``` +Para ejecutar los tests (pruebas), simplemente ejecutamos los siguientes comandos: + +```bash $ npm run test # También puedes activar el modo watch $ npm run test:watch - ``` ## Despliegue -Para ejecutar este proyecto, debemos colocarnos sobre el directorio y correr el comando: -`node src/index.js' - -## Construido con +Finalmente, para ejecutar nuestro BOT, nos aseguramos de estar en el directorio de nuestro proyecto y escribimos el siguiente comando en nuestra terminal: -* NodeJS -* API de Telegram +```bash +$ node src/index.js +``` ## Contribuyendo -Por favor lee [CONTRIBUTING.md](.github/CONTRIBUTING.md) para los detalle de nuestro código de conducta, -y el proceso para enviarnos pull requests. +Te invitamos a leer el documento [CONTRIBUTING](.github/CONTRIBUTING.md) para conocer todos los detalle de nuestro código de conducta y el proceso para enviarnos _Pull Requests_. ## Versionado -Utilizamos [SemVer](http://semver.org/) para el versionado. -Para ver las versiones disponibles, mira los [tags en este repositorio](https://github.com/ngVenezuela/wengy-ven/tags). +Utilizamos [SemVer](http://semver.org/) para el versionado. Para ver las versiones disponibles de nuestro BOT, mira los [Tags](https://github.com/ngVenezuela/wengy-ven/tags) en este repositorio. ## Autores * **Andrés Villanueva** - *Trabajo inicial* - [Villanuevand](https://github.com/Villanuevand) * **Leonardo Cabeza** - *Código inicial* - [leocabeza](https://github.com/leocabeza) -Ver también la lista de [contribuyentes](https://github.com/ngVenezuela/wengy-ven/graphs/contributors) que participaron en este proyecto. +Y por acá puedes ver la lista completa de [contribuyentes](https://github.com/ngVenezuela/wengy-ven/graphs/contributors) que participaron en este proyecto. ## Licencia -Este proyecto está licenciado bajo la licencia MIT - ver el archivo [LICENSE](LICENSE) para más detalles. +Este proyecto está licenciado bajo la [Licencia MIT](https://github.com/ngVenezuela/wengy-ven/blob/master/LICENSE) ## Expresiones de gratitud diff --git a/config/messages.js b/config/messages.js index 1e95fea..f2c796c 100644 --- a/config/messages.js +++ b/config/messages.js @@ -23,6 +23,7 @@ const messages = { 'Buenos días', 'Buenos días a todos', 'Buenos días comunidad', + 'Buenos días comunidad, Y como dice @frick: ¡A trabajar, vagos! Que los yates de sus jefes no se pagan solos' ], }, newBlogPost: '*#{author}* ha agregado una nueva entrada al blog titulada: *#{title}* '+ diff --git a/package.json b/package.json index 0e47e3c..2bc62c0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "wengy-ven", - "version": "1.0.0", + "version": "1.3.0", "description": "Official telegram bot for the ng-Venezuela community", "main": "index.js", "scripts": { @@ -23,14 +23,12 @@ }, "homepage": "https://github.com/ngVenezuela/wengy-ven#readme", "dependencies": { - "feedparser": "2.0.0", + "feedparser": "^2.0.0", "node-fetch": "^1.6.3", - "node-telegram-bot-api": "0.25.0" + "node-telegram-bot-api": "^0.27.1" }, "devDependencies": { - "eslint": "3.13.1", - "eslint-config-google": "0.7.1", "jest": "^19.0.2", - "jsdoc": "3.4.3" + "jsdoc": "^3.4.3" } } diff --git a/src/blog-event.js b/src/events/blog.js similarity index 85% rename from src/blog-event.js rename to src/events/blog.js index e29091c..5e0434b 100644 --- a/src/blog-event.js +++ b/src/events/blog.js @@ -1,21 +1,16 @@ -'use strict'; - const FeedParser = require('feedparser'); +// eslint-disable-next-line import/no-extraneous-dependencies const request = require('request'); const fs = require('fs'); -const config = require('../config/config'); const events = require('events'); +const config = require('./../../config/config'); -let feedparser = new FeedParser(); -let eventEmitter = new events.EventEmitter(); +const feedparser = new FeedParser(); +const eventEmitter = new events.EventEmitter(); let articles = []; let lastPubDate; let req; -setInterval(readLastPubDate, 60000 * 60 * 24); // check daily - -module.exports = eventEmitter; - /** * Check the blog feed for entries */ @@ -51,8 +46,8 @@ function makeRequest() { */ function readLastPubDate() { try { - let data = fs.readFileSync('./config/last-blog-pubDate.json', 'utf8'); - let parsed = JSON.parse(data); + const data = fs.readFileSync('./config/last-blog-pubDate.json', 'utf8'); + const parsed = JSON.parse(data); lastPubDate = new Date(parsed.lastPubDate); makeRequest(); } catch (err) { @@ -69,7 +64,7 @@ function lookupFinished() { try { fs.writeFileSync( './config/last-blog-pubDate.json', - JSON.stringify({'lastPubDate': articles[0].pubDate}), + JSON.stringify({ lastPubDate: articles[0].pubDate }), 'utf8' ); lastPubDate = undefined; @@ -79,18 +74,15 @@ function lookupFinished() { feedparser.emit('error', new Error('Could not save file')); } } -}; +} /** - * we print errors in console. * we capture 'lookupFinished' 'error' and * execute corresponding function. */ feedparser.on('error', (error) => { if (error === 'lookupFinished') { lookupFinished(); - } else { - console.log('error emitted: ', error); } }); @@ -115,8 +107,9 @@ feedparser.on('readable', () => { let item; if (lastPubDate !== undefined) { + // eslint-disable-next-line no-cond-assign while (item = feedparser.read()) { - let itemPubDate = new Date(item.pubDate); + const itemPubDate = new Date(item.pubDate); if (itemPubDate <= lastPubDate) { /** * This is the only way we can get @@ -134,3 +127,8 @@ feedparser.on('readable', () => { } } }); + +setInterval(readLastPubDate, 60000 * 60 * 24); // check daily + +module.exports = eventEmitter; + diff --git a/src/events/morning.js b/src/events/morning.js new file mode 100644 index 0000000..0d3eaf2 --- /dev/null +++ b/src/events/morning.js @@ -0,0 +1,29 @@ +const events = require('events'); +const timeUtility = require('./../utils/time'); + +const eventEmitter = new events.EventEmitter(); + +/** + * this function emits an event + * with the current hour/minute & + * it also emits an event when it's + * a new day + */ +function emitMinuteMark() { + const vzlanHour = timeUtility.vzlanHour(); + const vzlanMinute = timeUtility.vzlanMinute(); + + eventEmitter.emit( + 'minuteMark', + vzlanHour, + vzlanMinute, + timeUtility.vzlanWeekday() + ); + if (vzlanHour === 0 && vzlanMinute === 0) { + eventEmitter.emit('newDay'); + } +} + +setInterval(emitMinuteMark, 60 * 1000); // 60 seconds + +module.exports = eventEmitter; diff --git a/src/index.js b/src/index.js index 84e6770..d01e099 100644 --- a/src/index.js +++ b/src/index.js @@ -1,146 +1,37 @@ -'use strict'; - const TelegramBot = require('node-telegram-bot-api'); -const config = require('../config/config'); -const messages = require('../config/messages'); -const morningEvent = require('./morning-event'); -const blogEvent = require('./blog-event'); -const generateRandom = require('./time-utility').generateRandom; -const fetch = require('node-fetch'); - -const token = config.telegramToken; -const groupId = config.groupId; -const goodMorningRegExp = config.goodMorningRegExp; - -let bot = new TelegramBot(token, {polling: true}); +const telegramToken = require('./../config/config').telegramToken; +const morningEvent = require('./events/morning'); +const blogEvent = require('./events/blog'); +const chatUtility = require('./utils/chat'); +const blogUtility = require('./utils/blog'); +const morningUtility = require('./utils/morning'); +const generateRandom = require('./utils/time').generateRandom; + +const bot = new TelegramBot(telegramToken, { polling: true }); let goodMorningGivenToday = false; let minuteToCheck = generateRandom(0, 59); bot - .on('new_chat_participant', sayHello) - .on('left_chat_participant', sayGoodbye) - .on('text', newText); + .on('new_chat_participant', msg => chatUtility.sayHello(bot, msg)) + .on('left_chat_participant', msg => chatUtility.sayGoodbye(bot, msg)) + .on('text', (msg) => { + goodMorningGivenToday = + chatUtility.checkGoodMorning(goodMorningGivenToday, msg.text); + }) + .on('text', msg => chatUtility.checkForCode(bot, msg)); morningEvent .on('minuteMark', (vzlanHour, vzlanMinute, weekday) => { - if (morningConditions(vzlanHour, vzlanMinute)) { - goodMorningGivenToday = true; - minuteToCheck = generateRandom(0, 59); - bot.sendMessage( - groupId, - getMorningMsg(weekday) - ); - } - - function morningConditions(vzlanHour, vzlanMinute) { - return !goodMorningGivenToday && vzlanHour === config.morningHour - && vzlanMinute === minuteToCheck; - } + const executeGoodMorningCheck = + morningUtility.giveGoodMorning(bot, goodMorningGivenToday, minuteToCheck, + vzlanHour, vzlanMinute, weekday); - function getMorningMsg(weekday) { - let weekDays = { - 0: 'generic', - 1: 'mondays', - 2: 'generic', - 3: 'generic', - 4: 'generic', - 5: 'fridays', - 6: 'generic', - }; - - let randomIndex = generateRandom(0, messages.goodMornings[weekDays[weekday]].length - 1); - return messages.goodMornings[weekDays[weekday]][randomIndex]; - } + goodMorningGivenToday = executeGoodMorningCheck.goodMorningGivenToday; + minuteToCheck = executeGoodMorningCheck.minuteToCheck; }) .on('newDay', () => { goodMorningGivenToday = false; }); blogEvent - .on('newArticles', (articles) => { - articles.forEach((article) => { - bot.sendMessage( - groupId, - messages.newBlogPost - .replace('#{author}', article.author) - .replace('#{link}', article.link) - .replace('#{title}', article.title), - {parse_mode: 'Markdown'} - ); - }); - }); - -function formatName(msgContext) { - return msgContext.username ? - '@' + msgContext.username : msgContext.first_name; -} - -function newText(msg) { - if (!goodMorningGivenToday && isGoodMorningGiven(msg.text)) { - goodMorningGivenToday = true; - } - - function isGoodMorningGiven(text) { - return goodMorningRegExp.test(text); - } -} - -function sayHello(msg) { - bot.sendMessage( - msg.chat.id, - messages.welcomeMsg.replace('#{name}', formatName(msg.new_chat_member)), - {reply_to_message_id: msg.message_id, parse_mode: 'Markdown'} - ); -} - -function sayGoodbye(msg) { - bot.sendMessage( - msg.chat.id, - messages.goodbyeMsg.replace('#{name}', formatName(msg.left_chat_member)), - {reply_to_message_id: msg.message_id, parse_mode: 'Markdown'} - ); -} - -bot.on('text', (msg) => { - if ( !msg.hasOwnProperty('entities') ) { - return; - } - - if ( msg.entities[0].type !== 'pre' ) { - return; - }; - - if ( msg.text.length >= 200 ) { - return; - } - - const chatId = msg.chat.id; - const {firstName = '', lastName = '', username = ''} = msg.from; - const fullName = firstName === '' && lastName === '' ? '' : `${firstName} ${lastName} `; - const user = username === '' ? '' : `(@${username})`; - const filename = `${new Date().toISOString()}.js`; - const gist = msg.text; - - const body = { - 'description': 'gist creado por ' + fullName + user + - ' para https://t.me/ngvenezuela con https://github.com/ngVenezuela/wengy-ven', - 'public': true, - 'files': { - [filename]: { - 'content': gist, - }, - }, - }; - - fetch('https://api.github.com/gists', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify( body ), - }) - .then((response) => response.json()) - .then(({html_url}) => { - bot.sendMessage(chatId, html_url); - }).catch(() => {}); -}); + .on('newArticles', articles => blogUtility.sendNewArticles(bot, articles)); diff --git a/src/morning-event.js b/src/morning-event.js deleted file mode 100644 index a85ad33..0000000 --- a/src/morning-event.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -const events = require('events'); -const timeUtility = require('./time-utility.js'); -let eventEmitter = new events.EventEmitter(); - -setInterval(emitMinuteMark, 60000); // 60 seconds - -module.exports = eventEmitter; - -/** - * this function emits an event - * with the current hour/minute & - * it also emits an event when it's - * a new day - */ -function emitMinuteMark() { - let vzlanHour = timeUtility.vzlanHour(); - let vzlanMinute = timeUtility.vzlanMinute(); - - eventEmitter.emit('minuteMark', vzlanHour, vzlanMinute, timeUtility.vzlanWeekday()); - if (vzlanHour === 0 && vzlanMinute == 0) { - eventEmitter.emit('newDay'); - } -} diff --git a/src/utils/blog.js b/src/utils/blog.js new file mode 100644 index 0000000..b6c9306 --- /dev/null +++ b/src/utils/blog.js @@ -0,0 +1,19 @@ +const groupId = require('./../../config/config').groupId; +const newBlogPostMessage = require('./../../config/messages').newBlogPost; + +function sendNewArticles(bot, articles) { + articles.forEach((article) => { + bot.sendMessage( + groupId, + newBlogPostMessage + .replace('#{author}', article.author) + .replace('#{link}', article.link) + .replace('#{title}', article.title), + { parse_mode: 'Markdown' } + ); + }); +} + +module.exports = { + sendNewArticles +}; diff --git a/src/utils/chat.js b/src/utils/chat.js new file mode 100644 index 0000000..4d1c8f7 --- /dev/null +++ b/src/utils/chat.js @@ -0,0 +1,82 @@ +const fetch = require('node-fetch'); + +const messages = require('./../../config/messages'); +const config = require('./../../config/config.js'); + +function checkGoodMorning(goodMorningGivenToday, text) { + return !goodMorningGivenToday && config.goodMorningRegExp.test(text); +} + +function checkForCode(bot, msg) { + if (!Object.prototype.hasOwnProperty.call(msg, 'entities')) { + return; + } + + if (msg.entities[0].type !== 'pre') { + return; + } + + if (msg.text.length >= 200) { + return; + } + + const chatId = msg.chat.id; + const { firstName = '', lastName = '', username = '' } = msg.from; + const fullName = firstName === '' && lastName === '' ? '' : `${firstName} ${lastName} `; + const user = username === '' ? '' : `(@${username})`; + const filename = `${new Date().toISOString()}.js`; + const gist = msg.text; + + const body = { + description: 'gist creado por '.concat(fullName).concat(user).concat( + ' para https://t.me/ngvenezuela con https://github.com/ngVenezuela/wengy-ven'), + public: true, + files: { + [filename]: { + content: gist + } + } + }; + + fetch('https://api.github.com/gists', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(body) + }) + .then(response => response.json()) + .then(({ html_url }) => { + bot.sendMessage(chatId, html_url); + }).catch(() => {}); +} + +function formatName(msgContext) { + return msgContext.username + ? '@'.concat(msgContext.username) + : msgContext.first_name; +} + +function sayHello(bot, msg) { + bot.sendMessage( + msg.chat.id, + messages.welcomeMsg.replace('#{name}', formatName(msg.new_chat_member)), + { reply_to_message_id: msg.message_id, parse_mode: 'Markdown' } + ); +} + +function sayGoodbye(bot, msg) { + bot.sendMessage( + msg.chat.id, + messages.goodbyeMsg.replace('#{name}', formatName(msg.left_chat_member)), + { reply_to_message_id: msg.message_id, parse_mode: 'Markdown' } + ); +} + +module.exports = { + sayHello, + sayGoodbye, + checkGoodMorning, + checkForCode +}; + diff --git a/src/utils/morning.js b/src/utils/morning.js new file mode 100644 index 0000000..62218e6 --- /dev/null +++ b/src/utils/morning.js @@ -0,0 +1,51 @@ +const generateRandom = require('./../utils/time').generateRandom; +const messages = require('./../../config/messages'); +const config = require('./../../config/config'); + +function morningConditions(goodMorningGivenToday, minuteToCheck, vzlanHour, vzlanMinute) { + return ( + !goodMorningGivenToday && + vzlanHour === config.morningHour && + vzlanMinute === minuteToCheck + ); +} + +function getMorningMsg(weekday) { + const weekDays = { + 0: 'generic', + 1: 'mondays', + 2: 'generic', + 3: 'generic', + 4: 'generic', + 5: 'fridays', + 6: 'generic' + }; + + const randomIndex = generateRandom( + 0, + messages.goodMornings[weekDays[weekday]].length - 1 + ); + + return messages.goodMornings[weekDays[weekday]][randomIndex]; +} + + +function giveGoodMorning(bot, goodMorningGivenToday, + minuteToCheck, vzlanHour, vzlanMinute, weekday) { + if (morningConditions(goodMorningGivenToday, minuteToCheck, vzlanHour, vzlanMinute)) { + bot.sendMessage(config.groupId, getMorningMsg(weekday)); + return { + goodMorningGivenToday: true, + minuteToCheck: generateRandom(0, 59) + }; + } + + return { + goodMorningGivenToday: false, + minuteToCheck + }; +} + +module.exports = { + giveGoodMorning +}; diff --git a/src/time-utility.js b/src/utils/time.js similarity index 62% rename from src/time-utility.js rename to src/utils/time.js index 882459b..d717890 100644 --- a/src/time-utility.js +++ b/src/utils/time.js @@ -1,12 +1,3 @@ -'use strict'; - -module.exports = { - vzlanHour, - vzlanMinute, - vzlanWeekday, - generateRandom, -}; - /** * Generate random Integer with values with range: min-max * @param {Integer} min - Min value @@ -14,19 +5,44 @@ module.exports = { * @return {Integer} Random Integer value */ function generateRandom(min, max) { - return Math.floor(Math.random() * (max - min + 1)) + min; + return Math.floor(Math.random() * ((max - min) + 1)) + min; } +/** + * Get date in Venezuela, given a date + * @param {Date} date - Date + * @return {Date} date in Venezuela + */ +function getVzlanTime(date) { + const vzlanOffset = 4; + const actualTime = new Date( + Date.UTC( + date.getFullYear(), + date.getMonth(), + date.getDate(), + date.getHours(), + date.getMinutes(), + 0, + 0 + ) + ); + const vzlanTimeInMs = actualTime.setUTCHours(date.getUTCHours() - vzlanOffset); + const vzlanTime = new Date(vzlanTimeInMs); + + return vzlanTime; +} + + /** * Get hour in Venezuela, given a date * @param {Date} date - Date * @return {Integer} Hour in Venezuela */ function vzlanHour(date = new Date()) { - let vzlanTime = getVzlanTime(date); - let vzlanHour = vzlanTime.getUTCHours(); // 24 hours format (0-23) + const vzlanTime = getVzlanTime(date); + const venezuelanHour = vzlanTime.getUTCHours(); // 24 hours format (0-23) - return vzlanHour; + return venezuelanHour; } /** @@ -35,10 +51,10 @@ function vzlanHour(date = new Date()) { * @return {Integer} minute in Venezuela */ function vzlanMinute(date = new Date()) { - let vzlanTime = getVzlanTime(date); - let vzlanMinute = vzlanTime.getUTCMinutes(); // 0-59 + const vzlanTime = getVzlanTime(date); + const venezuelanMinute = vzlanTime.getUTCMinutes(); // 0-59 - return vzlanMinute; + return venezuelanMinute; } /** @@ -47,31 +63,16 @@ function vzlanMinute(date = new Date()) { * @return {Integer} weekday in Venezuela */ function vzlanWeekday(date = new Date()) { - let vzlanTime = getVzlanTime(date); - let vzlanWeekDay = vzlanTime.getUTCDay(); // sunday = 0 + const vzlanTime = getVzlanTime(date); + const venezuelanWeekDay = vzlanTime.getUTCDay(); // sunday = 0 - return vzlanWeekDay; + return venezuelanWeekDay; } -/** - * Get date in Venezuela, given a date - * @param {Date} date - Date - * @return {Date} date in Venezuela - */ -function getVzlanTime(date) { - const vzlanOffset = 4; - let actualTime = new Date( - Date.UTC( - date.getFullYear(), - date.getMonth(), - date.getDate(), - date.getHours(), - date.getMinutes(), - 0, 0 - ) - ); - let vzlanTimeInMs = actualTime.setUTCHours(date.getUTCHours() - vzlanOffset); - let vzlanTime = new Date(vzlanTimeInMs); +module.exports = { + vzlanHour, + vzlanMinute, + vzlanWeekday, + generateRandom +}; - return vzlanTime; -} diff --git a/tests/time-utility.spec.js b/tests/time-utility.spec.js index 0e8bfdf..1f8ff8a 100644 --- a/tests/time-utility.spec.js +++ b/tests/time-utility.spec.js @@ -1,9 +1,9 @@ -const {generateRandom} = require('../src/time-utility.js'); +const { generateRandom } = require('./../src/utils/time.js'); describe('Time Utility', () => { it('generates a random number between a min and max range', () => { - const random = generateRandom(1, 50); + const random = generateRandom(0, 50); - expect( random >= 1 && random <= 50 ).toBe(true); + expect(random >= 0 && random <= 50).toBe(true); }); });