> ## 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.

# Telegram Channel Setup

> Set up your Telegram bot using Telegraf and configure rich interactions with buttons, polls, and reactions

## Prerequisites

* A Telegram account
* OrcBot installed and configured
* Node.js 18+ installed

## Create Your Telegram Bot

<Steps>
  <Step title="Open BotFather">
    In Telegram, search for [@BotFather](https://t.me/botfather) and start a chat
  </Step>

  <Step title="Create New Bot">
    Send `/newbot` to BotFather
  </Step>

  <Step title="Choose Name">
    Enter a display name for your bot (e.g., "My OrcBot")
  </Step>

  <Step title="Choose Username">
    Enter a unique username ending in `bot` (e.g., "myorcbot\_bot")
  </Step>

  <Step title="Save Token">
    BotFather will send you an API token. Save this - you'll need it for configuration.

    Example: `123456789:ABCdefGHIjklMNOpqrsTUVwxyz`
  </Step>
</Steps>

## Configure OrcBot

### Using Environment Variables

<CodeGroup>
  ```bash Linux/macOS theme={null}
  export TELEGRAM_TOKEN="123456789:ABCdefGHIjklMNOpqrsTUVwxyz"
  ```

  ```powershell Windows theme={null}
  $env:TELEGRAM_TOKEN="123456789:ABCdefGHIjklMNOpqrsTUVwxyz"
  ```

  ```yaml Docker Compose theme={null}
  environment:
    - TELEGRAM_TOKEN=123456789:ABCdefGHIjklMNOpqrsTUVwxyz
  ```
</CodeGroup>

### Using Config File

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

```yaml theme={null}
telegramToken: "123456789:ABCdefGHIjklMNOpqrsTUVwxyz"

# Optional: Enable auto-reply in group chats
telegramAutoReplyEnabled: true

# Optional: Custom commands
telegramCommands:
  - command: news
    description: Get latest AI news
  - command: summarize
    description: Summarize recent conversation
```

## Start the Bot

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

# Or in development mode
npm run dev
```

You should see:

```
Telegraf: Bot connected as @myorcbot_bot
Agent: Telegram channel started
```

## Built-in Commands

OrcBot includes these commands out of the box:

| Command   | Description                              |
| --------- | ---------------------------------------- |
| `/start`  | Initialize bot and get welcome message   |
| `/status` | Show agent status, model, and queue info |
| `/queue`  | View active and pending tasks            |
| `/cancel` | Cancel currently running task            |
| `/logs`   | View recent log entries                  |
| `/memory` | Show memory statistics                   |
| `/skills` | List available skills and plugins        |
| `/models` | Show LLM model availability              |
| `/config` | Display current configuration            |
| `/admin`  | Admin panel (admin users only)           |
| `/reset`  | Clear session context                    |
| `/help`   | List custom commands                     |

### Command Examples

<CodeGroup>
  ```text Status Check theme={null}
  /status

  → Agent Status
    - Model: gpt-4o-mini (openai)
    - Short-term Memories: 8
    - Active Tasks: 1
    - Pending in Queue: 0
  ```

  ```text View Queue theme={null}
  /queue

  → Task Queue

    Active:
    • act_abc123: Research latest AI developments...

    Pending:
    Queue is empty.
  ```

  ```text Memory Stats theme={null}
  /memory

  → Memory Summary
    - Short-term: 12 items
    - Episodic: 3 items
    - Long-term: 45 items
  ```
</CodeGroup>

## Rich Telegram Features

OrcBot v2.1 supports advanced Telegram interactions:

### Inline Buttons

Send messages with interactive buttons:

```javascript theme={null}
// From a custom skill or plugin
telegram_send_buttons(
  chatId: "123456789",
  text: "Choose an option:",
  buttons: [["Option A", "Option B"], ["Cancel"]]
)
```

**Example interaction:**

```
User: "Show me AI news sources"

Bot: 📰 Choose a source:
     [TechCrunch] [VentureBeat]
     [ArXiv]      [Papers With Code]
```

### Native Polls

Create Telegram polls:

```javascript theme={null}
telegram_send_poll(
  chatId: "123456789",
  question: "Which feature should I prioritize?",
  options: ["Better search", "Faster responses", "More plugins"]
)
```

### Emoji Reactions

React to messages with emojis:

```javascript theme={null}
telegram_react(
  chatId: "123456789",
  messageId: 42,
  emoji: "👍"
)
```

<Note>
  If native reactions are blocked (privacy settings), OrcBot falls back to a text reply with the emoji.
</Note>

### Message Editing

Edit previously sent messages:

```javascript theme={null}
telegram_edit_message(
  chatId: "123456789",
  messageId: 42,
  newText: "Updated: Task completed successfully! ✅"
)
```

**Use case:** Live status updates

```
[Initial] Searching web...  🔍
[Edit]    Found 10 results  📊
[Edit]    Analysis complete ✅
```

### Message Pinning

Pin important messages:

```javascript theme={null}
telegram_pin_message(
  chatId: "123456789",
  messageId: 42
)
```

## Media Handling

### Sending Images

OrcBot automatically handles images:

```
User: "Show me a chart of Bitcoin prices"

Bot: [Generates chart]
     [Sends as image file]
     Caption: Bitcoin price trend (last 30 days)
```

### Receiving Media

OrcBot downloads and analyzes media you send:

<Tabs>
  <Tab title="Photos">
    ```
    User: [sends photo of plant]
          "What kind of plant is this?"

    Bot: Based on the image, this appears to be a 
         Monstera Deliciosa (Swiss Cheese Plant).
         Care instructions: ...
    ```
  </Tab>

  <Tab title="Voice Messages">
    ```
    User: [sends voice note]
          "Remind me to call John tomorrow"

    Bot: ✅ I've set a reminder to call John tomorrow.
         Transcription: "Remind me to call John tomorrow"
    ```
  </Tab>

  <Tab title="Documents">
    ```
    User: [sends PDF file]
          "Summarize this report"

    Bot: I've analyzed the 12-page document.
         Key points:
         1. Revenue increased 23% YoY
         2. New product line launched in Q3
         3. ...
    ```
  </Tab>
</Tabs>

### Auto-transcription

Voice and audio messages are automatically transcribed:

```typescript theme={null}
// TelegramChannel.ts automatically transcribes audio
if (mediaPath && (message.voice || message.audio)) {
  logger.info(`Telegram: Auto-transcribing audio from ${userName}...`);
  const result = await this.agent.llm.analyzeMedia(
    mediaPath,
    'Transcribe this audio message exactly.'
  );
  transcription = result.replace(/^Transcription result:\n/i, '').trim();
}
```

## Group Chat Features

### Auto-reply Configuration

```yaml theme={null}
# ~/.orcbot/orcbot.config.yaml

# Reply to all messages in groups
telegramAutoReplyEnabled: true

# Or reply only when mentioned
telegramAutoReplyEnabled: false  # Mention required: "@mybot help me"
```

### Reply Context

OrcBot preserves conversation threads:

```
Alice: "What's the weather like?"
Bob:   "@mybot answer Alice's question"
       [Replies to Alice's message]

Bot:   "Based on your location, it's currently 72°F and sunny."
       [Reply includes context: "Replying to Alice's message: 'What's the weather like?'"]
```

### Admin Permissions

Restrict elevated commands to specific users:

```yaml theme={null}
adminUsers:
  telegram:
    - "123456789"  # Your Telegram user ID
    - "987654321"  # Another admin's ID
```

Get your user ID:

```
1. Message your bot
2. Check logs: "Telegram: User 123456789 started the bot"
3. Add that ID to adminUsers config
```

## Custom Commands

Define custom slash commands:

```yaml theme={null}
telegramCommands:
  - command: deploy
    description: Deploy to production
  - command: metrics
    description: Show system metrics
  - command: backup
    description: Backup database
```

OrcBot registers these with BotFather automatically and handles them as high-priority tasks.

### Implementation

```typescript theme={null}
// TelegramChannel.ts
for (const cmdCfg of configuredCommands) {
  this.bot.command(cmdCfg.command, async (ctx) => {
    await this.agent.messageBus.dispatch({
      source: 'telegram',
      content: ctx.message.text || `/${cmdCfg.command}`,
      isCommand: true,
      metadata: { command: cmdCfg.command }
    });
  });
}
```

## Session Management

### Session Scoping

OrcBot tracks separate sessions per chat:

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

**Result:**

* Private chat: `telegram:123456789`
* Group chat: `telegram:group:-987654321`

### Reset Session

```
User: /reset

Bot: Context reset. Short-term memory for this session has been cleared.
```

This clears:

* Recent conversation history
* Short-term memories for this chat
* Pending clarification requests

Preserves:

* Long-term memory (journal, learnings)
* User profile
* Other chat sessions

## Advanced Configuration

### Markdown Rendering

OrcBot automatically converts markdown to Telegram HTML:

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

await ctx.reply(formatted, { parse_mode: 'HTML' });
```

**Supported:**

* `**bold**` → `<b>bold</b>`
* `*italic*` → `<i>italic</i>`
* `[link](url)` → `<a href="url">link</a>`
* `` `code` `` → `<code>code</code>`
* Code blocks → `<pre>code</pre>`

### File Size Limits

Telegram file size limits:

* **Photos:** 10 MB
* **Documents:** 50 MB (bots can send up to 50 MB)
* **Voice:** 20 MB

OrcBot handles oversized files:

```typescript theme={null}
if (fileSize > 50 * 1024 * 1024) {
  return `File too large for Telegram (${fileSize} bytes). Saved locally: ${filePath}`;
}
```

## Troubleshooting

### Bot Not Responding

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

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

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

    Should see: `Telegraf: Bot connected as @yourbot`
  </Step>

  <Step title="Test Connectivity">
    ```bash theme={null}
    curl https://api.telegram.org/bot<YOUR_TOKEN>/getMe
    ```
  </Step>

  <Step title="Restart OrcBot">
    ```bash theme={null}
    orcbot daemon stop
    orcbot run
    ```
  </Step>
</Steps>

### Messages Not Being Processed

Check auto-reply settings:

```yaml theme={null}
# For group chats, enable auto-reply or mention the bot
telegramAutoReplyEnabled: true
```

Or mention the bot:

```
@mybot summarize this conversation
```

### Media Download Failures

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

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

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

### Command Not Found

If custom commands aren't working:

1. Verify they're in the config:
   ```yaml theme={null}
   telegramCommands:
     - command: mycommand
       description: My custom command
   ```

2. Restart OrcBot to register new commands

3. Update BotFather manually if needed:
   ```
   /setcommands
   @yourbot
   mycommand - My custom command
   status - Show agent status
   ...
   ```

## Example Workflows

### Daily Briefing

```yaml theme={null}
# Schedule via Telegram
User: "Send me a daily briefing at 9 AM with news and my calendar"

Bot: ✅ Scheduled daily briefing
     Next run: Tomorrow at 09:00

# Bot creates scheduled task using heartbeat_schedule skill
```

### File Processing

```
User: [sends CSV file]
      "Analyze this sales data and create a summary report"

Bot: [Processing...]
     📊 Analysis Complete
     
     Key Insights:
     - Total sales: $1.2M (+15% vs last month)
     - Top product: Widget Pro (35% of revenue)
     - Regional breakdown: ...
     
     [Sends detailed report as PDF]
```

### Interactive Troubleshooting

```
User: "My website is down"

Bot: I'll help you diagnose the issue.
     
     What type of error are you seeing?
     [500 Internal Server]  [404 Not Found]
     [Timeout]              [Other]

User: [clicks "500 Internal Server"]

Bot: Checking your server status...
     
     Found the issue:
     ❌ Database connection failed
     ✅ Web server is running
     ✅ SSL certificate is valid
     
     Recommended action: Restart database service
     Run this command? [Yes] [No]
```

## Best Practices

<Card title="Security" icon="shield">
  * Never commit your bot token to version control
  * Use environment variables or secure config files
  * Set admin users to restrict elevated commands
  * Enable `safeMode` if you don't need command execution
</Card>

<Card title="Performance" icon="bolt">
  * Enable `skipSimulationForSimpleTasks` for faster responses
  * Use `compactSkillsPrompt: true` to reduce token usage
  * Set reasonable `maxStepsPerAction` limits (10-20)
</Card>

<Card title="User Experience" icon="sparkles">
  * Use inline buttons for common actions
  * Send typing indicators for long-running tasks
  * Edit messages for live updates instead of sending multiple messages
  * Use emoji reactions for quick acknowledgment
</Card>
