My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
How to build a bot for Twitter in Node (20 lines)

How to build a bot for Twitter in Node (20 lines)

Frank Peña's photo
Frank Peña
·Jun 22, 2021·

2 min read

This is the expected result:

image.png

How the bot works?

When someone mentions your username, the bot is going to reply that tweet with a personalized message.

Requirements

  • VS Code

  • Nodejs installed

LET'S START:

Create an APP on Twitter:

Let's build the app:

  • Create a folder for our node app, let's called it "Twitter Bot"

  • Now, open the folder with VS Code.

We need to initialize our node project.

npm init

Let's install twit to use the Twitter API.

npm install twit
  • Add a new file called "index.js", this is going to be the entry point of our node app.
  • Inside the file, let's initialize twit with our credential (Twitter give you the credentials after you create the app, see above):
const Twit = require('twit');
const T = new Twit({
    consumer_key: "YOUR_CONSUMER_KEY",
    consumer_secret: "YOUR_CONSUMER_SECRET_KEY",
    access_token: "YOUR_ACCESS_TOKEN",
    access_token_secret: "YOUR_ACCESS_TOKEN_SECRET"
})

Now, we need to listen when someone mentions our username, and reply to that tweet:

var stream = T.stream('statuses/filter', { track:'@FrankPena_' }); //Change it for your username.

stream.on('tweet', function (tweet) {  //this event is called when someone make a tweet mention the user @FrankPena
    const user = tweet.user;
    const resposne = `Hi ${user.name}, how may I help you?`

    T.post('statuses/update', { status:resposne,in_reply_to_status_id:tweet.id_str }, function(err, data, response) {
        console.log(err)
      })

  })

To run our project, we just need to write in the terminal:

node ./index.js

Testing our bot

  • You just need to go to Twitter and make a tweet mention your username

image.png

and our bot it's going to response:

image.png

Conclusion

This is a simple Twitter bot that you can personalize and make great things, you just need to read the Twitter API documentation and see all the possibilities that Twitter offers you.