Creating a Twitter Bot with JavaScript

Search for a command to run...

No comments yet. Be the first to comment.
Backtracking explained step by step with problems

Whether you're a blogger, startup, or business, blogging is a long-term strategy to build a strong presence in front of humans as well as search engines. With these small, easy-to-implement SEO tips, you can increase your blog's reach and traffic. 1....

12 Common uses of Java Streams with code examples
In the previous article, we looked at the fundamentals of session management. We also looked at two types of access tokens and how both of them are inadequate when it comes to providing strong security along with a good user experience. In this artic...

Introduction Session management is the process of maintaining a session " between a client and a server", "for a user", "for a period of time". A simple session management flow The process can be described as follows: A user authenticates with their...

I got back into using Twitter 2 months ago when I started my 100DaysOfCode journey. While posting my progress each day, I got curious about the bots that like and retweet my posts. Finally decided to create my own and experiment with the Twitter APIs.
Let's go through the whole process step by step. Before getting started, lets have a look at the Twitter APIs.
There are a number of things Twitter allows you to do programmatically from your bot account.
It has different versions and tiers of APIs
What we get for free and will use in this tutorial are Standard v1.1 and v2
v1.1 is the Standard API and v2 is a few additional methods on top of it.
Search for tweets
Status Update
Retweets
We will use these 3 APIs but there are many other possibilities. For example, the bot can search through its own tweets, it un-retweet, delete an old tweet, create favorites, etc.
Check out the entire API reference for more details.
Once you have an idea about what you are going to build and what APIs you are going to use, its time to move onto building things. First of all, we are going to apply for a developer account.
Prerequisite - You need to have a twitter account. You can either use your own account or create a new twitter account for your bot. Whichever account you use will require you to have a verified email id and phone number attached to it.
Once you are done with the process, you will have a Dashboard when approved. Generally, approval is instantaneous.

Edit the App Permissions section. By default, your app has only read permissions, we will allow it read and write permissions which will enable it to make tweets. If you have to use the Direct Messages feature as well, you can enable that as well.

Take a look at the Keys and tokens tab
We are going to need all these keys
So our configuration is all set. We have saved a bunch of keys and tokens. Now let's have a look at how the authentication works.
Without going too deep into OAuth, I will explain which kind of keys and tokens needs to be used in which scenario. You will not need to understand more than that. So if you are new to authentication headers, you can ignore the confusing terminology for now. It will be clearer when we write the code.
For example,
I will host the repo on Github and use Repl as my IDE and my runtime environment.
If you are new to Repl, here's a quickstart guide
Repl is not mandatory for your bot, you can also use an offline IDE/ VS Code in browser and other deployment environments like Heroku, Netlify, AWS, Azure, etc. So choose whichever you are comfortable with.
I will demonstrate this with Repl and even after working with Azure for years, I found Repl as a perfect fit for this little project. It's completely free, provides easy ways to store environment variables, runs the app in your browser.
Get started by doing the below steps
npm init. Fill in the required values.Although the library is not important and all API calls can be made with generic GET and POST requests, it takes care of all the boilerplate code and authorization headers for you and helps to focus on the app logic.
The library and its documentation can be found on Github
Let's install the library as a dependency
npm install twitter-lite
What are we going to make?
An authenticated client for the app
const app = new TwitterLite({
version: "2",
extension: false,
bearer_token: process.env.BEARER_TOKEN
})
Defining the parameters:
With this client, the app can call all endpoints of the v2 API that do not make changes from a user account.
Authenticated client for the user
const user = new TwitterLite({
access_token_key: process.env.ACCESS_TOKEN,
access_token_secret: process.env.ACCESS_SECRET,
consumer_key: process.env.CONS_KEY,
consumer_secret: process.env.CONS_SECRET
})
Parameters:
An example of a search query will be
(from:username1 OR from:username2 OR from:username3) -is:reply -is:retweet
This query gets the tweets from any of the three users excluding those which are replies or retweets.
For exact steps to create the query, refer to the github repo. (Find link below)
Params:
{
start_time: '2021-09-15T03:10:41.161Z',
max_results: 10,
'tweet.fields': 'public_metrics',
expansions: 'author_id',
'user.fields': 'id,username',
query: '(from:username1 OR from:username2 OR from:username3) -is:reply -is:retweet'
}
Parameters:
tweet.fields: 'public_metrics' - will return metrics like likes, comments, retweets along with the text of the tweet.user.fields will return a User object of the user who tweeted it - I have only specified id and username. expansions: author_id. User array and Tweet array will be separate. author_id in the Tweet object works like a foreign key to link with id field of the User object.Calling the API
const {meta, data, includes} = await app.get('tweets/search/recent' , params)
Uses the app client.
The call returns the three objects
Next step will be to find the best tweet among these tweets based on public metrics. Simple math and comparisons. Refer to the code for the same.
What we need at the end is the tweet id and the username of the best tweet
Based on switch or probability, the bot randomly chooses between retweeting and quote tweeting. Simple Math.random() logic.
Let's look at the API calls.
Quote tweet
const {data} = await user.post('statuses/update', {status: status})
Here status is the text that will be tweeted. It will also contain a link to the quoted tweet. Another point to figure out with the codebase.
Retweet
const {data} = await user.post('statuses/retweet/'+ id)
As simple as that - id here is the best tweet id we figured out before.
And that's it. Now every time our code runs, it will find 10 recent tweets from certain users and will share the best of them.
Now let's look at some supporting details.
All tokens and the user list are saved as environment variables. They should not be put into the code for the sake of security.
I have used Repl Secrets for the task. You can choose whatever way your environment provides.
There are multiple ways to do this. One popular way bot makers follow is to put it on Heroku and make it run on scheduled timestamps. Same can be achieved with AWS Lambda and Azure Functions.
My way was to keep it on Repl itself. Not sure how popular this is but let me share the steps:
language = "bash"
run = "node index.js"
That's it. Now the bot runs every hour and finds a new tweet to share. Provided the users have tweeted in that hour. Rarely misses because my user list is long.
Thanks for reading the article.
The code is on Github
And I'm on Twitter in case you want to reach out and say hello.
Oh wait! The bot is on Twitter too. Come see how its doing.