How to build a complete Twitter autoresponder in less than 100 source lines of code with Autohook
Tags: twitter, api, webhooks, javascript
Published: 2019-08-26 23:17:54

---
title: How to build a complete Twitter autoresponder in less than 100 source lines of code with Autohook
published: true
description: Autohook allows to setup your webhooks with zero configuration, so you can focus less on boilerplate and more on building awesome things. Learn how to build a DM autoresponder in no time.
tags: twitter, api, webhooks, javascript
cover_image: https://thepracticaldev.s3.amazonaws.com/i/hjebj9c5eqrjq8uc9ghd.jpg
---

_This tutorial was originally published in the [Twitter Developer](https://developer.twitter.com/en/docs/accounts-and-users/subscribe-account-activity/guides/twitter-account-activity-tutorial-autohook?utm_source=autohook_tutorial_devto&utm_medium=devto&utm_campaign=autohook_tutorial) website_

The [Account Activity API](https://developer.twitter.com/en/docs/accounts-and-users/subscribe-account-activity/overview.html?utm_source=autohook_tutorial_devto&utm_medium=devto&utm_campaign=autohook_tutorial) is one of the most versatile APIs in the Twitter Developer Platform. With this API, people can allow your app to get notifications about their activity on Twitter. What’s best, it uses webhooks to deliver real time updates.

Developers can achieve a lot with the Account Activity API. For example, companies can use this API to get a sense of how the global conversation is unfolding around their products and services. A popular use case is with customer service, where your favorite brands can reply to your Direct Messages in real time, and determine the best next action. This usually involves using the Account Activity API, configuring a webhook, figuring out OAuth, and understanding how to send back a message using additional Twitter APIs.

This would sound like quite the task, if you didn’t have the right tools. Thankfully, [Autohook](https://github.com/TwitterDev/autohook) is here to make things extremely easy for you.


Autohook is a Node.js module and a command line tool that sets up webhooks for you. This way, you can spend zero time figuring out how a webhook works and instead focus on building awesome things on Twitter.

Autohook makes things very easy — so easy that you can automate a DM conversation on Twitter in less than 100 lines of code. We’ll build a simple autoresponder that’ll greet whoever Direct Messages your user. Here’s what we’re going to do:

- We’ll set up a project, including a Twitter app enabled with an Account Activity environment
- We’ll set up Autohook, so it will do all the hard work for us
- We’ll build the logic to only respond to incoming Direct Messages
- We’ll add a way to show messages as read
- We’ll show a typing indicator before sending the message
- We’ll send back a sample autoresponder message


# Your Twitter app

First things first: in order to use Twitter’s Account Activity API, you will need to create an app on Twitter, and give it the **Read, write, and Direct Messages** permission. You also need to have a valid development environment assigned to this app. Chances are you’ve already done this: if so, you should see something like this in your [dev environments](https://developer.twitter.com/en/account/environments) page:

![](https://thepracticaldev.s3.amazonaws.com/i/1jqk0v444qie07dubjph.png)

If you don’t already have a dev environment created, simply click **Set up dev environment**, type a label and assign it to an app. The label can be anything, but make sure you remember it because you’re going to need it for later.

You will need to get your access tokens from your [Twitter app dashboard](https://developer.twitter.com/en/apps). From the app that contains the environment you just created, click **Details**, then click **Keys and tokens**. Make a note of the values reported under:

- API key
- API secret key
- Access token
- Access token secret


Create a file in your home folder called `.env.twitter`, and add the values you found in that page, plus your environment label:

```bash
TWITTER_CONSUMER_KEY=Details ➡️ API key 
TWITTER_CONSUMER_SECRET=Details ➡️ API secret key 
TWITTER_ACCESS_TOKEN=Details ➡️ Access token 
TWITTER_ACCESS_TOKEN_SECRET=Details ➡️ Access token secret 
TWITTER_WEBHOOK_ENV=Your env label
```

Developers are often confused by consumer keys and access tokens. Long story short, think of those as if they were encrypted username and passwords. A consumer key/secret pair are identify your app, while access tokens are user credentials. This means your consumer key/secret do not change, but your access token/secret changes based on the user who’s authenticating with your app.

![This images shows that different users authenticate using different access tokens, while the consumer key and secret are always the same, because they belong to the authenticating app.](https://thepracticaldev.s3.amazonaws.com/i/cmlnvlfrxyc1ss2hvmdz.png)


You’ve probably noticed that if you’re the owner of your own app, `TWITTER_ACCESS_TOKEN` and `TWITTER_ACCESS_TOKEN_SECRET` identify yourself. If that’s the case, you don’t really have to go through OAuth to identify yourself – we already generated those tokens for you (keep that in mind, it’s going to come in handy later).

# Install Autohook
Next, we’ll install Autohook. Its package is available from both npm and Yarn.

```bash
npm i -S twitter-autohook
```

I almost wish there were more steps, but that’s it. Autohook is that easy!

# Create a new project
We’ll start with a new project. We’re setting it up in your home folder, but naturally it can live anywhere:

```bash
mkdir ~/autohook-tutorial
cd autohook-tutorial
```

Let’s create a file named `index.js`. We’ll add code to call Autohook and make sure everything is configured as intended. Just so we can start with a clean environment, this code will remove all existing webhooks from your environment. If you don’t want to lose your existing webhooks, choose a different dev environment from your developer dashboard. As an alternative, you can remove the call to `removeWebhooks()`, and replace `start()` with `startServer()`.

{% gist https://gist.github.com/taniele/101a25f4357f454d69b924f533125e0e file=index-step1.js %}

Save and run your file. You should see something similar to this (note that your URL will be different, and so will be your subscribing username):

```bash
$ node index.js
Getting webhooks…
Removing webhooks…
Removing https://ce085a0d.ngrok.io/webhook…
Registering https://e3fd0ff6.ngrok.io/webhook as a new webhook…
Webhook created.
Subscribed to i_am_daniele's activities.
```

Behind the scenes, Autohook handled OAuth for us. It also ran a development server with logic to create a webhook and to validate the [CRC signature](https://developer.twitter.com/en/docs/accounts-and-users/subscribe-account-activity/guides/securing-webhooks?utm_source=autohook_tutorial_devto&utm_medium=devto&utm_campaign=autohook_tutorial). And because we provided your access token/secret, it also subscribed your app to listen to your user’s activity (it did come in handy)!

What can go wrong at this point? The most common pitfall is that the authenticating user won’t authenticate. Remember, users need to authorize your app before it can access their activity; if you’re trying to authenticate a test user (or even better, if you’re asking a friend to help you test your app), make sure they’re authenticating using Sign In With Twitter and the [3-legged OAuth flow](https://developer.twitter.com/en/docs/basics/authentication/overview/3-legged-oauth.html?utm_source=autohook_tutorial_devto&utm_medium=devto&utm_campaign=autohook_tutorial). Autohook’s got your back – you can find a [sample implementation on the project’s page](https://github.com/twitterdev/autohook/blob/master/test/listen.js).


If you bump into an error, most likely your credentials are not set correctly; check your `.env.twitter` and try again. If you’re still stuck, come visit the [Twitter Community forums](https://twittercommunity.com) and we’ll be more than happy to help you out!

# Detect and filter incoming events
Now that Autohook took care of the underlying wiring, it’s time to focus on our app logic. The Account Activity API can ping your webhook with [many activity types](https://developer.twitter.com/en/docs/accounts-and-users/subscribe-account-activity/overview.html?utm_source=autohook_tutorial_devto&utm_medium=devto&utm_campaign=autohook_tutorial), so it’s important we only react to the activity type related to an incoming message.

Since you’re using Autohook, you can listen to an incoming event listener – The event name is just `event`. Add this right before the call to `removeWebhooks()`:


{% gist https://gist.github.com/taniele/101a25f4357f454d69b924f533125e0e file=index-step2.js %}

If you run your code now, nothing may seem to happen at first. But try and like a Tweet and something like this will show up in your Terminal:

```js
You received an event! { for_user_id: '102010879991606016',
  favorite_events:
   [ { id: '92274d54c83ff07669999a00cad3e835',
       created_at: 'Fri Aug 02 21:54:13 +0000 2019',
       timestamp_ms: 1564782853144,
       favorited_status: [Object],
       user: [Object] } ] }
```

Because your app subscribed to your user’s activities, we received that activity in realtime. The object is always starts with `for_user_id`, which indicates a user ID (if you subscribe to multiple users, this is how you know which user this activity belongs to). The actual activity is described by a dictionary key. In this case, we received a key named `favorite_events` because we just liked a Tweet. There are many activities, like `tweet_create_events`, `follow_events`, and `direct_message_events` just to mention a few. In Autohook, these values will all be event keys in your event object from the listener. So if we want to listen to direct messages only, all we have to do is to explicitly detect those events:

```js
webhook.on('event', async event => {
      if (event.direct_message_events) {
        await sayHi(event);
      }
    });
```

{% gist https://gist.github.com/taniele/101a25f4357f454d69b924f533125e0e file=index-step3.js %}

In this case, we will only process direct message events, and we’ll send the details to a function named `sayHi()`. This function will process the event and shoot a DM back waving hi to any incoming direct message!

# Say hi 👋
We'll create a message to wave hi back to our friend who just messages us. But how do we know who’s the sender, and how can we be sure this message is directed to our account? Thankfully, the Direct Message event will contain full details about both parties involved in the conversation. You already have the OAuth credentials of the recipient (yourself), which is all you need to send a message back by means of `sayHi()`. The logic for this function is straightforward:

- We’ll double check that the Direct Message event is valid and was intended for to your user. You don't really need to do this since this code will only work with your user credentials, but it will be useful to implement in case you want to expand your code to make it say hi for other accounts.
- We’ll only listen to incoming messages (outgoing messages generate an activity too, and we want to filter those out otherwise we’ll run into an infinite loop).
- We’ll say hi!

To check that the message is valid, we’ll need to check that the message object exists and contains a `message_create` key. This key contains all the relevant details about the message, including the sender and recipient IDs, and the message itself. We’ll also check the sender and recipient’s details, and if they’re the same, it means you are sending a message to yourself. If this happens, the autoresponder we’ll say hi to you, which in turn will cause the autoresponder to say hi to you, which in turn will cause the autoresponder to say hi to you… causing an infinite loop. It’s actually easier done than said:

```js
  // We check that the message is a direct message
  if (!event.direct_message_events) {
    return;
  }

  // Messages are wrapped in an array, so we'll extract the first element
  const message = event.direct_message_events.shift();

  // We check that the message is valid
  if (typeof message === 'undefined' || typeof message.message_create === 'undefined') {
    return;
  }

  // We filter out message you send, to avoid an infinite loop
  if (message.message_create.sender_id === message.message_create.target.recipient_id) {
    return;
  }

```

All we have to do next is to prepare the request body for the message reply and send it as using the Direct Messages API. The request body of this API has the exact [same format of an Account Activity message response](https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/guides/message-create-object?utm_source=autohook_tutorial_devto&utm_medium=devto&utm_campaign=autohook_tutorial), which makes it easy to consume and produce.

```js
  // Prepare and sent the message reply
  const senderScreenName = event.users[message.message_create.sender_id].screen_name;

  const requestConfig = {
    url: 'https://api.twitter.com/1.1/direct_messages/events/new.json',
    oauth: oAuthConfig,
    json: {
      event: {
        type: 'message_create',
        message_create: {
          target: {
            recipient_id: message.message_create.sender_id,
          },
          message_data: {
            text: `Hi @${senderScreenName}! 👋`,
          },
        },
      },
    },
  };
  await post(requestConfig);

```

{% gist https://gist.github.com/taniele/101a25f4357f454d69b924f533125e0e file=index-step4.js %}

This is it! Run your code and ask a friend to send you a message. You should see an incoming message, followed by an automated direct message:
![](https://thepracticaldev.s3.amazonaws.com/i/hi0fh9cnpe78bnhukshz.png)

# Mark as read and typing indicator

Our code so far is about 80 lines of code, so we have plenty of room to implement all the fancy things an autoresponder can do. Direct Messages on Twitter can indicate when a message has been read (it’s the blue check next to the message timestamp). Since our autoresponder will read an incoming message for us, it would be nice to tell the sender our autoresponder read our message and that it’s about to reply.

![](https://thepracticaldev.s3.amazonaws.com/i/ijqboew0delmehgvscy6.png)

Because the message body doesn’t have to be sophisticated, you will send these POST requests as form encoded, rather than sending raw JSON data like we did before. 

To get the read check mark, we’ll simply extract the message ID from the activity we received earlier. Just like before, we’ll create the appropriate request body to send it to the [Mark Read](https://developer.twitter.com/en/docs/direct-messages/typing-indicator-and-read-receipts/api-reference/new-read-receipt?utm_source=autohook_tutorial_devto&utm_medium=devto&utm_campaign=autohook_tutorial) endpoint:

```js
async function markAsRead(messageId, senderId, auth) {
  const requestConfig = {
    url: 'https://api.twitter.com/1.1/direct_messages/mark_read.json',
    form: {
      last_read_event_id: messageId,
      recipient_id: senderId,
    },
    oauth: auth,
  };

  await post(requestConfig);
}
```

Similarly, we’ll now display a typing indicator which will present in the Direct Message window as a bubble with three dots. Since this is just an animation, there is no message attached to it; we will simply need to pass the ID of the person we want to show this bubble to the [Indicate Typing API call](https://developer.twitter.com/en/docs/direct-messages/typing-indicator-and-read-receipts/api-reference/new-typing-indicator?utm_source=autohook_tutorial_devto&utm_medium=devto&utm_campaign=autohook_tutorial).

```js
async function indicateTyping(senderId, auth) {
  const requestConfig = {
    url: 'https://api.twitter.com/1.1/direct_messages/indicate_typing.json',
    form: {
      recipient_id: senderId,
    },
    oauth: auth,
  };

  await post(requestConfig);
}
```

You're all set! The complete code should look like this:

{% gist https://gist.github.com/taniele/101a25f4357f454d69b924f533125e0e file=index.js %}

# Time to say bye
And there you have it! Because you didn’t have to deal with the complexity of webhooks and authentication, you may have noticed that you just wrote the entire code in less than 100 lines! This has been a quick and easy way to explore the power of the Account Activity API, and a great starting point for your next 100 lines of code.