npm package: @openpets/reddit
Description: Reddit plugin for OpenCode - navigate subreddit communities and get trending stories
Latest version: 1.0.4

# Reddit Plugin for OpenCode

Navigate Reddit communities and get trending stories with this OpenCode plugin. Fetch hot posts from any subreddit and dive deep into post content with threaded comments.

## Table of Contents

1. [Features](#features)
2. [Prerequisites](#prerequisites)
3. [Setup](#setup)
4. [Available Tools](#available-tools)
5. [Usage Examples](#usage-examples)
6. [Configuration](#configuration)
7. [Error Handling](#error-handling)
8. [Troubleshooting](#troubleshooting)

---

## Features

- Fetch hot/trending posts from any subreddit
- Get detailed post content with threaded comments
- Configurable result limits and comment depth
- Support for all post types (text, link, video, gallery)
- Formatted output with post metadata (score, author, comments count)
- Hierarchical comment tree visualization

---

## Prerequisites

Before using this plugin, you'll need:

1. **Reddit Account**: Create one at [reddit.com](https://reddit.com)
2. **Reddit Application**: Register at [reddit.com/prefs/apps](https://www.reddit.com/prefs/apps)
3. **OAuth Credentials**: Client ID and Client Secret (Refresh Token is optional for read-only access)

---

## Setup

### 1. Create a Reddit Application

1. Go to [https://www.reddit.com/prefs/apps](https://www.reddit.com/prefs/apps)
2. Click "create another app..." at the bottom
3. Fill in the form:
   - **name**: Choose any name (e.g., "OpenCode Reddit Plugin")
   - **App type**: Select **"script"**
   - **description**: Optional description
   - **about url**: Leave blank
   - **redirect uri**: Use `http://localhost:8080`
4. Click "create app"
5. Note your **client ID** (under the app name) and **secret**

### 2. (Optional) Get Your Refresh Token

**For read-only access (fetching posts/comments), you can SKIP this step!** The plugin will use Application-Only OAuth.

**Only get a refresh token if you need to:**
- Post content
- Comment on posts
- Vote on posts
- Access private subreddits

**Method A: Manual OAuth Flow**

1. Visit this URL (replace `YOUR_CLIENT_ID`):
```
https://www.reddit.com/api/v1/authorize?client_id=YOUR_CLIENT_ID&response_type=code&state=RANDOM_STRING&redirect_uri=http://localhost:8080&duration=permanent&scope=read,identity
```

2. Click "allow" - you'll be redirected to `http://localhost:8080/?code=...`
3. Copy the `code` parameter from the URL
4. Exchange the code for a refresh token:

```bash
curl -X POST -d "grant_type=authorization_code&code=YOUR_CODE&redirect_uri=http://localhost:8080" \
  --user "YOUR_CLIENT_ID:YOUR_CLIENT_SECRET" \
  https://www.reddit.com/api/v1/access_token
```

5. Save the `refresh_token` from the response

### 3. Configure Environment

```bash
# Copy the example environment file
cp .env.example .env

# Edit with your credentials
nano .env
```

Add your credentials to `.env`:

**For read-only access (recommended for most users):**
```bash
REDDIT_CLIENT_ID=<your_actual_client_id>
REDDIT_CLIENT_SECRET=<your_actual_client_secret>
REDDIT_USER_AGENT=openpets-reddit-plugin/1.0.0
```

**For full access (posting, voting, etc.):**
```bash
REDDIT_CLIENT_ID=<your_actual_client_id>
REDDIT_CLIENT_SECRET=<your_actual_client_secret>
REDDIT_REFRESH_TOKEN=<your_actual_refresh_token>
REDDIT_USER_AGENT=openpets-reddit-plugin/1.0.0
```

### 4. Install Dependencies

```bash
npm install
```

### 5. Test the Plugin

```bash
# Fetch hot posts from r/programming
opencode run "get hot posts from r/programming"

# Or use the quickstart command
npm run quickstart
```

---

## Available Tools

### 1. fetch-reddit-hot-threads

Fetch hot/trending threads from a subreddit.

**Parameters:**
- `subreddit` (required): Name of the subreddit (without "r/" prefix)
- `limit` (optional): Number of posts to fetch (default: 10, max: 100)

**Returns:**
- Post title, score, comment count
- Author username
- Post type (text/link/video/gallery)
- Post content or URL
- Reddit permalink
- Post ID for deep-dive queries

**Example:**
```bash
opencode run "get hot posts from r/programming"
opencode run "fetch trending posts from r/technology with 20 results"
opencode run "get hot posts from r/AskReddit with 5 results"
```

### 2. fetch-reddit-post-content

Fetch detailed content of a specific Reddit post including comments.

**Parameters:**
- `post_id` (required): Reddit post ID (e.g., '1abc234')
- `comment_limit` (optional): Number of top-level comments (default: 20)
- `comment_depth` (optional): Maximum comment tree depth (default: 3)

**Returns:**
- Full post details
- Hierarchical comment tree
- Comment scores and authors
- Nested replies with proper indentation

**Example:**
```bash
opencode run "get post content for post ID 1abc234"
opencode run "fetch post 1abc234 with 50 comments and depth 5"
opencode run "show detailed content for Reddit post xyz789"
```

---

## Usage Examples

### Browse Trending Topics

```bash
# Tech news
opencode run "get hot posts from r/programming with 15 results"
opencode run "get hot posts from r/technology"

# Ask Reddit
opencode run "get hot posts from r/AskReddit with 10 results"

# News and current events
opencode run "get hot posts from r/worldnews"
opencode run "get hot posts from r/news with 20 results"
```

### Deep Dive into Posts

```bash
# First, get hot posts and note the post IDs
opencode run "get hot posts from r/programming with 5 results"

# Then fetch detailed content with comments
opencode run "get post content for post ID 1abc234"

# Get more comments with deeper nesting
opencode run "get post content for post ID 1abc234 with 50 comments and depth 5"
```

### Research Workflow

```bash
# 1. Find trending topics
opencode run "get hot posts from r/MachineLearning with 10 results"

# 2. Read top discussions
opencode run "get post content for post ID xyz789 with 30 comments"

# 3. Check related subreddits
opencode run "get hot posts from r/artificial with 10 results"
```

---

## Configuration

### Environment Variables

| Variable | Description | Required | Default |
|----------|-------------|----------|---------|
| `REDDIT_CLIENT_ID` | Reddit app client ID | Yes | - |
| `REDDIT_CLIENT_SECRET` | Reddit app client secret | Yes | - |
| `REDDIT_REFRESH_TOKEN` | OAuth refresh token | No (only for posting/voting) | - |
| `REDDIT_USER_AGENT` | Custom user agent string | No | `openpets-reddit-plugin/1.0.0` |

**Authentication Modes:**
- **Application-Only OAuth** (Client ID + Secret): Read-only access to public content
- **Full OAuth** (Client ID + Secret + Refresh Token): Full access including posting and voting

### User Agent Best Practices

Reddit requires a descriptive user agent. Format:

```
platform:app_id:version (by /u/username)
```

Example:
```bash
REDDIT_USER_AGENT="openpets:reddit-plugin:v1.0.0 (by /u/your_username)"
```

---

## Error Handling

The plugin provides structured error responses:

```json
{
  "success": false,
  "error": "Error message",
  "subreddit": "programming"
}
```

### Common Errors

**"Missing Reddit credentials"**
- Ensure all required environment variables are set in `.env`

**"403 Forbidden"**
- Check your OAuth token is valid and not expired
- Verify your app type is set to "script"

**"404 Not Found"**
- Verify the subreddit name is correct (case-insensitive)
- Check that the post ID is valid

**"429 Too Many Requests"**
- Reddit API rate limiting (60 requests per minute)
- Wait a minute before retrying

---

## Troubleshooting

### Cannot Initialize Reddit Client

**Problem**: Plugin fails to start with credential errors

**Solution**:
1. Verify `.env` file exists in the plugin directory
2. Check all three credentials are set correctly
3. Ensure no extra spaces or quotes in `.env` values
4. Ensure credentials are not placeholder values (e.g., 'your_client_id_here')
5. Try regenerating your refresh token

### Timeout Errors (TimeoutNegativeWarning)

**Problem**: Error message: "TimeoutNegativeWarning: -Infinity is a negative number"

**Solution**:
This error occurred in older versions when Reddit credentials were missing or invalid. **Fixed in current version** with:
1. Proper timeout configuration (30 second timeout, 1 second delay between requests)
2. Support for Application-Only OAuth (only requires Client ID + Secret)
3. Better error messages for missing credentials

If you still see this error:
1. Update to the latest plugin version
2. Set valid Reddit Client ID and Secret in your `.env` file
3. Remove placeholder values (e.g., 'your_client_id_here')
4. Restart the plugin

### No Posts Returned

**Problem**: Query succeeds but returns empty results

**Solution**:
1. Check the subreddit exists and is public
2. Try a different subreddit (e.g., r/programming)
3. Verify you're not shadowbanned on Reddit

### Comments Not Loading

**Problem**: Post content shows but no comments

**Solution**:
1. Some posts genuinely have no comments
2. Try increasing `comment_limit` parameter
3. Check if you have read access to the subreddit

### Rate Limiting

**Problem**: "429 Too Many Requests" errors

**Solution**:
1. Reddit allows 60 requests per minute
2. Reduce the number of consecutive requests
3. Implement delays between bulk operations
4. Use smaller `limit` values

---

## Using from Other Projects

Add this plugin to your OpenCode configuration:

```json
{
  "$schema": "https://opencode.ai/config.json",
  "plugin": [
    "/absolute/path/to/openpets/pets/reddit/index.ts"
  ]
}
```

---

## Testing

```bash
# Test with example queries
npm run test:queries

# Test workflow scenarios
npm run test:scenarios

# Run all tests
npm run test:all
```

---

## API Reference

### Snoowrap

This plugin uses [snoowrap](https://github.com/not-an-aardvark/snoowrap), a fully-featured JavaScript wrapper for the Reddit API.

Key features:
- Promise-based API
- Automatic rate limiting
- Lazy object fetching
- Full TypeScript support

### Reddit API Documentation

- [Reddit API Documentation](https://www.reddit.com/dev/api)
- [OAuth2 Quick Start](https://github.com/reddit-archive/reddit/wiki/OAuth2-Quick-Start-Example)
- [API Terms of Use](https://www.redditinc.com/policies/data-api-terms)

---

## Contributing

Found a bug or want to add a feature? Contributions are welcome!

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Submit a pull request

---

## License

MIT

---

## Need Help?

- **Reddit API Issues**: Check [r/redditdev](https://www.reddit.com/r/redditdev/)
- **Plugin Issues**: Open an issue on GitHub
- **OpenCode Documentation**: See the main OpenCode docs

---

**Happy Reddit browsing! 🚀**