🤖 I Was Bored, so I made a fun little Twitter bot
Tags: tutorial, bot, javascript, webdev
Published: 2020-05-25 20:28:37

_This article was first published on [my blog](https://words.mjsarfatti.com/i-was-bored-so-i-made-a-fun-little-twitter-bot) 🔗_

Two things happened tonight as I was logging off work:

1. I still felt a good level of mental energy and capacity
2. I realized most tutorials for people learning web-dev are **boring**

So I thought to myself: wouldn't it be nice if there was a resource that collected the fun-nest and most interesting tutorials out there? And since I am investing more and more on Twitter, I settled on making this a 🤖 Twitter bot: [@_andfun](https://twitter.com/_andfun).

{% twitter 1264984261637091330 %}

The whole thing took me only a couple of hours. It's amazing what we can do with technology today!

So let's dive right in and see what it takes to make a simple bot, step by step 👇

## 1. I like Airtable

I decided to host my curated list of tweets on [Airtable](https://airtable.com/), because it's fun and easy. The _base_ is a very simple table with the URL to the tutorial, a hand-written text for the tweet, a helpful character counter and a field to set the date on which I wish the tweet to be published.

![Screenshot of the Airtable base](https://dev-to-uploads.s3.amazonaws.com/i/ndjxbi18avm7lse5e2wx.png)

Since I plan to only tweet once a day I made a separate view, called **Today** (the one screenshotted is **Grid view**), filtered to list only the tweets with the "Post On" column equal to `TODAY()`. Which will actually be only one tweet. You'll see how this comes handy later on.

## 2. I also like Glitch

While I've never used [Glitch](https://glitch.com/) before, I found out there is [a project](https://glitch.com/edit/#!/twitterbot?path=README.md%3A1%3A0) that you can easily fork (or, _remix_, in Glitch slang) aptly named **twitterbot**. The project is written in JavaScript, which is very nice since Airtable provides a useful little **npm** package to work with its APIs.

## 3. But first: Twitter apps

Before going forward, I needed to create a new Twitter account for my bot, and a new Twitter app. **twitterbot**'s README file points to a well made resource for this ([How to create a twitter app](https://botwiki.org/tutorials/how-to-create-a-twitter-app/)), so I won't repeat the steps here. Just a couple of notes:

1. I needed a new email. I submitted a modified version of my personal email, in the form: [myactualgmailaccount]+twitterbot@gmail.com. It's awesome: it's a different email address, but it gets automatically redirected to my main account (everything after the `+` sign is effectively ignored).
2. I also had to provide and validate a real phone number. Just so you know if you try this.


## 4. Creating the Twitter profile

I wanted something fun and cute. I found the perfect robot face on [Flaticon](https://www.flaticon.com/free-icon/android_1462493). it's a great resource for illustrations and icons, some are free (with attribution), others come with a paid subscription. For the background I screenshotted a frame from this super cool [gradient generator](https://grad.superhi.com/).

## 5. Putting it all together

With the Twitter profile ready, and the Twitter app approved (it took only a few seconds for Twitter to approve my app), it was time to get my hands dirty. Luckily, Airtable provides a well made API with very good [docs](https://airtable.com/api).

The Glitch template also provides a `server.js` file skeleton, and it wasn't too hard to put the two together. Here is my full code:

```js
// File: server.js

/* Setting things up. */

const express = require("express"),
  app = express(),
  Twit = require("twit"),
  config = {
    /* Be sure to update the .env file with your API keys. See how to get them: https://botwiki.org/tutorials/how-to-create-a-twitter-app */

    twitter: {
      consumer_key: process.env.TWITTER_CONSUMER_KEY,
      consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
      access_token: process.env.TWITTER_ACCESS_TOKEN,
      access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
    }
  },
  T = new Twit(config.twitter);

/* Set up connection to Airtable base */

const base = require("airtable").base("[yourbaseid]");

app.use(express.static("public"));

/* Using cron-job.org to periodically visit /BOT_ENDPOINT to wake up the app and make Twitter bot tweet. */

app.all(`/${process.env.BOT_ENDPOINT}`, function(req, res) {
  base("Tweets")
    .select({
      /* Selecting the first record in "Today" (it should only be one anyway) */

      maxRecords: 1,
      view: "Today"
    })
    .firstPage(function(err, records) {
      if (err) {
        console.log("airtable error!", err);
        res.sendStatus(500);
      }

      /* This will only actually run once */

      records.forEach(function(record) {
        const URL = record.get("URL");
        const text = record.get("Tweet");

        T.post("statuses/update", { status: text + "\n\n" + URL }, function(
          err,
          data,
          response
        ) {
          if (err) {
            console.log("error!", err);
            res.sendStatus(500);
          } else {
            res.sendStatus(200);
          }
        });
      });
    });
});

let listener = app.listen(process.env.PORT, function() {
  console.log("Your bot is running on port " + listener.address().port);
});
```

I made sure to also update the `.env` file with:

1. My Twitter API tokens
2. The secret endpoint that will trigger a Tweet (keep it secret, you don't want randoms to be able to trigger it just by visiting a URL)
3. My Airtable API token

## 6. Time to test 🙌

I added mw first tweet to the Airtable (making sure it had the date of today), and visited my endpoint (yes, a regular browser will do!). The endpoint looks something like https://[my-glitch-project-name].glitch.com/[the-super-secret-endpoint].

I saw an `OK`, and my bot's account had just tweeted it's very first tweet!

## 7. One last thing

Now, I still needed to automate this though, right?

It was simple: I opened a free account on [cron-job.org](https://cron-job.org/) and activated a new cron job to run daily at 3pm (European time, which would be morning US time). The job simply calls the endpoint (see above), and the endpoint will tweet the tweet of the day according to what's on my Airtable.

![Screenshot of cron-job.org setup](https://dev-to-uploads.s3.amazonaws.com/i/leebjg5o7z042pxaldvr.png)

Tadaaaa 🎉

---

I hope that you found this interesting, and saw how making a Twitter bot is approachable and requires very little code to get started. Are you going to try? Let me know what your bot will tweet about!

So, follow 👉 [@_andfun](https://twitter.com/_andfun) and let's be friends on Twitter ([@mjsarfatti](https://twitter.com/mjsarfatti), DMs are open) and on [dev.to](https://dev.to/mjsarfatti).

If you'd like to be notified of the next article, you can subscribe to my [email list](https://buttondown.email/mjsarfatti). No spam ever, cancel anytime, and never more than one email per week (most probably fewer).