Building a Real Time Twitter Bot that Replies with Media | by Praneeth Guduguntla | Towards Data Science

Source Code: https://github.com/pguduguntla/twitter-bot-reply-media
Twitter makes it really easy to build bots that can interact with tweets, users, and analytics tools that can scrape the platform for useful insights.
I wanted to develop a simple real time Twitter bot that actively filters through all tweets containing a certain hashtag and replies with videos/images directly to the tweet.
In this tutorial, I’ll go over how to set up and build a simple Twitter bot that searches for tweets with the hashtag #FilterMe . If that tweet contains some media, then our bot will reply with a video, and if it does not have any media attached, our bot will respond with a message like Oops, looks like you didn’t provide a media file! . So, let’s get started!
In order to access Twitter’s API, we need to first create a developer account. You will need to make a Twitter account (if you don’t already have one) which will be the account that makes the posts. If you don’t want your bot to be associated with your personal account, create a new Twitter account under your bot’s name.
Then, you’re going to need to apply for a developer account through their website here. The application will ask you for a bunch of details regarding your contact information, reasons for using the Twitter API, and programming experience levels. The forms are pretty standard, but make sure to provide adequate information when asked about the type of projects you expect to build with the API. The more thorough your answers, the faster the approval process.
Once, you’ve completed the approval process (which may take up to 24 hours), you will have access to your own personal developer portal that look something like this. As you can see, I’ve already created an App, but I’ll show you how to create your own.
Go to the Projects & Apps section on the left navigation bar. Go to Overview and you should able to create either a Project or an App. Projects allow you to use Twitter’s latest v2 API which is still in production so for a simple project such as this one, I suggest creating a standalone app by clicking the Create App button.
Once you click Create App, you will be asked to name your App before receiving your API keys.
Make sure to store your API keys in a safe location since these keys will be used to authenticate our account. We’re almost done with the set up! We just need to get a few more Access Token keys which we also need to authenticate our account. Head over to your App’s settings page which can be accessed by clicking on your App name on the left navigation bar. Click on Keys and Tokens and click Generate for the Access Token and Access Token Secret.
Take a deep breath...and we’re done with the set up. Now to the fun part! Let’s get our hands dirty with some code.
Before we can write any code, let’s set up our Node.js project. You will need to install Node.js if you don’t have it already. You can find instructions on how to do that here.
Once you’ve done that, start by creating and entering your project folder. Head over to the directory where you store your projects and run the following command:
mkdir twitter-botcd twitter-bot
In order to initialize it as a Node.js project run
npm init
You will be asked to name your project and accept all the prompts before initializing your project. This will generate a package.json file which keeps tracking of your project details and packages used.
Now, we will create three files.
touch bot.jstouch config.jstouch .env
First, bot.js which will store the main source code for our Twitter bot. The file config.js will store several helper methods that will help us interact with the API and simplify our code in bot.js.
The .env file will store our API keys as global variables. Add the following code in your .env file. Replace the ‘X’s which your own API keys obtained above.
API_KEY=XXXXXXXXXXXXXXXXSECRET_KEY=XXXXXXXXXXXXXXXXACCESS_TOKEN=XXXXXXXXXXXXXXXXACCESS_TOKEN_SECRET=XXXXXXXXXXXXXXXX
Finally, let’s install some modules to our project that will help us navigate the Twitter API and store our API keys.
npm install twitter dotenv bluebird --save
The twitter package is a third party module that makes interacting with the Twitter API easier for Node.js users. Dotenv allows us to load in global variables (such as our API keys) to keep them separate from our project code. Bluebird allows us to handle API request Promises.
Let’s start by opening up our config.js file in your favorite text editor. Add the following code to define our authentication with the Twitter API.
In the code above, we import both the Twitter and dotenv packages. In the auth method, we create a object named secret containing our authentication keys from our .env file. We then define a new Twitter client with the secret object and return the client. Lastly, we export the auth method so it can be accessed in bot.js.
In our bot.js file, we have the following code:
We begin by importing the auth function defined in our config file. We then define our Twitter client by calling the auth function. We, then use our client’s stream() function to track all public tweets with the text “#FilterMe” present. We pass a callback function to stream() that accepts a stream object. When the real time stream detects a tweet, it runs another callback function that contains a tweet object. This object contains details about the tweet and the user that posted it.
Now that we’ve received a tweet, we need to check whether the tweet has media attached to it and then reply with a video if it does!
So far, we are able to create a Twitter client that can stream tweets in realtime and identify tweets that match a specific criteria. Now, we have to publish a reply to this tweet with some media.
First, let’s add a video to our project folder in a subdirectory called ./sample-media. Make sure that your video is in mp4 format.
With the Twitter API, there are 3 steps to upload and access media:
Initialize media upload: Allocate space in Twitter’s backend for our video file. Retrieve a mediaId for this space.Append media file: Add our file data to the Twitter backend with the mediaId .Finalize upload: Once we upload to the file, we need to finalize the upload to ensure that the upload has completed safely.Publish the media to a Tweet reply: Post a reply to the original tweet with some text and our uploaded video.
Initialize media upload: Allocate space in Twitter’s backend for our video file. Retrieve a mediaId for this space.
Append media file: Add our file data to the Twitter backend with the mediaId .
Finalize upload: Once we upload to the file, we need to finalize the upload to ensure that the upload has completed safely.
Publish the media to a Tweet reply: Post a reply to the original tweet with some text and our uploaded video.
We will add methods to complete the above steps in our config.js file. Add the following code to the file:
You will need to update your import statements to include these modules:
const fs = require('fs');const Promise = require('bluebird')
You will also need to update module.exports at the bottom of the file to include postReplyWithMedia:
module.exports = { auth, postReplyWithMedia, postReply };
Let’s dissect the code above to see what each of the functions are doing.
The initializeMediaUpload method takes in a Twitter client and a file path to a file. Inside the function, we define the video format and the size of the file. We then call the media/upload endpoint on the twitter client to allocate space for an mp4 video file with the size of our video. The initialize returns a Promise object, which when fulfilled, contains the mediaId for our video in Twitter’s database.
The appendFileChunk method takes in a client, mediaId, and a path to the file to upload. This method runs on completion of initializeMediaUpload and thus, we are given a mediaId tho which we append our actual file data to Twitter’s backend. We extract the data from our file using fs.readFileSync(pathToFile) and store it in mediaData. Sonce again, we make a call to the media/upload endpoint with the command “APPEND” and pass our file. A Promise is returned which contains our mediaId.
Finally, the finalizeUploadMethod takes in a client and mediaId and makes another call to media/upload to ensure that our file uploaded successful. It then returns a Promise with the mediaId.
The function postReplyWithMedia is the function that will be called from bot.js. It takes in client, mediaFilePath, and replyTweet which is the tweet object we want to make a reply to. In this method, we initialize our media upload, append our media file, and finalize the upload before publishing our reply. We build a statusObj which stores our reply message in status, the tweet Id in in_reply_to_status_id and the mediaId to our video in media_ids. Then, we publish our status using the statuses/update endpoint where we receive our newly published tweet in a callback.
The function postReply takes a client, message, and a tweet and posts a reply to it in a similar fashion to the above function.
Almost done! Now we just need to import and call the postReplyWithMedia and postReply methods in bot.js.
In our bot.js file, we just need to add an if statement to check whether the original tweet contains media or not. We can do this by checking if the tweet object has a media_url key. Your final bot.js file should look like this:
And there we go! You should be able to run your bot by running:
node bot.js
Try tweeting yourself or having a friend tweet your bot with the hashtag “#FilterMe” and see if your account makes a post to the thread. It may take a second, but if you followed these steps, it should work!
Congrats! You built a working Twitter Bot that responds to tweets with videos in real time. However, our application currently runs locally. If you wish to deploy your application to the cloud, look into to hosting your project on Heroku or AWS. Here’s a good tutorial to quickly deploy your bot on Heroku for free.
I hope you learned something new! If you have any feedback or questions, feel free to let me know. As always, thanks for reading! :))
Source Code: https://github.com/pguduguntla/twitter-bot-reply-media