# Reddit Sentiment Analyzer (`credible_sandal/reddit-sentiment-analyzer`) Actor

A Reddit posts and comments scrapper, then performs comprehensive sentiment analysis to understand community opinions and trends.

- **URL**: https://apify.com/credible_sandal/reddit-sentiment-analyzer.md
- **Developed by:** [RK K](https://apify.com/credible_sandal) (community)
- **Categories:** Social media, Other
- **Security:** Full permissions
- **Stats:** 2 total users, 0 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per usage

This Actor is paid per platform usage. The Actor is free to use, and you only pay for the Apify platform usage, which gets cheaper the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-usage

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Reddit Sentiment Analyzer

A powerful Apify Actor that scrapes Reddit posts and comments, then performs comprehensive sentiment analysis to understand community opinions and trends.

### What Does This Actor Do?

This actor helps you:

- **Extract Reddit Data**: Scrape posts and comments from any public subreddit
- **Analyze Sentiment**: Automatically classify content as Positive, Negative, or Neutral
- **Discover Trends**: Identify top keywords, controversial discussions, and sentiment patterns
- **Track Topics**: Monitor specific keywords or search queries across Reddit
- **Generate Insights**: Get comprehensive statistics and extreme examples

Perfect for market research, brand monitoring, trend analysis, and understanding community sentiment.

### Features

- ✅ Scrape multiple subreddits simultaneously
- ✅ Search Reddit with custom queries
- ✅ Filter by keywords, time ranges, and post scores
- ✅ Analyze both posts and comments
- ✅ Extract top keywords using TF-IDF
- ✅ Identify most positive/negative discussions
- ✅ Detect controversial posts
- ✅ Track sentiment trends over time
- ✅ Per-subreddit sentiment breakdown

### Prerequisites

You'll need Reddit API credentials (free):

1. Go to https://www.reddit.com/prefs/apps
2. Click "Create App" or "Create Another App"
3. Select **"script"** as the app type
4. Fill in:
   - **Name**: Your app name (e.g., "Sentiment Analyzer")
   - **Redirect URI**: `http://localhost:8080`
5. Click "Create app"
6. Copy your **Client ID** (below app name) and **Client Secret**

### Input Configuration

#### Required Parameters

| Parameter | Type | Description |
|-----------|------|-------------|
| `redditClientId` | String | Your Reddit API Client ID |
| `redditClientSecret` | String | Your Reddit API Client Secret (kept secure) |
| `subreddits` | Array | List of subreddit names, e.g., `["technology", "python"]` |

#### Optional Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `searchQuery` | String | - | Search Reddit for specific topics (alternative to subreddits) |
| `keywords` | Array | - | Filter posts containing these keywords |
| `timeFilter` | Select | `"week"` | Time period: `hour`, `day`, `week`, `month`, `year`, `all` |
| `sortBy` | Select | `"hot"` | Sort method: `hot`, `new`, `top`, `rising`, `controversial` |
| `maxPosts` | Number | `100` | Maximum posts per subreddit (1-1000) |
| `includeComments` | Boolean | `true` | Analyze comments in addition to posts |
| `maxCommentsPerPost` | Number | `50` | Maximum comments per post (0-500) |
| `minScore` | Number | `0` | Minimum post score (upvotes) to include |
| `includePostText` | Boolean | `true` | Include full post content in results |
| `generateSummary` | Boolean | `true` | Generate sentiment summary and trends |

### Usage Examples

#### Example 1: Analyze Technology News Sentiment

```json
{
  "redditClientId": "your_client_id",
  "redditClientSecret": "your_client_secret",
  "subreddits": ["technology", "tech"],
  "timeFilter": "week",
  "sortBy": "top",
  "maxPosts": 100,
  "minScore": 100
}
```

#### Example 2: Track AI/ML Discussions

```json
{
  "redditClientId": "your_client_id",
  "redditClientSecret": "your_client_secret",
  "searchQuery": "artificial intelligence",
  "keywords": ["AI", "GPT", "machine learning"],
  "timeFilter": "month",
  "maxPosts": 200
}
```

#### Example 3: Monitor Brand Mentions

```json
{
  "redditClientId": "your_client_id",
  "redditClientSecret": "your_client_secret",
  "subreddits": ["technology", "gadgets", "reviews"],
  "keywords": ["YourBrand"],
  "includeComments": true,
  "maxCommentsPerPost": 100,
  "generateSummary": true
}
```

#### Example 4: Quick Post Analysis (No Comments)

```json
{
  "redditClientId": "your_client_id",
  "redditClientSecret": "your_client_secret",
  "subreddits": ["worldnews"],
  "timeFilter": "day",
  "maxPosts": 50,
  "includeComments": false
}
```

### Output Data

#### Individual Posts

Each post in the dataset includes:

- Post title, content, and metadata (author, subreddit, score, timestamps)
- Sentiment analysis (label, compound score, positive/negative/neutral percentages)
- URL and permalink
- Engagement metrics (upvotes, comments count)
- All comments with individual sentiment scores (if enabled)

#### Sentiment Summary

The actor generates a comprehensive summary including:

- **Overview**: Total posts/comments analyzed
- **Sentiment Distribution**: Percentage breakdown by sentiment type
- **Average Scores**: Overall and per-category sentiment scores
- **Top Keywords**: Most relevant terms extracted via TF-IDF
- **Extreme Examples**: Most positive and negative posts
- **Controversial Posts**: Discussions with mixed sentiment
- **Subreddit Breakdown**: Per-subreddit statistics
- **Temporal Trends**: Daily sentiment patterns

### Understanding Sentiment Scores

- **Compound Score**: Overall sentiment from -1 (very negative) to +1 (very positive)
- **Label**: Classification as `Positive`, `Negative`, or `Neutral`
- **Component Scores**: Individual positive, neutral, and negative percentages

**Interpretation**:

- `0.5 to 1.0`: Very Positive
- `0.1 to 0.5`: Positive
- `-0.1 to 0.1`: Neutral
- `-0.5 to -0.1`: Negative
- `-1.0 to -0.5`: Very Negative

### Use Cases

#### Market Research

- Analyze customer sentiment about products or services
- Identify emerging trends in your industry
- Track competitor mentions and reputation

#### Brand Monitoring

- Monitor brand mentions across relevant subreddits
- Identify PR issues early through sentiment tracking
- Understand customer pain points and preferences

#### Content Strategy

- Discover trending topics in your niche
- Understand what content resonates with communities
- Identify controversial subjects to address or avoid

#### Academic Research

- Study online community behavior and sentiment
- Analyze public opinion on social issues
- Track sentiment evolution over time

#### Product Development

- Gather feature requests and user feedback
- Identify common complaints or praise
- Understand user priorities through keyword analysis

### Performance & Limits

- **Reddit API Rate Limit**: 60 requests/minute (automatically handled)
- **Max Posts per Request**: 1000 (Reddit API limitation)
- **Processing Time**: Varies based on post count and comment depth
  - \~1-2 minutes for 100 posts without comments
  - \~5-10 minutes for 100 posts with 50 comments each
- **Actor Privacy**: This actor is **private** and only accessible to your account

### Data Privacy

- Only scrapes **publicly available** Reddit content
- No access to private subreddits or messages
- Usernames are public Reddit handles (not PII)
- All data stored in your private Apify datasets
- API credentials are encrypted and never exposed

### Compliance

This actor:

- ✅ Uses official Reddit API (PRAW)
- ✅ Respects Reddit's rate limits
- ✅ Complies with Reddit API Terms of Service
- ✅ Only accesses public data
- ✅ Does not bypass any restrictions

**You are responsible for**:

- Using your own Reddit API credentials
- Complying with Reddit's terms of service
- Respecting data privacy laws in your jurisdiction

### Troubleshooting

**No results returned?**

- Check your Reddit API credentials are correct
- Verify the subreddit names are spelled correctly (without "r/" prefix)
- Try increasing `maxPosts` or removing keyword filters
- Ensure posts exist in your specified time filter

**API authentication errors?**

- Verify Client ID and Client Secret are correct
- Make sure you created a "script" type app on Reddit
- Check that your Reddit account is in good standing

**Slow performance?**

- Reduce `maxPosts` or `maxCommentsPerPost`
- Set `includeComments` to `false` for faster scraping
- Use narrower time filters

**Empty sentiment scores?**

- Posts/comments with no text return neutral sentiment
- Deleted/removed content is filtered out

### Support

For issues or questions:

- Review Reddit API documentation
- Contact your Apify account administrator

### License

**Last Updated**: 2025-11-10

# Actor input Schema

## `redditClientId` (type: `string`):

Reddit API Client ID (get from https://www.reddit.com/prefs/apps)

## `redditClientSecret` (type: `string`):

Reddit API Client Secret

## `redditUserAgent` (type: `string`):

User agent string for Reddit API (e.g., 'MyApp/1.0')

## `subreddits` (type: `array`):

List of subreddit names to scrape (without r/ prefix)

## `searchQuery` (type: `string`):

Search query to find specific posts (leave empty to get all posts from subreddits)

## `keywords` (type: `array`):

Filter posts/comments containing these keywords (optional)

## `timeFilter` (type: `string`):

Filter posts by time period

## `sortBy` (type: `string`):

How to sort posts

## `maxPosts` (type: `integer`):

Maximum number of posts to scrape per subreddit

## `includeComments` (type: `boolean`):

Whether to scrape and analyze comments

## `maxCommentsPerPost` (type: `integer`):

Maximum number of comments to analyze per post

## `minScore` (type: `integer`):

Minimum score (upvotes) for posts to include

## `sentimentModel` (type: `string`):

Which sentiment analysis model to use

## `includePostText` (type: `boolean`):

Include full post content in results

## `generateSummary` (type: `boolean`):

Generate overall sentiment summary and trends

## Actor input object example

```json
{
  "redditClientId": "your_client_id",
  "redditClientSecret": "your_client_secret",
  "redditUserAgent": "RedditSentimentAnalyzer/1.0",
  "subreddits": [
    "technology",
    "python",
    "machinelearning"
  ],
  "searchQuery": "artificial intelligence",
  "keywords": [
    "AI",
    "machine learning",
    "neural network"
  ],
  "timeFilter": "week",
  "sortBy": "hot",
  "maxPosts": 100,
  "includeComments": true,
  "maxCommentsPerPost": 50,
  "minScore": 10,
  "sentimentModel": "vader",
  "includePostText": true,
  "generateSummary": true
}
```

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "subreddits": [
        "technology"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("credible_sandal/reddit-sentiment-analyzer").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "subreddits": ["technology"] }

# Run the Actor and wait for it to finish
run = client.actor("credible_sandal/reddit-sentiment-analyzer").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "subreddits": [
    "technology"
  ]
}' |
apify call credible_sandal/reddit-sentiment-analyzer --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,credible_sandal/reddit-sentiment-analyzer"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/gnAuUny9eCDJIN2VV/builds/JNLBKBziyfR8caNwb/openapi.json
