> For the complete documentation index, see [llms.txt](https://docs.gaming.skillfulai.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.gaming.skillfulai.io/web-sdk/templates/kick-stream-bot/advanced-configurations.md).

# Advanced Configurations

## `Advanced Configuration Options`

This guide covers advanced configuration options and usage patterns for Kick Bot, helping you fine-tune your bot's behavior and create more sophisticated integrations.

### `Complete Configuration Reference`

Kick Bot supports numerous configuration options. Here's the complete reference:

```javascript
const bot = createBot({
  // Required Configuration
  clientId: 'your-kick-client-id',           // Kick.com OAuth client ID
  clientSecret: 'your-kick-client-secret',   // Kick.com OAuth client secret
  skillfulApiKey: 'your-skillful-api-key',   // Skillful AI API key
  chatroomId: 'your-chatroom-id',            // Kick.com chatroom ID
  
  // Authentication & Server Options
  redirectUri: 'http://localhost:3000/callback',  // OAuth redirect URI
  serverPort: 3000,                              // Port for the server
  
  // AI Options
  defaultAgent: 'General Assistant',             // Default Skillful agent
  allowAgentChanges: true,                       // Allow viewers to change agents
  
  // Message Options
  maxResponseLength: 500,                        // Maximum message length
  
  // Logging Options
  logLevel: 'info',                              // Log level (error/warn/info/debug/trace)
  debug: false,                                  // Enable debug mode
  
  // Command Options
  enabledCommands: ['8ball', 'imagine']          // Additional commands to enable

  // Enabled / Disable the dashboard
  enableDashboard: true,                         // Enable the web dashboard
  dashboardPassword: 'your-strong-password'      // The password used for access
});
```

### `Advanced AI Configuration`

#### `Working with Different AI Agents`

Kick Bot integrates with Skillful AI, which allows you to create different AI agents with distinct personalities and capabilities.

```javascript
// Using a specific default agent
const bot = createBot({
  // Basic configuration...
  defaultAgent: 'Customer Support Agent',  // Use a specific agent by name
  
  // Control whether viewers can change agents
  allowAgentChanges: true  // Set to false to lock to the default agent
});

// Programmatically change the agent
bot.start().then(async () => {
  // Get available agents
  const agents = await bot.skillfulClient.getAgents();
  console.log('Available agents:', agents.map(a => a.name));
  
  // Find a specific agent
  const customAgent = await bot.skillfulClient.findAgentByName('Custom Agent');
  if (customAgent) {
    // Change to this agent
    await bot.skillfulClient.setAgent(customAgent);
    bot.activeAgent = customAgent;
    console.log('Changed to agent:', customAgent.name);
  }
});
```

#### `Advanced Agent Change Control`

You can provide fine-grained control over agent changes:

```javascript
// Allow agent changes but disable specific core commands
const bot = createBot({
  // Basic configuration...
  allowAgentChanges: true
});

// Disable specific commands programmatically
bot.start().then(() => {
  // Disable voting commands but keep agents list available
  bot.disableCommand('changeagent');
  bot.disableCommand('yes');
  bot.disableCommand('no');
  
  // Later, you can re-enable them
  setTimeout(() => {
    bot.enableCommand('changeagent');
    bot.enableCommand('yes');
    bot.enableCommand('no');
    console.log('Agent voting is now enabled');
  }, 30 * 60 * 1000); // Enable after 30 minutes
});
```

### `Advanced Logging`

KickBot uses a customizable logging system that allows different levels of verbosity for different components.

```javascript
// Configure logging during bot creation
const bot = createBot({
  // Basic configuration...
  logLevel: 'debug',  // Set the global log level
  debug: true         // Shorthand for enabling debug mode
});

// Access component loggers
bot.start().then(() => {
  // Log a message using the main logger
  bot.logger.info('Bot started successfully');
  
  // Use component-specific loggers
  bot.wsLogger.debug('WebSocket connection details...');
  bot.authLogger.info('Authentication status...');
  
  // Create a custom component logger
  const myLogger = bot.logger.createComponentLogger('MyModule');
  myLogger.info('Custom component initialized');
});
```

#### `Available Log Levels`

* `error`: Only critical errors
* `warn`: Errors and warnings
* `info`: General information (default)
* `debug`: Detailed information for debugging
* `trace`: Very verbose, includes all details

### `Event System`

Kick Bot provides an event system that lets you respond to various occurrences:

```javascript
// Register event handlers
bot.on('message', (messageData) => {
  console.log(`Chat message from ${messageData.username}: ${messageData.content}`);
});

bot.on('command', (commandData) => {
  console.log(`Command executed: !${commandData.command} by ${commandData.username}`);
});

bot.on('connected', (connectionData) => {
  console.log(`Connected to channel: ${connectionData.channel}`);
});

bot.on('error', (errorData) => {
  console.error(`Error (${errorData.type}): ${errorData.message}`);
});

// Start the bot after registering handlers
bot.start();
```

### `Command Manager Advanced Usage`

The Command Manager provides powerful tools for managing commands:

```javascript
// Access the Command Manager after bot creation
const { commandManager } = bot.messageHandler;

// Get all registered commands
const allCommands = commandManager.getAllCommands();
console.log('Registered commands:', Array.from(allCommands.keys()));

// Get all enabled commands
const enabledCommands = commandManager.getEnabledCommands();
console.log('Enabled commands:', Array.from(enabledCommands.keys()));

// Check if a specific command is enabled
const isHelpEnabled = commandManager.isEnabled('help');
console.log('Help command enabled:', isHelpEnabled);

// Enable/disable commands programmatically
commandManager.enable('8ball');
commandManager.disable('8ball');

// Work with command state
commandManager.setCommandState('mycommand', 'mykey', 'myvalue', 3600000); // TTL: 1 hour
const value = commandManager.getCommandState('mycommand', 'mykey');
```

### `Dynamic Command Registration`

You can dynamically register and manage commands at runtime:

```javascript
// Load commands from a directory
const fs = require('fs');
const path = require('path');

// Start the bot
bot.start().then(() => {
  // Command directory
  const commandDir = path.join(__dirname, 'commands');
  
  // Read command files
  fs.readdir(commandDir, (err, files) => {
    if (err) {
      console.error('Error reading command directory:', err);
      return;
    }
    
    // Load each command file
    files.forEach(file => {
      if (file.endsWith('.js')) {
        try {
          const commandPath = path.join(commandDir, file);
          const command = require(commandPath);
          
          // Register the command
          bot.messageHandler.commandManager.register(command, true);
          console.log(`Loaded command: ${command.name}`);
        } catch (error) {
          console.error(`Error loading command file ${file}:`, error);
        }
      }
    });
  });
});
```

### `Custom Authentication Flow`

For special cases, you can implement a custom authentication flow:

```javascript
const { KickBot } = require('kickbot');

// Create a bot instance directly without using createBot
const bot = new KickBot({
  // Configuration...
});

// Custom authentication logic
async function customAuth() {
  // Check if a valid token exists
  const hasToken = await bot.auth.hasValidTokenFile();
  
  if (hasToken) {
    console.log('Valid token found, using existing authentication');
    await bot.startBot();
  } else {
    console.log('No valid token, starting custom auth flow...');
    
    // Implement custom auth flow
    // ...
    
    // After obtaining a token:
    await bot.startBot();
  }
}

// Start with custom auth
customAuth().catch(console.error);
```

### `WebSocket Connection Management`

For advanced scenarios, you might need more control over the WebSocket connection:

```javascript
// Start the bot with event monitoring
bot.start().then(() => {
  // Monitor connection status
  setInterval(() => {
    console.log('Connection status:', bot.isConnected ? 'Connected' : 'Disconnected');
    
    // Force reconnect if needed
    if (!bot.isConnected) {
      console.log('Attempting to reconnect...');
      bot.connectToWebSocket().catch(console.error);
    }
  }, 60000); // Check every minute
});

// Handle graceful shutdown
process.on('SIGINT', () => {
  console.log('Shutting down bot...');
  bot.stop();
  process.exit(0);
});
```

### `Custom Status Endpoints`

Extend the built-in status server with custom endpoints:

```javascript
// Start the bot
bot.start().then(() => {
  // Get access to the Express app
  const { app } = bot;
  
  // Add custom endpoints
  app.get('/stats', (req, res) => {
    // Collect some stats
    const stats = {
      uptime: process.uptime(),
      memory: process.memoryUsage(),
      commandCount: bot.messageHandler.commandManager.getEnabledCommands().size,
      isConnected: bot.isConnected,
      activeAgent: bot.activeAgent ? bot.activeAgent.
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.gaming.skillfulai.io/web-sdk/templates/kick-stream-bot/advanced-configurations.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
