Skip to content

Commit

Permalink
Merge pull request #69 from ngVenezuela/develop
Browse files Browse the repository at this point in the history
(Agrega) Integración con API.AI
  • Loading branch information
leocabeza authored May 14, 2017
2 parents 5f2e8f1 + 3657e51 commit 2515972
Show file tree
Hide file tree
Showing 10 changed files with 130 additions and 28 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ Te invitamos a leer el documento [CONTRIBUTING](.github/CONTRIBUTING.md) para co

## Versionado

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.
Utilizamos [SemVer](http://semver.org/lang/es/) 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

Expand Down
12 changes: 11 additions & 1 deletion config/config.sample.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,18 @@
const uuidV4 = require('uuid/v4');

const config = {
telegramToken: 'MY_SUPER_SECRET_TOKEN',
telegramToken: 'MY_SUPER_SECRET_TELEGRAM_TOKEN',
morningHour: 7,
groupId: -1001031605415,
// groupId: -165387746 //test group,
botUsername: 'WengyBot',
// botUsername: 'LeoTestsBot', // test bot username
apiAI: {
lang: 'es',
sessionId: uuidV4(),
queryUrl: 'https://api.api.ai/v1/query?v=20150910',
clientAccessToken: 'MY_SUPER_SECRET_APIAI_TOKEN'
},
goodMorningRegExp: new RegExp('buen(os)*\\sd[ií]+as', 'iu'),
blogFeedUrl: 'https://medium.com/feed/ngvenezuela',
};
Expand Down
18 changes: 11 additions & 7 deletions config/messages.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
const messages = {
welcomeMsg: 'Hola #{name}, ¡Bienvenid@ a ngVenezuela!. Te invitamos a '+
'seguirnos en twitter como [@ngVenezuela](https://twitter.com/ngVenezuela) ' +
'y a mirar nuestra comunidad en Github: https://github.com/ngvenezuela.\n\n'+
'Además nos gustaría que respondieras esta pequeña encuesta: http://bit.ly/ngve-encuesta',
goodbyeMsg: '¡Nos vemos pronto #{name}! Esperamos NO verte por el grupo de React Venezuela',
welcome: 'Hola #{name}, ¡Bienvenid@ a ngVenezuela!. Te invitamos a '.concat(
'seguirnos en twitter como [@ngVenezuela](https://twitter.com/ngVenezuela) ',
'y a mirar nuestra comunidad en Github: https://github.com/ngvenezuela.\n\n',
'Además nos gustaría que respondieras esta pequeña encuesta: http://bit.ly/ngve-encuesta'),
goodByes: [
'¡Nos vemos pronto #{name}! Esperamos NO verte por el grupo de React Venezuela',
'Goodbye, Hasta la vista, Sayonara #{name}'
],
goodMornings: {
mondays: [
'Buenos días comunidad, ¡Que tengan un excelente inicio de semana! \u{1F60E}',
Expand All @@ -23,11 +26,12 @@ const messages = {
'Buenos días',
'Buenos días a todos',
'Buenos días comunidad',
'Buenos días #ngPanas',
'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}* '+
'y está disponible en: #{link}',
newBlogPost: '*#{author}* ha agregado una nueva entrada al blog titulada: '.concat(
'*#{title}* y está disponible en: #{link}'),
};

module.exports = messages;
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@
"dependencies": {
"feedparser": "^2.0.0",
"node-fetch": "^1.6.3",
"node-telegram-bot-api": "^0.27.1"
"node-telegram-bot-api": "^0.27.1",
"uuid": "3.0.1"
},
"devDependencies": {
"jest": "^19.0.2",
Expand Down
4 changes: 3 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const chatUtility = require('./utils/chat');
const blogUtility = require('./utils/blog');
const morningUtility = require('./utils/morning');
const generateRandom = require('./utils/time').generateRandom;
const apiAIUtility = require('./utils/api-ai');

const bot = new TelegramBot(telegramToken, { polling: true });
let goodMorningGivenToday = false;
Expand All @@ -18,7 +19,8 @@ bot
goodMorningGivenToday =
chatUtility.checkGoodMorning(goodMorningGivenToday, msg.text);
})
.on('text', msg => chatUtility.checkForCode(bot, msg));
.on('text', msg => chatUtility.checkForCode(bot, msg))
.on('text', msg => apiAIUtility.canBotRespondToThis(bot, msg));

morningEvent
.on('minuteMark', (vzlanHour, vzlanMinute, weekday) => {
Expand Down
55 changes: 55 additions & 0 deletions src/utils/api-ai.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
const fetch = require('node-fetch');
const apiAIConfig = require('./../../config/config').apiAI;
const botUsername = require('./../../config/config').botUsername;
const sendMessage = require('./send-message');

const validResponse = response =>
response.result && response.result.fulfillment &&
response.result.fulfillment.messages.length > 0 &&
response.result.fulfillment.messages[0].speech !== '';

const botHasReplies = msgContext =>
Object.prototype.hasOwnProperty.call(msgContext, 'reply_to_message') &&
msgContext.reply_to_message.from.username === botUsername;

const botWasMentioned = (entities, text) =>
entities && entities.findIndex(entity => entity.type === 'mention') > -1 &&
text.includes(`@${botUsername}`);

const query = (bot, queryString, chatId, messageId) => {
fetch(apiAIConfig.queryUrl, {
method: 'POST',
headers: {
Authorization: `Bearer ${apiAIConfig.clientAccessToken}`,
'Content-Type': 'application/json; charset=utf-8'
},
body: JSON.stringify({
lang: 'es',
sessionId: apiAIConfig.sessionId,
query: queryString
})
})
.then(response => response.json())
.then((response) => {
if (validResponse(response)) {
sendMessage(bot, chatId, response.result.fulfillment.messages[0].speech, true, messageId);
}
}).catch(() => {});
};

const canBotRespondToThis = (bot, msgContext) => {
if (botHasReplies(msgContext)) {
query(bot, msgContext.text, msgContext.chat.id, msgContext.message_id);
} else if (botWasMentioned(msgContext.entities, msgContext.text)) {
query(
bot,
msgContext.text.replace(`@${botUsername}`, ''),
msgContext.chat.id,
msgContext.message_id
);
}
};

module.exports = {
canBotRespondToThis
};
19 changes: 11 additions & 8 deletions src/utils/blog.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
const groupId = require('./../../config/config').groupId;
const newBlogPostMessage = require('./../../config/messages').newBlogPost;
const sendMessage = require('./../utils/send-message');

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' }
);
setTimeout(() => {
sendMessage(
bot,
groupId,
newBlogPostMessage
.replace('#{author}', article.author)
.replace('#{link}', article.link)
.replace('#{title}', article.title)
);
});
});
}

Expand Down
30 changes: 22 additions & 8 deletions src/utils/chat.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ const fetch = require('node-fetch');

const messages = require('./../../config/messages');
const config = require('./../../config/config.js');
const sendMessage = require('./../utils/send-message');
const generateRandom = require('./../utils/time').generateRandom;

function checkGoodMorning(goodMorningGivenToday, text) {
return !goodMorningGivenToday && config.goodMorningRegExp.test(text);
Expand Down Expand Up @@ -41,13 +43,13 @@ function checkForCode(bot, msg) {
fetch('https://api.github.com/gists', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Type': 'application/json; charset=utf-8',
},
body: JSON.stringify(body)
})
.then(response => response.json())
.then(({ html_url }) => {
bot.sendMessage(chatId, html_url);
sendMessage(bot, chatId, html_url, true, msg.message_id);
}).catch(() => {});
}

Expand All @@ -58,18 +60,30 @@ function formatName(msgContext) {
}

function sayHello(bot, msg) {
bot.sendMessage(
sendMessage(
bot,
msg.chat.id,
messages.welcomeMsg.replace('#{name}', formatName(msg.new_chat_member)),
{ reply_to_message_id: msg.message_id, parse_mode: 'Markdown' }
messages.welcome.replace(
'#{name}',
formatName(msg.new_chat_member)
),
true,
msg.message_id
);
}

function sayGoodbye(bot, msg) {
bot.sendMessage(
const randomIndex = generateRandom(0, messages.goodByes.length - 1);

sendMessage(
bot,
msg.chat.id,
messages.goodbyeMsg.replace('#{name}', formatName(msg.left_chat_member)),
{ reply_to_message_id: msg.message_id, parse_mode: 'Markdown' }
messages.goodByes[randomIndex].replace(
'#{name}',
formatName(msg.left_chat_member)
),
true,
msg.message_id
);
}

Expand Down
3 changes: 2 additions & 1 deletion src/utils/morning.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const generateRandom = require('./../utils/time').generateRandom;
const messages = require('./../../config/messages');
const config = require('./../../config/config');
const sendMessage = require('./../utils/send-message');

function morningConditions(goodMorningGivenToday, minuteToCheck, vzlanHour, vzlanMinute) {
return (
Expand Down Expand Up @@ -33,7 +34,7 @@ function getMorningMsg(weekday) {
function giveGoodMorning(bot, goodMorningGivenToday,
minuteToCheck, vzlanHour, vzlanMinute, weekday) {
if (morningConditions(goodMorningGivenToday, minuteToCheck, vzlanHour, vzlanMinute)) {
bot.sendMessage(config.groupId, getMorningMsg(weekday));
sendMessage(bot, config.groupId, getMorningMsg(weekday));
return {
goodMorningGivenToday: true,
minuteToCheck: generateRandom(0, 59)
Expand Down
12 changes: 12 additions & 0 deletions src/utils/send-message.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
module.exports = (bot, chatId, messageText, replyMode = false, messageId) => {
try {
const defaultOptions = { parse_mode: 'Markdown' };
if (replyMode && messageId) {
Object.assign(defaultOptions, { reply_to_message_id: messageId });
}
bot.sendChatAction(chatId, 'typing');
setTimeout(() => {
bot.sendMessage(chatId, messageText, defaultOptions);
}, 2000);
} catch (e) {} // eslint-disable-line no-empty
};

0 comments on commit 2515972

Please sign in to comment.