Sling Academy
Home/Node.js/How to Create a Reddit Bot with Node.js

How to Create a Reddit Bot with Node.js

Last updated: December 30, 2023

Introduction

Creating a Reddit bot can be a great way to automate tasks, interact with users, or analyze data on Reddit. With Node.js, you can set up a simple bot with JavaScript or TypeScript, allowing you to take advantage of modern syntax and features. In this article, we’ll go through a step-by-step guide on setting up a Reddit bot using Node.js, incorporating arrow functions, async/await, and ES modules.

The Steps to Create a Reddit Bot with Node.js

Setting up Your Project

First, create a new directory for your bot and initialize a Node.js project. Install the necessary packages, including the relevant Reddit API wrappers such as snoowrap.

mkdir reddit-bot
 cd reddit-bot
 npm init -y
 npm install snoowrap

Configuring Your Bot

Before writing the bot’s code, you’ll need to create a Reddit script application for API access:

  1. Go to the Reddit apps page.
  2. Click ‘Create an app’ or ‘Create another app’ button.
  3. Fill out the form with the appropriate information.
  4. Once submitted, note down your Client ID and Client Secret.

Implementing the Bot

With your API credentials in hand, it’s time to start coding your bot. Set up your authentication and instantiate the Reddit API wrapper.

import Snoowrap from 'snoowrap';

const r = new Snoowrap({
  userAgent: 'reddit-bot-v1',
  clientId: 'YOUR_CLIENT_ID',
  clientSecret: 'YOUR_CLIENT_SECRET',
  username: 'YOUR_REDDIT_USERNAME',
  password: 'YOUR_REDDIT_PASSWORD'
});

Creating the Bot Logic

With your API client set up, you can now write functions to interact with Reddit. For example, you might create a function using async/await to fetch and log new comments from a specific subreddit:

const fetchComments = async subreddit => {
  try {
    const comments = await r.getSubreddit(subreddit).getNewComments();
    comments.forEach(comment => console.log(comment.body));
  } catch (error) {
    console.error(error);
  }
};

fetchComments('subreddit-name');

Listening for Events and Reacting

To make your bot interactive, you can have it listen for specific events, such as new posts or comments, and execute corresponding actions. Here’s an example of how you could reply to a comment with a specific phrase:

const replyToComments = async () => {
  const stream = r.getSubreddit('subreddit-name').stream.comments();
  stream.on('comment', async (comment) => {
    try {
      if (comment.body.includes('phrase-to-look-for')) {
        await comment.reply('Response from the bot.');
      }
    } catch (error) {
      console.error(error);
    }
  });
};

replyToComments();

Complete Code Example

Below is a simple bot that logs new comments and replies to them if they contain a certain word:

import Snoowrap from 'snoowrap';

const r = new Snoowrap({
  userAgent: 'reddit-bot-v1',
  clientId: 'YOUR_CLIENT_ID',
  clientSecret: 'YOUR_CLIENT_SECRET',
  username: 'YOUR_REDDIT_USERNAME',
  password: 'YOUR_REDDIT_PASSWORD'
});

const replyToComments = async () => {
  const stream = r.getSubreddit('subreddit-name').stream.comments();
  stream.on('comment', async (comment) => {
    console.log(`New comment: ${comment.body}`);
    if (comment.body.includes('phrase-to-look-for')) {
      console.log('Found a comment to reply to.');
      await comment.reply('Response from the bot.');
    }
  });
};

replyToComments();

Conclusion

With these steps and some JavaScript or TypeScript, you’ve successfully created a simple Reddit bot using Node.js, which can log and reply to comments in a subreddit. The wonders of Node.js and modern JavaScript features make such tasks more intuitive and fun. Venture further into customization by exploring the Reddit API documentation and expanding your bot’s capabilities!

Next Article: How fetch data from GitHub API with Node.js

Previous Article: How to create a Twitter bot with Node.js

Series: Node.js Intermediate Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates