help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
discord-ai-bot
/
cogs
RSK World
discord-ai-bot
Discord AI Bot - Python + discord.py + OpenAI API + AI Bot + Server Management + Moderation
cogs
  • __pycache__
  • __init__.py153 B
  • ai.py3.8 KB
  • automation.py2.2 KB
  • logging.py3.1 KB
  • management.py1.9 KB
  • moderation.py3.4 KB
ai.py
cogs/ai.py
Raw Download
Find: Go to:
"""
Discord AI Bot - AI Features (Enhanced with Memory)
Author: RSK World
Website: https://rskworld.in
Email: help@rskworld.in
Phone: +91 93305 39277
Year: 2026
"""

import discord
from discord.ext import commands
import openai
from collections import deque
from config import OPENAI_API_KEY, AI_MODEL

class AI(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.use_new_api = False
        if not OPENAI_API_KEY:
            print("Warning: OPENAI_API_KEY not set. AI features will not work.")
        else:
            # Support both old and new OpenAI API versions
            try:
                # Try new API (v1.0+)
                self.client = openai.OpenAI(api_key=OPENAI_API_KEY)
                self.use_new_api = True
            except (AttributeError, TypeError):
                # Fall back to old API
                openai.api_key = OPENAI_API_KEY
                self.use_new_api = False
        # Memory structure: {user_id: deque([{"role": "user", "content": "..."}, {"role": "assistant", "content": "..."}, ...], maxlen=10)}
        self.memory = {}

    def get_user_memory(self, user_id):
        if user_id not in self.memory:
            self.memory[user_id] = deque(maxlen=10)
        return self.memory[user_id]

    @commands.hybrid_command(name="ask", description="Ask the AI a question with memory")
    async def ask(self, ctx, *, question: str):
        """Interact with the AI using GPT-3.5 Turbo and conversation memory."""
        await ctx.defer()
        user_id = ctx.author.id
        user_memory = self.get_user_memory(user_id)
        
        # Build messages payload
        messages = [{"role": "system", "content": "You are a helpful Discord assistant powered by RSK World. You remember the last few exchanges with this user."}]
        messages.extend(list(user_memory))
        messages.append({"role": "user", "content": question})

        if not OPENAI_API_KEY:
            await ctx.send("❌ OpenAI API key is not configured. Please set OPENAI_API_KEY in your .env file.")
            return

        try:
            if hasattr(self, 'use_new_api') and self.use_new_api and hasattr(self, 'client'):
                # New API (v1.0+)
                response = self.client.chat.completions.create(
                    model=AI_MODEL,
                    messages=messages
                )
                answer = response.choices[0].message.content
            else:
                # Old API
                response = openai.ChatCompletion.create(
                    model=AI_MODEL,
                    messages=messages
                )
                answer = response.choices[0].message.content
            
            # Update memory
            user_memory.append({"role": "user", "content": question})
            user_memory.append({"role": "assistant", "content": answer})

            embed = discord.Embed(
                title="AI Response",
                description=answer,
                color=discord.Color.blue()
            )
            embed.set_footer(text=f"Memory Active | Requested by {ctx.author}", icon_url=ctx.author.display_avatar.url)
            await ctx.send(embed=embed)
        except Exception as e:
            await ctx.send(f"An error occurred: {e}")

    @commands.hybrid_command(name="clear_memory", description="Clear your conversation memory")
    async def clear_memory(self, ctx):
        """Wipe the user's AI conversation history."""
        if ctx.author.id in self.memory:
            self.memory[ctx.author.id].clear()
            await ctx.send("Your conversation memory has been cleared!", delete_after=5)
        else:
            await ctx.send("You have no active conversation memory.", delete_after=5)

async def setup(bot):
    await bot.add_cog(AI(bot))
97 lines•3.8 KB
python

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer