Skip to main content

Router Class

Constructor

new Router(options)
apiKey
string
required
BoostGPT API key
projectId
string
required
BoostGPT project ID
adapters
Array<BaseAdapter>
default:"[]"
Array of channel adapter instances
defaultBotId
string
Default bot ID for all adapters (can be overridden per adapter)
onError
Function
Global error handler function
enableLogging
boolean
default:"true"
Enable console logging
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:
message
Object
Normalized message object:
{
  content: string,      // Message text
  userId: string,       // User identifier
  userName: string,     // User display name
  metadata: Object      // Channel-specific data
}
context
Object
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:
error
Error
The error that occurred
message
Object
The message that caused the error
context
Object
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.
await router.start();
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.
await router.stop();
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:
channelName
string
required
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:
channelName
string
required
Channel name (‘discord’, ‘telegram’, etc.)
recipient
string
required
User/channel ID (format varies by channel)
message
string
required
Message content to send
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:
message
string
required
Message to broadcast
channels
Array<string>
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.
router.getStatus()
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:
adapter
BaseAdapter
required
Adapter instance to add
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:
channelName
string
required
Channel name to remove
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

new BaseAdapter(options)
boostgpt
BoostGPT
required
BoostGPT client instance
botId
string
required
Bot ID for this adapter
channelName
string
required
Channel identifier (e.g., ‘discord’, ‘custom’)
model
string
Override model for this channel
sourceIds
Array<string>
Limit knowledge to specific sources
tags
Array<string>
Limit knowledge to specific tags
top
number
Override top setting for training data
maxReplyTokens
number
Override max tokens for this channel
providerKey
string
Use custom OpenAI/Anthropic key
errorMessage
string
Default error message
enableLogging
boolean
default:"true"
Enable logging for this adapter

Methods

setMessageHandler()

adapter.setMessageHandler(handler)
Set a custom message handler for this adapter.

start()

await adapter.start()
Start the adapter (must be implemented by child class).

stop()

await adapter.stop()
Stop the adapter.

sendMessage()

await adapter.sendMessage(recipient, message)
Send a message (must be implemented by child class).

getStatus()

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