diff --git a/config/messages.js b/config/messages.js index 97db6f9..39020c0 100644 --- a/config/messages.js +++ b/config/messages.js @@ -40,7 +40,8 @@ const messages = { githubRelease: '*#{name}* acaba de alcanzar la versión *#{version}*\n\n'.concat( '[Puedes ver los cambios aquí](#{url})'), githubOpenVeLink: 'El enlace de github para comunidades de Telegram es: #{link}', - gistCreated: 'gist creado por #{fullName} #{user} para #{telegramLink} con #{githubLink}' + gistCreated: 'gist creado por #{fullName} #{user} para #{telegramLink} con #{githubLink}', + gistRecommendation: 'Utiliza el comando /gist _codigo_ para generar un gist en github' }; module.exports = messages; diff --git a/src/index.js b/src/index.js index 7538ff9..2442778 100644 --- a/src/index.js +++ b/src/index.js @@ -41,16 +41,20 @@ let minuteToCheck = generateRandom(0, 59); redisClient .on('ready', () => { bot - .onText(/\/groupId/, (msg, match) => + .onText(/^\/groupId$/, (msg, match) => devUtility.sendGroupId(bot, msg.chat.id, msg.from.id, match[0], redisClient)); bot - .onText(/\/comunidades/, (msg, match) => + .onText(/^\/comunidades$/, (msg, match) => githubUtility.sendOpenVeGithubLink(bot, msg, match[0], redisClient)); - bot - .onText(/\/github/, (msg, match) => + .onText(/^\/github$/, (msg, match) => githubUtility.sendCommunityRepo(bot, msg, match[0], redisClient)); + bot + // eslint-disable-next-line no-useless-escape + .onText(/^\/gist ([\s\S\.]+)/, (msg, match) => + githubUtility.createGist(bot, msg, redisClient, match[1], false)); + bot .on('new_chat_participant', msg => chatUtility.sayHello(bot, msg)) .on('left_chat_participant', msg => chatUtility.sayGoodbye(bot, msg)) diff --git a/src/utils/command.js b/src/utils/command.js index ad854b6..5c42f93 100644 --- a/src/utils/command.js +++ b/src/utils/command.js @@ -29,9 +29,11 @@ const verifyCommand = async (redisClient, command, userId) => { /* * create key again * ttlReply might be -2, it means key doesn't exist - * and it could happen if ttl is close to zero + * and it could happen if ttl is close to zero. + + * 5 minutes cooldown for each user-command */ - const newSet = await redisClient.setAsync(`${userId}-${command}`, 1, 'EX', 60); + const newSet = await redisClient.setAsync(`${userId}-${command}`, 1, 'EX', 60 * 5); return newSet === 'OK'; } catch (error) { return false; diff --git a/src/utils/github.js b/src/utils/github.js index a35317f..3450734 100644 --- a/src/utils/github.js +++ b/src/utils/github.js @@ -7,12 +7,14 @@ const githubOpenVeLinkMessage = require('./../../config/messages').githubOpenVeL const gistCreated = require('./../../config/messages').gistCreated; const telegramLink = require('./../../config/config').community.telegram.link; const githubLink = require('./../../config/config').community.github; +const gistRecommendation = require('./../../config/messages').gistRecommendation; const sendMessage = require('./../utils/send-message'); const commandUtility = require('./../utils/command'); const GITHUB_LINK_OPENVE_TELEGRAM_COMMUNITY = 'https://github.com/OpenVE/comunidades-en-telegram'; const GIST_COMMAND = '/gist'; +const MAX_LENGTH_GIST_TEXT = 200; const isItAGithubRelease = (repository, feed) => feed && feed.status.feed && feed.status.feed.search(repository) !== -1; @@ -22,10 +24,10 @@ const sendRelease = (bot, release, repository, changelogExist) => { return; } - const name = repository.match(/[\w.-]+$/gi)[0]; + const name = repository.match(/[\w\.-]+$/gi)[0]; // eslint-disable-line no-useless-escape release.items.forEach((item) => { - const tag = item.id.match(/[\w.-]+$/gi)[0]; + const tag = item.id.match(/[\w\.-]+$/gi)[0]; // eslint-disable-line no-useless-escape sendMessage( bot, @@ -52,59 +54,69 @@ const checkAndSendRelease = (bot, feed) => { } }; -const checkForCode = (bot, msgContext, redisClient) => { +const prepareAndSendGist = (bot, msgContext, checkingForCode, code = '') => { + const chatId = msgContext.chat.id; + const { firstName = '', lastName = '', username = '' } = msgContext.from; + const fullName = firstName === '' && lastName === '' ? '' : `${firstName} ${lastName} `; + const user = username === '' ? '' : `(@${username})`; + const filename = `${new Date().toISOString()}.js`; + const gist = checkingForCode ? msgContext.text : code; + + const body = { + description: gistCreated + .replace('#{fullName}', fullName) + .replace('#{user}', user) + .replace('#{telegramLink}', telegramLink) + .replace('#{githubLink}', githubLink), + public: true, + files: { + [filename]: { + content: gist + } + } + }; + + fetch('https://api.github.com/gists', { + method: 'POST', + headers: { + 'Content-Type': 'application/json; charset=utf-8', + }, + body: JSON.stringify(body) + }) + .then(response => response.json()) + .then(({ html_url }) => { + sendMessage(bot, chatId, html_url, true, msgContext.message_id); + }).catch(() => { }); +}; + +const createGist = (bot, msgContext, redisClient, text = '', checkingForCode = true) => { commandUtility.verifyCommand(redisClient, GIST_COMMAND, msgContext.from.id) .then((canExecuteCommand) => { if (canExecuteCommand) { - if (!Object.prototype.hasOwnProperty.call(msgContext, 'entities')) { - return; - } - - if (msgContext.entities[0].type !== 'pre') { - return; - } - - if (msgContext.text.length >= 200) { - return; - } - - const chatId = msgContext.chat.id; - const { firstName = '', lastName = '', username = '' } = msgContext.from; - const fullName = firstName === '' && lastName === '' ? '' : `${firstName} ${lastName} `; - const user = username === '' ? '' : `(@${username})`; - const filename = `${new Date().toISOString()}.js`; - const gist = msgContext.text; - - const body = { - description: gistCreated - .replace('#{fullName}', fullName) - .replace('#{user}', user) - .replace('#{telegramLink}', telegramLink) - .replace('#{githubLink}', githubLink), - public: true, - files: { - [filename]: { - content: gist - } + if (text === '' && msgContext.text.length >= MAX_LENGTH_GIST_TEXT) { + if (checkingForCode) { + sendMessage(bot, msgContext.chat.id, gistRecommendation, true, msgContext.message_id); } - }; - - fetch('https://api.github.com/gists', { - method: 'POST', - headers: { - 'Content-Type': 'application/json; charset=utf-8', - }, - body: JSON.stringify(body) - }) - .then(response => response.json()) - .then(({ html_url }) => { - sendMessage(bot, chatId, html_url, true, msgContext.message_id); - }).catch(() => { }); + } else { + prepareAndSendGist(bot, msgContext, checkingForCode, text); + } } }) .catch(() => { }); }; +const checkForCode = (bot, msgContext, redisClient) => { + if (!Object.prototype.hasOwnProperty.call(msgContext, 'entities')) { + return; + } + + if (msgContext.entities[0].type !== 'pre') { + return; + } + + createGist(bot, msgContext, redisClient); +}; + const sendOpenVeGithubLink = (bot, msgContext, command, redisClient) => { commandUtility.verifyCommand(redisClient, command, msgContext.from.id) .then((canExecuteCommand) => { @@ -137,5 +149,6 @@ module.exports = { checkAndSendRelease, checkForCode, sendOpenVeGithubLink, - sendCommunityRepo + sendCommunityRepo, + createGist };