> ## Documentation Index
> Fetch the complete documentation index at: https://docs.orcbot.buzzchat.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Discord Channel Setup

> Set up Discord bot integration with server management, slash commands, and attachment handling

## Prerequisites

* A Discord account
* Server admin permissions (to add bot)
* OrcBot installed and configured
* Node.js 18+ installed

## Create Discord Bot

<Steps>
  <Step title="Open Discord Developer Portal">
    Go to [Discord Developer Portal](https://discord.com/developers/applications)
  </Step>

  <Step title="Create New Application">
    Click "New Application"

    Enter a name (e.g., "OrcBot")
  </Step>

  <Step title="Create Bot User">
    1. Navigate to the "Bot" tab
    2. Click "Add Bot"
    3. Confirm "Yes, do it!"
  </Step>

  <Step title="Configure Bot Settings">
    Enable these Privileged Gateway Intents:

    * ☑ SERVER MEMBERS INTENT
    * ☑ MESSAGE CONTENT INTENT
    * ☑ PRESENCE INTENT (optional)
  </Step>

  <Step title="Copy Bot Token">
    Under the "Bot" tab, click "Reset Token" and copy the new token

    **Save this token securely** - you won't be able to see it again!
  </Step>

  <Step title="Generate Invite Link">
    1. Go to "OAuth2" → "URL Generator"
    2. Select scopes:
       * `bot`
       * `applications.commands` (for slash commands)
    3. Select bot permissions:
       * Send Messages
       * Send Messages in Threads
       * Embed Links
       * Attach Files
       * Read Message History
       * Add Reactions
       * Use Slash Commands
    4. Copy the generated URL
  </Step>

  <Step title="Add Bot to Server">
    1. Open the invite URL in your browser
    2. Select your server
    3. Click "Authorize"
  </Step>
</Steps>

## Configure OrcBot

### Using Environment Variables

<CodeGroup>
  ```bash Linux/macOS theme={null}
  export DISCORD_TOKEN="your-bot-token-here"
  ```

  ```powershell Windows theme={null}
  $env:DISCORD_TOKEN="your-bot-token-here"
  ```

  ```yaml Docker Compose theme={null}
  environment:
    - DISCORD_TOKEN=your-bot-token-here
  ```
</CodeGroup>

### Using Config File

Add to `~/.orcbot/orcbot.config.yaml`:

```yaml theme={null}
discordToken: "your-bot-token-here"

# Optional: Enable auto-reply
discordAutoReplyEnabled: true
```

## Start the Bot

```bash theme={null}
cd ~/orcbot
npm run build
npm run start
```

You should see:

```
Discord bot logged in as OrcBot#1234
Agent: Discord channel started
```

Your bot will now appear online in your server!

## Sending Messages

### Direct Messages (DMs)

```
User: "Hello!"
Bot:  "Hi! I'm OrcBot. How can I help you today?"
```

### Server Channels

```
User: "@OrcBot summarize this conversation"
Bot:  "Here's a summary of the last 10 messages..."
```

### Using Channel IDs

From skills or code:

```javascript theme={null}
// Send to specific channel
await agent.discord.sendMessage(
  "123456789012345678",  // Channel ID
  "Hello from OrcBot!"
);
```

Get channel ID:

1. Enable Developer Mode: User Settings → Advanced → Developer Mode
2. Right-click channel → Copy Channel ID

## Handling Attachments

### Receiving Files

OrcBot automatically downloads and processes attachments:

<Tabs>
  <Tab title="Images">
    ```
    User: [uploads diagram.png]
          "Explain this architecture"

    Bot: Based on the diagram, this shows a microservices
         architecture with:
         - API Gateway at the front
         - 3 backend services
         - Shared database layer
         - Message queue for async processing
    ```

    Implementation:

    ```typescript theme={null}
    if (attachment.contentType?.startsWith('image/')) {
      const localPath = path.join(downloadPath, `discord_${messageId}_${fileName}`);
      fs.writeFileSync(localPath, buffer);
      mediaPaths.push(localPath);
    }
    ```
  </Tab>

  <Tab title="Audio Files">
    ```
    User: [uploads meeting.mp3]
          "Transcribe this recording"

    Bot: [Processing audio...]
         
         Transcription:
         "Welcome everyone to the Q4 planning meeting.
          Let's start with the sales update..."
    ```

    Auto-transcription:

    ```typescript theme={null}
    const audioExts = ['.ogg', '.mp3', '.m4a', '.wav', '.opus'];
    if (audioExts.includes(path.extname(fileName).toLowerCase())) {
      const result = await this.agent.llm.analyzeMedia(
        localPath,
        'Transcribe this audio message exactly.'
      );
      transcriptionResult = result.replace(/^Transcription result:\n/i, '');
    }
    ```
  </Tab>

  <Tab title="Documents">
    ```
    User: [uploads report.pdf]
          "Summarize the key points"

    Bot: I've analyzed the 15-page report.
         
         Key Points:
         1. Revenue up 23% YoY
         2. New product line launching Q2
         3. Expansion into APAC markets
         4. 5 new hires planned
    ```
  </Tab>
</Tabs>

### Sending Files

Use the `send_file` skill:

```javascript theme={null}
send_file(
  to: "123456789012345678",  // Channel ID
  filePath: "/path/to/report.pdf",
  caption: "Here's the quarterly report",
  channel: "discord"
)
```

Implementation:

```typescript theme={null}
const attachment = new AttachmentBuilder(filePath);
await textChannel.send({
  content: caption || undefined,
  files: [attachment]
});
```

**File size limit:** 25 MB (100 MB with Nitro boost level 2)

## Message Formatting

### Markdown Support

Discord supports rich markdown:

<CodeGroup>
  ```markdown Text Formatting theme={null}
  **bold text**
  *italic text*
  ~~strikethrough~~
  __underline__
  ||spoiler||
  ```

  ````markdown Code theme={null}
  Inline `code`

  ```python
  # Code block
  print("Hello World")
  ````

  ````

  ```markdown Lists & Quotes
  - Bullet point
  1. Numbered list

  > Quote block
  ````

  ```markdown Links theme={null}
  [Click here](https://example.com)
  ```
</CodeGroup>

### OrcBot Markdown Conversion

OrcBot automatically converts markdown for Discord:

```typescript theme={null}
const formatted = hasMarkdown(message) 
  ? renderMarkdown(message, 'discord') 
  : message;

// Headings → bold
// Images → URLs
// Clean up formatting
```

### Message Splitting

Discord has a 2000 character limit. OrcBot auto-splits long messages:

```typescript theme={null}
if (formatted.length <= 2000) {
  await textChannel.send(formatted);
} else {
  const chunks = this.splitMessage(formatted, 2000);
  for (const chunk of chunks) {
    await textChannel.send(chunk);
    await this.delay(500);  // Avoid rate limiting
  }
}
```

## Server Management

### List Servers (Guilds)

```javascript theme={null}
const guilds = await discordChannel.getGuilds();
guilds.forEach(g => {
  console.log(`${g.name} (${g.id})`);
});
```

### List Channels in Server

```javascript theme={null}
const channels = await discordChannel.getTextChannels(guildId);
channels.forEach(c => {
  console.log(`#${c.name} (${c.id})`);
});
```

### Find Channel by Name

```javascript theme={null}
const channel = await discordChannel.findChannelByName(
  guildId,
  "general"
);
```

## Reply Context & Threads

OrcBot preserves conversation context:

```typescript theme={null}
if (message.reference?.messageId) {
  const repliedMessage = await message.fetchReference();
  const repliedText = repliedMessage.content || '[Media/Embed]';
  const repliedUser = repliedMessage.author?.username || 'Unknown';
  
  replyContext = `[Replying to ${repliedUser}'s message: "${repliedText}"]`;
}
```

**Example:**

```
Alice: "What's the deployment status?"
Bob:  [Replies to Alice] "@OrcBot answer this"

Bot:  [Replies to Bob's message]
      "Based on Alice's question about deployment status:
       Current deployment is at 85% completion..."
```

## Typing Indicators

OrcBot sends typing indicators for long operations:

```typescript theme={null}
await discordChannel.sendTypingIndicator(channelId);

// Typing indicator lasts ~10 seconds
// Auto-refresh for longer operations
const interval = setInterval(() => {
  discordChannel.sendTypingIndicator(channelId);
}, 8000);

// Clear when done
clearInterval(interval);
```

## Permissions & Roles

### Required Bot Permissions

Minimum permissions needed:

* **View Channels** - See server channels
* **Send Messages** - Reply to users
* **Send Messages in Threads** - Participate in threads
* **Embed Links** - Send rich embeds
* **Attach Files** - Send files and images
* **Read Message History** - View conversation context
* **Add Reactions** - React to messages
* **Use External Emojis** - Use custom emojis

### Check Bot Permissions

```javascript theme={null}
const channel = await client.channels.fetch(channelId);
const permissions = channel.permissionsFor(client.user);

if (!permissions.has('SendMessages')) {
  console.log('Bot cannot send messages in this channel');
}
```

## Advanced Features

### Voice Channels

For voice channel support (future):

```yaml theme={null}
# Config for voice features
discordVoiceEnabled: false
```

<Note>
  Voice channel integration is not yet implemented in OrcBot v2.1. Audio files sent as attachments are transcribed instead.
</Note>

### Slash Commands

Register slash commands (future enhancement):

```javascript theme={null}
const { SlashCommandBuilder } = require('discord.js');

const command = new SlashCommandBuilder()
  .setName('summarize')
  .setDescription('Summarize recent conversation')
  .addIntegerOption(option =>
    option.setName('messages')
      .setDescription('Number of messages to summarize')
      .setRequired(false)
  );
```

### Embeds

Send rich embeds:

```javascript theme={null}
const { EmbedBuilder } = require('discord.js');

const embed = new EmbedBuilder()
  .setTitle('Task Complete')
  .setDescription('Your report has been generated')
  .setColor(0x00FF00)
  .addFields(
    { name: 'Status', value: 'Success', inline: true },
    { name: 'Duration', value: '2.3s', inline: true }
  )
  .setTimestamp();

await channel.send({ embeds: [embed] });
```

## Session Management

### Session Scoping

OrcBot tracks separate sessions per channel:

```typescript theme={null}
const sessionScopeId = this.agent.resolveSessionScopeId('discord', {
  sourceId: channelId,
  userId
});
```

**Result:**

* DM: `discord:987654321098765432`
* Server channel: `discord:123456789012345678`

### Metadata Storage

Messages include metadata:

```typescript theme={null}
metadata: {
  guildId,           // Server ID (if in server)
  channelName,       // Channel name
  replyToMessageId   // If replying to another message
}
```

## Troubleshooting

### Bot Not Responding

<Steps>
  <Step title="Check Token">
    Verify token is correct:

    ```bash theme={null}
    grep discordToken ~/.orcbot/orcbot.config.yaml
    ```
  </Step>

  <Step title="Check Intents">
    Ensure MESSAGE CONTENT INTENT is enabled in Discord Developer Portal
  </Step>

  <Step title="Check Permissions">
    Verify bot has Send Messages permission in the channel
  </Step>

  <Step title="Check Logs">
    ```bash theme={null}
    tail -f ~/.orcbot/logs/orcbot.log | grep -i discord
    ```

    Should see: `Discord bot logged in as YourBot#1234`
  </Step>
</Steps>

### Missing Permissions Error

```
Error: Missing Access
```

**Fix:** Re-invite the bot with correct permissions:

1. Generate new invite URL with proper permissions
2. Open URL and select your server
3. Bot permissions will be updated

### Messages Not Being Received

**Check:**

1. Message Content Intent is enabled (Developer Portal)
2. Bot has Read Messages permission
3. Auto-reply is enabled: `discordAutoReplyEnabled: true`

### Rate Limiting

```
DiscordAPIError: You are being rate limited
```

OrcBot includes built-in delays:

```typescript theme={null}
for (const chunk of chunks) {
  await textChannel.send(chunk);
  await this.delay(500);  // 500ms between messages
}
```

If you still hit limits:

* Reduce message frequency
* Batch multiple responses
* Increase delay between messages

### Attachment Download Failures

```bash theme={null}
# Check download directory
ls -la ~/.orcbot/downloads/

# Check disk space
df -h ~/.orcbot/

# Check permissions
chmod 755 ~/.orcbot/downloads/
```

## Best Practices

<Card title="Security" icon="shield">
  * Never commit bot token to version control
  * Use environment variables or secure config
  * Regularly rotate your bot token
  * Use least-privilege permissions
</Card>

<Card title="Performance" icon="bolt">
  * Send typing indicators for long operations
  * Split large messages to avoid rate limits
  * Clean up old downloads periodically
  * Use message caching for context
</Card>

<Card title="User Experience" icon="sparkles">
  * Use embeds for structured information
  * Add reactions for quick feedback
  * Keep messages concise in busy channels
  * Use threads for extended conversations
</Card>

<Card title="Moderation" icon="gavel">
  * Set up role-based permissions
  * Use channel restrictions for sensitive commands
  * Log all bot actions
  * Implement cooldowns for expensive operations
</Card>

## Example Workflows

### Code Review Assistant

```
User: [uploads code.py]
      "Review this code for security issues"

Bot:  [Typing...]
      
      Security Analysis:
      
      ⚠️ Critical:
      - Line 23: SQL injection vulnerability
      - Line 45: Hardcoded API key
      
      💡 Recommendations:
      1. Use parameterized queries
      2. Move credentials to environment variables
      3. Add input validation on lines 15-20
```

### Server Monitoring

```
#alerts channel

Bot: 🚨 Alert: High CPU Usage
     
     Server: web-prod-01
     CPU: 92%
     Memory: 78%
     Uptime: 14 days
     
     [Restart Service] [View Logs] [Dismiss]
```

### Team Coordination

```
#general channel

Alice: "Who's working on the API refactor?"
Bob:   "When is the deadline?"
Carol: "What's the progress?"

@OrcBot: "Summarize this project discussion"

Bot:  Project: API Refactor
      
      Team: Alice, Bob, Carol
      Deadline: March 15 (8 days away)
      Progress: 65% complete
      
      Recent updates:
      - Authentication module done (Alice)
      - Database layer in progress (Bob)
      - Testing pending (Carol)
      
      Next steps:
      1. Complete DB migration (Bob, 2 days)
      2. Integration testing (Carol, 3 days)
      3. Final review (All, 1 day)
```
