DEV Community

Cover image for How to build a simple Twitter bot in 17 lines of code
Omar Sinan
Omar Sinan

Posted on • Updated on

How to build a simple Twitter bot in 17 lines of code

A few months ago I created this twitter bot that retweets anything from a specified list of users. And guess what? It was only 17 lines of code. The reason I’m sharing this is because I think it’s crazy how online services charge at least $15 for a simple tool to create bots when you can just build your own. So are you ready?

Here’s what we’re going to use to build the bot:

Aaaand that’s basically it.

Creating an application

Before we get into writing code, we have to setup our Twitter application. You can do that at https://apps.twitter.com/. Press the “Create New App” button and this is what you’ll see:

Fill in the information. If you don’t have a website to put in the “Website” field, you can just write https://www.example.com.
Once you create the application, there are 4 important things to note down over at the “Keys and Access Tokens” tab:

  • Consumer Key
  • Consumer Secret
  • Access Token Key
  • Access Token Secret

If you don’t see your “Access Token Key” and “Access Token Secret” just click the “Create my access token” button and you’ll be set.

Initializing the project

Open up CMD or Terminal and cd to a new directory for your twitter bot and execute the command:

npm init
Enter fullscreen mode Exit fullscreen mode

and fill in the information. Next, we need to install the proper dependencies, in this case it’s only one:

npm install twit --save
Enter fullscreen mode Exit fullscreen mode

Now create a file in that directory called index.js . 

NOTE: If you changed the entry point when you ran npm init then make sure that the file name matches what you put in package.json. If you didn’t change anything, then don’t worry just call it index.js.

The fun part

Open up a blank text editor of your choice and create a Twit instance that can be used to make requests to Twitter's APIs. The config should be an object of the form:

var Twit = require('twit')
var T = new Twit({
    consumer_key:         ' ... ',
    consumer_secret:      ' ... ',
    access_token:         ' ... ',
    access_token_secret:  ' ... ',
})
Enter fullscreen mode Exit fullscreen mode

Replace the ' ... ' with your consumer and access keys.
Now create an array which holds the string IDs of the users you want to retweet (you can change the IDs I put in the code snippet below):

var users = ["10228272", "155659213", "783214"];
Enter fullscreen mode Exit fullscreen mode

Now we’re going to create a stream which is in the form T.stream(path, [params]):

var stream = T.stream('statuses/filter', {follow: users});
Enter fullscreen mode Exit fullscreen mode

Notice that in the second parameter, for the key follow we set the value as the variable users.
Now we’re going to listen to that stream when the event tweet is fired:

stream.on('tweet', function (tweet) {
    if (users.indexOf(tweet.user.id_str) > -1) {
        console.log(tweet.user.name + ": " + tweet.text);
        T.post('statuses/retweet/:id', { id: tweet.id_str }, function (err, data, response) {
            console.log(data)
        })
    }
})
Enter fullscreen mode Exit fullscreen mode

This function is emitted each time a status (tweet) comes into the stream. Line 2 is necessary to ensure that the ID of the user who just tweeted is present in the array users.
Line 4 is basically using twit to retweet that tweet with an id of tweet.id_str . If you want to check out what other properties the tweet object has, you can head over to: https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/tweet-object

Lets run the bot!

That’s basically it, You just created your first twitter bot in 17 lines of code! To run it, just execute this command in CMD or Terminal:

node index.js
Enter fullscreen mode Exit fullscreen mode

Future updates

I’ll be writing another post later on which explains how to deploy your bot to Heroku so that you don’t have to run it on your local system 24/7.

Final code

var Twit = require('twit')
var T = new Twit({
    consumer_key:         ' ... ',
    consumer_secret:      ' ... ',
    access_token:         ' ... ',
    access_token_secret:  ' ... ',
})
var users = ["10228272", "155659213", "783214"];
var stream = T.stream('statuses/filter', {follow: users});
stream.on('tweet', function (tweet) {
    if (users.indexOf(tweet.user.id_str) > -1) {
        console.log(tweet.user.name + ": " + tweet.text);
        T.post('statuses/retweet/:id', { id: tweet.id_str }, function (err, data, response) {
            console.log(data)
        })
    }
})
Enter fullscreen mode Exit fullscreen mode

Top comments (34)

Collapse
 
kidkkr profile image
kidkkr

fun to read :)

Collapse
 
bengreenberg profile image
Ben Greenberg

Excellent article! Twit is a great package, really versatile. A while back I wrote a bot that retweets web dev jobs, forgot about it for a while and just checked in on it and it has more than 1,300 tweets and a little more than 50 followers. It's also just a few lines of code. Wrote about it back then at dev.to/benhayehudi/how-i-created-t....

Collapse
 
oohsinan profile image
Omar Sinan

That's awesome! Just checked out your article, I really liked how comprehensive it is.

Collapse
 
bengreenberg profile image
Ben Greenberg

Thanks!

Collapse
 
andypiper profile image
Andy Piper

Nice article. Worth being aware of Twitter's automation rules, though, which you agreed to follow when you acknowledged the developer agreement.

help.twitter.com/en/rules-and-poli...

Also note that the new Account Activity API provides callbacks (webhooks) rather than requiring a constant connection, which is a more modern way of handling these kinds of scenarios. I'm not certain whether the twit node module supports this yet.

Collapse
 
sscarduzio profile image
Simone Scarduzio

So if I want this to be a Serverless app, I'd need to run it periodically to poll twitter for new tweets. Right?

Is there anything in the Twitter API or (any other service) that callbacks my app URL upon new tweets from a list of users?

Collapse
 
zalithka profile image
Andre Greeff

From what I can tell, Twit.stream() keeps an active connection to the Twitter API, so there's no polling required to get information. In this case, a handler is being attached to the tweet event, which should stay active as long as the app is running.

Collapse
 
sscarduzio profile image
Simone Scarduzio

Thanks Andre, so yes. It's not callback based. Serverless fail :(

Collapse
 
ivanoats profile image
Ivan Storck

Great tutorial!

If you're following along, make sure not to check in your Auth keys or other secrets to Github.

You could use the dotenv package to keep secrets in environment variables.

Collapse
 
zoedsoupe profile image
Zoey de Souza Pessanha

Hi! So, how can I use this package?

Collapse
 
oihamza profile image
Hamza

Fun read 😍

Just note that apps.twitter.com has been sunsetted. You can manage any of your existing/new apps in all of the same ways through developer.twitter.com/en/apps

Collapse
 
kr428 profile image
Kristian R.

Enjoyed reading this from a code point of view. :) Only thing I felt like mentioning: Given the fact that online services offer this for $15, you might miss some costs that go beyond just writing code. Heroku hosting for running this thing all time, maintaineance, debugging, making sure it's up and running - if you really want to use this for anything meaningful, I doubt your solution will be much cheaper than $15 per month. ;)

Collapse
 
mrm8488 profile image
Manuel Romero

Great tutorial. You could add error management

Collapse
 
oohsinan profile image
Omar Sinan

Thank you! I’ll look into error management in the next tutorial hopefully :-)

Collapse
 
dance2die profile image
Sung M. Kim

Loved the article and especially the title 👍

If the title was How to write a simple twitter bot, I'd have turned away.
But 17 lines of code really caught my attention 😝

Collapse
 
slidenerd profile image
slidenerd • Edited

nice post! how does streaming work if your list of users for the statuses/filter is dynamic? say you have a database with a table of users to follow, you stream from them currently, now you add another user and you want to modify your stream, how does it work?

Collapse
 
dagrooms52 profile image
Daniel Grooms

And remember to put those secrets into Environment Variables before you upload code to Github!

Collapse
 
ewoks profile image
Beeblebrox

You just got featured in 7 must reads from last week!!! Congrats on great post! :) Looking forward part to with Heroku

Collapse
 
oohsinan profile image
Omar Sinan

Didn’t even realize, thank you! :-)

Collapse
 
tejasrsuthar profile image
Tejas Suthar

Omar, that's awesome use of twit package. I just would like to add one more thing to your article is that even we can create Lambda function in AWS just for this and it would be pretty simple instead of spinning a Heroku stack.

Definitely its a matter of choice but, I would prefer to go with Lambda function as it does not require any kind of state management.

Collapse
 
stock_ex_news profile image
TRADING News

Hi !

I have proudly done it ! I have launched my own stock exchange news feed (rather than subscribe to all of that accounts on my personal Twitter account). Is it possible to have unlimited Retweet posts ?

While I'm trading, that really helps me, I would be so grateful if we can find a issue to this problem.

Thanks a lot.
Pierre

PS: I'm french, I apologize in advance if there are some mistakes...

Collapse
 
fafafava profile image
Favascript

This is very useful and simple explanation, thanks!

Collapse
 
oohsinan profile image
Omar Sinan

I'm glad you found it useful! :-)