DEV Community


Building a Twitter Bot /w Node.js

Berat Bozkurt
I'm a freelance developer. I have a start-up. I love to open-source and coding
・3 min read

I wanted build a bot about Twitter for avoid manually tweeting the keywords I want. Because this is a very demanding and time consuming task. Am I not a developer? Why don’t I programming a bot and it doesn’t do these things for me? And I was started :)

We will use to 3 library for the bot.

In fact only Twit library is enough, but I included Node-cron and Express libraries for I wanted it to work constantly.

npm init -y

Let’s create the project with the code above. Later, let’s install the libraries I mentioned the above to our project and keep going.

Now we’re in the the twitter api creation section. I won’t explain this. Because you can find it on the google. This way you can create to API. Later create to api, let’s adding to config.js file on the project, and write to api keys and tokens here. File will be like this.

don’t forget to change to the XXX’s

Now, we will coding to the bot. For this, let’s import to install libraries and config file to our project.

const twiti = require(‘twit’);

const twit = new twiti(config);

You can connect the library as above.

in params object;

  • q: I access tweets that contain the word I want.
  • count: I determine how many tweets I will access.
  • result_type: I determine what type of results are.

I determine that I have made the tweets I want by making a request to search/tweets parameter with the twit.get function. There are also a few controls inside the function. If it passes these checks, I tweet and like.

If I talk about the logic here, firstly I’m accessing tweets that I want and doing controls in function. The controls are about that not reply or not retweet and I’m checking to just send one reply to a tweet. If it’s okay, i’m reply and like to the tweet. Totally like this.

Well, why are we using to express and node-cron libraries? I want the project to be running constantly on Heroku. For that reason, I built to web framework with express. I redirect to/ and I used to node-cron to run it every 20 minutes. Because Twitter is blocking to the app for constantly tweeting and you don’t tweeting again. That’s why we put a 20-minute interval. Hereby the system works in 20 minute intervals.

I also shared the project as open source. (Don’t forget to start and follow :) )

Original of the post:

You can reach me on my Twitter, Instagram, mail address. You can also go to my site.

Discussion (0)