Skip to content

Commit

Permalink
(Agrega): Comando para crear gists (#102)
Browse files Browse the repository at this point in the history
También recomienda al usuario usar el comando cuando coloca un código mayor a 200 caracteres
  • Loading branch information
leocabeza authored Jun 4, 2017
1 parent c83e162 commit 316f24c
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 54 deletions.
3 changes: 2 additions & 1 deletion config/messages.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
12 changes: 8 additions & 4 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
6 changes: 4 additions & 2 deletions src/utils/command.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
107 changes: 60 additions & 47 deletions src/utils/github.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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,
Expand All @@ -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) => {
Expand Down Expand Up @@ -137,5 +149,6 @@ module.exports = {
checkAndSendRelease,
checkForCode,
sendOpenVeGithubLink,
sendCommunityRepo
sendCommunityRepo,
createGist
};

0 comments on commit 316f24c

Please sign in to comment.