How to Create Your Own Auto Direct Message Twitter Bot for Free

Engaging with your Twitter audience is crucial for building a following and promoting your brand. One effective tactic is setting up an auto direct message (DM) that welcomes new followers and encourages them to check out your content. Rather than paying for this service, you can build your own Twitter auto DM bot for free!

In this guide, we‘ll walk through how to create a Node.js Twitter bot that automatically sends a customized welcome DM to each new follower. No prior bot-building experience is required, and the bot can be up and running in just a few steps. Let‘s get started!

Overview of the Twitter Auto DM Bot

Our auto DM bot will use the Twitter API to watch for new follower events. When someone follows the account, the bot will send them a personalized welcome message via DM. The DM can include text, links, and even buttons using Twitter‘s Quick Reply feature.

To interact with the Twitter API, we‘ll use the excellent twit library in Node.js. Twit makes authenticating with the Twitter API and sending DMs easy. We‘ll deploy our bot to Heroku so it can run 24/7 for free.

Here‘s a high-level look at how the bot will work:

  1. Listen for new follower events via Twitter‘s streaming API
  2. When a new follower is detected, generate the welcome message
  3. Send the welcome message to the new follower via DM
  4. Handle any errors and log events for debugging

With this basic flow in mind, let‘s set up our development environment and start building!

Creating Your Twitter Bot

Follow along with the steps below to create your own Twitter auto DM bot.

Step 1: Set Up Your Environment

First, make sure you have Node.js and npm (node package manager) installed on your machine. You can download Node.js from the official site if you don‘t have it installed.

Next, create a new directory for your bot project:

mkdir twitter-bot 
cd twitter-bot

Initialize a new Node.js project and install the twit dependency:

npm init
npm install twit --save

Answer the prompts from npm init to set up your project. You can accept the defaults for most of the options.

Step 2: Create a Twitter App

To authenticate our bot with the Twitter API, we need to create a Twitter app. Follow these steps:

  1. Go to the Twitter Developer site and click "Create an app"
  2. Fill in your app details. The app name, description and website can be anything you want. Use a unique name that isn‘t already taken.
  3. For the Callback URL field, enter: http://127.0.0.1:3000
  4. Check the Developer Agreement box and click "Create"
  5. Navigate to the "Keys and Tokens" tab and take note of your Consumer API keys and Access token & access token secret. We‘ll need these to authenticate with the Twitter API.
  6. On the Permissions tab, make sure "Read, Write, and Direct Message" is selected so the bot has permission to send DMs.

Congrats, you‘ve created your Twitter app! Now let‘s use those API keys in our bot.

Step 3: Authenticate with the Twitter API

Create a new file named .env in your project directory and add your Twitter app‘s API keys:

TWITTER_CONSUMER_KEY=your_consumer_key
TWITTER_CONSUMER_SECRET=your_consumer_secret
TWITTER_ACCESS_TOKEN=your_access_token 
TWITTER_ACCESS_TOKEN_SECRET=your_access_token_secret

Replace the placeholder values with your actual keys and tokens.

Next, create a new file named bot.js. We‘ll write our bot code here. Start by requiring the dependencies and creating a new twit instance:

require(‘dotenv‘).config();
const twit = require(‘twit‘);

const bot = new twit({
  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
});

The dotenv library loads the environment variables from our .env file. We use these to create a new twit instance that‘s authorized to make requests to the Twitter API on behalf of our app.

Step 4: Listen for New Follower Events

To send auto DMs, we first need to know when someone follows the bot‘s account. We can use Twitter‘s streaming API to listen for follow events in real-time.

Add this code to your bot.js file:

const stream = bot.stream(‘user‘);

stream.on(‘follow‘, onNewFollower);

function onNewFollower(event) {
  const screenName = event.source.screen_name;
  const userId = event.source.id;

  console.log(`New follower: @${screenName} (ID: ${userId})`);
  // TODO: generate and send welcome DM
}

Here we create a new stream that watches for events on the authenticated user‘s account. We listen for ‘follow‘ events and trigger the onNewFollower function when one occurs.

The onNewFollower function receives the follow event object which contains info about the new follower, including their user ID and screen name. We log this info for now.

Step 5: Generate the Welcome DM

Next, let‘s generate the actual message we want to send to new followers. You can customize this to include whatever text, emojis, and links you want.

For this example, we‘ll use a simple template that includes the user‘s name and a link to our website:

function generateWelcomeDM(screenName) {
  const msg = 
    `Hi @${screenName} 👋

Welcome to my Twitter account! I‘m so glad you followed me. 

Be sure to check out my website here: https://my-cool-site.com

Feel free to DM me any time if you have questions!

- Your Name`;

  return msg;
}

You can get as creative as you want with your welcome message. Just keep in mind Twitter‘s DM character limit and terms of service.

Step 6: Send the Auto DM

With our message generated, the final step is actually sending the DM to the new follower. Update the onNewFollower function to call sendDM:

function onNewFollower(event) {
  const screenName = event.source.screen_name;
  const userId = event.source.id;

  const welcomeDM = generateWelcomeDM(screenName);

  sendDM(userId, welcomeDM);
}

function sendDM(userId, msg) {
  bot.post(‘direct_messages/new‘, {
    user_id: userId,
    text: msg
  }, (err, data, response) => {
    if (err) {
      console.error(`Error sending DM: ${err}`);
    } else {
      console.log(`Successfully sent DM to user ${userId}`);
    }
  });
}

The sendDM function uses twit‘s post() method to send a new DM to the specified user ID. We pass the generated welcome message as the text parameter.

The callback function logs any errors and a success message. This is helpful for debugging if the bot isn‘t working as expected.

That‘s it! You now have a fully functional auto DM Twitter bot. Let‘s test it out.

Step 7: Running the Bot

To start the bot, run this command in your terminal:

node bot.js

You should see output like:

Welcome message bot is running...

Now, try following your bot‘s Twitter account. You should receive the welcome DM within a few seconds! Check the bot‘s console output and Twitter DMs to confirm it‘s working.

Deploying Your Bot to Heroku

So far we‘ve been running the bot locally on our own machine. But to have it send auto DMs around the clock, we need to deploy it to a server.

One easy (and free) option is Heroku. Heroku lets you deploy Node.js apps with just a few commands.

If you don‘t have a Heroku account, sign up for a free one at https://signup.heroku.com/. Then follow these steps to deploy the bot:

  1. Install the Heroku CLI by following the instructions at https://devcenter.heroku.com/articles/heroku-cli
  2. In your project directory, run heroku login and enter your credentials
  3. Run heroku create to create a new Heroku app
  4. Add your Twitter API keys as config vars:
    heroku config:set TWITTER_CONSUMER_KEY=your_consumer_key 
    heroku config:set TWITTER_CONSUMER_SECRET=your_consumer_secret
    heroku config:set TWITTER_ACCESS_TOKEN=your_access_token
    heroku config:set TWITTER_ACCESS_TOKEN_SECRET=your_access_token_secret
  5. Commit your code to git:
    git init
    git add .
    git commit -m "Initial commit"
  6. Push your code to Heroku:
    git push heroku master
  7. Scale the app‘s worker dyno:
    heroku ps:scale worker=1

Your bot is now deployed and running in the cloud! It will automatically restart if it crashes and scale to handle any load.

To view the bot‘s output, you can use Heroku‘s log command:

heroku logs --tail

Next Steps

Congrats, you‘ve built and deployed your own Twitter auto DM bot! Let‘s look at some ways to extend it further:

  • Customize the welcome message with richer content like images, GIFs, or QR codes
  • Add buttons to your DM using Quick Replies
  • Store welcomed user IDs in a database to avoid sending duplicate DMs
  • Extend the bot to perform additional functions like retweeting or answering FAQs
  • Run the bot on a free AWS EC2 instance for more control

I hope this guide has been helpful for getting started with Twitter bots and Node.js development. The code for this bot is available on GitHub – feel free to fork and customize it!

If you have any questions or feedback, let me know. Happy bot building!

Similar Posts