codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

Build a simple Twitter Bot with Node.js in just 38 lines of code

7 min readMay 30, 2017

--

Twitter! via unsplash.me

Create an Application

Here’s what the page should look like.
Keys and Access Tokens

Configuration

npm init
{
"name": "twitter-bot",
"version": "1.0.0",
"description": "Nodejs Twitter Bot",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/bmorelli25/Twitter-Bot.git"
},
"author": "Brandon Morelli",
"license": "ISC",
"bugs": {
"url": "https://github.com/bmorelli25/Twitter-Bot/issues"
},
"homepage": "
https://github.com/bmorelli25/Twitter-Bot#readme"
}
npm install --save twitter
// config.jsmodule.exports = {
consumer_key: '',
consumer_secret: '',
access_token_key: '',
access_token_secret: ''
}
// app.jsvar Twitter = require('twitter');
var config = require('./config.js');
var T = new Twitter(config);

Build the Bot

var Twitter = require('twitter');
var config = require('./config.js');
var T = new Twitter(config);
// Set up your search parameters
var params = {
q: '#nodejs',
count: 10,
result_type: 'recent',
lang: 'en'
}
T.get('search/tweets', params, function(err, data, response) {
if(!err){
// This is where the magic will happen
} else {
console.log(err);
}
})
// Loop through the returned tweets
for(let i = 0; i < data.statuses.length; i++){
// Get the tweet Id from the returned data
let id = { id: data.statuses[i].id_str }
// Try to Favorite the selected Tweet
T.post('favorites/create', id, function(err, response){
// If the favorite fails, log the error message
if(err){
console.log(err[0].message);
}
// If the favorite is successful, log the url of the tweet
else{
let username = response.user.screen_name;
let tweetId = response.id_str;
console.log('Favorited: ', `
https://twitter.com/${username}/status/${tweetId}`)
}
});
}

Run your bot!

Full Code

Coming Soon

❤ If this post was helpful, please hit the little green heart!

--

--

codeburst
codeburst

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Brandon Morelli
Brandon Morelli

Written by Brandon Morelli

Creator of @codeburstio — Frequently posting web development tutorials & articles. Follow me on Twitter too: @BrandonMorelli

Responses (33)