Skip to content

JupiterLikeThePlanet/Twitter-Bot-2

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

41 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

This is a twitter bot called SHEEPLE (@sheeplefollows)

Before coding, please read.

The following ReadMe includes boilerplate code that can be found in the folder /boilerplate-code. The current code in the main folder called index has a different code base to demonstrate further functionality. If you just want to get up and running and start with the basics, refer to the index.js in the boilerplate file as our example. However, please follow these instructions as if the index file you are using is in the main folder

Non Code Setup

  • Either create a twitter account or use one you are comfortable making into a bot.
  • You'll need to sign up to create a Twitter App
  • Once you create the application, there are 4 important things to note down over at the “Keys and Access Tokens” tab:
  • Consumer Key
  • Consumer Secret
  • Access Token Key
  • Access Token Secret

A good breakdown of these past steps can be found here. https://dev.to/omarhashimoto/how-to-build-a-simple-twitter-bot-in-17-lines-ofcode-2aan)

Initializing the Project

  • create a project in github making sure to add a .gitignore shaped around node and an MIT License

  • git clone the project in the terminal.

  • Open the project in your text editor and in your terminal, type npm init. You can fill the information any way you please.

  • We will install a few npm packages. Run npm install twit dotenv --save. This will install twit api client for node, documentation here, which will help us create all the actions we need for our bot. The dotenv package will help us conceal our api keys.

  • Lets start by creating our .env file. Inside of this file we create 4 variable names to set equal to our keys. Name them what you will but here's an example of what's in the file.


BOT_CONSUMER_KEY=YourKeyHere

BOT_CONSUMER_SECRET=YourKeyHere

BOT_ACCESS_TOKEN=YourKeyHere

BOT_ACCESS_TOKEN_SECRET=YourKeyHere
  • Let's start with creating a folder called /src. Inside this folder we will create a file called config.js.

  • inside the config file, add the following code. Note that the variable names I'm using here are the same ones we used in the .env file.


require('dotenv').config()

module.exports = ({
    consumer_key: process.env.BOT_CONSUMER_KEY,
    consumer_secret: process.env.BOT_CONSUMER_SECRET,
    access_token: process.env.BOT_ACCESS_TOKEN,
    access_token_secret: process.env.BOT_ACCESS_TOKEN_SECRET
});
  • inside your .gitignore file, add .env to list of file types to ignore

** note that the .env file will not appear in this github repo because it is in our gitignore file, which is the whole point. You want to hide those keys!

Creating core Functionality

  • create a file called index.js. At the top, add our required packages:

const config = require('./src/config');
const Twit = require('twit');

This allows us to use our concealed api keys and brings in the twit package.

  • create a new instance of your bot by setting ait equal to a variable, like so: const Bot = new Twit(config). Of course, you can call the variable anything you want.

  • I personally use variables to store my times because their written in milliseconds and var name is less confusing. So because we are going to test our twitter bot, there's no need have long run times. Create a variable that is set to ten seconds like so: var tenSeconds = 10000

  • Next, create a function called tweet like so:


    function tweet(txt) {
        Bot.post('statuses/update', {
            status: txt
        }, (err, data, response) => {
            if (err) {
                console.log(err)
            } else {
                console.log(`${data.text} tweeted!`)
        }
    })
    }

This code takes a string as it's param. The Bot var uses a twit post command that specifically targets your tweeter posts (here read as 'statuses/update') and takes as it's status the parameter. If it errors out the console will receive an error message, else log a successful tweet.

  • Next is function I created to help me tweet a random number. Why random? Because twitter will not post 2 duplicate statuses in a row. So for the sake of just making something work, I created a tweetRandomNumber function like so:

function tweetRandomNumber(){
    var randomNumber = Math.floor(Math.random()*1000)
    tweet(randomNumber)
}
  • Then finally at the bottom of the file, we call fire off our functions using javascripts built in function setInterval, taking as it's parameters our tweetRandomNumber function and the amount of time, here tenSeconds:

setInterval(tweetRandomNumber, tenSeconds);
  • To test to see if this works, go to terminal and type, node index.js. Check your twitter feed to see that it works. Check console for logs or errors.

Launching to Heroku

  • If you don't have one, get a heroku account here and follow the install instructions

  • In the terminal, type heroku login and press any key to be taken to the web browser to login OR If you’d prefer to stay in the CLI to enter your credentials, you may run heroku login -i

  • In your terminal, create your app by typing heroku create app {insert name of app here}. (i.e. heroku create app weatherApp)

  • If you have multiple apps and you want to push changes to a specific one, this stack overflow article explains how to do that.

  • in package.json file add this:


  "scripts": {
    "start": "node index.js"
  },
  • Since we are not uploading our .env file, we need to tell heroku what our environment variables are. They can be added in the settings tab of the application in the heroku dashboard, or by the command line using the command:

$ heroku config:set VARIABLE_NAME=VALUE

  • Since our app is a bot, you need an additional step. Because it’s not a web server, you have to tell heroku that this app is a “worker” app. This is done with a “Procfile”. This is a file called exactly “Procfile” (so create it without extension to the filename [i.e. Procfile, not Procfile.js] in your node directory with a single line:

worker: node index.js

  • At this point you should commit your changes BOTH TO GITHUB AND HEROKU. For git, in your terminal follow these three steps:
  1. git add . This will add all changes
  2. git commit -m {enter your commit message here}
  3. git push origin master And now you can push to heroku master:
  4. git push heroku master
  • You'll then need to login to your dashboard and navigate to the app. The “worker” dyno must be enabled rather than the default web one (npm start). In the heroku dashboard, select the resources tab and you should look like the following:

Resources Tab

** Note you will not see the worker dyno in the dash if you did not commit and push your changes!

  • Depending on the order in which you have done things, you might need to restart your app using $ heroku restart in the terminal for any troubleshooting

And that's where I leave you. Feel free to continue on from there using the twit documentation to expand on other twitter api features.


-please note twitter limitations

-additional documenation for the twitter api can be found here and here

-thorough heroku launching notes here and here. That second one is the best!

About

Making an example of a simple twitter bot

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published