paint-brush
Deploying Twitter Bot to Herokuby@sujan-chhetri
2,219 reads
2,219 reads

Deploying Twitter Bot to Heroku

by Sujan ChhetriAugust 27th, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Node.js and a package called Twit can be used to deploy the bot to Heroku. The bot gets the twitter data, post the status and retweeting tweets. It can be run using Node.JS and Twit to search for tweets containing the word'suJJJan' T.get('search/tweets',parameters,fetchData); function fetchData (err, data, response) { { { created_at : 'Thu Aug 06 10:38:09 +0000 2020', id : 1291311562636183600, id_str : '12911021010106626183559', text : "RT @Hello2: @random twitter is best @random Twitter is best",

Companies Mentioned

Mention Thumbnail
Mention Thumbnail

Coin Mentioned

Mention Thumbnail
featured image - Deploying Twitter Bot to Heroku
Sujan Chhetri HackerNoon profile picture

Most of us are familiar with Twitter. But we are not much familiar that we can automate the activities like status posting, retweeting, liking, commenting and so on. So,here I'll show you how we can automate some of the activities like getting the twitter data,posting the status and retweeting with Node.js and a npm package called Twit.

And we ll deploy the project to github and heroku and keep it running...

Let's start by signing in to a twitter developer section, You'll get insight of creating a developer account and will be able to Create an app where you will get the following keys:

consumer_key : 'key',
consumer_secret : 'key',
access_token : 'key',
access_token_secret : 'key'

Project structure:

project---| 
          |--config--config.env--config.js
          |--botget.js //not needed for deployment
          |--botpost.js //not needed for deployment
          |--botretweet.js
          |--Procfile           

Installation:

Node.js must be installed on your system.

In the project folder,In terminal enter the following commands:

$ git init -y
$ npm i twit

Setting up the environment variables:

Let's install dotenv to hide the keys when uploading to github and heroku

$ npm i dotenv

Create a folder config in the project directory.And inside that create a file called config.env:

API_KEY=key
API_SECRET_KEY=key
ACCESS_TOKEN=key
ACCESS_TOKEN_SECRET=key

Create another file inside project directory as config.js:

const path = require('path')
const dotenv = require('dotenv')
require('dotenv').config();
// Load config
dotenv.config({ path: './config/config.env' })

//exports the keys
module.exports = {
    consumer_key : process.env.API_KEY,
    consumer_secret : process.env.API_SECRET_KEY,
    access_token : process.env.ACCESS_TOKEN,
    access_token_secret : process.env.ACCESS_TOKEN_SECRET
}

Now we are ready to work on the bot scripts.

You might want to look Sample JSON data from twitter and twit before going on further.

Create a file as botget.js in the root of the project:

console.log("Bot is starting")
var config = require('./config/config')//imports keys 
var Twit = require('twit');


var T = new Twit(config);


var parameters = {
    q : 'node',//query to search the twitter,can be any thing count : 2 //no. of data to fetch
}


//  search twitter for all tweets containing the word 'suJJJan' 
T.get('search/tweets',parameters,fetchData); 


function fetchData (err, data, response) {
    var tweets = data.statuses; 
    for(var i=0;i< tweets.length;i++){ // checks the statuses twiceconsole.log(tweets[i].text);//prints the text
    }
    console.log(data)
} 

To run the script.Use:

$ node  botget.js

Sample Output:

Bot is startingRT @Hello2: @random twitter is best
@random twitter is best
{
  statuses: [
    {
      created_at: 'Thu Aug 06 10:38:09 +0000 2020',
      id: 1291311562636183600,
      id_str: '129110210662636183559',
      text: "RT @Hello2: @random twitter is best",
      truncated: false,
      entities: [Object],
      metadata: [Object],
      source: '',
      in_reply_to_status_id: null,
      in_reply_to_status_id_str: null,
      in_reply_to_user_id: null,
      in_reply_to_user_id_str: null,
      in_reply_to_screen_name: null,
      user: [Object],
      geo: null,
      coordinates: null,
      place: null,
      contributors: null,
      retweeted_status: [Object],
      is_quote_status: false,
      retweet_count: 1,
      favorite_count: 0,
      favorited: false,
      retweeted: false,
      lang: 'en'
    },
    {
      created_at: 'Sat Aug 01 02:24:27 +0000 2020',
      id: 1289386479903371300,
      id_str: '1289386479903371265',
      text: "@ randomtwitter is best",
      truncated: false,
      entities: [Object],
      metadata: [Object],
      source: '<a href="http://twitter.com/download/android" rel="nofollow">Twitter for Android</a>',
      in_reply_to_status_id: 128921230498288600,
      in_reply_to_status_id_str: '1289469260498288640',
      in_reply_to_user_id: 832773717648143900,
      in_reply_to_user_id_str: '832773417688143873',
      in_reply_to_screen_name: 'random',
      user: [Object],
      geo: null,
      coordinates: null,
      place: null,
      contributors: null,
      is_quote_status: false,
      retweet_count: 1,
      favorite_count: 0,
      favorited: false,
      retweeted: false,
      lang: 'en'
    }
  ],
  search_metadata: {
    completed_in: 0.027,
    max_id: 1291322662436183600,
    max_id_str: '1291322662636183559',
    next_results: '?max_id=1289386479904371264&q=random&count=2&include_entities=1',
    query: 'node',
    refresh_url: '?since_id=1291322662646183559&q=random&include_entities=1',
    count: 2,
    since_id: 0,
    since_id_str: '0'
  }
}
Create a file as botpost.js in the root of the project:

console.log("Bot is starting")
var config = require('./config/config')
var Twit = require('twit');


var T = new Twit(config);


tweetThis();

//uncomment this if u want to run the event in certain interval
//setInterval(tweetThis,3600000)//every 1 hour(time is in ms)



function tweetThis() {
    var statsArray = ["hello","How ya doin","I love node"];
    //selects random tweets from the arrayvar stat = statsArray[Math.floor(Math.random()*statsArray.length)]


    var tweet = {
    status: stat
    }


T.post('statuses/update',tweet,tweeted); //posts tweets


function tweeted (err, data, response) {
    if(err){
        console.log("Something is wrong")
    }else{
        console.log("Works fine")
    }
} 
}

Now we will create a bot which retweets and deploy it to heroku.

Create a file as botretweet.js in the root of the project:

console.log("Bot is started");


var twit = require('twit');
var config = require('./config/config');


var T = new twit(config);


reTweet();


// find latest tweet according the query 'q' in parameters
//set q as # or @ for hashtags and username.Can keep both as '@tag,#hash'
function reTweet() {
    var parameters = {
        q: '@suJJJan', 
        result_type: 'recent',
        lang: 'en'
    }


    T.get('search/tweets', parameters, function(err, data) {
        if (!err) {
//gets the tweetidvar retweetId = data.statuses[0].id_str;
//retweets the status in which the 'q' is mentioned
            T.post('statuses/retweet/:id',{ id : retweetId },tweeted);
            function tweeted(err, response) {
                if (response) {
                    console.log('Retweeted successfully');
                }
                // if there was an error while tweeting if (err) {
                    console.log('Duplicate tweet or Something went wrong');
                }
            }
        }
        else {
        console.log('Nothing found');
        }
    });
}

Create Procfile in the root of the project folder:

Add the code below and save the file.

worker:node botretweet.js

Pushing Code to Github:

  • Create a github account
  • Create a new repository
  • install git if u are familiar with it or else you can directly upload from the Github site
  • create a file called .gitignore,inside that:
  • node_modules
    config/config.env

    save the file.

    Now use the following commands to push code to github.

    $ git init
    $ git add .
    $ git commit -m "initial commit"
    $ git remote add origin https://github.com/username/project.git
    $ git push -u origin master

    This will deploy the project to github.

    • Now we will deploy the code to heroku and keep the script running forever.
    • Pushing Code to Heroku:
    • Create a heroku account
    • You'll see new,create new app.. read the docs to deploy from browser
    • Install heroku cli
    • Follow the commands
    • we ll have to add the keys as below:
      $  heroku create appname
      $  heroku config:set API_KEY=yourkeyhere API_SECRET_KEY=yourkeyhere ACCESS_TOKEN=yourkeyhere   ACCESS_TOKEN_SECRET=yourkeyhere
      $ git remote set-url heroku https://git.heroku.com/appname.git
      $ git push heroku master

      The code will be deployed to heroku.

      Then goto heroku dashboard:

      • you will see the app which you have created
      • select the app
      • select 'resource
      • 'In 'free dynos section', you ll see 'web npm start' (for webapps only)
      • click on edit and turn if off
      • you ll see 'worker node botretweet.js' (worker are typically used for background jobs, queueing systems, and timed jobs)
      • click on edit and turn it on.
      • On adds-on section search 'Heroku-Scheduler'
      • Select it and you ll reach to another dash boardSelect create job.
      • Set time as you like and in 'Run Command' add node botretweet.js and save job

      You are all set. Your bot will run and retweet every hour or so on as per the time duration you have set.

      Check the full code here

      Previously published at https://blogue.tech/blogs/twitter-bot-with-node.js-and-deploy-to-heroku