How to Build Multi-Agent Discord Bots with ElizaOS and TypeScript on Ubuntu 22.04 (2025)

How to Build Multi-Agent Discord Bots with ElizaOS and TypeScript on Ubuntu 22.04 (2025)

ElizaOS is an open-source framework for building autonomous AI agents that has gained significant traction in 2025 for its modular architecture and out-of-the-box platform connectors. If you're running Ubuntu 22.04 and want to build sophisticated Discord bots with multi-agent orchestration capabilities, this guide walks you through the complete setup process using TypeScript.

Prerequisites for ElizaOS on Ubuntu 22.04

Before starting, ensure your Ubuntu 22.04 system has the following installed:

  • Node.js 18.x or higher (20.x recommended)
  • npm 9.x or higher
  • Git 2.34 or higher
  • Discord application credentials (bot token and application ID)
  • At least 4GB RAM available
  • OpenAI API key or another supported LLM provider

Installing Node.js 20.x on Ubuntu 22.04

curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs
node --version  # Should output v20.x.x
npm --version   # Should output 10.x.x

Understanding ElizaOS Architecture for Discord Bots

ElizaOS separates concerns into three distinct layers:

  1. Framework layer (@elizaos/core) - The runtime, agent loop, and plugin model
  2. Project layer - Your deployable product workspace with branded app shell
  3. Plugin layer - Runtime plugins including plugin-discord for Discord connectivity

For Discord bots, you'll primarily work with the framework and plugin layers. The multi-agent architecture allows you to create specialized agents that handle different aspects of your Discord server—moderation, support, content creation, or game NPCs.

Step 1: Initialize Your ElizaOS Project

ElizaOS provides a CLI tool that scaffolds new projects with best practices built-in.

# Install the ElizaOS CLI globally
npm install -g @elizaos/elizaos

# Create a new project
elizaos create my-discord-bot --template min-project

# Navigate into your project
cd my-discord-bot

# Install dependencies
npm install

The min-project template creates a minimal workspace structure:

my-discord-bot/
├── apps/
│   └── app/           # Your main application shell
├── src/
│   ├── agents/        # Agent definitions
│   └── config/        # Configuration files
├── package.json
└── tsconfig.json

Step 2: Configure Discord Plugin and Credentials

ElizaOS uses environment variables for sensitive credentials. Create a .env file in your project root:

touch .env
chmod 600 .env  # Secure the file on Ubuntu

Add your Discord and LLM credentials:

# Discord Configuration
DISCORD_BOT_TOKEN=your_discord_bot_token_here
DISCORD_APPLICATION_ID=your_application_id_here

# LLM Provider (OpenAI example)
OPENAI_API_KEY=your_openai_key_here
MODEL_PROVIDER=openai
MODEL_NAME=gpt-4-turbo-preview

# Optional: Multiple agents configuration
AGENT_COUNT=3

Setting Up Your Discord Application

  1. Navigate to Discord Developer Portal
  2. Create a new application
  3. Go to the "Bot" section and create a bot
  4. Enable "Message Content Intent" and "Server Members Intent"
  5. Copy the bot token to your .env file
  6. Generate an OAuth2 URL with bot and applications.commands scopes
  7. Add required permissions: Send Messages, Read Message History, Use Slash Commands

Step 3: Install and Configure Discord Plugin

Add the Discord plugin to your project:

npm install @elizaos/plugin-discord

Create an agent configuration file at src/agents/discord-agent.ts:

import { AgentRuntime } from '@elizaos/agent';
import { DiscordClientInterface } from '@elizaos/plugin-discord';

export const discordAgentConfig = {
  name: 'discord-moderator',
  description: 'AI moderator for Discord server',
  modelProvider: process.env.MODEL_PROVIDER || 'openai',
  plugins: [
    {
      name: '@elizaos/plugin-discord',
      config: {
        token: process.env.DISCORD_BOT_TOKEN,
        applicationId: process.env.DISCORD_APPLICATION_ID,
        // Enable message handling
        handleMessages: true,
        // Respond to mentions and DMs
        respondToMentions: true,
        respondToDMs: true,
      },
    },
  ],
  // Agent-specific actions and behaviors
  actions: [
    'moderate_content',
    'answer_questions',
    'welcome_users',
  ],
};

Step 4: Create Multiple Specialized Agents

ElizaOS's multi-agent architecture shines when you create specialized agents for different tasks. Create src/agents/multi-agent-setup.ts:

import { AgentRuntime } from '@elizaos/agent';

interface AgentConfig {
  name: string;
  role: string;
  triggers: string[];
  systemPrompt: string;
}

const agentConfigs: AgentConfig[] = [
  {
    name: 'moderator-agent',
    role: 'moderation',
    triggers: ['@mod', 'report'],
    systemPrompt: 'You are a Discord moderator focused on maintaining community guidelines.',
  },
  {
    name: 'support-agent',
    role: 'support',
    triggers: ['@support', 'help'],
    systemPrompt: 'You are a technical support agent helping users with product questions.',
  },
  {
    name: 'engagement-agent',
    role: 'engagement',
    triggers: ['@engage', 'poll', 'event'],
    systemPrompt: 'You create engaging content and manage community events.',
  },
];

export async function initializeAgents(): Promise<AgentRuntime[]> {
  const agents = await Promise.all(
    agentConfigs.map(async (config) => {
      const runtime = new AgentRuntime({
        name: config.name,
        modelProvider: process.env.MODEL_PROVIDER,
        plugins: ['@elizaos/plugin-discord'],
        systemPrompt: config.systemPrompt,
      });
      
      await runtime.initialize();
      return runtime;
    })
  );
  
  return agents;
}

Step 5: Implement Message Routing Logic

Create intelligent routing between agents based on message content. Add src/services/agent-router.ts:

import { Message } from 'discord.js';
import { AgentRuntime } from '@elizaos/agent';

interface RoutingRule {
  keywords: string[];
  agentName: string;
  priority: number;
}

const routingRules: RoutingRule[] = [
  { keywords: ['ban', 'kick', 'warn', 'toxic'], agentName: 'moderator-agent', priority: 10 },
  { keywords: ['how', 'tutorial', 'guide', 'help'], agentName: 'support-agent', priority: 8 },
  { keywords: ['poll', 'vote', 'event', 'giveaway'], agentName: 'engagement-agent', priority: 5 },
];

export class AgentRouter {
  constructor(private agents: Map<string, AgentRuntime>) {}

  routeMessage(message: Message): AgentRuntime | null {
    const content = message.content.toLowerCase();
    
    // Find matching rules sorted by priority
    const matchedRule = routingRules
      .filter(rule => rule.keywords.some(kw => content.includes(kw)))
      .sort((a, b) => b.priority - a.priority)[0];
    
    if (matchedRule) {
      return this.agents.get(matchedRule.agentName) || null;
    }
    
    // Default to first agent if no match
    return this.agents.values().next().value || null;
  }
}

Step 6: Main Application Entry Point

Create src/index.ts to tie everything together:

import { config } from 'dotenv';
import { initializeAgents } from './agents/multi-agent-setup';
import { AgentRouter } from './services/agent-router';

config(); // Load .env file

async function main() {
  console.log('Initializing ElizaOS Discord multi-agent system...');
  
  // Initialize all agents
  const agents = await initializeAgents();
  const agentMap = new Map(agents.map(a => [a.name, a]));
  
  console.log(`Initialized ${agents.length} agents:`);
  agents.forEach(agent => console.log(`  - ${agent.name}`));
  
  // Set up router
  const router = new AgentRouter(agentMap);
  
  // Start all agents
  await Promise.all(agents.map(agent => agent.start()));
  
  console.log('All agents are now online and connected to Discord!');
}

main().catch(error => {
  console.error('Fatal error:', error);
  process.exit(1);
});

Step 7: Build and Deploy on Ubuntu 22.04

Development Mode

# Run with hot reload
npm run dev

Production Build

# Build TypeScript
npm run build

# Start production server
node dist/index.js

Running as a Systemd Service

For persistent operation on Ubuntu, create a systemd service at /etc/systemd/system/eliza-discord-bot.service:

[Unit]
Description=ElizaOS Discord Multi-Agent Bot
After=network.target

[Service]
Type=simple
User=your-ubuntu-username
WorkingDirectory=/home/your-ubuntu-username/my-discord-bot
Environment="NODE_ENV=production"
ExecStart=/usr/bin/node dist/index.js
Restart=on-failure
RestartSec=10

[Install]
WantedBy=multi-user.target

Enable and start the service:

sudo systemctl daemon-reload
sudo systemctl enable eliza-discord-bot
sudo systemctl start eliza-discord-bot
sudo systemctl status eliza-discord-bot

Comparison: ElizaOS vs Other Discord Bot Frameworks

| Feature | ElizaOS | Discord.js | Discord.py | |---------|---------|------------|------------| | Multi-agent support | Native | Manual implementation | Manual implementation | | LLM integration | Model-agnostic, built-in | Requires custom code | Requires custom code | | Plugin ecosystem | Growing, official registry | Extensive third-party | Extensive third-party | | TypeScript support | First-class | First-class | N/A (Python) | | RAG capabilities | Built-in document ingestion | Not included | Not included | | Learning curve | Medium | Low | Low | | Production readiness | Active development | Mature | Mature |

Troubleshooting Common Ubuntu 22.04 Issues

Permission Denied on .env File

chmod 600 .env
chown $USER:$USER .env

Node.js Version Conflicts

Use nvm to manage Node.js versions:

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
nvm install 20
nvm use 20

Port Already in Use

ElizaOS doesn't expose ports by default for Discord bots, but if you're running the web UI:

sudo lsof -i :3000
# Kill the process using the port
sudo kill -9 <PID>

Performance Optimization for Multi-Agent Systems

  1. Memory management: Each agent consumes approximately 200-300MB. Monitor with htop
  2. Rate limiting: Implement message queuing to avoid Discord API rate limits
  3. Caching: Use Redis for shared state between agents
  4. Log rotation: Configure logrotate for /var/log/eliza/
sudo apt-get install redis-server
sudo systemctl enable redis-server
sudo systemctl start redis-server

Deploying to Production with CI/CD

For Ubuntu 22.04 servers, consider using GitHub Actions with self-hosted runners or deploying to platforms like DigitalOcean or Render for managed hosting. Both offer Ubuntu-based environments and easy integration with ElizaOS projects.

Create .github/workflows/deploy.yml:

name: Deploy ElizaOS Bot
on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-22.04
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: '20'
      - run: npm ci
      - run: npm run build
      - run: npm test
      # Deploy steps here

Conclusion

ElizaOS provides a robust foundation for building multi-agent Discord bots on Ubuntu 22.04. Its model-agnostic approach, native plugin system, and TypeScript-first design make it an excellent choice for developers who need more than basic bot functionality. The framework's multi-agent architecture particularly excels when you need specialized agents handling different aspects of community management.

For production deployments, consider using managed hosting platforms that support Node.js applications and provide easy scaling options as your Discord community grows. The combination of ElizaOS's plugin ecosystem and Ubuntu's stability creates a powerful environment for autonomous agent development.

Recommended Tools