So.. If you’re reading this, then you’re most likely looking for information on how to create a Twitter bot, using NodeJS and JavaScript.
Well, look no further; This article will detail everything you need to get a (simple) bot running.
First of all, here are the things you’ll need:
– NodeJS installed on your computer
– NPM package Twit (handles interacting with the Twitter API)
– Applied for API Developer access on Twitter (You need to first apply for Essential access, then Elevated access if / when the first is approved).
I much prefer to code in Visual Studio Code (VSC from now on), and I’m using my 2021 MacBook Pro 16″ M1 Pro as my developer platform.
When you have installed NodeJS and VSC, open a console (PowerShell on Windows or Terminal on MacOS). Make sure that NodeJS is added to your systems Environment Variable PATH.
Create a new folder for the Twitter bot with: mkdir TwitterBot
(replace TwitterBot with what you want the folder named.
Open VSC, and open the Folder you just created.
Start a new Terminal session in VSC, and run this command: npm init -y
This will create a package.json file that is essential to your project.
Next, it’s time to add the package we’re using to interact with the Twitter API: npm i twit --save
We will be using the Dotenv package to store environment variables for this project: npm i dotenv
We’ll be needing to edit the package.json file, and add one line of code.
//Locate the section that looks like this: "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, //Now edit to look like this: "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "nodemon --ext js index.js" },
What we’ve done now, is to make sure that the correct file is run with nodemon when we use the command: npm run dev
nodemon runs the file index.js and monitors for changes in any file in the whole project, if a change (you’ve saved a file) it restarts the project.
I have added the --ext js
so that it only restarts the bot if a change is detected in files ending with .js
Now we’re ready to write some code!
Start by creating a new file called .env
and it should be located on the root level of the project
We’re using 4 variables that we get from Twitter API Dashboard
This is what it looks like:
ACK=<POST YOUR API KEY HERE> ACS=<POST YOUR API KEY SECRET HERE> AT=<POST YOUR USER ACCESS TOKEN HERE> ATS=<POST YOUR USER ACCESS TOKEN SECRET HERE>
Those are all the authentication variables we’ll need.
Now it’s time to create the actual bot.
Create a new file on the root level and call it index.js
//We're starting with requiring the packages we're using const Twit = require('twit'); require('dotenv').config(); //We need to create a new instance of Twit const T = new Twit({ consumer_key: process.env.ACK, consumer_secret: process.env.ACS, access_token: process.env.AT, access_token_secret: process.env.ATS }); //Let's console log that everything is OK so far, and that we're online console.log(`New Twitter bot is online and ready`);
This is your basic bot, but it’s not doing anything right now other than connecting and logging that it’s online.
(If you get an error when starting the bot, read the error. It tells you what’s wrong. It will be related to your Twitter Developer account.)
In your VSC terminal run the command: npm run dev
This starts the project, and you should see: New Twitter bot is online and ready
in the console.
This is all fine and well, but we want to actually do something with this code.
Remember that I said this was going to be a very simple bot? What I have in mind is that we’re going to monitor all tweets that has the hashtag javascript in it, and like those tweets.
We’re still in the index.js
file, and we’re going to be adding this code below the console.log
line.
//We need a phrase we're looking for in the tweets let phrase = '#javascript'; //Now it's time to start detecting tweets. We do that by creating a new stream let stream = T.stream('statuses/filter', { track: phrase }); //This starts a stream on the endpoint statuses/filter and tracks the phrase we've defined //Now we need a function that is triggered when a tweet matches our phrase const sawTweet = (tweet) => { //We said we wanted to Like the tweet we detected, so we use the post method on the endpoint favorites/create T.post('favorites/create', { id: tweet.id_str }, ilike); //We take the variable tweet from the stream below and we post an Object with id: tweet.id_str then we run the callback function ilike const ilike = (err, data, response) => { if (err) { console.log("Error: " + err.message); } else { console.log('I just liked a tweet!'); }; }; //This function has three variables, but we only care about the err //If an error is thrown it will console log the error message, if no error then the tweet was liked and we get a message in console saying we liked a tweet } //So: We have the function that is run when a tweet is detected, but we're not detecting anything yet stream.on('tweet', sawTweet); //This is triggered every time a tweet matching our phrase is detected, so we run the function sawTweet
And that is it! You now have a running, working Twitter bot =)
There are of course tons of possibilities to improve on this code, and I would be happy to discuss them with you!
You can email me at codelog@geirandersen.com,
You can join my Discord server,
You can contact me on Twitter: @GeirAndersen,
or you can leave a comment on this article.