AI-powered Discord bot package integrating AccuralAI orchestration.
Project description
AccuralAI Discord Bot Package
High-level abstraction for building AI-powered Discord bots with minimal boilerplate, integrating seamlessly with AccuralAI orchestration.
Quick Start
Minimal Example
from accuralai_discord import DiscordBot
# Minimal example (10 lines)
bot = DiscordBot(
token="DISCORD_BOT_TOKEN",
personality="friendly assistant",
accuralai_config_path="config.toml"
)
bot.run()
Test Bot (Recommended for Testing)
Use the included test bot for quick testing:
Linux/Mac:
export DISCORD_BOT_TOKEN="your_bot_token_here"
python -m accuralai_discord.test_bot
Windows CMD:
set DISCORD_BOT_TOKEN=your_bot_token_here
set ACCURALAI_CONFIG_PATH=C:\path\to\config.toml
python -m accuralai_discord.test_bot
Windows PowerShell:
$env:DISCORD_BOT_TOKEN="your_bot_token_here"
$env:ACCURALAI_CONFIG_PATH="C:\path\to\config.toml"
python -m accuralai_discord.test_bot
Relative path (relative to current directory):
export DISCORD_BOT_TOKEN="your_token"
export ACCURALAI_CONFIG_PATH="config.toml" # or "./config.toml"
python -m accuralai_discord.test_bot
Or use the CLI command:
accuralai-discord-test
The test bot includes:
- Example tools (
echo,calculate) - Custom commands (
/test,/analytics) - Built-in analytics tracking
- Full feature configurability via environment variables
See TEST_BOT.md for complete documentation and environment variable reference.
Installation
pip install accuralai-discord
Features
- Minimal Boilerplate: Get a working bot in ~10 lines
- AccuralAI Integration: Automatic integration with AccuralAI orchestration pipeline
- Conversation Memory: Persistent conversation history with configurable scopes
- Built-in Commands:
/help,/reset,/personality,/status - Custom Commands: Easy registration of custom commands
- Tool/Function Calling: Register tools for AI to call during conversations
- Multi-Modal Support: Handle images and file attachments
- Rich Embeds: Formatted Discord embeds for responses
- Context Awareness: Automatic Discord context (roles, permissions) in prompts
- Smart History: Intelligent conversation history management with summarization
- Analytics: Built-in usage tracking and telemetry
- Streaming Responses: Support for streaming with typing indicators
- Rate Limiting: Built-in rate limiting per conversation context
- Error Handling: User-friendly error messages
- Event Hooks: Pre/post-processing hooks for customization
Configuration
Basic Configuration
bot = DiscordBot(
token="DISCORD_BOT_TOKEN",
personality="technical expert",
conversation_scope="per-user", # or "per-channel", "per-thread"
accuralai_config_path="accuralai-config.toml"
)
Advanced Configuration
from accuralai_discord import DiscordBot, DiscordBotConfig
config = DiscordBotConfig(
token="DISCORD_BOT_TOKEN",
personality="helpful assistant",
conversation_scope="per-channel",
max_history_entries=50,
max_history_tokens=2000,
rate_limit_per_minute=20,
accuralai_config_path="config.toml",
accuralai_config_overrides={
"backends.ollama.options.model": "llama3"
}
)
bot = DiscordBot(config=config)
bot.run()
Conversation Scopes
- per-channel: All users in a channel share conversation history
- per-user: Each user has isolated context across all channels
- per-thread: Each Discord thread = separate conversation
- per-channel-user: Per user within each channel
Custom Commands
Prefix Commands (Text-based)
@bot.command("/weather", description="Get weather info")
async def weather_command(ctx):
return "It's sunny today!"
# Or register manually
async def custom_handler(ctx):
return f"Hello {ctx.user.name}!"
bot.add_command("/greet", custom_handler, "Greet a user")
Slash Commands (Application Commands)
Slash commands provide a modern Discord UI with autocomplete and better UX.
Global Slash Commands
import discord
# Register a global slash command
async def ping_handler(interaction: discord.Interaction) -> str:
return "Pong! 🏓"
bot.add_slash_command("ping", "Ping the bot", ping_handler)
# Or use decorator-style
@bot.slash_command("ping", "Ping the bot")
async def ping_slash(interaction: discord.Interaction) -> str:
return "Pong! 🏓"
Per-Guild Slash Commands
import discord
# Register a command for a specific guild (server)
async def admin_handler(interaction: discord.Interaction) -> str:
return "Admin command executed!"
GUILD_ID = 123456789012345678 # Your guild ID
bot.add_slash_command(
"admin",
"Admin-only command",
admin_handler,
guild_id=GUILD_ID
)
Slash Commands with Parameters
import discord
@app_commands.describe(user="The user to greet")
async def greet_handler(interaction: discord.Interaction, user: discord.Member) -> str:
return f"Hello {user.mention}!"
bot.add_slash_command("greet", "Greet a user", greet_handler)
Configuration
Enable slash commands in your config:
from accuralai_discord import DiscordBot, DiscordBotConfig
config = DiscordBotConfig(
token="YOUR_TOKEN",
enable_slash_commands=True, # Enable slash commands
auto_sync_slash_commands=True, # Auto-sync on startup
sync_guild_commands=[123456789012345678], # Sync to specific guilds (optional)
)
bot = DiscordBot(config=config)
Note: Global commands can take up to 1 hour to propagate. Guild commands sync instantly.
Event Hooks
@bot.on_message_preprocess
async def preprocess(message, context):
# Modify message before AI processing
return message.content.upper()
@bot.on_message_postprocess
async def postprocess(response, message, context):
# Modify AI response before sending
return f"[BOT] {response}"
Accessing Orchestrator
orchestrator = bot.get_orchestrator()
# Use orchestrator directly for advanced use cases
Enhanced AI Features
Tool/Function Calling
Register custom tools that the AI can call during conversations:
bot.add_tool(
name="get_weather",
description="Get weather for a location",
parameters={
"type": "object",
"properties": {
"location": {"type": "string", "description": "City name"}
},
"required": ["location"]
},
handler=async def get_weather(location: str, context: dict):
# Your tool logic
return f"Weather in {location}: Sunny"
)
Multi-Modal Support
Handle images and file attachments:
bot = DiscordBot(
token="YOUR_TOKEN",
enable_multimodal=True, # Automatically processes images
accuralai_config_path="config.toml"
)
The bot automatically includes image attachments in AI requests.
Rich Embeds
Use Discord embeds for formatted responses:
bot = DiscordBot(
token="YOUR_TOKEN",
use_embeds=True, # Use embeds instead of plain text
accuralai_config_path="config.toml"
)
Context Awareness
Bot automatically includes Discord context (roles, permissions, channel info):
bot = DiscordBot(
token="YOUR_TOKEN",
context_aware=True, # Include Discord metadata in prompts
accuralai_config_path="config.toml"
)
Analytics & Telemetry
Track bot usage and performance:
analytics = bot.get_analytics()
summary = analytics.get_summary()
print(f"Total messages: {summary['total_messages']}")
print(f"Cache hit rate: {summary['cache_hit_rate']}")
Smart History Management
Enable intelligent conversation history management:
bot = DiscordBot(
token="YOUR_TOKEN",
smart_history=True, # Enable summarization and relevance-based pruning
accuralai_config_path="config.toml"
)
Streaming Responses
Stream responses with typing indicators (requires backend support):
from accuralai_discord import stream_response
# In your custom handler
async def stream_handler(response_stream):
await stream_response(
channel=message.channel,
response_stream=response_stream,
show_typing=True
)
CLI Usage
You can also run the bot from the command line:
accuralai-discord-bot --token YOUR_TOKEN --personality "friendly assistant"
Or with a configuration file:
accuralai-discord-bot --config bot-config.toml
Error Handling
The bot includes built-in error handling for:
- AccuralAI pipeline errors
- Discord API errors
- Rate limiting
- Network issues
Errors are automatically formatted into user-friendly messages.
Architecture
The bot integrates with AccuralAI's orchestration pipeline:
- Message Reception: Discord messages are received via
discord.py - Context Extraction: Conversation context is determined by scope
- Rate Limiting: Per-context rate limits are enforced
- Command Parsing: Commands are routed to handlers
- AI Generation: Non-command messages are sent to AccuralAI orchestrator
- Memory Management: Conversation history is stored using AccuralAI cache
- Response Delivery: AI responses are sent back to Discord
Configuration Files
Bot Configuration (TOML)
[discord]
token = "${DISCORD_BOT_TOKEN}"
personality = "helpful assistant"
conversation_scope = "per-channel"
max_history_entries = 50
rate_limit_per_minute = 20
[discord.accuralai]
config_path = "accuralai-config.toml"
overrides = { "backends.ollama.options.model" = "llama3" }
Examples
Simple Q&A Bot
from accuralai_discord import DiscordBot
bot = DiscordBot(
token="YOUR_TOKEN",
personality="knowledgeable assistant",
accuralai_config_path="config.toml"
)
bot.run()
Bot with Custom Commands
from accuralai_discord import DiscordBot
bot = DiscordBot(
token="YOUR_TOKEN",
personality="helpful bot",
accuralai_config_path="config.toml"
)
@bot.command("/ping")
async def ping(ctx):
return "Pong!"
@bot.command("/info")
async def info(ctx):
return f"Hello {ctx.user.name}! I'm a helpful bot."
bot.run()
Bot with Custom Hooks
from accuralai_discord import DiscordBot
bot = DiscordBot(
token="YOUR_TOKEN",
personality="friendly assistant",
accuralai_config_path="config.toml"
)
@bot.on_message_preprocess
async def log_messages(message, context):
print(f"User {context['user_id']} said: {message.content}")
return None # Don't modify message
@bot.on_message_postprocess
async def add_prefix(response, message, context):
return f"🤖 {response}"
bot.run()
Testing
Run tests with:
pytest tests/
License
Apache-2.0
Documentation
See the AccuralAI documentation for more details.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file accuralai_discord-0.2.1.tar.gz.
File metadata
- Download URL: accuralai_discord-0.2.1.tar.gz
- Upload date:
- Size: 67.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.10.19
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
011e79e4ba05ccfd7d2e825c94790af4197aeb0e73c9531e8d61e4ab542fc816
|
|
| MD5 |
606860249baeb183d12e4f0e894ac4e4
|
|
| BLAKE2b-256 |
4c16ea512c3dabdba337e85464c97877eec4130590e41e9a83b47647db94cecc
|
File details
Details for the file accuralai_discord-0.2.1-py3-none-any.whl.
File metadata
- Download URL: accuralai_discord-0.2.1-py3-none-any.whl
- Upload date:
- Size: 66.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.10.19
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f5eb9396f773372be346d920553545f46184ad5ffc3e9ef3f8d50d98c82d4bbd
|
|
| MD5 |
fc3776e0c957c429ad4454a8c0dbe72b
|
|
| BLAKE2b-256 |
c4f23f08a41667a1be40b1a35fdd8fb9114bdf744b64d2642348256a49006a5e
|