Twitter bot that listens to keyword
In this project we will create a new NodeJS application that is connected to a Twitter Developer account, and it listens to a keyword which, every time is used in a tweet, triggers an event.
Code
Lets start by creating a new NodeJS project using npm init
in an empty directory and accepting all the default configurations. After that we should add the script for running our app inside the package.json
.
"scripts": {
"start": "node index.js"
},
We also need to install some dependencies:
dotenv
is for the credentials, we are going to store the credentials of the Twitter account inside a.env
file and this file must not be pushed to the repository.twitter-api-sdk
is the library we are going to use for subscribing to the events and then creating and posting the new tweet.
npm i dotenv twit --save
But as you can see, the JS file that we are going to use doesn’t exist yet so let’s go ahead and create it. Once inside this new file, we need to add some variables like the client for the Twitter account, and library for the credentials.
import { Client } from "twitter-api-sdk";
import * as dotenv from 'dotenv'
dotenv.config({ path: './config.env' })
async function main() {
const client = new Client(process.env.BEARER_TOKEN);
}
main()
These credentials will be stored in a gitignored file called config.env
that looks like this:
BEARER_TOKEN=
I usually commit a similar file named config.env.copy
with just the structure of the file, this way it is easier to know how the file should look like.
Now we can continue with the index.js
, where we need to create the rules for the subscription of the client. This rule is applied to the tweets and means that the tweet has to contain the text “The Medium test”. Also, every rule needs a tag field.
await client.tweets.addOrDeleteRules(
{
add: [
{
value: "The Medium test", tag: "text_filtered_tag"
}
]
}
);
You can check if the rules were applied correctly with:
const rules = await client.tweets.getRules();
Now lets create the stream and log every time we receive a response. To the stream method we need to pass an object indicating the fields to retrieve from each tweet. More on the fields here.
const stream = client.tweets.searchStream({
"tweet.fields": ["author_id", "created_at"],
});
for await (const tweet of stream) {
console.log('🔷 TWEET ', tweet);
}
Twitter App
Now it is time to create the application in the Twitter Developers Portal.
Now that we have the app and the credentials, lets add them to the environment file and lets test it!
In this post we are not going to be polite and reply to the tweet invoking us, that is for another post. But after getting the event of the new tweet, we could add any code to create the application that we need.
For more information about this content, feel free to visit my code repository twitter-reply-bot-heroku.