Skip to content

Instantly share code, notes, and snippets.

@taslabs-net
Last active July 15, 2025 15:33
Show Gist options
  • Save taslabs-net/bd89dc50aa1c6ad54ba5eeddcaac145a to your computer and use it in GitHub Desktop.
Save taslabs-net/bd89dc50aa1c6ad54ba5eeddcaac145a to your computer and use it in GitHub Desktop.
A Discord bot that combines AI models (Anthropic Claude, OpenAI GPT, Meta Llama) with personal document search, built with Cloudflare Workers, R2, D1, AutoRAG, Discord, and Docker

Cloudflare-Powered Discord AI Bot with Role-Based Document Intelligence

A Discord bot that combines AI models (Anthropic Claude, OpenAI GPT, and Meta Llama via Cloudflare Workers AI) with channel-based document search, built entirely on Cloudflare's edge platform. Share knowledge within Discord channels with role-based access control - if you can see the channel, you can access its AI and documents.

Why This Matters: A Real Scenario

Imagine you're at a client meeting. They ask about specific terms in a contract you uploaded months ago. Instead of awkwardly searching through emails or saying "I'll get back to you," you simply pull out your phone, open Discord, and type:

#docs What are the termination clauses in the Acme Corp agreement?

Within seconds, your AI assistant searches through your personal document library and responds with the exact information, complete with a link to view the full document. No VPN, no laptop, no special apps - just Discord on your phone and the power of Cloudflare's edge network.

This isn't just another chatbot. It's your team's shared AI knowledge base that travels with you everywhere, with natural role-based access through Discord's channel permissions.

High-Level Workflow

  1. User sends message in Discord → Bot receives message with channel context
  2. Bot processes commands → Determines AI model and features to use
  3. Bot forwards to Cloudflare Worker → Worker handles AI processing
  4. Worker searches documents (if requested) → AutoRAG searches channel's indexed files
  5. Worker calls AI model → Gets response from selected AI
  6. Worker stores conversation history → Saves to D1 database by channel
  7. Bot sends response → User receives AI-generated answer in Discord

Architecture Components

Discord Bot (Node.js)

  • Runs in Docker container
  • Monitors Discord channels for messages
  • Handles file uploads to R2 storage
  • Routes requests to Cloudflare Worker
  • Manages user permissions and quotas

Cloudflare Worker

  • Processes AI requests at the edge
  • Manages conversation history in D1 database
  • Integrates with AI models:
    • External models (Anthropic, OpenAI) via AI Gateway
    • Native Meta Llama via Workers AI
  • Provides web-based file browser interface
  • Handles document search via AutoRAG

Storage Systems

  • R2: Object storage for files organized by channel (channels/{channelId}/)
  • D1: SQL database for conversation history
  • KV: Key-value store for user settings and preferences
    • Feature flags (can_use_claude, can_use_openai, can_upload_files, can_use_autorag)
    • Channel preferences (default AI model per channel)
    • User quotas and limits
    • OAuth sessions and authentication

Detailed Workflow

1. Message Reception

When a user sends a message in Discord:

  • Bot automatically knows user's channel access through Discord permissions
  • Bot verifies user hasn't exceeded daily message quota
  • Bot identifies any command prefixes (!, #) or file attachments
  • No hardcoded channel lists - truly role-based access control

2. Command Processing

The bot supports several command types:

  • !claude - Set Claude as default AI for the channel
  • !chatgpt - Set ChatGPT as default AI for the channel
  • !llama - Set Llama as default AI for the channel
  • !docs - Enable document search for the channel
  • #claude - Use Claude for just this message
  • #docs - Search documents for just this message
  • !sync - Manually sync documents with AutoRAG indexing

3. Worker Request

The Discord bot sends a request to the Cloudflare Worker with:

  • User ID and username
  • Message content
  • Channel ID for conversation context
  • Selected AI model preference
  • Document search flag (if applicable)
  • User settings and permissions

4. Document Search (Optional)

If document search is enabled:

  • Worker queries AutoRAG with the user's message
  • AutoRAG searches through indexed documents in the user's namespace
  • Relevant document excerpts are included as context for the AI
  • File references are converted to clickable links to the file browser

5. AI Model Selection

The worker routes to the appropriate AI based on user preference:

  • Claude (Anthropic): Advanced reasoning and analysis - accessed via Cloudflare AI Gateway
  • ChatGPT (OpenAI): General purpose conversations - accessed via Cloudflare AI Gateway
  • Llama (Meta): Default free-tier model - runs natively on Cloudflare Workers AI
  • Claude Code (Opus-4): Specialized coding model - accessed via Cloudflare AI Gateway (restricted to specific channel)

6. Conversation History

The worker manages conversation context:

  • Stores unlimited conversation history in D1 database
  • Intelligently retrieves the most recent messages (up to 150) for AI context
  • Maintains separate history per channel - conversations never mix
  • Full history always available, with smart windowing for optimal AI performance
  • Preserves complete context for follow-up questions

7. Response Generation

The AI model generates a response considering:

  • Current message
  • Conversation history
  • Document context (if applicable)
  • System prompts for helpful behavior

8. Response Delivery

The worker sends the response back to Discord:

  • Long responses are automatically split into multiple messages
  • File references include clickable links to the file browser
  • Rate limiting prevents message flooding

File Management

Upload Process

  1. User attaches files to a Discord message in any channel
  2. Bot downloads files from Discord
  3. Bot uploads to R2 at path: channels/{channelId}/{filename}
  4. Files are automatically indexed by AutoRAG for searching
  5. Files are associated with the channel - accessible to all channel members

File Browser

  • Web interface at https://aibot.schenanigans.com/
  • OAuth authentication via Discord (requests identify and guilds scopes)
  • Browse all channels you have access to in the Discord server
  • Channel-based file organization - see files from any channel you can access
  • Vintage Mac OS-inspired interface with traffic light buttons
  • Direct links to specific folders from document search results

Browser Features

File Management

  • Drag-and-drop file upload
  • Folder creation and organization
  • Multi-part upload for large files
  • Right-click context menu for advanced options
  • HTTP/Custom metadata editing

File Handling

  • In-browser file preview for:
    • PDF documents
    • Images (PNG, JPG, GIF)
    • Text files
    • Markdown files
    • CSV files
    • Logpush files
  • In-browser file editing
  • Folder upload support

Schenanigans RAG Login

Login screen with Discord OAuth

File Browser Interface

Native file browser interface for managing uploaded documents

Security & Permissions

Role-Based Authorization

  • Dynamic Channel Access: OAuth flow fetches channels from Discord API
  • No Hardcoded Lists: If you're in a channel, you have access - simple as that
  • Bot Token Integration: Uses Discord bot to fetch all server channels
  • Graceful Fallbacks: User OAuth token as backup if bot token fails
  • Per-user permissions for AI models and features
  • Daily message quotas to prevent abuse
  • File size limits for uploads

Data Isolation & Access Control

  • Channel-based storage paths (channels/{channelId}/)
  • Dynamic permission checks - if you can see the Discord channel, you can access its files
  • No hardcoded permissions - purely role-based through Discord
  • Shared AutoRAG namespace for all users (documents tagged by channel)
  • Channel-based conversation history
  • OAuth flow dynamically fetches user's accessible channels

Technical Stack

  • Discord Bot: Node.js with Discord.js
  • Runtime: Docker container with health monitoring
  • Edge Computing: Cloudflare Workers
  • AI Models:
    • Cloudflare AI Gateway (Anthropic Claude, OpenAI GPT)
    • Cloudflare Workers AI (Meta Llama)
  • Object Storage: Cloudflare R2
  • Database: Cloudflare D1 (SQLite)
  • Search: Cloudflare AutoRAG (Vectorize)
  • Configuration: KV namespaces

Key Features

  1. Multi-Model Support: Switch between different AI models on demand
  2. Channel-Based Documents: Upload and search documents organized by Discord channel
  3. True Role-Based Access: If you're in the channel, you have access - no configuration needed
  4. Unlimited Conversation Memory: Never lose context - all conversations stored permanently by channel
  5. Native File Browser: Vintage Mac OS-inspired web interface for managing files
  6. OAuth Integration: Seamless Discord authentication with dynamic channel discovery
  7. Flexible Commands: Channel defaults or per-message overrides
  8. High Performance: Edge-based processing for low latency

Access Your Knowledge Anywhere

One of the most powerful features is complete mobile accessibility. Since everything runs through Discord:

  • Search channel documents from iPhone, Android, or any device with Discord
  • No app installation required - works through native Discord apps
  • Full AI capabilities on the go - ask questions about your team's documents from anywhere
  • Upload files directly from mobile - take a photo, save a PDF, instantly searchable by your team
  • Your team's AI knowledge base travels with you - plane, train, or coffee shop
  • Natural permissions - see a Discord channel? You can access its documents and AI

Example mobile workflow:

[On iPhone at a meeting]
User: #docs What were the payment terms in the Johnson contract?
Bot: Based on documents in this channel, the Johnson contract specifies NET 30 payment terms...
[Contract.pdf](https://aibot.schenanigans.com/?path=channels%2F1392959736600592534%2Fcontracts)

Example Usage

Basic Conversation

User: What's quantum computing?
Bot: Quantum computing is a type of computation that uses quantum bits...

Document Search

User: #docs What were the terms in my lease agreement?
Bot: Based on documents in this channel, the key terms from your lease are...
[lease_agreement.pdf](https://aibot.schenanigans.com/?path=channels%2F1392959736600592534%2Fdocuments)

Document Search Example

Real example showing AutoRAG sync and document search with German tax documents

Model Switching

User: !claude
Bot: Claude set as default for this channel

User: Explain the theory of relativity
Bot: [Claude responds with detailed explanation]

File Upload

User: [Attaches contract.pdf]
Bot: Uploading 1 file to this channel's storage...
contract.pdf: File uploaded successfully
Your files are being indexed for search

OAuth & Dynamic Permissions Flow

The system uses Discord OAuth to dynamically determine user access:

  1. User visits https://aibot.schenanigans.com/
  2. Redirected to Discord OAuth with scopes: identify guilds
  3. Discord returns user info and guild memberships
  4. Worker fetches channels using Discord Bot token
  5. Filters to text channels user can access
  6. Creates session with allowed channels
  7. File browser shows only accessible channels

This means:

  • Zero configuration - No hardcoded channel lists
  • Instant updates - New channel? Instant access
  • Role changes reflected immediately - Lost access? Can't see files
  • True RBAC - Discord permissions are the single source of truth

System Flow Diagram

Discord User
    ↓ (message/file)
Discord Bot (Node.js)
    ↓ (API request with channelId)
Cloudflare Worker
    ↓ ↙ ↘
AutoRAG  D1   AI Gateway
    ↓     ↓      ↓
    ↓     ↓   AI Models
    ↓     ↓   (Claude/GPT/Llama)
    ← ← ← ← ← ←
    ↓ (response)
Discord User
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment