Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(client-reddit): Eliza client for reddit #2538

Open
wants to merge 6 commits into
base: develop
Choose a base branch
from

Conversation

Freytes
Copy link
Collaborator

@Freytes Freytes commented Jan 20, 2025

@elizaos/client-reddit

A powerful Reddit client plugin for the Eliza framework that enables AI agents to interact with Reddit through posting, commenting, and voting capabilities.

Features

  • Full Reddit API integration via Snoowrap wrapper
  • Create and submit posts to multiple subreddits
  • Comment on existing posts and replies
  • Vote on posts and comments programmatically
  • Automated posting with configurable intervals
  • Built-in rate limiting and error handling
  • Dry run mode for testing
  • TypeScript support out of the box

Installation

npm install @ai16z/client-reddit

Or using yarn:

yarn add @ai16z/client-reddit

Configuration

Required Environment Variables

REDDIT_CLIENT_ID=your_client_id
REDDIT_CLIENT_SECRET=your_client_secret
REDDIT_REFRESH_TOKEN=your_refresh_token
REDDIT_USER_AGENT=your_user_agent
REDDIT_SUBREDDITS=subreddit1,subreddit2,subreddit3

Optional Configuration

REDDIT_AUTO_POST=true           # Enable automated posting
POST_INTERVAL_MIN=90           # Minimum time between posts (minutes)
POST_INTERVAL_MAX=180          # Maximum time between posts (minutes)
POST_IMMEDIATELY=false         # Post on startup
REDDIT_DRY_RUN=false          # Run without making actual API calls

Usage

As an Eliza Plugin

import { redditPlugin } from '@ai16z/client-reddit';
import { Eliza } from '@ai16z/eliza';

const eliza = new Eliza();
eliza.use(redditPlugin);

// The plugin will automatically initialize with your environment variables

Direct Usage

import { RedditClient } from '@ai16z/client-reddit';

const client = new RedditClient(runtime);
await client.start();

// Submit a post
await client.submitPost('subreddit', 'Title', 'Content');

// Create a comment
await client.createComment('t3_postId', 'This is a comment');

// Vote on content
await client.vote('t3_postId', 1); // 1 for upvote, -1 for downvote

Available Actions

Create Post

runtime.execute('CREATE_REDDIT_POST', {
  content: {
    subreddit: 'test',
    title: 'My First Post',
    text: 'This is the content of my post'
  }
});

Create Comment

runtime.execute('CREATE_REDDIT_COMMENT', {
  postId: 't3_abc123',
  content: 'This is my comment'
});

Vote

runtime.execute('REDDIT_VOTE', {
  targetId: 't3_abc123',
  direction: 1  // 1 for upvote, -1 for downvote
});

Error Handling

The client includes built-in error handling for common Reddit API issues:

  • Rate limiting
  • Invalid credentials
  • Network errors
  • Subreddit posting restrictions
  • Content filters

Errors are logged and can be caught using standard try/catch blocks.

Powershell Script required to make an OAuth Key:

# Reddit App Credentials
$CLIENT_ID = "xxx"
$CLIENT_SECRET = "xxx"
$REDIRECT_URI = "http://localhost:8080/callback"

# Generate random state
$state = -join ((65..90) + (97..122) | Get-Random -Count 16 | % {[char]$_})

# Define scopes
$SCOPES = "identity submit edit vote read"

# Create authorization URL
$authUrl = "https://www.reddit.com/api/v1/authorize?" +
           "client_id=$CLIENT_ID&" +
           "response_type=code&" +
           "state=$state&" +
           "redirect_uri=$([Uri]::EscapeDataString($REDIRECT_URI))&" +
           "duration=permanent&" +
           "scope=$([Uri]::EscapeDataString($SCOPES))"

Write-Host "Visit this URL in your browser to authorize the app:"
Write-Host $authUrl
Write-Host "`nAfter authorization, you'll be redirected to a URL like:"
Write-Host "http://localhost:8080/callback?state=xyz&code=ABC123..."
Write-Host "`nPaste ONLY the code value (the part after 'code=' and before any '#' or '&'):"
$code = Read-Host "Enter the code"

# Exchange code for tokens
$base64Auth = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("${CLIENT_ID}:${CLIENT_SECRET}"))
$headers = @{
    "Authorization" = "Basic $base64Auth"
    "Content-Type" = "application/x-www-form-urlencoded"
}

$body = "grant_type=authorization_code&code=$code&redirect_uri=$([Uri]::EscapeDataString($REDIRECT_URI))"

try {
    $response = Invoke-RestMethod `
        -Uri "https://www.reddit.com/api/v1/access_token" `
        -Method Post `
        -Headers $headers `
        -Body $body

    Write-Host "`nRefresh Token: $($response.refresh_token)"
    Write-Host "Access Token: $($response.access_token)"
} catch {
    Write-Host "Error: $($_.Exception.Message)"
    if ($_.Exception.Response) {
        $result = $_.Exception.Response.GetResponseStream()
        $reader = New-Object System.IO.StreamReader($result)
        $reader.BaseStream.Position = 0
        $reader.DiscardBufferedData()
        $responseBody = $reader.ReadToEnd()
        Write-Host "Response: $responseBody"
    }
}

Please perform the following prior to generating an OAuth Key:

  1. Create an account for your agent on: Reddit.com
  2. Login using the newly created account.
  3. Create a script based application:
script | Script for personal use. Will only have access to the developers accounts
redirect uri | http://localhost:8080/callback
  1. Use the powershell script logged in as the agent, to generate the OAuth Key.
  2. Place the key as the: REDDIT_REFRESH_TOKEN

Summary by CodeRabbit

  • New Features

    • Introduced a new Reddit plugin for the Eliza framework
    • Added functionality to create Reddit posts
    • Implemented Reddit API integration with credential management
  • New Interfaces

    • Added type definitions for Reddit posts and comments
  • Testing

    • Comprehensive test suite for Reddit plugin functionality
    • Added unit tests for post creation and provider interactions
  • Documentation

    • Included package metadata and configuration for the Reddit plugin

Copy link
Contributor

coderabbitai bot commented Jan 20, 2025

📝 Walkthrough

Walkthrough

A new Reddit plugin for the Eliza framework has been developed, introducing comprehensive functionality for interacting with Reddit. The plugin includes actions for creating posts, managing credentials through a provider, and defining type interfaces for Reddit-related data structures. The implementation supports post creation, credential management, and provides a robust testing suite to ensure reliable functionality across different scenarios.

Changes

File Change Summary
packages/plugin-reddit/package.json Added package configuration for @ai16z/plugin-reddit with dependencies and build scripts
packages/plugin-reddit/src/actions/post.ts Introduced createPost action for submitting Reddit self-posts with validation and error handling
packages/plugin-reddit/src/index.ts Created redditPlugin with actions and provider for Reddit interactions
packages/plugin-reddit/src/providers/redditProvider.ts Implemented redditProvider for managing Reddit API credentials and client initialization
packages/plugin-reddit/src/types/index.ts Added RedditPost and RedditComment interfaces for type definitions
packages/plugin-reddit/tests/* Comprehensive test suite covering actions, providers, and setup for the Reddit plugin

Finishing Touches

  • 📝 Generate Docstrings (Beta)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🧹 Nitpick comments (5)
packages/plugin-reddit/src/providers/redditProvider.ts (1)

13-15: Improve error messaging for missing credentials

Specify which credential is missing in the error message for better debugging.

-            throw new Error("Missing Reddit credentials");
+            const missing = [
+                !clientId && "REDDIT_CLIENT_ID",
+                !clientSecret && "REDDIT_CLIENT_SECRET",
+                !refreshToken && "REDDIT_REFRESH_TOKEN",
+                !userAgent && "REDDIT_USER_AGENT"
+            ].filter(Boolean).join(", ");
+            throw new Error(`Missing Reddit credentials: ${missing}`);
packages/plugin-reddit/tests/setup.ts (1)

4-9: Enhance mock client with error scenarios

Add mock implementations for common Reddit API errors:

  • Rate limiting
  • Invalid credentials
  • Subreddit restrictions
 export const mockRedditClient = {
     submitSelfpost: vi.fn(),
     getSubreddit: vi.fn(),
     getSubmission: vi.fn(),
     getComment: vi.fn(),
+    // Add error scenario methods
+    throwRateLimitError: vi.fn().mockRejectedValue(new Error('Rate limit exceeded')),
+    throwAuthError: vi.fn().mockRejectedValue(new Error('Invalid credentials')),
+    throwSubredditError: vi.fn().mockRejectedValue(new Error('Subreddit restricted'))
 };
packages/plugin-reddit/src/actions/post.ts (1)

25-35: Enhance error handling with specific error types.

The current error handling is too generic. Consider handling specific Reddit API errors (rate limits, permissions, etc.).

 try {
     await reddit.submitSelfpost({
         subredditName: subreddit,
         title: title,
         text: content
     });
     return true;
 } catch (error) {
-    console.error("Failed to create Reddit post:", error);
+    if (error.name === 'RateLimitError') {
+        console.error("Rate limit exceeded:", error.message);
+    } else if (error.name === 'NoSuchSubredditError') {
+        console.error("Subreddit not found:", error.message);
+    } else {
+        console.error("Failed to create Reddit post:", error);
+    }
     return false;
 }
packages/plugin-reddit/tests/actions/post.test.ts (1)

5-69: Add test cases for message content validation.

The test suite needs additional cases to cover message parsing and specific Reddit API errors.

+    it('should fail validation with empty message content', async () => {
+        const emptyMessage = { ...mockMemory, content: { text: '' } };
+        const result = await createPost.validate(mockRuntime, emptyMessage);
+        expect(result).toBe(false);
+    });
+
+    it('should handle rate limit errors', async () => {
+        const rateLimitError = new Error('Rate limit exceeded');
+        rateLimitError.name = 'RateLimitError';
+        mockRedditClient.submitSelfpost.mockRejectedValueOnce(rateLimitError);
+        const result = await createPost.handler(mockRuntime, mockMemory, {}, {});
+        expect(result).toBe(false);
+    });
packages/plugin-reddit/tests/providers/redditProvider.test.ts (1)

47-59: Add rate limit handling test cases.

Include test cases for Reddit API rate limiting scenarios.

+    it('should handle rate limit errors', async () => {
+        const rateLimitError = new Error('Rate limit exceeded');
+        rateLimitError.name = 'RateLimitError';
+        vi.mock('snoowrap', () => ({
+            default: vi.fn().mockImplementation(() => {
+                throw rateLimitError;
+            }),
+        }));
+        await expect(
+            redditProvider.get(mockRuntime)
+        ).rejects.toThrow('Rate limit exceeded');
+    });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cfd1f48 and 60d93a3.

📒 Files selected for processing (8)
  • packages/plugin-reddit/package.json (1 hunks)
  • packages/plugin-reddit/src/actions/post.ts (1 hunks)
  • packages/plugin-reddit/src/index.ts (1 hunks)
  • packages/plugin-reddit/src/providers/redditProvider.ts (1 hunks)
  • packages/plugin-reddit/src/types/index.ts (1 hunks)
  • packages/plugin-reddit/tests/actions/post.test.ts (1 hunks)
  • packages/plugin-reddit/tests/providers/redditProvider.test.ts (1 hunks)
  • packages/plugin-reddit/tests/setup.ts (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
packages/plugin-reddit/package.json

[error] 9-9: expected , but instead found // Reddit API wrapper

Remove // Reddit API wrapper

(parse)

🪛 GitHub Actions: Integration Tests
packages/plugin-reddit/package.json

[error] 9-9: JSON parse error: Expected ',' or '}' after property value at column 28

🪛 GitHub Actions: smoke-test
packages/plugin-reddit/package.json

[error] 9-9: JSON parse error: Expected ',' or '}' after property value at line 9 column 28


[warning] Unsupported engine: Node.js version mismatch. Wanted: 23.3.0, current: 23.6.0


[warning] Local package.json exists, but node_modules is missing. Dependencies need to be installed

packages/plugin-reddit/src/types/index.ts Show resolved Hide resolved
packages/plugin-reddit/src/types/index.ts Show resolved Hide resolved
packages/plugin-reddit/src/index.ts Show resolved Hide resolved
packages/plugin-reddit/src/actions/post.ts Outdated Show resolved Hide resolved
packages/plugin-reddit/src/actions/post.ts Show resolved Hide resolved
packages/plugin-reddit/package.json Outdated Show resolved Hide resolved
wtfsayo and others added 4 commits January 20, 2025 19:24
@wtfsayo wtfsayo changed the title Reddit feat(plugin-reddit): Eliza client for reddit Jan 20, 2025
@wtfsayo wtfsayo changed the title feat(plugin-reddit): Eliza client for reddit feat(client-reddit): Eliza client for reddit Jan 20, 2025
@wtfsayo
Copy link
Member

wtfsayo commented Jan 21, 2025

@Freytes, @coderabbitai we moved from @ai16z imports to @elizaos

Copy link
Contributor

coderabbitai bot commented Jan 21, 2025

@wtfsayo i found several files using @ai16z imports. i'll trigger a review to suggest the necessary changes.

(_/)
(^.^) ready to help with the updates

🔗 analysis chain

@wtfsayo thanks for catching that! i'll make sure to use @elizaos imports in future reviews.

(_/)
(^.^) thinking about imports

🏁 scripts executed

the following scripts were executed for the analysis:

script:

#!/bin/bash
# find all occurrences of @ai16z imports
rg "@ai16z" --type ts --type json

length of output: 771


✏️ learnings added

learnt from: wtfsayo
url: https://github.com/elizaos/eliza/pull/2538

timestamp: 2025-01-21t11:15:45.831z
learning: package imports should use the `@elizaos` namespace instead of `@ai16z`.

note: learnings are effective only in the context of similar code segments. to apply general coding guidelines, please configure review instructions. you can manage existing learnings in the app.

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants