Skip to content

Commit

Permalink
Merge pull request #81 from ngVenezuela/develop
Browse files Browse the repository at this point in the history
Se actualiza rama master desde develop
  • Loading branch information
leocabeza authored May 22, 2017
2 parents d000f5d + d6b9f72 commit d96d7d1
Show file tree
Hide file tree
Showing 9 changed files with 173 additions and 3 deletions.
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,9 @@ config.js

# Webstorm config files
.idea

# JShint config file
.jshintrc

# Vscode config files
.vscode
3 changes: 0 additions & 3 deletions .vscode/settings.json

This file was deleted.

2 changes: 2 additions & 0 deletions config/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# File that save the last tracked tweet id
/last-tweetId.json
11 changes: 11 additions & 0 deletions config/config.sample.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,17 @@ const config = {
server: {
url: 'MY_HTTPS_SERVER', // ej: 'https://9c386d7d.ngrok.io'
port: 'MY_PORT'
},
twitterFeed: {
// Create these keys here: https://apps.twitter.com/
auth: {
consumer_key: 'CONSUMER_KEY',
consumer_secret: 'CONSUMER_SECRET',
access_token_key: 'ACCESS_TOKEN_KEY',
access_token_secret: 'ACCESS_TOKEN_SECRET'
},
twitterAccount: 'ngVenezuela',
hashtagMessage: '#ngVenezuelaTweet'
}
};

Expand Down
4 changes: 4 additions & 0 deletions config/messages.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ const messages = {
},
newBlogPost: '*#{author}* ha agregado una nueva entrada al blog titulada: '.concat(
'*#{title}* y está disponible en: #{link}'),
newTweet: '#{hashtagMessage} \u{1F426}\n'.concat(
'#{tweetText}\n',
'----\n',
'[Puedes ver el Tweet aquí](#{tweetUrl})'),
};

module.exports = messages;
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"feedparser": "^2.0.0",
"node-fetch": "^1.6.3",
"node-telegram-bot-api": "^0.27.1",
"twitter": "^1.7.0",
"uuid": "3.0.1"
},
"devDependencies": {
Expand Down
114 changes: 114 additions & 0 deletions src/events/tweets.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
const fs = require('fs');
const events = require('events');
const Twitter = require('twitter');

const eventEmitter = new events.EventEmitter();
const twitterFeed = require('./../../config/config').twitterFeed;

const twitterTokens = twitterFeed.auth;
const twitterAccount = twitterFeed.twitterAccount;
const twitterClient = new Twitter(twitterTokens);


/**
* Get the last tracked tweet id registered int the file: last-tweetId.json.
*
* Note: If there is no file then create it and return false
*
* @return {number} Last Tracked Tweet Id
* OR {boolean} false - If there is no last-tweetId.json file
*/
function getLastTrackedTweetId() {
try {
// Read the last-tweetId.json to get the last tracked tweet id
const data = fs.readFileSync('./config/last-tweetId.json', 'utf8');
const parsed = JSON.parse(data);

return parsed.lastTweetId;
} catch (err) {
/**
* If the file doesn't exist, create the file and return false because there is no last
* tweet tracked
*/
if (err.code === 'ENOENT') {
fs.writeFileSync('./config/last-tweetId.json', '');
return false;
}
throw err;
}
}

/**
* Save the last tweet id sent by ngVenezuela in the last-tweetId.json file
*
* @param {number} lastTweetId Last tweet id sent by ngVenezuela
*/
function updateLastTrackedTweetId(lastTweetId) {
fs.writeFileSync('./config/last-tweetId.json', `{"lastTweetId":${lastTweetId}}`);
}

/**
* Callback function when gettting latest tweets since the last tracked tweet registered
*
* @param {error} error
* @param {array} tweets Array of tweets object
* @param {response} response HTTP response
*/
function getLatestTweets(error, tweets) {
// If there is no tweets then do nothing
if (tweets.length === 0) {
return;
}

/**
* If the last tweet id is the same that the last tracked tweet id, do nothing
*
* Note: The Twitter API has a strange behavior, when you use
* the parameter since_id equal to the most
* recent tweet, it brings you the same tweet...
* But, when you use since_id equal to an older tweet, it doesn't include the since_id tweet
*/
if (getLastTrackedTweetId() === tweets[0].id) {
return;
}

// Update the last tracked tweet id with the last tweet gotten
updateLastTrackedTweetId(tweets[0].id);
tweets.map(tweet => eventEmitter.emit('newTweet', tweet));
}

/**
* Check if there are new tweets from ngVenezuela account since the last tracked tweet.
*
* If there is no last tracked tweet registered, save the last tweet id sent by ngVenezuela
* in the last-tweetId.json file
*/
function checkNewTweets() {
// Get the last tracked tweet id
const lastTrackedTweetId = getLastTrackedTweetId();

if (lastTrackedTweetId) {
twitterClient.get(
'statuses/user_timeline',
{ screen_name: twitterAccount, since_id: lastTrackedTweetId },
getLatestTweets
);
} else {
// No last tracked tweet registered
// Get latest tweets since the last tracked tweet registered
twitterClient.get(
'statuses/user_timeline',
{ screen_name: twitterAccount, count: 1 },
(error, tweets) => {
const lastNgTweetId = tweets[0].id;
updateLastTrackedTweetId(lastNgTweetId);
}
);
}
}

if (twitterFeed) {
setInterval(checkNewTweets, 60 * 1000); // 60 seconds
}

module.exports = eventEmitter;
8 changes: 8 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
const TelegramBot = require('node-telegram-bot-api');
const BotServer = require('./server/bot-server');

const telegramToken = require('./../config/config').telegramToken;
const server = require('./../config/config').server;

const morningEvent = require('./events/morning');
const blogEvent = require('./events/blog');
const twitterEvent = require('./events/tweets');

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 twitterUtility = require('./utils/tweets');

const bot = new TelegramBot(telegramToken);
// eslint-disable-next-line no-unused-vars
Expand Down Expand Up @@ -46,3 +51,6 @@ morningEvent

blogEvent
.on('newArticles', articles => blogUtility.sendNewArticles(bot, articles));

twitterEvent
.on('newTweet', tweet => twitterUtility.sendNewTweet(bot, tweet));
27 changes: 27 additions & 0 deletions src/utils/tweets.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const config = require('./../../config/config');
const sendMessage = require('./../utils/send-message');
const newTweetMessage = require('./../../config/messages').newTweet;
const hashtagMessage = require('./../../config/config').twitterFeed.hashtagMessage;

/**
* Construct and send the message to notify a new tweet in the group
*
* @param {Object} bot Telegram bot
* @param {Object} tweet New tweet
*/
function sendNewTweet(bot, tweet) {
const tweetUrl = `https://twitter.com/${tweet.user.screen_name}/status/${tweet.id_str}`;

sendMessage(
bot,
config.groupId,
newTweetMessage
.replace('#{tweetText}', tweet.text)
.replace('#{tweetUrl}', tweetUrl)
.replace('#{hashtagMessage}', hashtagMessage)
);
}

module.exports = {
sendNewTweet
};

0 comments on commit d96d7d1

Please sign in to comment.