CodeForge Logo

CodeForge Documentation

Find guides on how to use CodeForge, customize your rank card, set up custom commands, and use the ByteKnight features.

Getting Started with ByteKnight

ByteKnight is a customizable C# Discord bot framework. Follow these steps to set it up:

  • Clone the Repository: Visit the ByteKnight GitHub Repository and clone the project.
  • Open in IDE: Use Visual Studio Code (Free) or a similar C# IDE to open the solution file.
  • Configure Settings: Update the UserCFG.ini file with:
    • Bot token (required for Discord API authentication).
    • MongoDB connection string for database integration.
    • Additional server-specific settings in ServerSettings.cs (e.g., XP multipliers, role IDs).
  • Create a Discord Bot: Visit the Discord Developer Portal to create an application and copy the bot token.
  • Run the Bot: Build and run the solution. The bot will connect to Discord and MongoDB.

MongoDB Integration

Use MongoDB for persistent data storage. Examples:

  • Initialization: MongoDB is initialized in Init.cs. Here's a sample:
    
    if (string.IsNullOrWhiteSpace(_connectionString) || string.IsNullOrWhiteSpace(_databaseName))
    {
        Console.WriteLine("MongoDB connection string or database name is missing.");
        return false;
    }
    
    try
    {
        MongoClient client = new MongoClient(_connectionString);
        _database = client.GetDatabase(_databaseName);
        Console.WriteLine("MongoDB initialized successfully.");
    }
                    
  • Collections: These collections and others are defined in Init.cs and used throughout ByteKnight:
    • _serverSettingsCollection: Stores Server Settings.
    • _userLevelsCollection: Stores user XP and level data.
    • _warningsCollection: Tracks user warnings.

User Levels

The UserLevelData class defines the schema for user data in MongoDB. Key fields include:

  • XP: User experience points.
  • MessageCount: Tracks the number of messages sent.
  • BackgroundImageUrl: URL for the user's rank card background. (If using the Paid Tier ByteKnight GUI Framework)
  • Level: Calculated dynamically using CalculateLevel.

To update a user's XP:


var filter = Builders.UserLevelData.Filter.Eq(u => u.ID, userId);
var update = Builders.UserLevelData.Update.Inc(u => u.XP, xpToAdd);
await _userLevelsCollection.UpdateOneAsync(filter, update);
        

Adding Slash Commands

Here's how you can add new slash commands to ByteKnight:

Step 1: Register your command in CommandRegistration.cs. Example:


var greetCommand = new SlashCommandBuilder()
    .WithName("greet")
    .WithDescription("Sends a greeting message")
    .AddOption("name", ApplicationCommandOptionType.String, "Your name", true);
await _client.CreateGlobalApplicationCommandAsync(greetCommand.Build());
        

Step 2: Create a new class file (e.g., Greet.cs) in your CommandModules directory for the command logic. Example:


using Discord.WebSocket;
namespace ByteKnight_GUI.ByteKnightCore.CommandModules
{
    public class Greet
    {
        private readonly ByteKnightEngine _botInstance;

        public Greet(ByteKnightEngine botInstance)
        {
            _botInstance = botInstance;
        }

        public async Task CommandHandler(SocketSlashCommand slashCommand)
        {
            var name = slashCommand.Data.Options
                .FirstOrDefault(o => o.Name == "name")?.Value?.ToString();
            await slashCommand.RespondAsync($"Hello, {name}!");
        }
    }
}
    

Step 3: Add the new command to CommandsCore.cs:

Add the command handler to the constructor:


// Declare at the top with other handlers
private readonly Greet _greetHandler;

// Initialize in the constructor
_greetHandler = new Greet(botInstance);
            

Register the command in the switch statement:


case "greet":
    await _greetHandler.CommandHandler(slashCommand);
    break;
            

Once these steps are complete, rebuild and run your bot. The new /greet command will now be available globally!

If you'd like to scope the command to specific guilds instead of global registration, use CreateGuildApplicationCommandAsync instead of CreateGlobalApplicationCommandAsync and specify the guild ID.

Helpers and Utilities

Key utility classes in ByteKnight:

  • Helpers.cs: Includes utility methods like safe casting and object management.
  • RateLimits.cs: Manages Discord API rate limits.

Example of rate limit handling:


if (_rateLimiter.IsRateLimited(endpoint))
{
    Console.WriteLine("Rate limit active. Retrying...");
    await Task.Delay(_rateLimiter.GetRetryAfter(endpoint));
}
        

Troubleshooting

  • MongoDB Initialization Issues: Ensure the _connectionString and _databaseName in Init.cs are correct.
  • Slash Command Errors: Verify that the commands class file is registered in CommandRegistration.cs and handled in CommandsCore.cs.
  • Rate Limit Issues: Review the logic in RateLimits.cs.