🚀 Executive Summary

TL;DR: Manually tracking brand mentions on Reddit is inefficient and risky. This guide provides a Python script solution to automatically stream Reddit for specified keywords and send real-time alerts to Telegram, significantly improving responsiveness and saving time.

🎯 Key Takeaways

  • Utilize PRAW’s `subreddit.stream.comments` for real-time, continuous monitoring of new Reddit comments and submissions across specified subreddits.
  • Securely manage API credentials (Reddit Client ID/Secret, Telegram Bot Token/Chat ID) using `python-dotenv` and a `config.env` file, preventing direct code exposure.
  • Implement `requests.post` to the Telegram Bot API with `parse_mode=’HTML’` for formatted, instant notifications of brand mentions, including keyword, subreddit, user, and permalink.

Monitor Brand Mentions on Reddit and Alert via Telegram

Monitor Brand Mentions on Reddit and Alert via Telegram

Hey everyone, Darian here. A few months ago, I had a recurring task in my calendar: “Manually search Reddit for ‘TechResolve’ mentions.” It was a tedious, 20-minute chore that I honestly dreaded. Then one morning, I missed a critical post that was gaining some negative traction because I got pulled into a P1 incident. That was the tipping point. I realized I was wasting time and taking on unnecessary risk by doing this manually.

So, I built a small Python script to do the work for me. It streams Reddit for our brand keywords and pings me on Telegram the moment something pops up. It’s been a game-changer for our team’s responsiveness. Today, I’m going to walk you through how to build the exact same thing. Let’s reclaim some of that time.

Prerequisites

Before we dive in, make sure you have the following ready to go:

  • A Reddit Account and API credentials (Client ID, Client Secret).
  • A Telegram Account and a Bot Token from BotFather.
  • Python 3 installed on your system.
  • Basic comfort with running Python scripts and using APIs.

The Guide: Step-by-Step

Step 1: Get Your API Credentials

First, we need to get our keys to the kingdom. Store these securely and never commit them directly to your code repository.

  • For Reddit:
    1. Log in to your Reddit account and go to Preferences > Apps (or just visit reddit.com/prefs/apps).
    2. Scroll down and click “are you a developer? create an app…”.
    3. Fill out the form. Name it something like “BrandMonitor”, select “script” for the app type, and set the “redirect uri” to http://localhost:8080 (it’s required for script apps but won’t be used).
    4. Once created, you’ll see your app’s personal use script ID (this is your Client ID) and your secret (this is your Client Secret). Copy these down.
  • For Telegram:
    1. Open Telegram and search for the BotFather (the official one with the blue checkmark).
    2. Start a chat with him and send the /newbot command.
    3. Follow the prompts to name your bot. He will give you an HTTP API token. This is your Bot Token.
    4. Next, you need your Chat ID. Search for your new bot in Telegram and send it a message (any message, like “/start”).
    5. To get your Chat ID, the easiest way is to use another bot. Search for a “userinfobot” or similar, start a chat, and it will immediately tell you your user ID. This is your Chat ID.

Step 2: Project Setup and Dependencies

Alright, let’s get our environment ready. I’ll skip the standard virtualenv setup commands since you likely have your own workflow for that. Just make sure you’re working in a clean, isolated Python environment.

Once that’s running, you’ll need to install three Python packages using pip: praw for the Reddit API, requests to talk to Telegram, and python-dotenv to manage our secrets safely. I trust you know how to run pip for those.

Next, create a file named config.env in your project directory. This is where we’ll store our credentials. It should look like this:

REDDIT_CLIENT_ID=your_client_id_here
REDDIT_CLIENT_SECRET=your_client_secret_here
REDDIT_USER_AGENT=BrandMonitor by u/YourUsername
TELEGRAM_BOT_TOKEN=your_bot_token_here
TELEGRAM_CHAT_ID=your_chat_id_here

Step 3: The Python Script

Now for the fun part. Create a file named monitor.py. We’ll build this out logically, starting with loading our config, setting up the alert function, and then writing the main monitoring logic.

import os
import praw
import requests
from dotenv import load_dotenv
import logging

# Basic logging setup
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# Load environment variables from config.env
load_dotenv('config.env')

# --- Configuration ---
REDDIT_CLIENT_ID = os.getenv('REDDIT_CLIENT_ID')
REDDIT_CLIENT_SECRET = os.getenv('REDDIT_CLIENT_SECRET')
REDDIT_USER_AGENT = os.getenv('REDDIT_USER_AGENT')
TELEGRAM_BOT_TOKEN = os.getenv('TELEGRAM_BOT_TOKEN')
TELEGRAM_CHAT_ID = os.getenv('TELEGRAM_CHAT_ID')

SUBREDDITS_TO_MONITOR = ['devops', 'sysadmin', 'technology', 'programming']
KEYWORDS_TO_TRACK = ['TechResolve', 'Tech Resolve', 'our-product-name']


def send_telegram_alert(message):
    """Sends a formatted message to a Telegram chat."""
    if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CHAT_ID:
        logging.error("Telegram credentials not found.")
        return

    api_url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
    
    try:
        response = requests.post(
            api_url,
            json={'chat_id': TELEGRAM_CHAT_ID, 'text': message, 'parse_mode': 'HTML'}
        )
        response.raise_for_status()
        logging.info("Telegram alert sent successfully.")
    except requests.exceptions.RequestException as e:
        logging.error(f"Failed to send Telegram alert: {e}")

def monitor_reddit():
    """Initializes Reddit instance and monitors for keywords in comments and submissions."""
    if not all([REDDIT_CLIENT_ID, REDDIT_CLIENT_SECRET, REDDIT_USER_AGENT]):
        logging.critical("Reddit API credentials missing. Please check your config.env file.")
        return

    try:
        reddit = praw.Reddit(
            client_id=REDDIT_CLIENT_ID,
            client_secret=REDDIT_CLIENT_SECRET,
            user_agent=REDDIT_USER_AGENT
        )
        
        subreddit_string = "+".join(SUBREDDITS_TO_MONITOR)
        subreddit = reddit.subreddit(subreddit_string)
        logging.info(f"Monitoring subreddits: {subreddit_string}")
        logging.info(f"Tracking keywords: {', '.join(KEYWORDS_TO_TRACK)}")
        
        # Monitor comments
        for comment in subreddit.stream.comments(skip_existing=True):
            process_item(comment, 'comment')

    except Exception as e:
        logging.error(f"An error occurred in the main monitoring loop: {e}")
        send_telegram_alert(f"Monitoring Script Error:\n{e}")

def process_item(item, item_type):
    """Checks an item (comment/submission) for keywords and sends an alert."""
    body = item.body.lower() if hasattr(item, 'body') else ''
    title = item.title.lower() if hasattr(item, 'title') else ''
    
    # Check if any keyword is present
    for keyword in KEYWORDS_TO_TRACK:
        if keyword.lower() in body or keyword.lower() in title:
            logging.info(f"Keyword '{keyword}' found in a {item_type}!")
            
            message = (
                f"Reddit Brand Mention Alert!\n\n"
                f"Keyword: {keyword}\n"
                f"Subreddit: r/{item.subreddit.display_name}\n"
                f"User: u/{item.author.name}\n"
                f"Link: https://www.reddit.com{item.permalink}"
            )
            send_telegram_alert(message)
            # We found a match, no need to check other keywords for this same item
            break


if __name__ == "__main__":
    monitor_reddit()

The logic is straightforward: We use PRAW’s streaming functionality, which gives us a live feed of new comments. For each item, we check if any of our keywords appear in the text. If we find a match, we format a clean message and fire it off using our `send_telegram_alert` function.

Pro Tip: In my production setups, I often expand the `KEYWORDS_TO_TRACK` list to include common misspellings or related acronyms. It’s also wise to keep a simple log file or a small SQLite database of comment IDs you’ve already alerted on. This prevents duplicate notifications if the script has to restart for any reason.

Step 4: Automating the Script

This script is designed to run continuously. The `subreddit.stream` creates a persistent connection. The best way to run this is as a background service. You could use a tool like `screen` for simplicity, or for a more robust solution, run it in a Docker container or as a `systemd` service on a Linux server.

If you don’t need real-time alerts, you could modify the script to fetch recent posts instead of streaming and run it on a schedule. For example, a cron job to run it daily at 2 AM might look like this: `0 2 * * * python3 your_script.py`. Just remember to change the core logic from a stream to a one-time fetch.

Common Pitfalls

Here is where I usually mess up when deploying something like this, so you can avoid my mistakes:

  • Being Too Vague with Keywords: If your brand name is a common word like “Connect” or “Core,” you will get flooded with false positives. Be as specific as possible. Use “TechResolve” instead of “resolve”.
  • Ignoring API Rate Limits: PRAW is fantastic at handling Reddit’s rate limits for you, but if you modify the script to make lots of custom, rapid-fire API calls, you can get temporarily blocked. Stick to the stream for the best results.
  • Forgetting About Script Failures: What if your server reboots or the script crashes? The `skip_existing=True` flag helps, but it’s not foolproof. For a mission-critical monitor, you need a process manager (`systemd`, `supervisor`) to automatically restart the script.

Conclusion

And there you have it. With a bit of Python and a few API keys, you’ve built an automated brand intelligence system. This simple automation frees you up to focus on what actually matters: engaging with your community, not spending your valuable time searching for them. It’s a small investment that pays huge dividends in awareness and responsiveness. Happy monitoring!

Darian Vance - Lead Cloud Architect

Darian Vance

Lead Cloud Architect & DevOps Strategist

With over 12 years in system architecture and automation, Darian specializes in simplifying complex cloud infrastructures. An advocate for open-source solutions, he founded TechResolve to provide engineers with actionable, battle-tested troubleshooting guides and robust software alternatives.


🤖 Frequently Asked Questions

âť“ How do I set up continuous, real-time brand mention monitoring from Reddit to Telegram?

Configure a Python script using the PRAW library to stream Reddit comments and submissions for specific keywords, then use the Telegram Bot API via `requests` to send immediate, formatted alerts to a designated chat ID.

âť“ How does this automated solution compare to manual Reddit monitoring or third-party services?

This script offers a highly customizable, cost-effective, and real-time alternative to manual checks, providing immediate alerts. While it lacks the advanced features of commercial tools, it excels in direct, focused brand mention detection without subscription costs.

âť“ What are the critical considerations to avoid issues when deploying this Reddit monitoring script?

Key considerations include defining highly specific `KEYWORDS_TO_TRACK` to minimize false positives, understanding PRAW’s rate limit handling, and employing a process manager like `systemd` or `supervisor` to ensure the script automatically restarts after failures or reboots.

Leave a Reply

Discover more from TechResolve - SaaS Troubleshooting & Software Alternatives

Subscribe now to keep reading and get access to the full archive.

Continue reading