Building and Deploying Random Quote Twitter Bot Easy Way
Medium is full of post about twitter bots. Why another bot post? đ¤ đ¤ Chill đ we will be learning to build fully functional Twitter Bot which can grab the random quotes and tweet the quotes on itâs own. We will be deploying our bot to heroku and embed twitter time line in our static website.
What this bot will do?
This is a simple Twitter bot which will retrieve Quotes from the Formastic Api and post the quotes with #quotes and smiley emoji. This bot favorite #Nature post and stream the tweet about Nepal in command prompt.
What you need?
- You must have Node.js installed on your system.
- A Twitter Account.
- Your bot will be using node-twitter which is an npm module to manipulate tweets and streams, and to communicate with the Twitter API.
- Heroku account which is Platform as a Service (PaaS) that effortlessly serves and host our webapps.
Letâs Start
Create the new folder and initialize it with npm init -f which will initialize package.json file with default setting or use can use npm init.
Create index.js and tweet.js which will be our server and Tweet script respectively.
Your current directory structure should look like this:
root/Twitter_bot
|- index.js
|- tweet.js
|- package.json
Create the folder inside Twitter_bot as a config where we will be having our app secret from the Twitter API
Config folder looks like this:
root/Twitter_bot/config
|- dev.js
|- keys.js
|- prod.js
Configuring and granting permissions from Twitter API
After logging to to your Twitter account, follow to this link: https://apps.twitter.com/app/new to create a new application. Fill out the necessary fields in the form click on the button Create Your Twitter Application. After creating the application, look for âKeys and Access Tokensâ under the nav-panes and click on âGenerate Token Actions` and then copy:
- Consumer Key
- Consumer Secret
- Access Token
- Access Token Secret
Open the dev.js
file and paste all four values inside it. Expose those values using module.export
:
//config.js
/** TWITTER APP CONFIGURATION
* consumer_key
* consumer_secret
* access_token
* access_token_secret
*/module.exports = {
consumer_key: '',
consumer_secret: '',
access_token: '',
access_token_secret: ''
};
Open the prod.js
file and paste all four values inside it.
//prod.js
/** TWITTER APP CONFIGURATION
* consumer_key
* consumer_secret
* access_token
* access_token_secret
*/ module.exports={
consumer_key: process.env.TWITTER_CONSUMER_KEY,
consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
};
We will be using this value later to deploy our bot to heroku.
In the keys.js
file and paste these:
if(process.env.NODE_ENV === 'production'){
module.exports = require('./prod');
} else{
module.exports=require('./dev');
}
Thatâs it for our config file. Letâs move on.
Building the server
When deploying to heroku and making our twitter bot tweet automated we need express server.
index.js
const express = require('express');
const app = express();
const port = process.env.PORT||5000;
app.listen(port,()=>{
console.log(`Server is running at port ${port}`);
})
Now,our server is up and running now we shift our focus to main task of utilizing twitter API to create Quote Bot.
Quote Bot
We will start by installing the dependency we need for our application.
$ npm install --save twitter
After the dependency has finished installing, go to the tweet.js
file and require the dependency and config.
file.
const Hero= require(âtwitâ);
const Keys= require(â.config/keysâ);
Pass the configuration (consumer and access tokens) of our Twitter application in dev.js
to twitter:
const Hero = new Twitter(Keys);
So far, so good?
Letâs write a function expression that finds the random quotes from Formastic Api and tweet this quote.
Letâs Install additional dependency to get access to Formastic API
const request = require('request');
const requestPromise = require('request-promise');
const API_URL = 'https://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=json';
Letâs write the function that will actually get information from API and post tweets .
const getQuote = (() => {
/* request options */
const OPTIONS = {
uri: API_URL,
json: true
};
requestPromise( OPTIONS )
/* Successful call */
.then( (response) => {
if ( !response )
getQuote();let quoteText = response.quoteText;
let author = response.quoteAuthor || âUnknownâ;
let fullQuote = `â${quoteText}â` + â â â +` ${author}`
printQuote( fullQuote );
Hero.post(âstatuses/updateâ, {status: fullQuote+âđđ #Quotesâ}, function(error, tweet, response){
if(error){
console.log(error);
}
console.log(tweet); // Tweet body.
console.log(response); // Raw response object.
});
})/* Handling errors */
.catch( (err) => {
console.log(âUnable to retrieve quote, try againâ);
})})();
let printQuote = (fullQuote) => {
console.log( fullQuote )
}
Favorite Bot
We will initialise a params
object that will hold various properties to search a tweet, but most importantly query
or q
property that will refine our searches. Whatever value you feed in this property, our bot will search the tweets to favorite based on this criteria. For our example bot, we have find latest tweets on #nature. The result_type:'mixed recent'
will find recent and popular tweet in the searched parameters and favorite these tweet.
const params = {
q: â#Natureâ,
result_type: âmixed recentâ,
lang: âenâ
}
Functional part of Favorite Bot
Hero.get('search/tweets', params, function(err, data, response) {
// If there is no error, proceed
if(!err){
// Loop through the returned tweets
for(let i = 0; i < data.statuses.length; i++){
// Get the tweet Id from the returned data
let id = { id: data.statuses[i].id_str }
// Try to Favorite the selected Tweet
Hero.post('favorites/create', id, function(err, response){
// If the favorite fails, log the error message
if(err){
console.log(err[0].message);
}
// If the favorite is successful, log the url of the tweet
else{
let username = response.user.screen_name;
let tweetId = response.id_str;
console.log('Favorited: ', `https://twitter.com/${username}/status/${tweetId}`)
}
});
}
} else {
console.log(err);
}
})
Tada you have created your twitter bot !!
Now, in your index.js
file simply require tweet.js
as:
require('./app');
index.js
should look like this
const express = require('express');
const app = express();
require('./app');
app.use(express.static('public'));
const port = process.env.PORT||5000;
app.listen(port,()=>{
console.log(`Server is running at port ${port}`);
})
In the package.json
file add the start script as
"scripts": {
"start": "node index.js"
},
Then from the terminal run npm start
To Deploying Bots to Heroku
I assume you are familiar with Heroku Platform. If not donât sweat it you can read it from Here.
Create a public
in the root directory and add the index.html
file then inside of index.html
add the following embed script inside the body tag which will simply emded your twitter time line.
</style>
<a class="twitter-timeline" href="https://twitter.com/CoastQuote?ref_src=twsrc%5Etfw">Tweets by CoastQuote</a> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
<script>
Note that
app.use(express.static('public'));
This will serve our static HTML. You can made fully dynamic as well.
GIT and HEROKU
Initialize git for your project if you havenât done already.
$ git init
$ git add remote origin //From your repo$ git add .
$ git commit -m "Quote Bot Finished"
$ git push origin master
$ heroku create
$ git push heroku master
$ heroku open //your bot will be live on your browser
This is mine first medium post so bare with me for mistakes.
You can find source code at here.