How to Set Up Discord Messaging Platform Integration for Free-Claude-Code
Install discord.py, configure the DISCORD_BOT_TOKEN environment variable, and instantiate the platform via the messaging factory to enable Discord bot capabilities in free-claude-code.
Free-Claude-Code ships with a pluggable DiscordPlatform adapter that transforms the proxy into a Discord bot. Setting up the Discord messaging platform integration for free-claude-code involves installing the Discord client library, configuring environment variables, and leveraging the factory pattern to handle message routing and rate limiting automatically.
Install the Discord Client Library
The Discord integration depends on discord.py. Without this dependency, the platform adapter in messaging/platforms/discord.py sets DISCORD_AVAILABLE = False and raises an ImportError if instantiation is attempted【/messaging/platforms/discord.py#L25-L34】.
Install the library using your preferred package manager:
uv add discord.py
Or alternatively:
pip install discord.py
Configure Environment Variables
The global settings model in config/settings.py defines two critical fields that map to environment variables【/config/settings.py#L87-L92】:
DISCORD_BOT_TOKEN: Your Discord bot authentication token (defaults toNone)ALLOWED_DISCORD_CHANNELS: Comma-separated list of channel IDs to restrict the bot to (defaults toNonefor unrestricted access)
Both fields pass through a validator that converts empty strings to None, allowing flexible configuration【/messaging/platforms/discord.py#L89-L102】.
Create or edit your .env file:
DISCORD_BOT_TOKEN="YOUR_BOT_TOKEN_HERE"
ALLOWED_DISCORD_CHANNELS="123456789012345678,987654321098765432"
Leave ALLOWED_DISCORD_CHANNELS empty to allow the bot to respond in all channels where it has permissions.
Instantiate the Platform via the Factory
Free-Claude-Code uses a factory pattern to manage platform lifecycle. The messaging-platform factory in messaging/platforms/factory.py automatically creates a DiscordPlatform instance when it detects a Discord token in the configuration【/messaging/platforms/factory.py#L40-L51】.
The factory passes the token and allowed channel list directly to the DiscordPlatform constructor:
from messaging.platforms.factory import create_messaging_platform
from config.settings import get_settings
settings = get_settings()
platform = create_messaging_platform(
"discord",
discord_bot_token=settings.discord_bot_token,
allowed_discord_channels=settings.allowed_discord_channels,
)
Handle Discord Messages
The DiscordPlatform class creates a lightweight subclass of discord.Client that forwards on_message events to your custom handler. Only the message_content intent is enabled, which is required for reading user messages【/messaging/platforms/discord.py#L106-L109】.
Register a message handler to process incoming Discord messages:
async def echo_handler(msg):
"""Simple echo handler demonstrating outgoing queue."""
await platform.queue_send_message(
chat_id=msg.chat_id,
text=f"Echo: {msg.text}",
reply_to=msg.message_id,
)
platform.on_message(echo_handler)
Incoming messages pass through filtering logic that ignores bots and validates against allowed channels before converting to IncomingMessage dataclasses【/messaging/platforms/discord.py#L54-L77】.
Manage Platform Lifecycle
Control the bot connection using start() and stop() methods. The start() method validates the token, initializes the MessagingRateLimiter, and establishes the Discord client connection【/messaging/platforms/discord.py#L38-L51】.
import asyncio
async def main():
# Start the platform
await platform.start()
print("Discord bot connected")
# Keep alive until interrupted
try:
while True:
await asyncio.sleep(3600)
except (KeyboardInterrupt, SystemExit):
await platform.stop()
if __name__ == "__main__":
asyncio.run(main())
If no token is found, the platform emits a warning during construction and raises a ValueError when start() is called【/messaging/platforms/discord.py#L340-L342】.
Rate Limiting and Message Rendering
Outgoing messages use queue_send_message, queue_edit_message, and queue_delete_message, all of which automatically respect Discord's rate limits through the shared MessagingRateLimiter【/messaging/platforms/discord.py#L64-L78】.
Discord-specific markdown escaping is handled by messaging/rendering/discord_markdown.py, which provides format_status_discord for status updates like "Transcribing voice note…"【/messaging/rendering/discord_markdown.py#L1-L70】.
Summary
- Install
discord.pybefore attempting to instantiate the platform, or the import will fail withDISCORD_AVAILABLE = False. - Set
DISCORD_BOT_TOKENin your environment; the factory inmessaging/platforms/factory.pyuses this to create the DiscordPlatform instance. - Configure
ALLOWED_DISCORD_CHANNELSwith comma-separated channel IDs to restrict where the bot responds, or omit it for unrestricted access. - Use the factory pattern via
create_messaging_platform("discord", **config)to ensure proper initialization with rate limiting. - Call
await platform.start()to connect the bot andawait platform.stop()for graceful shutdown.
Frequently Asked Questions
What happens if I don't set DISCORD_BOT_TOKEN?
The DiscordPlatform constructor will emit a warning during instantiation and raise a ValueError when you call start(), preventing the bot from attempting to connect without credentials【/messaging/platforms/discord.py#L340-L342】.
How do I restrict the bot to specific Discord channels?
Set the ALLOWED_DISCORD_CHANNELS environment variable to a comma-separated list of channel IDs (e.g., "123456789,987654321"). The platform parses this into a set of strings during initialization and filters incoming messages accordingly【/messaging/platforms/discord.py#L89-L102】.
Can I run Discord integration alongside other messaging platforms?
Yes. The factory pattern supports multiple platform types simultaneously. Call create_messaging_platform() with different platform identifiers (e.g., "discord", "telegram") using their respective configuration dictionaries to run multiple adapters concurrently.
How does rate limiting work for Discord messages?
All outgoing operations use the MessagingRateLimiter automatically. When you call queue_send_message or similar methods, the platform queues the request and handles Discord's rate limits transparently without blocking your handler code【/messaging/platforms/discord.py#L64-L78】.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →