Router Class
Constructor
adapters
Array<BaseAdapter>
default:"[]"
Array of channel adapter instances
Default bot ID for all adapters (can be overridden per adapter)
Global error handler function
Example:
const router = new Router({
apiKey: process.env.BOOSTGPT_API_KEY,
projectId: process.env.BOOSTGPT_PROJECT_ID,
defaultBotId: process.env.BOOSTGPT_BOT_ID,
adapters: [
new DiscordAdapter({ discordToken: '...' }),
new TelegramAdapter({ telegramToken: '...' })
],
enableLogging: true
});
Methods
onMessage()
Set a custom message handler for all channels.
router.onMessage(async (message, context) => {
// Your logic here
return response;
});
Parameters:
Normalized message object:{
content: string, // Message text
userId: string, // User identifier
userName: string, // User display name
metadata: Object // Channel-specific data
}
Context object:{
channel: string, // Channel name ('discord', 'telegram', etc.)
adapter: BaseAdapter, // Adapter instance
router: Router, // Router instance
boostgpt: BoostGPT // BoostGPT client instance
}
Returns:
string - Send this as the response
null / undefined - Let BoostGPT handle it automatically
Example:
router.onMessage(async (message, context) => {
console.log(`[${context.channel}] ${message.userName}: ${message.content}`);
// Custom commands
if (message.content === '/ping') {
return 'Pong!';
}
// Let BoostGPT handle everything else
return null;
});
onError()
Set a custom error handler for all channels.
router.onError(async (error, message, context) => {
// Handle error
return errorMessage;
});
Parameters:
The message that caused the error
Context object with channel information
Returns:
string - Error message to send to user
Example:
router.onError(async (error, message, context) => {
console.error(`[${context.channel}] Error:`, error);
// Log to monitoring service
await logToSentry(error, { channel: context.channel, userId: message.userId });
return 'Sorry, something went wrong. Please try again!';
});
start()
Start all adapters and begin listening for messages.
Returns: Promise<void>
Example:
try {
await router.start();
console.log('✅ Router started successfully');
} catch (error) {
console.error('Failed to start router:', error);
process.exit(1);
}
stop()
Stop all adapters and disconnect from channels.
Returns: Promise<void>
Example:
process.on('SIGINT', async () => {
console.log('Shutting down...');
await router.stop();
process.exit(0);
});
getAdapter()
Get a specific adapter by channel name.
router.getAdapter(channelName)
Parameters:
Channel name (‘discord’, ‘telegram’, etc.)
Returns: BaseAdapter | null
Example:
const discordAdapter = router.getAdapter('discord');
if (discordAdapter) {
console.log('Discord adapter status:', discordAdapter.getStatus());
}
sendMessage()
Send a message to a specific user on a specific channel.
await router.sendMessage(channelName, recipient, message)
Parameters:
Channel name (‘discord’, ‘telegram’, etc.)
User/channel ID (format varies by channel)
Returns: Promise<any>
Example:
// Send to Discord user
await router.sendMessage('discord', 'user-id-123', 'Hello from bot!');
// Send to Telegram chat
await router.sendMessage('telegram', 'chat-id-456', 'Hi there!');
// Send to Slack channel
await router.sendMessage('slack', 'C1234567890', 'Team update!');
broadcast()
Broadcast a message to all or specific channels.
await router.broadcast(message, channels?)
Parameters:
Optional array of channel names. If omitted, broadcasts to all channels.
Returns: Promise<Array<Object>>
Returns an array of results indicating success/failure for each channel.
Example:
// Broadcast to all channels
await router.broadcast('Server maintenance in 5 minutes!');
// Broadcast to specific channels only
await router.broadcast('Discord and Telegram announcement', ['discord', 'telegram']);
// Handle results
const results = await router.broadcast('Test message');
results.forEach(result => {
if (result.success) {
console.log(`✅ ${result.channel}: Sent successfully`);
} else {
console.log(`❌ ${result.channel}: ${result.error}`);
}
});
getStatus()
Get the current status of the router and all adapters.
Returns:
{
isStarted: boolean,
adapters: Array<{
channel: string,
isStarted: boolean,
botId: string,
// ... adapter-specific fields
}>,
projectId: string,
defaultBotId: string
}
Example:
const status = router.getStatus();
console.log('Router started:', status.isStarted);
console.log('Active channels:', status.adapters.map(a => a.channel).join(', '));
addAdapter()
Add a new adapter at runtime.
await router.addAdapter(adapter)
Parameters:
Returns: Promise<void>
Example:
const newAdapter = new SlackAdapter({
slackToken: process.env.SLACK_TOKEN,
slackSigningSecret: process.env.SLACK_SIGNING_SECRET
});
await router.addAdapter(newAdapter);
console.log('✅ Slack adapter added');
removeAdapter()
Remove an adapter by channel name.
await router.removeAdapter(channelName)
Parameters:
Returns: Promise<void>
Example:
await router.removeAdapter('discord');
console.log('✅ Discord adapter removed');
BaseAdapter Class
All channel adapters extend BaseAdapter. Use this to create custom adapters.
Constructor
Channel identifier (e.g., ‘discord’, ‘custom’)
Override model for this channel
Limit knowledge to specific sources
Limit knowledge to specific tags
Override top setting for training data
Override max tokens for this channel
Use custom OpenAI/Anthropic key
Enable logging for this adapter
Methods
setMessageHandler()
adapter.setMessageHandler(handler)
Set a custom message handler for this adapter.
start()
Start the adapter (must be implemented by child class).
stop()
Stop the adapter.
sendMessage()
await adapter.sendMessage(recipient, message)
Send a message (must be implemented by child class).
getStatus()
Get adapter status.
Type Definitions
Message Object
interface Message {
content: string;
userId: string;
userName: string;
metadata: Record<string, any>;
}
Context Object
interface Context {
channel: string;
adapter: BaseAdapter;
router: Router;
boostgpt: BoostGPT;
}
Adapter Status
interface AdapterStatus {
channel: string;
isStarted: boolean;
botId: string;
model?: string;
}
Next Steps