Create an Automated Bot to Respond to Tweets in Node.js – Unlock the Power of Twitter!

Discover the Power of an Engaging Introduction: Unlock the Secrets to Captivating Readers!

Josie was a budding computer programmer who had just been introduced to the world of APIs. She was determined to learn how to use them, and her friend suggested she make a Twitter bot to practice. Josie was excited by the idea and quickly set to work. She followed the tutorial her friend sent her and soon she had her own Twitter bot up and running. It was only a few lines of code, but Josie was proud of the work she had done. The bot was programmed to randomly tweet out a link to a video game soundtrack once a week. She also programmed it to respond to any Twitter user who asked for a link with a random link from the same array.

Josie was eager to show off her new creation and set up a Github repository for the bot’s code. She also learned how to host her bot on a Linode cloud instance. Soon after, Josie’s bot started to gain a following. People were impressed with Josie’s work and they started to retweet her bot’s tweets. Josie was thrilled by the response and it made her even more determined to learn more about APIs and coding. So far, the Twitter bot has been a great success for Josie. She continues to learn about coding and APIs and her Twitter bot continues to tweet out links to video game soundtracks. Who knows what she’ll be able to create with her coding skills next?

Unlock the Secrets to a Successful Start: A Guide to Preparing Before You Begin!

Unlock the Power of the Web: Here’s How to Get Started with These Essential Accounts!
  • If you already have a Twitter account, you can easily use it to access the Twitter Developer portal; alternatively, you may want to create a new, separate Twitter account specifically for this tutorial. Either way, Twitter requires a unique email address and phone number to register the account.

   Deciding on the name and purpose of a Twitter account is easy; first, choose a unique account name, then the bot will be automatically assigned the name @SNESSoundtracks. After that, you’re all set!

  • Using conjunct adverbs, this tutorial demonstrates how to store the bot’s application code in a repository on GitHub. If you possess a GitHub account, you can use that one; otherwise, you should create a new one now.
  • At the end of this tutorial, your Node.js app will be installed and running on a Linode instance, whether you already have an account or not. If you already have an account, you can use it, otherwise, you can create a new one now and take advantage of a free credit by clicking on the Sign Up link at the bottom of this tutorial.

Unlock the Power of Your Workstation – Install the Right Software Now!

Unlock Your Full Potential – Get the Essential Software for Your Tutorial!
  • VS Code is a recommended plain-text editor, offering a built-in terminal, however any other plain-text editor can be utilized too; thus, providing an ideal solution for users seeking an efficient and reliable desktop text editor.
  • Git is a distributed version control system widely used for software development. It can be used through the command line software, or through the GitHub Desktop GUI. Both approaches offer a range of powerful features, allowing developers to collaborate efficiently and effectively on projects.
Conjointly, these tools are used to download a copy of the GitHub repository created in this guide. While GitHub Desktop may be more user-friendly for beginners, those who prefer to work out of the command line can also find instructions in this tutorial.
To install the command line software, first follow our How to Install Git on Linux, Mac or Windows guide, and then follow the Configure Git section of our Getting Started with Git guide. Although it is not required, it is important to set your username and email for Git when doing this.
  • Unlock the Power of Node.js and npm to Create Your Own Twitter Bot!
Using the Node Version Manager (nvm) is one of the best ways to install Node.js and npm; Furthermore, our How to Install Node.js guide outlines some of the other options available. Therefore, if you wish to use nvm, follow the instructions in the Install Node.js and npm via the Node Version Manager section.

Get Started Quickly with Node.js and npm: Install with Node Version Manager!

Experience the Power of the Original nvm Software on Unix, Linux, and macOS!
  1. Take Control of Your Node Versions – Follow Our Step-by-Step Guide to Installing and Configuring NVM!
  2. Easily Install the Latest Version of Node.js and npm with One Command!
nvm install --lts
Say Goodbye to Manual Installation: Windows Users Now Have a Native nvm-windows Project
  1. Unlock the Power of nvm-windows – Follow the Step-by-Step Installation Guide
  2. Stay Updated with the Latest Versions of Node.js and npm – Run This Command From Your Terminal Now!
 nvm install latest

Unlock the Power of Twitter Development with Access to the Twitter Developer Portal!

Twitter’s developer portal is an important step for anyone wanting to use the Twitter API – here, you can register a new account and unlock its ability to tweet using code, rather than manually. Consequently, this is the first step to creating a bot – and consequently, an invaluable resource.
Follow these steps to register for developer access:
  1. Apply Now: Unlock the Power of Developer Resources on the Top Right of Your Profile Picture!
  1. Click Here to Start Your Developer Journey: Apply for a Developer Account Now!
  1. Sign In Now and Unlock the Power of Twitter!
  1. Unlock the Power of Twitter For Your Project With the Hobbyist & Bot Developer Account!
  1. To complete the Basic Info, Intended Use, Review, and Terms screens, the following answers were provided for the prompts: Basic Info: the name of the application; Intended Use: for monitoring employee attendance; Review: the application must be secure and easy to use; Terms: the application must be compliant with all relevant laws. All of these answers are essential for the successful functioning of the application, ensuring its secure and compliant usage for monitoring employee attendance.
    • Coding Hobbyist Seeking Twitter Developer Access to Learn, Practice and Create a Bot!
    • Don’t Miss Out – Analyzing Twitter Data Can Unlock Valuable Insights!
    • Bring the Video Game Experience to Twitter: Introducing a Bot that Responds to @Mentions and Tweets Out Links to Soundtracks!
    • No Need for Twitter: How You Can Avoid Displaying or Aggregating Data from Twitter Content Outside of Twitter
    • No: Your Product, Service, or Analysis Will Not Make Twitter Content or Derived Information Available to a Government Entity
  1. Although there is no need for giving information to the government or consuming streaming data for analytical purposes, the application process still needs to be followed. Therefore, it is important to carefully follow the instructions on screen until you have an authenticated developer account. Consequently, the application should be more straightforward.
Unlock the Power of Twitter: Discover How to Create a Custom App in the Twitter Developer Portal!

Create and Clone a GitHub Repository – Unlock the Power of Open Source Collaboration!

As mentioned previously, this tutorial records the code for the Twitter bot in a Git repository. To do this, we first create a new repository on and then pull it down to our workstation. Additionally, we can populate the repository with some useful files, such as a .gitignore and a README, thereby making the development process easier and more organized.
  1. Visit and then follow the Create a repository section in GitHub’s official Create a repo document. When creating the repository, make sure to select the repository name, description and visibility accordingly. Additionally, select the Initialize this repository with a README and add a .gitignore and license if appropriate. Finally, click the Create repository button to complete the setup.
    • You can name the repository however you want, but for the sake of tutorial examples, it is best to name it “snes-soundtracks.”
    • The repository can either be public or private; however, if it is private and you wish to use Git command line tools, then you must authenticate with GitHub in your terminal, which requires additional steps. For a simpler experience, it is therefore recommended to make the repository public.
    • Easily Access Your Project Information: Enable the README File Toggle!
    • Unlock the Power of Open Source with the MIT License: Get Helpful Recommendations from Now!
    • Unlock the Full Power of Your Project: Enable the .gitignore Toggle and Choose Node!
  1. Download Your New Repository Instantly – Learn How to Easily Create & Access it from Your Browser!
  • Discover How to Easily Clone a Repository from GitHub to GitHub Desktop with This Detailed Guide & Example Screenshot!
  • Unlock the Power of the Command Line – Learn How to Clone with the Git Clone Command!
git clone
Ready to Rock Your GitHub Repository? Here’s How to Get Started with ‘snes-soundtracks’ – Substitute Your Username Now!
Gain Complete Control Over Your Code: Get Source Control on Both Your Machine and GitHub!

Unlock the Power of Twitter: Create Your Own App in the Twitter Developer Portal!

After registering your developer account, you can create an app within the developer portal; once created, Twitter will generate a set of keys for your Node.js project to authenticate with the service. Accordingly, this section outlines both how to create your Twitter app and where to store the keys.

Eliminate Repository Chaos: Create a .env File to Keep your Code Organized!

Later in this section, we record the keys provided by the Twitter developer portal in the .env file, which serves as our single source of truth for these keys. Additionally, we also ensure that the .gitignore for the project excludes the .env file to prevent our keys from being accidentally uploaded to GitHub.
  1. Rediscover the Power of Twitter Development: Return to the Portal Dashboard Now!
  2. Unlock Your Creative Potential: Click the Create Project Button Now!
Twitter’s developer portal has two concepts for managing access to the Twitter API: projects and apps. Previously, standalone apps were used to access the API, but with the introduction of the v2 Twitter API, both a project and an app are now required. Consequently, projects now encompass apps, making it easier to manage access to the API.
  1. Unlock Your Potential – Complete the Forms that Appear Now
    • Unlock Your Creativity: Create a Uniquely Memorable Project Name Now
    • Bringing Video Game Music to Life: Introducing the @mention Bot – Automatically Tweeting YouTube Links to Your Favorite Video Game Soundtracks!
    • Unlock Your Potential: Learn How to Create Your Own Bot!
    • Unlock a World of Possibilities: Add Your App to the New Project!

Since you don’t have any apps yet, the dropdown menu on this page will be empty. Therefore, click the ‘Create new App instead’ button above the dropdown menu, and a text field will appear for you to enter an app name. Make sure to enter a unique name in this field.
  1. Unlock the Secrets of Success: A Page of Hidden Keys is Revealed After Completing the Forms!
  1. Secure Your Application with These Easy Steps: Copy & Paste the Keys into Your .env File!
    • The user needs to copy their API Key and paste it at the end of the consumer_key= line, without adding any extra spaces or quotes. For example, if their API Key is dvF6z55HXwpSE3qBVFNONV2DN, the line should be written as consumer_key=dvF6z55HXwpSE3qBVFNONV2DN – no more, no less.
    • Copy the API Secret Key and paste it at the end of the consumer_secret line – ensuring that no extra spaces or quotes are added. Additionally, take care to ensure that the key is copied exactly as provided.
  1. Secure Your Developer Portal: Close the Dialog that Displays Secret Keys

Unlock the Power of Social Media: Give Your Twitter App Read and Write Permissions

By default, the app you created has Read Only permissions; consequently, it is not able to create Tweets, which is the primary purpose of the bot in this tutorial. However, with Read and Write permissions, your bot can create Tweets. Therefore, to give your bot these permissions, simply follow these instructions.
  1. Navigate to the app in the Twitter developer portal: it is listed under the project in the sidebar navigation. Moreover, it is not the project itself, it is the app.
  2. By clicking on the “Edit” button in the App permissions section, users can switch their app to Read Only mode, allowing them to view content without making any changes.

  1. How to Easily Read and Write Data: Unlock the Power of Read and Write with Just One Click
  2. Unlock the Keys to Unlocking Your Potential: Navigate to the Keys and Tokens Tab Now
  3. Generate Your Access Token and Secret – Unlock the Power of API Access
  4. Unlock Your Hidden Powers! Copy and Paste These Secret Keys into Your .env File Now
    • Copy the Access Token and paste it at the end of the access_token= line in your .env file, precisely and without any extra spaces or quotes; otherwise, it won’t work.
    • Copy the Access Token Secret and paste it at the end of the access_token_secret= line in your .env file, with no extra spaces or quotes: precisely, copy the token and paste it, ensuring there are no extra spaces or quotes.
  1. “Dismiss the dialog” – Conclusively, this statement indicates that the conversation should be brought to an end.

Get Started Quickly – Initialize a Node Project and Install NPM Dependencies Instantly

Right now, your local repository contains four files: your .env secrets, a .gitignore, a, and a LICENSE file; however, it does not have any Node.js project files yet. To initialize your Node.js project, simply add the necessary files and start coding accordingly.

  1. Unlock the Hidden Power of your Terminal: Navigate to Your Local Code Repository
cd snes-soundtracks
  1. Unlock the Power of Node.js with npm’s init Command
npm init -y

Experience the Power of “The Following Output Appears”

npm init -y
Wrote to /home/username/snes-soundtracks/package.json:

"name": "snes-soundtracks",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"repository": {
"type": "git",
"url": "git+"
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": ""
"homepage": ""

This output displays the details of a new package.json file, which was created with the npm init command. The package.json file is used to store metadata information about the Node.js project. For further details, please refer to the ‘What is the file package.json’ article in the official Node.js documentation, as well as the ‘package.json reference’ in the npm documentation.

In order to ensure that your bot’s application code runs smoothly, it is necessary to install a few dependencies from npm. To do this, simply enter the relevant commands in your terminal while within the code repository; this will ensure that all dependencies are properly installed.

npm install node
npm install node-schedule
npm install twit
npm install dotenv

All You Need to Create a Fully-Functional Twitter Bot: Discover These Dependencies!

  • Installing the node package provides a local Node.js binary inside your project folder, which makes your project more portable and independent of the system-wide version of Node.js. This ensures that the project can be easily installed on other systems, even if they run different versions of Node.js. Consequently, this creates a better user experience, as it eliminates the need to install the same project multiple times on different systems.
  • Node-schedule is a package used by the tutorial to periodically schedule new Tweets; thus, it enables users to automate their Tweets and post updates at regular intervals. This is a convenient way to keep followers informed and engaged, as well as to ensure content distribution is regularly maintained.
  • Dotenv is a package that is used to successfully read secrets that have been stored in a .env file. Specifically, it enables applications to utilize variables stored in an environment file, allowing developers to keep sensitive information secure and out of their codebase. Consequently, it is a highly effective way to store and access confidential information.
  • This is a Twitter API client for Node.js, providing an easy way to access and interact with the Twitter API simultaneously. Additionally, it enables developers to write their own custom API calls, thereby allowing for a more tailored approach.

Your Directory has Never Looked Better: See What It Now Looks Like!

ls -a

. .env .gitignore package-lock.json
.. .git LICENSE node_modules package.json

Effortlessly Keep Your Packages Up-to-Date with These Simple Scripts

Before we can begin adding our code, we should first adjust a few parts of the package.json file in the new Node.js project; not only to ensure that the project is configured properly, but also to ensure that it is running the correct dependencies.

  1. Transform Your Package.json Scripts – Follow These Steps for a Quick & Easy Setup

File: package.json

 "scripts": {
"test": "echo \"Error: no test specified\" && exit 1"

The “scripts” section in package.json contains commands that can be used to invoke your project; furthermore, for more information on this part of package.json, the npm documentation’s “scripts reference” should be consulted.

Transform Your Scripts Section – Modify It to Match This Snippet Now!

File: package.json

"scripts": {
"test": "snes.js",
"start": "node ./snes.js",
"develop": "NODE_ENV=develop node snes.js"
  1. Discover the Hidden Secrets Inside: Scroll to the Main Section to Uncover What Lies Beneath

File: package.json

"main": "index.js",

Get the Latest Update: Stay Ahead of the Curve with This Important Information

File: package.json

"main": "snes.js",
  1. In order to ensure that the changes referenced an snes.js file which doesn’t exist yet, one can create an empty placeholder file with this name in their code repository. This can be done by using the touch command from the terminal or simply creating an empty file using a text editor.
touch snes.js

Add Your Own Twitter Bot Application Code Now – Unlock the Power of Automation

Now that your Node.js project is ready for the Twitter bot application code, you can open snes.js in your text editor and proceed through the next sections accordingly; furthermore, ensure that you understand the code and its implications.

Discover How to Unlock Hidden Secrets, Automate Tasks, and Control YouTube Videos with These Easy Tips

This snippet of code can be used to create a Twitter bot that posts random SNES soundtracks. After copying and pasting the snippet into snes.js, the @SnesSoundtracks string on line 3 needs to be replaced with the user’s own Twitter username in order for the bot to work properly. Once this is done, the bot will be ready to go, allowing the user to enjoy a variety of SNES soundtracks at random intervals.

File: snes.js

console.log("SNES Soundtracks booting up");

const twitterUsername = '@SnesSoundtracks';

//making sure npm run develop works
if (process.env.NODE_ENV === "develop") {

//rules for node-schedule
var schedule = require("node-schedule");
var rule = new schedule.RecurrenceRule();
rule.dayOfWeek = 1,
rule.hour = 10;
rule.minute = 0; = "Etc/GMT+4";

//array to pull soundtracks from
var soundtrackArray = [
"", // Legend of Zelda
"", // Chrono Trigger
"", // Super Metroid
"", // Final Fantasy VI
"", // Super Mario World
"", // Super Street Fighter II
"", // Super Mario World 2: Yoshi's Island
"", // Super Mario Kart
"", // Star Fox
"", // Super Mario RPG: Legend of the Seven Stars
var soundtrackArrayLength = soundtrackArray.length;

Uncover the Power of Code: Reveal What It Can Do for You!

  • Startup Message Successfully Logged – Run Your Code with Confidence
  • Using the built-in Node.js require() function, the dotenv module is included on line 7. Furthermore, the dotenv module’s config() function is used to read the values from the .env file and place them in the process.env Node.js property. Consequently, the consumer_key secret can be accessed inside process.env.consumer_key within the code – all in one line.

The if statement on lines 6-8 ensures that the Node.js environment is set to develop, thereby preventing any unwanted behaviour. This is handled by adding the “develop”: “NODE_ENV=develop node snes.js” line in the scripts section of the package.json file; thereby allowing the user to control when the Node.js environment is set to develop.

  • We utilized the node-schedule package by setting up a few variables on lines 11-15. These variables specify that the bot should tweet periodically every Monday at 10 am Eastern Daylight Savings Time. Furthermore, a RecurrenceRule was created to ensure this schedule could be followed.
  • Using conjunct adverb, lines 18-30 set up an array of soundtrack links for the bot to pull from at random; thus, enabling the bot to generate a variety of different soundtracks for users to enjoy.

Unlock the Power of Twitter: Guide to Authenticating and Listening for Tweets

Supercharge Your App Development: Add snes.js to the Bottom of Your Script

File: snes.js

// ... append to bottom of file:

// Create a Twitter client object to connect to the Twitter API
var Twit = require('twit');

// Pulling keys from another file
var config = require('./config.js');
// Making a Twit object for connection to the API
var T = new Twit(config);

// Setting up a user stream
var stream ='statuses/filter', { track: twitterUsername });

// Now looking for Tweet events
// See:
stream.on('tweet', pressStart);

Take Your Code to the Next Level: Introducing Twit

  • Unlock the Power of Twitter with the Twit Twitter API Client Module!
  • Create a New Configuration Object in Just Two Steps – With Line 7 and a config.js File!
  • The new operator of JavaScript is used in line 9 to create an instance of the Twitter API client and the configuration object from line 7 is passed to its constructor function. This instance is stored in the variable T and the T.propertyName syntax is used to access any property, field, or method from the API client’s library; thus, simplifying the usage.
  • Line 12 establishes a stream that is constantly tracking for any Tweet mentions of your Twitter username from other users while the code is running. Consequently, you are able to keep up with the latest interactions on your account in real-time.
  • Listen and Respond: Utilize the Stream.on Method to Create an Event Listener
    • Listen for the Right Event: Unlock the Power of a String Parameter!
    • Unlock Incredible Power With pressStart: A Comprehensive Tutorial On Event Handling!
  1. Unlock the Power of Your Code Repository with This Simple Configuration Trick!


 module.exports = {

consumer_key: process.env.consumer_key,

consumer_secret: process.env.consumer_secret,

access_token: process.env.access_token,

access_token_secret: process.env.access_token_secret,

This file exports an object which perfectly conforms to the configuration object accepted by the twit module’s constructor function – as stated in the twit README file on GitHub. Specifically, twit expects an object with the following form.
consumer_key: '...',
consumer_secret: '...',
access_token: '...',
access_token_secret: '...'
Unlock the Secrets of Process.env and Generate the Perfect Configuration Object!

Boost Your Visibility and Engagement – Learn How to Effectively Reply to Tweets!

// ... append to bottom of file:
function pressStart(tweet) {

var id = tweet.id_str;
var text = tweet.text;
var name = tweet.user.screen_name;

let regex = /(please)/gi;

let playerOne = text.match(regex) || [];
let playerTwo = playerOne.length > 0;

//this helps with errors, so you can see if the regex matched and if playerTwo is true or false

// checks text of tweet for mention of SNESSoundtracks
if (text.includes(twitterUsername) && playerTwo === true) {

// Start a reply back to the sender
var soundtrackArrayElement = Math.floor(Math.random() * soundtrackArrayLength);
var replyText = ("@" + name + " Here's your soundtrack: " + soundtrackArray[soundtrackArrayElement]);

// Post that tweet'statuses/update', { status: replyText, in_reply_to_status_id: id }, gameOver);

} else {
console.log("uh-uh-uh, they didn't say the magic word.");

function gameOver(err, reply) {
if (err) {
console.log("Game Over");
} else {
console.log('Tweeted: ' + reply.text);
This section of code defines a pressStart function that is invoked whenever another Twitter user mentions the bot. It includes several local variables, some logic and another callback function which must be included in the method. Furthermore, additionally, the pressStart function is responsible for replying to the user who initiated the mention.
  • The pressStart function, defined on line 3, utilizes a tweet object as a parameter, representing a Tweet that has mentioned the bot. This tweet object contains a plethora of data, and the Twit client aids in filtering through it efficiently; consequently, allowing the bot to respond appropriately.
  • Unlock the Power of 3: Extract Tweet ID, Text and Username to Respond Instantly!
  • The code in lines 9-13 uses a regular expression (regex) to analyze the text of a Tweet object. Specifically, it searches for a keyword that you can set, such as ‘please’, that when matched will activate the bot to send a reply Tweet with a random soundtrack. As a result, users can politely engage with the bot and receive a response in kind.
  • The /(please)/gi regex definition at the end of the expression denotes two separate options for execution – the “g” flag meaning global and the “i” flag meaning case-insensitive. Consequently, this expression will be applied globally and is not case-sensitive, ensuring a more comprehensive search.
    • By default, a regex only looks for the first match in the text string; however, by using the ‘g’ option, all matches throughout the string can be returned. For instance, if a Tweet includes the word “please” three times, the regex will return all three matches.
    • Discover How the “i Option” Ignores Capitalization and Enhances Your Writing!
  • No Matches? No Problem – Setting the playerOne Variable to an Empty Array!
  • Verifying Tweet Text with Regex: Discover How to Use the playerTwo Variable to Check if the Array playerOne Has Anything In It!
  • Build a Perfect Reply Tweet with an if Block: Unlock the Power of Line 21-30!
  • Maximize Your Bot’s Efficiency: Use the if Statement to Ensure Your Tweet Text Includes the Bot’s Name and Keyword!
  • Time to Rock Out: Create a Reply Tweet with a Random Element of the Soundtrack List Array!
  • Send Tweets Instantly – Leverage the Power of the Method and Twitter API Endpoint!
  • An object with two properties, status and in_reply_to_status_id, is passed to the method; the status property is set to the replyText variable, and the in_reply_to_status_id is set to the id variable from the pressStart function. This allows Twit to identify which Tweet the bot replies to with the actual text, thus allowing for a reply to a Tweet from Twitter’s API.
  • The method is passed a gameOver callback function, which is defined on lines 34-41. This function prints either the reply Tweet to the console, or any errors returned from the Twitter API, after the POST request has been made.
  • Otherwise, if the Tweet mention does not say “please”, the else block on lines 30-32 is invoked; this logs a quote from Jurassic Park to the console, illustrating why the bot didn’t tweet back.

Unlock the Power of Automation: Get Your Tweets Scheduled to Reach More Audiences!

File: snes.js

// ... append to bottom of file:

function pressSelect() {
var now = new Date();
const dateOptions = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
const timeOptions = { timeZoneName: 'short' };
const dateString = now.toLocaleDateString("en-US", dateOptions) + " at " + now.toLocaleTimeString("en-US", timeOptions);

var soundtrackArrayElement = Math.floor(Math.random() * soundtrackArrayLength);
var weeklyText = soundtrackArray[soundtrackArrayElement] + " Here's your soundtrack for " + dateString;'statuses/update', { status: weeklyText }, gameOver2);

function gameOver2(err, reply) {
if (err) {
console.log("Game Over");
} else {
console.log('Tweeted: ' + reply.text);

const job1 = schedule.scheduleJob(rule, pressSelect);

Automate Your Twitter Presence with a Link to a Soundtrack – PressSelect Function Does the Work For You!

  • Using a conjunct adverb, this content can be summarized as follows: Likewise, a weeklyText string is crafted and slightly modified to become an original Tweet, including an element from the soundtrack list array.
  • The method is invoked with the same statuses/update API endpoint, and no in_reply_to_status_id property is passed; accordingly, the function is composing an original Tweet, not a reply.
  • Although the gameOver callback function is present on lines 13-20, it has been renamed to gameOver2 to prevent any name conflicts; even though both gameOver and gameOver2 are local variables within their respective functions, we have changed the name merely for safety.
  • After the pressSelect definition, line 23 invokes the node-schedule module’s scheduleJob function and stores the result in the job1 variable, thus completing the setup of periodic scheduled Tweets. Notably, this function requires two arguments: the trigger time and the job to be executed.
    • Unlock the Power of Automation: Run Your Scheduled Job Once a Week on Mondays
    • Advanced Functionality at Your Fingertips: Introducing pressSelect!

Transform Your Code into a Powerful Piece of Software with GitHub!

Now that the bot code has been added to your workstation’s copy of the repository, we should make a new commit; this will record your file changes in the version control history. Additionally, after making the new commit, you can then push it to your repository on GitHub.
In this tutorial, two methods of creating a commit and pushing it to GitHub are demonstrated. Users can either choose to commit and push with GitHub Desktop, or commit and push with the Git Command Line. Both methods are detailed in the subsequent sections, thus allowing users to select the one they prefer.

Unlock the Power of GitHub: Easily Commit and Push with GitHub Desktop!

  1. Effortless Commitment of New Files – Open GitHub Desktop on Your Workstation Now!
  1. Introducing the New Twitter Bot Application Code – Committing to a More Robust User Experience!
  2. Commit to Success – Press the Main Button Now to Create a New Commit on Your Repository!
Baffled by an Empty Changes Tab After Creating a Commit? Here’s What to Do!
  1. Easily Push Your New Commit to Your GitHub Repository – Just Click the Push Origin in the Top Navigation!
New Node.js Project Files: Ready to Explore on Your GitHub Repository!

Unlock the Power of Git Command Line: Learn How to Commit and Push with Ease!

  1. Get Ready to Take Your Code to the Next Level – Run Your Local Repository Now!
git status
The following output appears:
On branch main
Your branch is up to date with 'origin/main'.

Untracked files:
(use "git add <file>..." to include in what will be committed)
Unlock the Hidden Potential of Your Application Files: Discover Untracked Files in Git!
  1. Staging Your Files for Commit: Learn How to Ensure Your Changes are Saved!
git add .
  1. Reveal the Hidden Status of Your System – Run the Status Command Again!
 git status

The output now appears as:

On branch main
Your branch is up to date with 'origin/main'.
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
new file: config.js
new file: package-lock.json
new file: package.json
new file: snes.js
Discovering the Default Branch Name for GitHub Repositories: Uncovering the Power of the Main Branch!
  1. A New Way To Easily Include All Files In Your Next Git Commit – Here’s How!
 git commit -m "Add Twitter bot application code"

This output appears:

[main e5d6839] Add Twitter bot application code
4 files changed, 599 insertions(+)
create mode 100644 config.js
create mode 100644 package-lock.json
create mode 100644 package.json
create mode 100644 snes.js
  1. Commit Your Code to a Secure Repository on GitHub – Make Your Projects Easier to Manage!
git push origin main

This output appears:

Enumerating objects: 7, done.
Counting objects: 100% (7/7), done.
Delta compression using up to 12 threads
Compressing objects: 100% (6/6), done.
Writing objects: 100% (6/6), 7.57 KiB | 1.08 MiB/s, done.
Total 6 (delta 0), reused 0 (delta 0)
735ecd1..e5d6839 main -> main
  1. Node.js Project Gets an Update – Check Out the New Files in Your GitHub Repository!
Unlock Your Success: Run the Code and Achieve Your Goals!
Test Your Code Now and Make Sure It’s Working: Type ‘npm run develop’ into the Terminal!
npm run develop

If successful, the following output appears:

> [email protected] develop
> NODE_ENV=develop node snes.js

SNES Soundtracks booting up
If any errors appear, then they are likely related to an authentication failure with the Twitter API; in this case, your .env file might have syntax errors, or your secret keys may have been incorrectly pasted into it. To resolve this issue, review the Troubleshooting consumer_key Twit Config Error and Troubleshooting Twitter Error 401 Unauthorized sections.

Test your Tweet Reach: See How Far Your Messages Go with Our Tweet Function!

Test Your Bot’s Twitter Functionality: Modify the Code and Watch it Send a Scheduled Tweet!

  1. Unlock Hidden Features in Snes.js By Commenting Out the Last Line and Directly Calling pressSelect!

File: snes.js


// ... modify end of file as follows:

// const job1 = schedule.scheduleJob(rule, pressSelect);

By doing this, the tweeting function runs immediately, and you don’t have to wait until the next scheduled Tweet.
  1. Stop and Restart Easily: Interrupt and Restart Your Bot with Just One Keystroke!
 npm run develop

If successful, output like the following output appears:

> [email protected] develop
> NODE_ENV=develop node snes.js

SNES Soundtracks booting up
Tweeted: Here's your soundtrack for Tuesday, June 1, 2021 at 10:59:19 AM UTC

If you don’t see the expected output, you might instead see an error which says “Read-only application cannot POST”. In this case, your app’s permissions are likely set to Read Only in the Twitter developer portal. Therefore, it is necessary to revisit the earlier step of giving your Twitter App Read and Write Permissions, and then return to this section.

Discover How Test Tweet Replies Can Help You Maximize Engagement!

Test Your Bot’s Interaction with Other Users – See How It Stacks Up!
  1. Easily Reverse Your Code – Remove the pressSelect(); Line, Uncomment the Last Line, and Save the File!
  1. Type CTRL-c to Instantly Stop and Restart Your Bot – It’s That Easy!
 npm run develop
Tweet at Your Bot and See the Magic Unfold: Log in to Another Twitter Account and Use the Keyword to Activate!

Unlock Your Code-Writing Potential with ‘Host the Code’!

Run Your Bot In Minutes On A Compute Instance – Learn How To Create & Host On Linode Now!

Unlock the Power of the Cloud with a Linode – Create Yours Today!

Experience the Power of the Cloud with Linode Cloud Manager – Create Your First Linode Now!

  1. Create an Instance with Unprecedented Options – Follow Our Step-by-Step Guide!
  • Experience the Unparalleled Power of Ubuntu 20.04: The Ultimate Linux Distribution!
  • Choose Your Region: Find the Nearest Location for an Unforgettable Experience!
  • Experience Maximum Power and Performance With Nanode: The Smallest, Most Affordable Linode Plan At Just $5/Month!
  • Secure Your Server: Choose a Unique, Long, and Complex Root User Password!
  • Name Your Project First: Discover the Power of Labelling Your Linode!
  1. Unlock the Potential of Your New Linode – Get Inside and Clean Up in Just a Few Moments!

Engage in Security Best Practices: Log In and Secure the Server Now!

  1. To log into the server, start by following the Connect to Your Linode via SSH section of the Getting Started guide. Alternatively, if you don’t have access to an SSH client or if SSH connections are firewalled, you can use the Lish console from the Cloud Manager in your web browser by following the Use a Web Browser instructions in the Lish guide.
Create a Limited User for Your Linode – Log In Securely with Root Credentials!
  1. To create a non-root-user, follow the Add a Limited User Account section of our Setting Up and Securing a Compute Instance guide; naming the user ‘tutorialbotuser’ or whatever desired. Additionally, instructions in this section also demonstrate how to provide the user with sudo privileges, allowing it to complete software updates and other administrative tasks accordingly.
  1. After creating the limited user, log out of your current SSH (or Lish) session by running the exit command, and then log back in immediately as the new user.

Stay Ahead of the Curve: Perform Software Updates and Prepare for the Bot Revolution!

  1. Keep Your System Up-To-Date: Run sudo apt update and sudo apt dist-upgrade with Your Limited User!
  1. Install Node.js and NPM on Ubuntu 20.04 for Bot Running – Use nvm for Best Results!
    1. Unlock the Power of the Linode with the NVM Installer!
 wget -qO- | bash
    1. Log Out and Log Back In Again to Start Using NVM – An Essential Step!
    1. Easily Install the Latest Node.js and npm with nvm!
 nvm install --lts
Two Simple Ways To Upload Your Bot’s Code To The Server – Get Ready To Run Your Bot Now!
  • Filezilla is a GUI desktop application that makes transferring code from your workstation to a Linux instance easier for beginners. It can be done by following the Upload the Bot Using Filezilla section, thus providing a more user-friendly experience.
  • Clone Your GitHub Repository Directly to Your Linode Instantly – Follow the Easy Steps in the ‘Upload the Bot with Git Clone’ Section!

Unlock the Power of Automation: Upload Your Bot with Filezilla!

  1. Unlock the Power of Filezilla: Download the Installation Files Now!
  2. Discover the Power of Filezilla: Unveiling the User Interface of the Popular FTP Client!
  1. Unlock Access to Your Data – Get Started with Filezilla Through Setting Up Host, Username, Password and Port Values!
Field Value
Host The IP Address for your Linode. Use the Find your Linode’s IP Address guide to locate your IP address in the Cloud Manager.
Username This should be the name for the limited non-root-user you created.
Password The password for the limited non-root-user you created.
Port This should be set to 22.
  1. Double-Check to Avoid Unwanted Surprises: How to Confirm IP Address in Filezilla When Connecting to Linode
  1. The Filezilla window is divided into two halves, with the left side showing your local files and the right side showing your Linode’s files. In order to set up the Twitter bot, you need to move the .env file, config.js file, package.json file, package-lock.json file, node_modules folder, and snes.js application code file to the directory where you’re keeping the files for your Twitter bot. All of these files are highlighted in the picture provided.
  1. By default, the right side of the FileZilla window shows the files in the home directory of your Linode’s user, which is where you want to install the bot. Consequently, simply highlight the files you want to transfer on the left side, and then click and drag them to the right.
Transfer Complete: Now Run the Bot for Optimal Performance!

Unlock the Power of Automation: Upload Your Bot with Git Clone!

  1. Git is already preinstalled on Ubuntu 20.04, however you must still configure it as you had done on your workstation. While inside your SSH or Lish connection to your Linode, follow the Configure Git section of the Getting Started with Git guide. Although it is not necessary to set the core.editor option, it is important to set your username and email for Git.
  1. To clone your GitHub repository to your Linode, first run the git clone command from your SSH or Lish connection, substituting your own GitHub username for ‘your-github-username’ and the name you chose for the repository for ‘snes-soundtracks’ before running the command; furthermore, ensure that the command is executed correctly.
 git clone
  1. Cloning the repository does not install the NPM dependencies for your project, since they were excluded from version control in your .gitignore file; however, the required dependencies are still outlined in the package.json file. Consequently, to reinstall the packages, navigate to the new cloned repository and then install them accordingly.
 cd snes-soundtracks
 npm install
Unlock the Full Power of npm: Discover How the ‘npm install’ Command Automatically Installs Dependencies!
  1. Additionally, the .env file was excluded from version control, so it needs to be copied separately to your Linode. To do this, open the local .env file on your workstation and copy its contents to the clipboard. Afterwards, create a new .env file inside the code repository on the Linode, using the nano command line text editor.
 nano .env

The nano editor’s interface looks like this when first opened:

Transform Your Clipboard Content into Professional Text with Just One Click!

Easily Setup Your Environment with Just a Few Clicks – CTRL-o and Enter!

  1. Type CTRL-X to Unlock Your Productivity: Exit the Editor with Ease!
  2. Secure Your .env File! Remove File System Read and Write Permissions for Groups and Other Users on the Linode
  3. Secure Your .env File! Remove File System Read and Write Permissions for Groups and Other Users on the Linode
 chmod go-rw .env
Doing this ensures that your secret keys can’t be read by other users on the system.
Get Ready to Run Your Bot – Cloning and Installing Dependencies Done Quickly!

Bring Your Bot to Life on a Linode Server!

Run Your Bot Anywhere with SSH Connection or Lish Console – File Transfer Made Easy!
npm run develop
However, even if you close your SSH connection or need to perform some other action in the Lish console, the bot will not remain running.
Screen is an invaluable tool for creating terminal sessions that stay alive and can be accessed from any SSH or Lish connection, and it’s preinstalled on Ubuntu 20.04, so you can start using it right away to keep your bot running uninterrupted.
  1. Stop Your Bot Now: What to Do When You Run npm run Develop on Your Linode
  1. Unlock the Power of Your Linux Server: Run Commands from Your Linode!
  1. By creating a new Screen session, a welcome message is presented to the user; to close the message, simply hit Enter on the keyboard. Furthermore, this allows for a more efficient and organized work flow.
  1. You are now in your Screen session. Run the bot again:
 npm run develop
  1. Then, to detach from the Screen session, press CTRL-a followed by the d key; afterwards, a message such as “detached” will appear, thereby bringing you back to your previous terminal history.
[detached from 38905.pts-0.localhost]
  1. Your bot continues to run seamlessly, even if you close your SSH or Lish connection. You can re-establish your connection from the same SSH or Lish connection, or from a new one; simply use the command to reattach to your screen session.
 screen -r
  1. Halt Your Bot Instantly – Reattach to the Screen Session and Press CTRL-c!
  1. Halt Your Bot Instantly – Reattach to the Screen Session and Press CTRL-c!

Troubleshoot Your Way to Success: Unravel the Mysteries of Fixing Issues!

Solve Your Twit Configuration Error with These Simple Troubleshooting Steps!

When starting the bot, you may see an error like this:
> [email protected] develop
> NODE_ENV=develop node snes.jsSNES Soundtracks booting up
throw new Error(err_msg)

Error: Twit config must include `consumer_key` when using user auth.
at /home/tutorialbotuser/snes-soundtracks/node_modules/twit/lib/twitter.js:511:13
at Array.forEach (<anonymous>)
at Twitter._validateConfigOrThrow (/home/tutorialbotuser/snes-soundtracks/node_modules/twit/lib/twitter.js:508:17)
at new Twitter (/home/tutorialbotuser/snes-soundtracks/node_modules/twit/lib/twitter.js:58:8)
at Object.<anonymous> (/home/tutorialbotuser/snes-soundtracks/snes.js:26:9)
at Module._compile (node:internal/modules/cjs/loader:1109:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1138:10)
at Module.load (node:internal/modules/cjs/loader:989:32)
at Function.Module._load (node:internal/modules/cjs/loader:829:14)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
at node:internal/main/run_main_module:17:47
This Twit error about your consumer_key likely indicates a syntax error in your .env file. To ensure this doesn’t happen, make sure there are no spaces between the variable, equals sign, and key itself. Thus, the .env file should be formatted like this example (where your keys are different): `consumer_key=your_key_here`.

File: .env

Don’t Let Twitter Error 401 Unauthorized Ruin Your Day – Follow These Troubleshooting Steps Now!

Solve the ‘Unauthorized’ Frustration: Troubleshoot Twitter Error 401!

When starting the bot, you may see an error like this:

 > [email protected] develop
> NODE_ENV=develop node snes.js

SNES Soundtracks booting up
throw er; // Unhandled 'error' event

Error: Bad Twitter streaming request: 401
at Object.exports.makeTwitError (/home/tutorialbotuser/snes-soundtracks/node_modules/twit/lib/helpers.js:74:13)
at Request.<anonymous> (/home/tutorialbotuser/snes-soundtracks/node_modules/twit/lib/streaming-api-connection.js:96:29)
at Request.emit (node:events:377:35)
at Gunzip.<anonymous> (/home/tutorialbotuser/snes-soundtracks/node_modules/request/request.js:1076:12)
at Object.onceWrapper (node:events:471:28)
at Gunzip.emit (node:events:365:28)
at endReadableNT (node:internal/streams/readable:1312:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
Emitted 'error' event on StreamingAPIConnection instance at:
at Request.<anonymous> (/home/tutorialbotuser/snes-soundtracks/node_modules/twit/lib/streaming-api-connection.js:99:14)
at Request.emit (node:events:377:35)
[... lines matching original stack trace ...]
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
code: null,
allErrors: [],
twitterReply: '<html>\\n<head>\\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>\\n<title>Error 401 Unauthorized</title>\n' +
'</head>\n' +
'<body>\n' +
'<h2>HTTP ERROR: 401</h2>\n' +
"<p>Problem accessing '/1.1/statuses/filter.json'. Reason:\n" +
'<pre> Unauthorized</pre>\n' +
'</body>\n' +
statusCode: 401
This error indicates that the wrong keys were copied into your .env file, or that the .env key names have been incorrectly associated with the wrong credentials from the Twitter developer portal. To rectify this, review the table below for the correct associations between the .env file and the Twitter developer portal credentials, so as to ensure accuracy.

env Key Name Twitter Developer Portal Credential Name

consumer_key API Key
consumer_secret API Secret Key
access_token Access Token
access_token_secret Access Token Secret
If you’re uncertain about your API keys, you can easily regenerate them within the Twitter developer portal – as outlined in the Regenerate API Keys and Tokens section of Twitter’s documentation.

Eliminate Frustration: Troubleshoot Read-Only Twitter Application & Fix ‘Cannot POST’ Error!

When your bot attempts to tweet, you may see an error like this in its logs:
Read-only application cannot POST.
This error indicates that your app’s permissions are set to Read Only in the Twitter developer portal. To rectify this, follow the instructions in the Give your Twitter App Read and Write Permissions section, which outlines how to switch to Read and Write permissions and then regenerate your Access Token and Access Token Secret. Consequently, both these steps need to be taken in order to ensure proper usage of your app.

Unlock Even More Insight with More Information!

While these resources may be useful, it is important to note that we cannot guarantee their accuracy or timeliness. Therefore, users should be mindful when consulting these external sources for additional information on this topic.