SkillfulAI
  • Skillful AI
    • Welcome
    • About us
    • Ecosystem
  • Web SDK
    • Overview
    • Getting Started
      • Installation
      • Quick Start
      • Authentication
    • SDK Reference
    • Templates
      • Telegram Bot Template
      • Express Server Template
        • API Reference
      • Discord Bot Template
        • ProActive Mode
      • Kick Stream Bot
        • Getting Started
          • Installation
          • Quick Start
        • Create Commands
        • Advanced Configurations
  • Unity Gaming SDK
    • Overview
    • Getting Started
      • Installation
      • Authentication
    • Services
      • Skillful Agents
        • Overview
        • Quick Start
        • Service Reference
      • Smart NPCs
        • Overview
        • Quick Start
        • Service Reference
      • Skillful Inference
        • Overview
        • Quick Start
        • Service Reference
          • Question Answering
          • Sentence Similarity
          • Speech Recognition
          • Text Classification
          • Text Generation
          • Text Summary
          • Text-To-Image
          • Zero Shot Classification
          • Translation (Localization)
    • Audio Recorder
    • Additional Utilities
Powered by GitBook

Registering Custom Commands

Kick Bot provides a flexible system to create and register your own custom commands. This guide will show you how to create, test, and register custom commands to extend Kick Bot's functionality.

Command Module Structure

A command module is a JavaScript object with the following structure:

const MyCustomCommand = {
  // Command name (without the ! prefix)
  name: 'commandname',
  
  // Command description (shown in !help)
  description: 'Description of what the command does',
  
  // Command usage example
  usage: '!commandname [arguments]',
  
  // Command handler function
  handler: async ({ username, args, bot, commandManager }) => {
    // Command logic goes here
    return `Response message to send to chat`;
  }
};

Creating Your First Custom Command

Let's create a simple command that returns the current time:

// timeCommand.js
const TimeCommand = {
  name: 'time',
  description: 'Shows the current time',
  usage: '!time',
  handler: async ({ username }) => {
    const now = new Date();
    const timeString = now.toLocaleTimeString();
    return `The current time is: ${timeString}`;
  }
};

module.exports = TimeCommand;

Integrating Custom Commands into Your Project

There are two ways to register your custom commands:

Method 1: Using the enabledCommands Option

  1. Create a directory for your custom commands, e.g., ./commands/

  2. Place your command modules in this directory

  3. Import and register them when creating the bot:

const { createBot } = require('kickbot');
const TimeCommand = require('./commands/timeCommand');

// First, create the bot
const bot = createBot({
  // Required configuration
  clientId: 'your-kick-client-id',
  clientSecret: 'your-kick-client-secret',
  skillfulApiKey: 'your-skillful-api-key',
  chatroomId: 'your-chatroom-id',
  
  // Include your custom command
  enabledCommands: ['8ball', 'imagine']
});

// Then, manually register your custom command
bot.messageHandler.commandManager.register(TimeCommand, true);

// Start the bot
bot.start()
  .then(() => console.log('Bot started!'))
  .catch(error => console.error('Failed to start bot:', error));

Method 2: Using the Command Manager After Bot Creation

const { createBot } = require('kickbot');
const TimeCommand = require('./commands/timeCommand');

// Create the bot
const bot = createBot({
  // Basic configuration
  clientId: 'your-kick-client-id',
  clientSecret: 'your-kick-client-secret',
  skillfulApiKey: 'your-skillful-api-key',
  chatroomId: 'your-chatroom-id'
});

// Register your custom command after creating the bot
bot.messageHandler.commandManager.register(TimeCommand, true);

// Start the bot
bot.start()
  .then(() => console.log('Bot started!'))
  .catch(error => console.error('Failed to start bot:', error));

Advanced Command Features

Accessing Bot Services

The command handler receives several useful objects:

handler: async ({ username, args, bot, commandManager, getState, setState }) => {
  // 'username' - The username of the user who sent the command
  // 'args' - Array of command arguments (words after the command name)
  // 'bot' - Reference to the KickBot instance
  // 'commandManager' - Reference to the CommandManager
  // 'getState' - Function to get command state
  // 'setState' - Function to set command state
}

Using the Skillful AI Client

You can use the Skillful AI client in your custom commands:

const WeatherCommand = {
  name: 'weather',
  description: 'Get the weather for a location',
  usage: '!weather [location]',
  handler: async ({ username, args, bot }) => {
    if (!args.length) {
      return `Please provide a location. Example: !weather New York`;
    }
    
    const location = args.join(' ');
    
    try {
      // Use the AI to generate a weather response
      const prompt = `Generate a brief, fun weather report for ${location}. Keep it to 1-2 sentences maximum.`;
      const response = await bot.skillfulClient.sendMessage(prompt);
      
      return response.text || `Sorry, I couldn't get the weather for ${location}.`;
    } catch (error) {
      return `Sorry, I couldn't process that request. Error: ${error.message}`;
    }
  }
};

Maintaining Command State

Commands can maintain state between invocations using the setState and getState functions:

const CounterCommand = {
  name: 'counter',
  description: 'Counts how many times the command has been used',
  usage: '!counter',
  handler: async ({ username, getState, setState }) => {
    // Get current count
    let count = getState('count') || 0;
    
    // Increment count
    count++;
    
    // Save updated count (with TTL of 1 hour)
    setState('count', count, 3600000);
    
    return `This command has been used ${count} times!`;
  }
};

Command with Initialization Logic

Some commands need to perform initialization when they're first enabled. Use the init method for this:

const StreamUptimeCommand = {
  name: 'uptime',
  description: 'Shows how long the stream has been live',
  usage: '!uptime',
  
  // Stream start time
  streamStartTime: null,
  
  // Initialization function
  init: function(commandManager) {
    // Record the time when the command is initialized
    this.streamStartTime = new Date();
    console.log('Uptime command initialized');
  },
  
  handler: async ({ username }) => {
    if (!this.streamStartTime) {
      return 'Stream start time not available.';
    }
    
    const now = new Date();
    const uptimeMs = now - this.streamStartTime;
    const hours = Math.floor(uptimeMs / (1000 * 60 * 60));
    const minutes = Math.floor((uptimeMs % (1000 * 60 * 60)) / (1000 * 60));
    
    return `Stream has been live for ${hours}h ${minutes}m.`;
  },
  
  // Cleanup function (called when command is disabled)
  cleanup: function() {
    this.streamStartTime = null;
    console.log('Uptime command cleaned up');
  }
};

Best Practices for Custom Commands

  1. Keep responses concise: Chat messages should be brief and to the point

  2. Add error handling: Always handle potential errors in your commands

  3. Respect rate limits: Avoid making too many external API calls

  4. Include help text: Make the command's usage clear in the description

  5. Clean up resources: If your command uses external resources, clean them up in the cleanup method

Testing Your Custom Commands

Before integrating into your bot, you can test your command handler function independently:

// test-command.js
const MyCommand = require('./commands/myCommand');

// Mock the handler parameters
const mockParams = {
  username: 'test_user',
  args: ['test', 'arguments'],
  bot: {
    // Mock bot services as needed
    skillfulClient: { /* ... */ }
  },
  commandManager: {
    // Mock command manager as needed
  },
  getState: (key) => null,
  setState: (key, value) => {}
};

// Test the command
async function testCommand() {
  try {
    const response = await MyCommand.handler(mockParams);
    console.log('Command response:', response);
  } catch (error) {
    console.error('Command error:', error);
  }
}

testCommand();

Run the test with node test-command.js.

Next Steps

PreviousQuick StartNextAdvanced Configurations

Last updated 1 month ago

Now that you know how to create custom commands, explore the to fine-tune your KickBot instance.

Advanced Configuration Options