How to write a Twitter bot in no time

I had recently played with the idea of creating a twitter bot, not for any specific reason but to see how hard or easy that would be. And to do something that would put a bit of fun into the experience I decided to make a bot that would create nice tweets with emoji of bugs. Here is an example:

It turned out that creating such a bot is a no time consumer when done in JavaScript with Node. The result of my experiment is available here: https://twitter.com/emojibugs.

This article explains the necessary steps to build a simple Twitter bot that posts messages periodically, at some pre-defined interval.

Twitter account and app

The first thing to start with is a Twitter account. This could be either an existing account or a new one.

After setting up the account the bot should be tweeting on behalf of you need to go and create an application. That can be done from https://apps.twitter.com/. You need to create a new app, provide a name, description, website and other optional ones.

After the app is created you need to go to Keys and Access Tokens and generate them for the application. These will be used later on to sign it to Twitter from the bot, and specifically:

  • Consumer key (API key)
  • Consumer secret (API secret)
  • Access token
  • Access token secret

NOTE: should these keys and secrets be compromised new ones can be generated (which invalidates the previous ones).

Creating a bot in JavaScript

A very simple solution for a simple bot like this is creating a Node package in JavaScript. Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine that enables running JavaScript code outside the browser. Node comes with npm, which is a package manager for JavaScript.

Download and install Node.js: https://nodejs.org/en/
Learn more about npm: https://www.npmjs.com/

There is a Node package for the Twitter client API. It’s called twit and is very easy to use. The following is the only JavaSCript code you need to write to post a new tweet with the text “hello world!” on the registered account.

var Twit = require('twit');
 
var T = new Twit({
  consumer_key:         '...',
  consumer_secret:      '...',
  access_token:         '...',
  access_token_secret:  '...',
});
 
T.post(
  'statuses/update', 
  { status: 'hello world!' }, 
  function(err, data, response) {
    console.log(data)
  });

What you need to do here is fill in the API key and secret and the access token and secret with the ones generated for your app.

Creating a Node package

To create a new package go to an empty folder where you want to locate the package and run the npm init command in a console. This will prompt you to provide some information (some of which are already filled in for you).

C:\demo\emojibugs>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
name: (emojibugs)
version: (1.0.0)
description: A bot that posts messages to Twitter.
entry point: (index.js) bot.js
test command:
git repository:
keywords: twitter bot app
author: Marius Bancila
license: (ISC) GPL-3.0
About to write to C:\Work\demo\emojibugs\package.json:

{
  "name": "emojibugs",
  "version": "1.0.0",
  "description": "A bot that posts messages to Twitter.",
  "main": "bot.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "twitter",
    "bot",
    "app"
  ],
  "author": "Marius Bancila",
  "license": "GPL-3.0"
}


Is this ok? (yes) yes

There result is a file called package.json that describes the Node package and its dependencies.

{
  "name": "emojibugs",
  "version": "1.0.0",
  "description": "A bot that posts messages to Twitter.",
  "main": "bot.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "twitter",
    "bot",
    "app"
  ],
  "author": "Marius Bancila",
  "license": "GPL-3.0"
}

To install the twit package for the Twitter client api run the following command in a console in the folder where the package is located:

npm install twit --save

The twit module and all its dependencies will be downloaded in this folder and the package.json file updated with the dependency:

{
  "name": "emojibugs",
  "version": "1.0.0",
  "description": "A bot that posts messages to Twitter.",
  "main": "bot.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "twitter",
    "bot",
    "app"
  ],
  "author": "Marius Bancila",
  "license": "GPL-3.0",
  "dependencies": {
    "twit": "^2.2.9"
  }
}

Writing the bot

When we created the Node package we specified that the entry point should be a file called bot.js. We need to create this and fill it with the following code:

var Twit = require('twit');
 
var T = new Twit({
  consumer_key:         '...',
  consumer_secret:      '...',
  access_token:         '...',
  access_token_secret:  '...',
});

// tweet at startup
tweetIt();

// tweet every 6 hours
setInterval(tweetIt, 1000 * 60 * 60 * 6);

function generateText() { }

function tweetIt() 
{
   T.post(
      'statuses/update',
      {
         status: generateText()
      },
      function (err, data, response) {
         if (err) {
            console.log("Something went wrong");
         } else {
            console.log("Tweet posted");
         }
      }
   );
}

The function generateText creates the text to be posted in a tweet. It can do anything and for the sake of this post its content is irrelevant. Function tweetIt does a status update with a text generated by generateText. This function is executed both when the package is run the first time as well as every six hours (a timer is created with setInterval).

Running the bot locally

You can run the script locally in two ways:

  • By running the following command:
    node bot.js
  • By adding a script to package.json and execuring that script.
    "scripts": {
        "start": "node bot.js",
        "test": "echo \"Error: no test specified\" && exit 1"
      },

    And then executing the following command:

    npm start

It’s done

That is all that is necessary for a Twitter bot to run and post to a Twitter account. Of course, there are things that have been let aside, such as how to generate the content of the message, how to host the bot on a cloud platform, or how to write a bot that does more that posting text, such as posting images, replying, etc. But some of that in the next article.

1 Reply to “How to write a Twitter bot in no time”

  1. Cool, thanks for writing this up. Now… are you going to show the modern C++ equivalent? 🙂

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.