Reddit Bot in Python
About the project: This is a simple Reddit bot project written in Python.
This bot uses the popular PRAW (Python Reddit API Wrapper) library, which makes interacting with the Reddit API much easier.
This project is a single, self-contained file that demonstrates how to authenticate with Reddit and perform a basic task: monitoring a subreddit for a specific keyword and replying to any comment that contains it.
The bot will then start monitoring the specified subreddit.
How to Use and Run the Bot
- Install the PRAW Library:Open your terminal or command prompt and run the following command to install the required library:
pip install praw
- Create a Reddit App: As explained in the code comments, you'll need to create a "script" app on Reddit to get your unique API credentials. Go to [reddit.com/prefs/apps](https://www.reddit.com/prefs/apps) to get started.
- Run the Script:Save the updated file and run it from your terminal:
python reddit_bot.py
Project Level: Intermediate
You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.
Steps: Follow these stepsStep 1: Copy below code using green 'copy' button.
Step 2: Paste the code on your chosen editor.
Step 3: Save the code with filename and .py extention.
Step 4: Run (Press F5 if using python IDLE).
# reddit_bot.py
import praw
import time
def create_reddit_instance():
"""
Creates and returns a PRAW Reddit instance with the necessary credentials.
IMPORTANT: You must replace the placeholder values below with your own
Reddit API credentials. Follow these steps to get them:
1. Go to https://www.reddit.com/prefs/apps
2. Click 'are you a developer? create an app...' at the bottom.
3. Fill out the form. Use 'script' for the app type.
4. You will be given a client ID and a client secret.
5. You also need your Reddit username and password.
Never share these credentials or hardcode them in a public repository!
"""
try:
reddit = praw.Reddit(
client_id="YOUR_CLIENT_ID",
client_secret="YOUR_CLIENT_SECRET",
user_agent="your-bot-name-by-u/your-reddit-username",
username="YOUR_REDDIT_USERNAME",
password="YOUR_REDDIT_PASSWORD"
)
print("Successfully authenticated with Reddit as:", reddit.user.me())
return reddit
except Exception as e:
print("Error during authentication. Please check your credentials.")
print("Error details:", e)
return None
def main():
"""
The main function of the bot. It monitors a subreddit for comments
containing a specific keyword and replies to them.
"""
# Create the Reddit instance
reddit = create_reddit_instance()
if not reddit:
return # Exit if authentication failed
# The subreddit to monitor. Use a test subreddit for development to avoid
# spamming real communities.
subreddit_name = 'test'
# The keyword the bot will look for in comments.
keyword = "bot_test"
# The message the bot will reply with.
reply_message = "This is an automated reply from a bot! Thanks for the test."
try:
# Get the Subreddit object
subreddit = reddit.subreddit(subreddit_name)
print(f"Monitoring r/{subreddit_name} for the keyword '{keyword}'...")
# Stream comments from the subreddit in real-time.
# This loop will run indefinitely.
for comment in subreddit.stream.comments():
# Check if the comment author is not the bot itself to prevent loops.
if comment.author and comment.author.name != reddit.user.me().name:
# Check if the keyword is in the comment text (case-insensitive)
if keyword in comment.body.lower():
print(f"\nKeyword found in comment ID: {comment.id}")
print(f"Comment by u/{comment.author.name}: {comment.body}")
try:
# Reply to the comment
comment.reply(reply_message)
print("Successfully replied to the comment.")
# Wait for a short period to respect API rate limits
time.sleep(10)
except praw.exceptions.APIException as e:
# Handle cases where the bot might be rate-limited or
# the comment is too old to reply to.
print(f"Could not reply to comment. Error: {e}")
else:
# If the comment is from the bot, just print a message and continue
if comment.author:
print(f"Ignoring own comment from u/{comment.author.name}")
else:
print("Ignoring comment with no author.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
if __name__ == "__main__":
main()
This is a starting point for building a Reddit bot. You could enhance this project by adding more features like monitoring multiple subreddits, logging bot activity to a file, or having the bot respond with a different message based on the keyword it finds.
← Back to Projects