Build a Social Media Monitor with Python

tags: python, socialmedia, automation, tools


tags: python, socialmedia, automation, tools


Build a Social Media Monitor with Python

Imagine waking up to a Slack notification that your brand just got mentioned in a viral Reddit thread—but this time, the sentiment is negative. You lose 15 minutes panicking, scrolling through tabs, and trying to figure out if it’s a real crisis. Now imagine that same scenario, but you’re already armed with a clear summary, the original post link, and a sentiment score before you even finish your coffee. That’s the power of a custom social media monitor built with Python.

You don’t need a $500/month enterprise tool or a team of data scientists to get real-time insights. With a few Python libraries and 30 minutes of setup, you can build a lightweight monitor that tracks mentions, analyzes sentiment, and alerts you instantly. Let’s build one together.

Why Build Your Own Monitor?

Third-party tools like Brandwatch or Sprout Social are great, but they’re expensive, rigid, and often overkill for startups or solo developers. A custom Python monitor gives you:

  • Full control over which platforms and keywords to track
  • Custom sentiment logic tailored to your niche
  • Zero recurring costs (just your API usage)
  • Instant alerts via Slack, email, or Discord

Plus, you’ll learn valuable skills in API integration, data processing, and automation—bonus points for your next job interview.

Step 1: Choose Your Platform and API

Start with one platform for your MVP. Twitter (now X) is the easiest via API, but Reddit is also straightforward using PRAW. Instagram and Facebook require approved app access via the Graph API, which adds friction.

For this tutorial, we’ll use Reddit because:

  • It’s free with PRAW
  • No OAuth complexity for basic reads
  • Rich data (comments, scores, timestamps)

Install the library:

pip install praw textblob python-dotenv

Enter fullscreen mode Exit fullscreen mode

Create a .env file to store your Reddit API credentials safely:

REDDIT_CLIENT_ID=your_client_id
REDDIT_CLIENT_SECRET=your_client_secret
REDDIT_USER_AGENT=my_social_monitor

Enter fullscreen mode Exit fullscreen mode

Never hardcode API keys in your scripts. Use python-dotenv to load them:

from dotenv import load_dotenv
load_dotenv()

Enter fullscreen mode Exit fullscreen mode

Step 2: Fetch Mentions with PRAW

Now, let’s write a script that searches Reddit for posts containing your brand keyword.

import praw
import os
from textblob import TextBlob

# Load credentials
from dotenv import load_dotenv
load_dotenv()

client_id = os.getenv("REDDIT_CLIENT_ID")
client_secret = os.getenv("REDDIT_CLIENT_SECRET")
user_agent = os.getenv("REDDIT_USER_AGENT")

# Initialize Reddit instance
reddit = praw.Reddit(
    client_id=client_id,
    client_secret=client_secret,
    user_agent=user_agent
)

# Search for mentions
keyword = "supercoolbrand"  # Replace with your brand
subreddit = reddit.subreddit("all")

print(f"Searching Reddit for '{keyword}'...")

for post in subreddit.search(keyword, limit=20):
    blob = TextBlob(post.title)
    sentiment = blob.sentiment.polarity  # -1 (negative) to 1 (positive)

    sentiment_label = "Positive" if sentiment > 0.1 else "Negative" if sentiment < -0.1 else "Neutral"

    print(f"\n[{sentiment_label}] Score: {sentiment:.2f}")
    print(f"Title: {post.title}")
    print(f"Link: https://reddit.com/{post.id}")
    print(f"Author: {post.author}")

Enter fullscreen mode Exit fullscreen mode

This script:

  1. Connects to Reddit using your credentials
  2. Searches for posts containing your keyword
  3. Analyzes sentiment using TextBlob
  4. Prints a clean summary with link and author

Run it with:

python bot.py

Enter fullscreen mode Exit fullscreen mode

You’ll see real Reddit posts with sentiment scores instantly.

Step 3: Add Sentiment Analysis

TextBlob is simple and fast, but for social media, VADER (from nltk) often performs better because it’s trained on slang and emojis. Alternatively, use HuggingFace’s transformers for production-grade accuracy:

pip install nltk transformers

Enter fullscreen mode Exit fullscreen mode

For VADER:

from nltk.sentiment.vader import SentimentIntensityAnalyzer

analyzer = SentimentIntensityAnalyzer()
scores = analyzer.sentiment_scores(post.title)
compound = scores['compound']

if compound >= 0.05:
    label = "Positive"
elif compound <= -0.05:
    label = "Negative"
else:
    label = "Neutral"

Enter fullscreen mode Exit fullscreen mode

VADER gives you a compound score from -1 to 1, which is more nuanced than TextBlob’s polarity.

Step 4: Store and Alert on Spikes

Don’t just print to console—store results and alert on negative spikes.

Store in a Database

Use SQLite for simplicity (no setup needed):

import sqlite3

conn = sqlite3.connect("monitor.db")
cursor = conn.cursor()

cursor.execute("""
CREATE TABLE IF NOT EXISTS posts (
    id TEXT PRIMARY KEY,
    title TEXT,
    sentiment TEXT,
    link TEXT,
    timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)
""")

cursor.execute("INSERT INTO posts VALUES (?, ?, ?, ?)", 
               (post.id, post.title, label, f"https://reddit.com/{post.id}"))
conn.commit()

Enter fullscreen mode Exit fullscreen mode

Alert on Negative Spikes

If you get 3+ negative posts in 10 minutes, send a Slack alert:

pip install requests

Enter fullscreen mode Exit fullscreen mode

import requests

SLACK_WEBHOOK = os.getenv("SLACK_WEBHOOK_URL")

def send_slack_alert(title, link, sentiment):
    payload = {
        "text": f"🚨 Negative spike detected!\n{title}\n{link} ({sentiment})"
    }
    requests.post(SLACK_WEBHOOK, json=payload)

Enter fullscreen mode Exit fullscreen mode

Set up a cron job to run this every 15 minutes:

crontab -e
# Add:
*/15 * * * * /usr/bin/python3 /path/to/bot.py

Enter fullscreen mode Exit fullscreen mode

Step 5: Visualize Trends (Optional)

Want to see sentiment over time? Use Streamlit for a 5-minute dashboard:

pip install streamlit pandas

Enter fullscreen mode Exit fullscreen mode

import streamlit as st
import pandas as pd
import sqlite3

conn = sqlite3.connect("monitor.db")
df = pd.read_sql("SELECT * FROM posts", conn)

st.title("📊 Social Media Monitor Dashboard")
st.line_chart(df.groupby("timestamp")["sentiment"].value_counts())

st.dataframe(df)

Enter fullscreen mode Exit fullscreen mode

Run with:

streamlit run dashboard.py

Enter fullscreen mode Exit fullscreen mode

What You Can Do Today

You now have a working social media monitor that:

  • ✅ Tracks Reddit mentions for your brand
  • ✅ Analyzes sentiment with VADER or TextBlob
  • ✅ Stores results in SQLite
  • ✅ Alerts you on negative spikes via Slack
  • ✅ Visualizes trends with Streamlit

Next steps:

  1. Swap Reddit for Twitter/X using tweepy
  2. Add email alerts with smtplib
  3. Deploy to AWS EC2 or DigitalOcean
  4. Add geolocation filtering for regional insights

Wrap It Up

Building your own social media monitor isn’t just about saving money—it’s about owning your data, customizing your logic, and reacting faster than ever. You’ve got a script that works today, and a foundation to scale tomorrow.

Try it now: Swap "supercoolbrand" with your actual brand name, run the script, and see what Reddit is saying about you. Then share your results in the Dev.to comments—I’ll be reading (and monitoring) them myself. 🚀


If you found this helpful, consider buying me a coffee ☕ — it keeps these articles coming!

Also check out my AI tools collection: AI 次元世界 — free AI tools for developers.