Easy Twitter Bot for Beginners

Carlos Rucker
Jul 20, 2017 · 6 min read
Image of actual project code made with Marmoset App

An Easy Twitter Bot in 16 lines of code. (Social media managers HATE him!)

Why Make a Twitter Bot?

Because reasons.

No really, why?

Two days ago I knew hardly anything about Node.js, Javascript, or the command line. I started to research each of these topics then decided to kill 3 birds with 1 stone and make a Twitter bot.

I unofficially named my Twitter bot Sisyphus after The Myth of Sisyphus by philosopher Albert Camus. Both share the fate of performing a pointless task for an eternity and have no choice but to embrace the absurdity of their existence.

Instead of pushing a boulder up hill, I picked the absurd task of making Sisyphus automatically tweet the top Reddit posts of the /r/politics subreddit.

The top posts of /r/politics could have just as easily been “What dumb thing did Trump do today?”

Aren’t Twitter Bots Evil?

Woah, that’s robophobic! Besides, some of them - I assume - are good bots. If you would rather your Twitter bot do something different, feel free to point your bot to another subreddit (or API for that matter).

Hold, on! Aren’t there bot websites to automate tweets?

No, YOU hold on! Those websites, although very easy to use, are very limited as they do not offer the flexibility of our bot. Those websites are limited by their pre-determined inputs and outputs.

The bot we are making is only limited by our imagination.

Do you want to learn how to fish?

Install Node.js

We’re using Node.js to run our bot. We won’t be using a website or front end interface.

Embrace the command line. It’s not as hard as it looks and you’ll look 10 times cooler (fedora not included). If you’re new to the command line there are really only a handful of commands you need to memorize.

You’ll quickly realize the command line is so much faster and easier than using a GUI (Graphical User Interface) and wonder why the general population went away from it.

Install Modules

[I’ll be using the phrase module and package interchangeably]

This website is a repository for useful packages. At the time of writing there are nearly half a million packages hosted. Make use of the search feature. Search “Reddit” and “Twitter” for packages. See which packages are currently maintained and popular.

Our bot will use the “Twit” and “Redditor” packages. Take the time to read and understand their supplied documentation.

Get used to seeing the “npm” command all the time. NPM stands for Node Package Manager. It helps us install essential packages to cut down on coding boilerplate.

Reddit API

Let’s understand Reddit’s API and the structure of the JSON response.

Twitter API

Now let’s look at Twitter’s API… Just kidding. Twitter’s API documentation is notoriously horrible! Besides, the twit package will facilitate most of the work. The endpoints are easy to understand and the many examples of post and get requests listed in the twit documentation are great.

All you need are your API keys. Go to https://dev.twitter.com and login into your account. Create a new app. Name it whatever you want. If you’re not sure about some of the form fields, just ignore them as they do not pertain to the bot we are making.

Generate and grab your API keys. Copy them into a text file for later or leave the browser tab open.

Let’s Get Coding!!!

Learn the command line. For Mac, 90% of the commands are the same. For Linux, you should already have them tattooed proudly.

Go to your project directory and initialize:

npm init

Follow the initialization steps. This creates a package.json file. This file acts like a manifest with important meta information and all the project dependencies.

Name the entry point whatever you want to call your main app file. I chose to call the file app.js.

Install our packages from the repository we looked at earlier.

npm install twit 

Look back in our “package.json” file. We now have the twit dependency declared. The twit module has now been installed into the “modules” folder.

Now install the “redditor” package the same way:

npm install redditor

In the editor create a new file for the entry point. Name it app.js or whatever you decided to call yours during the “npm init” process.

[app.js] Importing dependencies

const Twit = require("twit");
const Reddit = require("redditor");

Make a [config.js] file to hold our API keys

Why not just supply the keys inside of app.js? Safety. Making the keys external to the app.js allows for a level of abstraction so they aren’t in plain sight for anyone to see.

Create a config.js file and paste your keys:

module.exports = {
consumer_key: ‘...’
,consumer_secret: ‘...’
,access_token: ‘...’
,access_token_secret: ‘...’
}

Notice we define module.exports to this comma-separated object. This allows the main part of the app (app.js) to refer to these keys. We are “exporting” these keys from the config.js file. Then we’re going to “import” them in the app.js file.

[app.js] print a message

console.log(‘Hello, world!’);

[package.json] make a start script

"start": "node app.js"

Adding this inside “scripts” will allow us to run our app using the “npm start” command. Don’t forget to comma-separate them if there is more than one script!

[cmd.exe]

npm start

Our ‘Hello, world!’ should display in the command line. Cool.


Node.js allows for all ECMAScript2015 (ES6) features. We are using “const” instead of “var”. Stay tuned for a post on the difference between “var”, “let”, and “const”. In the meantime, Google and Stack Overflow exist.

[app.js]

Node.js allows for us to import modules to “app.js” using this syntax.

const Twit = require(‘twit’); //imports the twit package

Import the “redditor” module in the same way.

const reddit = require(‘redditor’);

Import the “config.js” file into “app.js” and pass the config dependency into a new Twit object “T”.

const config = require(‘./config’);
const T = new Twit(config);

Note: the dot-slash (./) prepends the custom module. This points to the file in the same directory as “app.js”. If, for some reason, we needed to import a file higher in the directory structure we would use the (../)notation. We can point to any file in any directory using these notations.

Note: Node.js knows to look for regular generated modules (Twit and Redditor) in the module folder so they don’t need their directories defined.

Call the “get” function on the reddit object we created. It takes two parameters: the subreddit endpoint and a callback function.

reddit.get(‘/r/politics.json’, function(err, response) {
if (err) throw err;
for (i = 0; i < 3; i++) {
const result = response.data.children;
const nestedUrls = result[i].data.url;
console.log(nestedUrls);
}

Above, we iterated over the JSON response which happens to return an array (nested inside a few objects). Research the Reddit API documentation to see how the JSON responses are structured.

[cmd.exe]

npm start

You should see the top 3 posts. Cool!


Pat yourself on the back, you have a way to programmatically grab urls from Reddit. But we’re not done yet! We want them to land on Twitter!

Call the post and pass in the ‘statuses/update’ to complete the API endpoint. I chose to concatenate the status (tweet) with the hashtag “ #news”. Remember to add a space before the hashtag to separate them so the url does not become invalid.

reddit.get(‘/r/politics.json’, function(err, response) {
if (err) throw err;
for (i = 0; i < 3; i++) {
const result = response.data.children;
const nestedUrls = result[i].data.url;
console.log(nestedUrls);
T.post(‘statuses/update’, {
status: nestedUrls + “ #news”
}, function(err, data, response) {});
}
});

Run the app with the “npm start” command. Now open your web browser and check your twitter profile. You should see the bot tweeted all by itself! The post should feature image “cards” that twitter generates since news organizations follow best practices of embedding social media tags into their html (The same is true for Instagram, Facebook, etc).


Hopefully you had fun on this weird bot journey! There’s so much more you can teach this bot. Navigate inside the Twit module folder and read the documentation and example projects. The Twitter API allows you to (in realtime) follow, retweet, search users, search phrases and hashtags, and more.

What other kinds of bot ideas do you have?

)
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade