klaus_k_1

Develop a chatbot named Klaus that incorporates natural language processing (NLP) capabilities to engage users in dynamic, sassy, and confident conversations. The bot should utilize sentiment analysis to tailor responses based on user emotions and implement machine learning algorithms to learn from interactions, improving its engagement style over time. Key features should include a customizable personality profile, context-aware responses, and integration with popular messaging platforms for seamless user interaction.

Kodari AI
KodariApr 24 at 2:51 am 17,876 (v2)

Iโ€™ll create an AI-powered Discord chatbot with NLP, sentiment analysis, and machine learning capabilities.

KlausBot
An intelligent Discord chatbot featuring natural language processing, sentiment analysis, and machine learning capabilities. Klaus has a sassy, confident personality that adapts responses based on user emotions and context. The bot learns from interactions to improve engagement over time, maintains conversation context, and includes customizable personality traits. Features include dynamic response generation, emotion detection, conversation memory, and persistent learning through an ML training pipeline.

Now Iโ€™ll create the complete bot structure with all necessary components:

Kodari can make mistakes. Review important code before using.
Files
.gitignore
bot.py
config.json
context_manager.py
database.py
ml_trainer.py
nlp_handler.py
personality.py
README.md
requirements.txt
Code
10 1,794
bot.py
import discord
from discord.ext import commands
import os
import logging
from dotenv import load_dotenv
import asyncio
from datetime import datetime

from nlp_handler import NLPHandler
from ml_trainer import MLTrainer
from context_manager import ContextManager
from personality import PersonalityEngine
from database import Database

load_dotenv()

# Setup logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger('KlausBot')

class KlausBot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.default()
        intents.message_content = True
        intents.members = True
        
        super().__init__(
            command_prefix='!klaus ',
            intents=intents,
            help_command=None
        )
        
        # Initialize components
        self.db = Database()
        self.nlp = NLPHandler()
        self.ml_trainer = MLTrainer(self.db)
        self.context_manager = ContextManager()
        self.personality = PersonalityEngine()
        
        logger.info("Klaus initialized with all components")
    
    async def setup_hook(self):
        """Called when the bot is starting up"""
        logger.info("Running setup hook...")
        # Train ML model on startup
        await self.ml_trainer.train_model()
        logger.info("Setup complete")
    
    async def on_ready(self):
        """Called when bot successfully connects to Discord"""
        logger.info(f'Klaus is ready! Logged in as {self.user}')
        logger.info(f'Connected to {len(self.guilds)} guilds')
        await self.change_presence(
            activity=discord.Activity(
                type=discord.ActivityType.watching,
                name="your emotions ๐Ÿ˜"
            )
        )
    
    async def on_message(self, message):
        """Handle incoming messages"""
        # Ignore messages from bots
        if message.author.bot:
            return
        
        # Process commands first
        await self.process_commands(message)
        
        # Check if Klaus is mentioned or DM
        is_dm = isinstance(message.channel, discord.DMChannel)
        is_mentioned = self.user in message.mentions
        
        if is_dm or is_mentioned:
            await self.handle_conversation(message)
    
    async def handle_conversation(self, message):
        """Handle natural conversation with Klaus"""
        try:
            # Show typing indicator
            async with message.channel.typing():
                user_id = str(message.author.id)
                user_message = message.content.replace(f'<@{self.user.id}>', '').strip()
                
                if not user_message:
                    return
                
                # Analyze sentiment
                sentiment = self.nlp.analyze_sentiment(user_message)
                intent = self.nlp.detect_intent(user_message)
                
                # Get conversation context
                context = self.context_manager.get_context(user_id)
                
                # Update context with current message
                self.context_manager.add_message(
                    user_id,
                    user_message,
                    sentiment,
                    intent
                )
                
                # Generate response based on personality and context
                response = self.personality.generate_response(
                    user_message=user_message,
                    sentiment=sentiment,
                    intent=intent,
                    context=context,
                    user_name=message.author.display_name
                )
                
                # Get ML-enhanced response
                enhanced_response = await self.ml_trainer.enhance_response(
                    response,
                    sentiment,
                    context
                )
                
                # Send response
                await message.reply(enhanced_response)
                
                # Store interaction in database for learning
                self.db.store_interaction(
                    user_id=user_id,
                    user_message=user_message,
                    bot_response=enhanced_response,
                    sentiment=sentiment['compound'],
                    intent=intent
                )
                
                logger.info(
                    f"Responded to {message.author.name} | "
                    f"Sentiment: {sentiment['label']} ({sentiment['compound']:.2f}) | "
                    f"Intent: {intent}"
                )
        
        except Exception as e:
            logger.error(f"Error handling conversation: {e}", exc_info=True)
            await message.reply("Ugh, something went wrong in my circuits. Try again? ๐Ÿ™„")
    
    async def on_command_error(self, ctx, error):
        """Handle command errors"""
        if isinstance(error, commands.CommandNotFound):
            await ctx.send("That's not a command I recognize, darling. Try `!klaus help` ๐Ÿ’…")
        elif isinstance(error, commands.MissingRequiredArgument):
            await ctx.send("You're missing something there. Need more details, sweetie.")
        else:
            logger.error(f"Command error: {error}", exc_info=True)
            await ctx.send("Well, that didn't work. Try again? ๐Ÿ˜")

# Create bot instance
bot = KlausBot()

@bot.command(name='help')
async def help_command(ctx):
    """Display help information"""
    embed = discord.Embed(
        title="Klaus - Your Sassy AI Companion ๐Ÿ’…",
        description="I'm Klaus, an AI chatbot with personality. Here's what I can do:",
        color=discord.Color.purple()
    )
    
    embed.add_field(
        name="๐Ÿ’ฌ Natural Conversation",
        value="Just mention me or DM me to chat! I understand emotions and context.",
        inline=False
    )
    
    embed.add_field(
        name="๐ŸŽญ Commands",
        value=(
            "`!klaus help` - Show this message\n"
            "`!klaus stats` - See your conversation stats\n"
            "`!klaus mood` - Check my current mood\n"
            "`!klaus personality` - View my personality traits\n"
            "`!klaus reset` - Reset our conversation context"
        ),
        inline=False
    )
    
    embed.add_field(
        name="๐Ÿง  Features",
        value="โ€ข Sentiment analysis\nโ€ข Context-aware responses\nโ€ข Machine learning\nโ€ข Sassy personality",
        inline=False
    )
    
    embed.set_footer(text="I learn from our conversations to serve better sass โœจ")
    
    await ctx.send(embed=embed)

@bot.command(name='stats')
async def stats_command(ctx):
    """Show user conversation statistics"""
    user_id = str(ctx.author.id)
    stats = bot.db.get_user_stats(user_id)
    
    if stats['total_interactions'] == 0:
        await ctx.send("We haven't talked much yet, stranger. Let's change that! ๐Ÿ˜")