beautiful dingbats ✎
Tools and tricks to stand out online.

How to make a twitter bot with node.js

A quick guide to building a twitter bot that helps people quit twitter.

Note — this tutorial assumes you have basic knowledge of javascript and node.js You can find the final code in this github repo .

Before we begin, we'll take a look at what a twitter bot can do, and some examples of existing twitter bots.

What is a twitter bot and what can they do?

A twitter bot is an automated program that tweets, likes, follows, or does any other action that a normal (human) twitter user can do.

But, unlike a human, a twitter bot can perform tasks over and over without becoming bored, sleep deprived, or dead. Here’s some examples of what a twitter bot can do:

  • Monitor every tweet being tweeted everywhere in the world in real time.

  • Automatically respond to tweets that mention a specific word, phrase, or hashtag.

  • Collect vast amounts of data and display that data in real-time anywhere on the web.

  • Automatically tweet in response to some event.
    e.g. 70% chance of snow in Colorado.

  • Interfere with the western democracy by pushing false narritives that sway the electorate to the far-right.

Types of twitter bots and some notable examples

Generally, twitter bots fall into one of these categories...


Bots that tweet at regular intervals

@tinycarebot — tiny care bot tweets a self care reminder every hour, like "please remember to listen to some music that helps you feel calm"

@poem_exe — generates tiny poems ("micropoetry") every few hours.


Bots that tweet based on an event

@earthquakebot — Tweets about any earthquack that registers 5.0 or above.


Bots that reply to you performing some action towards the bot

This could be as simple as an auto-responder for your business. Or a complex chat bot.

@botifuldingbot — the now shut-down beautiful dingbats font changing bot. It got a little carried away.


Bots that reply to your tweets when you didn't interact with it at all!

@yesyoureracist — This bot retweets any tweet that starts with the phrase "I'm not racist, but…" The results are always racist.

@_grammar_ — A bot that corrects you're your grammar.

This is the kind of bot we'll be making in this tutorial. Let's get started.

How to make a twitter bot...

I don’t really like twitter — it's reinforces toxic behaviour and is complicit in the downfall of democracy. So we're going to make a twitter bot that helps people quit twitter

Our twitter bot will find people who seem like they're on the edge of quitting twitter, and will give them encouragement and the instructions on how to do it.

Getting Started (non-coding bit)

Create an account

First you’ll need a twitter account for your bot. If you already have one, great. Otherwise go to twitter.com and follow the normal steps for making an account.

Create a developer account

You’ll also need to signup for a developer account. It doesn’t take long, just follow the instructions below…

  1. Navigate to https://developer.twitter.com/en/apply/user.html

  2. Click Apply (if you’re not logged into your twitter account, you’ll be asked to now.)

  3. Fill out the form. It contains a few steps including, why you want to join the twitter developer program, details about you, and the intended use of your bot.

  4. Create an app, navigate to ‘apps’ in the dropdown under your username it will take you to the apps page. Then click, ‘create an app.’ Fill out the form on the create and app page. It contains some repetitive information.

  5. Once you’ve created your app. You’ll be taken to the app details page. Click on “keys and tokens,” then generate consumer api keys, and access tokens. We’ll need all four tokens in a minute.

That’s the non-coding bit out of the way.

Coding our twitter bot

Running a node.js server.

Now you’ll need to set up a server running node.js If you don't know node.js you'll need to get familiar with it before we continue. There are lots of tutorials out there that cover how to make a basic node server.

Javascript is normally used just for front-end web development, for building functionality on a web page. Node allows us to use javascript, a language front-end developers are familiar with, on the back-end.

If you want to run your server for free, I recommend using a service like Heroku.

Installing and setting up twit

First install the twitter Api Client for Node. In your terminal type

npm install twit —save

We'll be making our twitter bot in one file called app.js

First require 'twit' and create an instance of twit with your twitter app's keys and tokens.

var Twit = require(‘twit’)

var T = new Twit({
    consumer_key:'<your consumer key>',
    consumer_secret:'<your consumer secret>',
    access_token:'<your access token>',
    access_token_secret:'<your access token secret>'
});

That’s the initial variables set up. Now we need to write the code that will run while our twitter bot is active.

When our node server starts, we need it to connect to twitter and verify itself with the credentials we defined above.

T.get('account/verify_credentials', {
    include_entities: false,
    skip_status: true,
    include_email: false
}, onAuthenticated)


function onAuthenticated(err) {
    if (err) {
        console.log(err)
    } else {
    console.log('Authentication successful.')
    }
}

// Once we're authenticated we run the onAuthenticated function, which we'll use now to send a tweet to test our bot.

Sending our first tweet

Let's see if we can get the bot to tweet. We’ll create a tweet function and test it by having it tweet 'hello world' after it's authenticated with twitter.

function onAuthenticated(err) {	  
    sendTweet()
}

function sendTweet(){
    T.post('statuses/update', {
        status:'hello world'
    })
}

Okay, now run your node app. Hopefully it worked and you’ll see that your twitter account has tweeted ‘hello world.’

Monitoring Tweets

Now, we want our bot to reply to people based on what they tweet. To do that we need to start monitoring tweets, twitter gives us a way to do this — the streaming api. It sends us a stream of tweets based on a set of words or phrases.

const termsToTrack = ['leave twitter', 'quit twitter', 'delete twitter']
function onAuthenticated(err) {

    var stream = T.stream('statuses/filter', {
        track:termsToTrack, 
        tweet_mode:'extended' 
    })

    stream.on('tweet', function (tweet) {
        console.log(tweet.text)
    }
}

Here I’ve chosen to use the phrases 'leave twitter', 'quit twitter', 'delete twitter'.

Now, we can log all the tweets we’re receiving in the console. See how many there are?! We’re getting more than a tweet per second. All that #maga streaming across your console? That’s twitter!

Twitter doesn't filter the tweets as as accurately as we’d like, so we'll need to check each of these tweet for exact phrases we want to match. (If we replied to all of these tweets, we’d get banned in an instant.)

We also want to make sure we don't reply to retweets or to any tweets sent by our own bot too.

stream.on('tweet', function (tweet) {

// We perform some checks before we send anyone a tweet.
if(
// We don't want our bot to reply to retweets
    !tweet.retweeted_status
    &&
// It's important that our twitter bot doesn't respond to itself.
// So we check if the tweet is from our handle
    tweet.user.screen_name !== handle
    &&
// The twitter stream api send us a lot of tweets that aren't exact matches of our text
// so we double check with a function
    isTweetExactMatch(tweet.text)

){
// If the tweet matches all the above criteria, we send our reply
// Note - here the tweet parameter refers to the tweet we're replying to.
        sendReply(tweet)
     }
  })
}

// A function to check if the tweets have exact matches for our search terms.
function isTweetExactMatch(text){
    // Make sure the text is in lowercase
    text = text.toLowerCase()
    // Check if tweet contains an exact match of the phrases we're looking for.
    return termsToTrack.some(term => text.includes(term))
}

Now let's get it to tweet a reply whenever somebody tweets a tweet with one of our target phrases.

Tweeting a reply

To send a reply to a tweet, you’ll need to add the handle of the account you want to reply to, to the text of your tweet.

You’ll also need to include the unique ID of the tweet you’re replying to.

Also, we don't want our bot to tweet the same thing all the time, so we're also going to create an array of replies and pick one at random when we respond.

Our bot's response will contain the handle of the account we're replying to , a random response from our array , and then instructions on how to quit twitter.

const replies = [
// an array containing all of our replies
]
		
function sendReply(tweet){
		
// get the screen name of the twitter account - we'll need to prepend our response with this in order to reply.
var screenName = tweet.user.screen_name
		  
// All our tweets will have the same instructions on how to quit twitter
const instructions = '\n\r\n\rsettings → scroll to the bottom of the page → deactivate your account → deactivate'
		  
// Now we create the reply - the handle + a random reply from our set of predefined replies + the instructions on how to quit
var response = '@' + screenName + ' ' + replies[Math.floor(Math.random() * replies.length)] + instructions
		
    T.post('statuses/update', {
        // To reply we need the id of tweet we're replying to.
        in_reply_to_status_id:tweet.id_str,
        // Status is the content of the tweet, we set it to the response string we made above.
        status:response
        // After we tweet we use a callback function to check if our tweet has been succesful.
    }, onTweeted)
}

testing the bot

We’ve already made sure our bot doesn’t reply to itself. (As this could cause an infinite loop and ultimately get it banned from twitter.)

To test your twitter bot, use a different account (maybe just ask a friend) and tweet something with one of the terms you want to match.

Release your bot into the wild.

Does your bot work? Great. Time to release it to the public. You can check out @qwitterbot here.

Bonus Round — Updating our profile if our bot gets rate limited.

Twitter has a limit on how many tweets your bot can send. You can read more about rate limits here: https://developer.twitter.com/en/docs/basics/rate-limiting

Your bot can tweet 15 tweets every 15 minutes — if you tweet more than that, your bot will be temporarily disabled.

You might want to let people know that your bot has been disabled, to do that we use the callback function on our tweet function. If it responds with an error, we check what caused the error.

If that error code is 88 we know it's because we've reached our rate limit. We can update our profile name and description to let people know.

We also want to update the profile if the bot is no longer disabled.

First we create a global variable named isAsleep and set it to false. Then we write our function…

let isAsleep = false
	
// Check if our tweet has been successful, if we've reached our rate limit, let people know that our bot is asleep.
function onTweeted(err) {
    if (err !== undefined) {
        console.log(err)
	if(err.code === 88){
	    console.log('rate limit reached')
            T.post('account/update_profile', {
	        name:'Qwitter Bot 💤',
	        description: 'I\'ve helped too many people quit twitter and have reached my rate limit. Try again later.'
	    }, onTweeted)
            isAsleep = true
        }
    } else {
        if(isAsleep){
        isAsleep = false
        T.post('account/update_profile', {
            name:'Qwitter Bot',
            description: 'I\'m a bot that helps you quit twitter. I appear only when I am needed most'
        }, onTweeted)
    }
  }
}

If you found this tutorial useful (or not), please let me know. (it's the first coding tutorial I've ever written, so any feedback is highly appreciated)

And of course, send me your twitter bots!

first published — 26 October 2019
last update — 31 October 2019