So, you want to build a bot with NodeJs?
[ajax_load_more]
I have used Node.js in a number of projects and in conjunction with the module bundler called Webpack and the automation toolkit Gulp, but still I wanted to experiment with something different that would bring up the advantages of using such a server-side platform. I remembered that the Microsoft Bot Framework employs Node.js for its Bot Builder SDK and why not building bots sounds interesting! I have actually found out that there are a few books specifically focusing on building bots with Node.js and that seemed to be like a fun task. The choice then became clear, let’s use Node.js and Twit, a Twitter API Client for Node, to build a Twitter bot that simply sends a query to the Twitter API, receives a response containing the results of the performed search, and then retweets the most recent tweet returned. Let’s see what we need to achieve this!
Set up a dedicated Twitter account for your Bot
Bots get usually banned from Twitter, so it is recommended to create Twitter account perhaps with a secondary email address specifically for the following experiment. It is highly recommended that you do not use your “official” Twitter account as it is likely that it will be short-lived. After your new account is activated, go to the Twitter Developer Center and sign in with your new details. You might also want to have a look around and in particular have a read through the documentation on how to get started with the Twitter Developer Platform and how to create your first app.
Create a Twitter App
From your acccount, you will be able to see the newly created app from here. After creating the application, look for ‘Keys and Access Tokens’ and click on ‘Generate Token Actions’. Make a copy of the details below as you will be using them later as part of your
config.js
- Consumer Key
- Consumer Secret
- Access Token
- Access Token Secret
The Part where you code
You will interact with your newly created Twitter App via a Nodejs library called Twit. Create a new project folder in your Dev directory (ideally the directory structure where your git installation resides):
mkdir twitter-bot cd twitter-bot npm init
This will kick off an utility that will take you through the process of creating the package.json file.
{ "name": "twitter-bot", "version": "1.0.0", "description": "sample twitter bot", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" }, "keywords": [ "node", "twit", "twitter", "bot" ], "author": "ilacorda", "license": "ISC" }
Then you will need to install Twit, the Twitter API Client for Node that supports REST and Streaming API.
npm install twit
and create a file called
touch bot.js
This will be your main application file, that means the entry point of your app. You will also need a third and additional file called
config.js
where you will past the following:
- Consumer Key
- Consumer Secret
- Access Token
- Access Token Secret
It will look like this:
module.exports = { consumer_key: '', consumer_secret: '', access_token: '', access_token_secret: '' }
Your directory structure should look as follows:
root/project-name |- bot.js |- config.js |- package.json
The part where you make the Bot do something
Next step is to make your bot to query the most recent tweets. We will need to write a function that finds the latest tweets according to the query passed as a parameter. To do so, we need to initialise a params
object holding aq
property that will refine our searches. In our case, we are targeting tweets with hashtag #nodejs and #Nodejs:
var retweet = function() { var params = { q: '#nodejs, #Nodejs', result_type: 'recent', lang: 'en' } }
the property
result_type: 'recent'
instructs the bot to search exclusively for the tweets that were posted since the bot was started. We can use
Twitter.get
, which accepts three arguments: API endpoint, params object (defined by us) and a callback.
Twitter.get('search/tweets', params, function(err, data) { // if there are no errors if (!err) { // fetch the ID of tweet var retweetId = data.statuses[0].id_str; // Instruct Tweeter to retweet Twitter.post('statuses/retweet/:id', { id: retweetId }, function(err, response) { if (response) { console.log('Retweeted!!!'); } // if there was an error while tweeting if (err) { console.log('No results were returned'); } }); }
To post or to retweet the tweet the bot has found, we have used the Twitter.post()
method to post to any of the REST API endpoints.
Usage
In order to run your bot, you should simply type the following command on terminal:
node bot.js
Alternatively, it is possible to use:
npm scripts
in a nutshell, they are scripts whose goal is to automate repetitive tasks. This requires to modify the file
package.json
by adding the following lines of code:
{ "scripts": { "start": "node bot.js", } }
and then you can type
npm start
Posted on April 1, 2018, in Development and Testing. Bookmark the permalink. Leave a comment.
You must log in to post a comment.
Leave a comment
Comments 0