Skip to content

Commit

Permalink
new commands and updated help
Browse files Browse the repository at this point in the history
  • Loading branch information
Drago-03 committed Dec 2, 2024
1 parent 2d2db0d commit c37ee95
Show file tree
Hide file tree
Showing 19 changed files with 1,035 additions and 410 deletions.
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,7 @@ env/
docker-compose.override.yml

# website
website/
website/

Ignore the Google client secret JSON file
client_secret_387366114996-cs5icp92iprh9bbuim7kffhrnbd3fvah.apps.googleusercontent.com.json
171 changes: 53 additions & 118 deletions cogs/ai_assistant.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import discord
from discord.ext import commands
from discord import app_commands
import openai
import anthropic
import google.generativeai as genai
import os
Expand All @@ -15,143 +14,79 @@ class AIAssistant(commands.Cog):
def __init__(self, bot):
self.bot = bot
# Initialize API keys from environment variables
self.openai_api_key = os.getenv('OPENAI_API_KEY')
self.anthropic_api_key = os.getenv('ANTHROPIC_API_KEY')
self.google_api_key = os.getenv('GOOGLE_API_KEY')
self.gemini_api_key = os.getenv('GEMINI_API_KEY')

# Initialize API clients
if self.openai_api_key:
openai.api_key = self.openai_api_key
if self.anthropic_api_key:
self.claude = anthropic.Client(api_key=self.anthropic_api_key)
if self.google_api_key:
genai.configure(api_key=self.google_api_key)
if self.gemini_api_key:
genai.configure(api_key=self.gemini_api_key)

# Rate limiting
self.cooldowns = {}
self.COOLDOWN_MINUTES = 1

# Message history
self.conversation_history = {}
self.message_history = {}

async def get_ai_response(self, prompt: str, user_id: str, model: str = "gpt-3.5-turbo") -> str:
"""Generate AI response using available models"""
try:
# Check cooldown
if not await self.check_cooldown(user_id):
return "Please wait a moment before making another request."
async def fetch_claude_response(self, prompt):
async with aiohttp.ClientSession() as session:
headers = {
'Authorization': f'Bearer {self.anthropic_api_key}',
'Content-Type': 'application/json'
}
data = {
'prompt': prompt,
'max_tokens': 150
}
async with session.post('https://api.anthropic.com/v1/complete', headers=headers, json=data) as response:
result = await response.json()
return result['choices'][0]['text']

# Handle different AI services
if self.openai_api_key and model.startswith("gpt"):
response = await self.get_openai_response(prompt)
elif self.anthropic_api_key and model == "claude":
response = await self.get_claude_response(prompt)
elif self.google_api_key and model == "gemini":
response = await self.get_gemini_response(prompt)
else:
response = "No AI service is currently available."
async def fetch_gemini_response(self, prompt):
async with aiohttp.ClientSession() as session:
headers = {
'Authorization': f'Bearer {self.gemini_api_key}',
'Content-Type': 'application/json'
}
data = {
'prompt': prompt,
'max_tokens': 150
}
async with session.post('https://api.gemini.com/v1/complete', headers=headers, json=data) as response:
result = await response.json()
return result['choices'][0]['text']

return response
@commands.command(name="ask")
async def ask_command(self, ctx, *, question: str):
"""Ask a question to the AI assistant"""
if ctx.author.id in self.cooldowns and self.cooldowns[ctx.author.id] > datetime.now():
await ctx.send("You are on cooldown. Please wait before asking another question.")
return

except Exception as e:
return f"An error occurred: {str(e)}"
prompt = f"User: {question}\nBot:"
claude_response = await self.fetch_claude_response(prompt)
gemini_response = await self.fetch_gemini_response(prompt)
response = f"Claude: {claude_response}\nGemini: {gemini_response}"
await ctx.send(response)

async def get_openai_response(self, prompt: str) -> str:
"""Get response from OpenAI's GPT"""
try:
response = await asyncio.to_thread(
openai.ChatCompletion.create,
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content
except Exception as e:
return f"OpenAI Error: {str(e)}"

async def get_claude_response(self, prompt: str) -> str:
"""Get response from Anthropic's Claude"""
try:
response = await asyncio.to_thread(
self.claude.messages.create,
model="claude-3-sonnet-20240229",
max_tokens=1024,
messages=[{"role": "user", "content": prompt}]
)
return response.content[0].text
except Exception as e:
return f"Claude Error: {str(e)}"

async def get_gemini_response(self, prompt: str) -> str:
"""Get response from Google's Gemini"""
try:
model = genai.GenerativeModel('gemini-pro')
response = await asyncio.to_thread(
model.generate_content,
prompt
)
return response.text
except Exception as e:
return f"Gemini Error: {str(e)}"

async def check_cooldown(self, user_id: str) -> bool:
"""Check if user is on cooldown"""
if user_id in self.cooldowns:
if datetime.now() < self.cooldowns[user_id]:
return False
self.cooldowns[user_id] = datetime.now() + timedelta(minutes=self.COOLDOWN_MINUTES)
return True
self.cooldowns[ctx.author.id] = datetime.now() + timedelta(minutes=self.COOLDOWN_MINUTES)

@app_commands.command(name="ask", description="Ask a question to the AI assistant")
async def ask(self, interaction: discord.Interaction, question: str, model: Optional[str] = "gpt-3.5-turbo"):
"""Ask a general question to the AI assistant"""
await interaction.response.defer()
answer = await self.get_ai_response(question, str(interaction.user.id), model)

embed = discord.Embed(
title="AI Assistant Response",
description=answer,
color=discord.Color.blue(),
timestamp=datetime.now()
)
embed.set_footer(text=f"Requested by {interaction.user.name} | Model: {model}")

await interaction.followup.send(embed=embed)
async def ask_slash(self, interaction: discord.Interaction, question: str):
"""Ask a question to the AI assistant"""
if interaction.user.id in self.cooldowns and self.cooldowns[interaction.user.id] > datetime.now():
await interaction.response.send_message("You are on cooldown. Please wait before asking another question.", ephemeral=True)
return

@app_commands.command(name="codehelp", description="Get coding help")
async def codehelp(self, interaction: discord.Interaction, code: str, language: Optional[str] = None):
"""Get coding help from the AI assistant"""
await interaction.response.defer()

prompt = f"Please help with this code in {language if language else 'any language'}:\n```\n{code}\n```"
response = await self.get_ai_response(prompt, str(interaction.user.id))

embed = discord.Embed(
title="Code Help",
description=response,
color=discord.Color.green(),
timestamp=datetime.now()
)
embed.set_footer(text=f"Requested by {interaction.user.name}")

await interaction.followup.send(embed=embed)
prompt = f"User: {question}\nBot:"
claude_response = await self.fetch_claude_response(prompt)
gemini_response = await self.fetch_gemini_response(prompt)
response = f"Claude: {claude_response}\nGemini: {gemini_response}"
await interaction.response.send_message(response)

@app_commands.command(name="explain", description="Explain code in simple terms")
async def explain(self, interaction: discord.Interaction, code: str):
"""Explain code in simple terms"""
await interaction.response.defer()

prompt = f"Explain this code in simple terms:\n```\n{code}\n```"
explanation = await self.get_ai_response(prompt, str(interaction.user.id))

embed = discord.Embed(
title="Code Explanation",
description=explanation,
color=discord.Color.purple(),
timestamp=datetime.now()
)
embed.set_footer(text=f"Requested by {interaction.user.name}")

await interaction.followup.send(embed=embed)
self.cooldowns[interaction.user.id] = datetime.now() + timedelta(minutes=self.COOLDOWN_MINUTES)

async def setup(bot):
await bot.add_cog(AIAssistant(bot))
71 changes: 69 additions & 2 deletions cogs/automod.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,25 @@
import discord
from discord.ext import commands
from discord import app_commands
import re

class AutoMod(commands.Cog):
"""Cog for advanced AutoMod features"""

def __init__(self, bot):
self.bot = bot
self.bad_words = ["badword1", "badword2"] # Add more bad words here
self.bad_words = [
"badword1", "badword2", "badword3", "badword4", "badword5",
"badword6", "badword7", "badword8", "badword9", "badword10"
] # Add more bad words here
self.auto_mod_enabled = False

@commands.Cog.listener()
async def on_message(self, message):
if message.author.bot:
return

if any(re.search(rf"\b{word}\b", message.content, re.IGNORECASE) for word in self.bad_words):
if self.auto_mod_enabled and any(re.search(rf"\b{word}\b", message.content, re.IGNORECASE) for word in self.bad_words):
await message.delete()
await message.channel.send(f"{message.author.mention}, your message contained inappropriate content and was deleted.")
await self.log_action(message.guild, f"Deleted message from {message.author} for inappropriate content.")
Expand All @@ -31,5 +36,67 @@ async def warn_command(self, ctx, member: discord.Member, *, reason: str):
await ctx.send(f"{member.mention} has been warned. Reason: {reason}")
await self.log_action(ctx.guild, f"{ctx.author} warned {member}.\nReason: {reason}")

@app_commands.command(name="warn", description="Warn a member")
@app_commands.describe(member="The member to warn", reason="The reason for the warning")
async def warn_slash(self, interaction: discord.Interaction, member: discord.Member, reason: str):
"""Warn a member"""
await member.send(f"You have been warned by {interaction.user}.\nReason: {reason}")
await interaction.response.send_message(f"{member.mention} has been warned. Reason: {reason}")
await self.log_action(interaction.guild, f"{interaction.user} warned {member}.\nReason: {reason}")

@commands.command(name="automod_setup")
@commands.has_permissions(administrator=True)
async def automod_setup_command(self, ctx):
"""Set up AutoMod in the server"""
self.auto_mod_enabled = True
await ctx.send("AutoMod has been enabled and set up for this server.")
await self.log_action(ctx.guild, "AutoMod has been enabled and set up.")

@app_commands.command(name="automod_setup", description="Set up AutoMod in the server")
@commands.has_permissions(administrator=True)
async def automod_setup_slash(self, interaction: discord.Interaction):
"""Set up AutoMod in the server"""
self.auto_mod_enabled = True
await interaction.response.send_message("AutoMod has been enabled and set up for this server.")
await self.log_action(interaction.guild, "AutoMod has been enabled and set up.")

@commands.command(name="add_bad_word")
@commands.has_permissions(administrator=True)
async def add_bad_word_command(self, ctx, *, word: str):
"""Add a bad word to the AutoMod filter"""
self.bad_words.append(word)
await ctx.send(f"Added '{word}' to the list of bad words.")
await self.log_action(ctx.guild, f"Added '{word}' to the list of bad words.")

@app_commands.command(name="add_bad_word", description="Add a bad word to the AutoMod filter")
@commands.has_permissions(administrator=True)
async def add_bad_word_slash(self, interaction: discord.Interaction, word: str):
"""Add a bad word to the AutoMod filter"""
self.bad_words.append(word)
await interaction.response.send_message(f"Added '{word}' to the list of bad words.")
await self.log_action(interaction.guild, f"Added '{word}' to the list of bad words.")

@commands.command(name="remove_bad_word")
@commands.has_permissions(administrator=True)
async def remove_bad_word_command(self, ctx, *, word: str):
"""Remove a bad word from the AutoMod filter"""
if word in self.bad_words:
self.bad_words.remove(word)
await ctx.send(f"Removed '{word}' from the list of bad words.")
await self.log_action(ctx.guild, f"Removed '{word}' from the list of bad words.")
else:
await ctx.send(f"'{word}' is not in the list of bad words.")

@app_commands.command(name="remove_bad_word", description="Remove a bad word from the AutoMod filter")
@commands.has_permissions(administrator=True)
async def remove_bad_word_slash(self, interaction: discord.Interaction, word: str):
"""Remove a bad word from the AutoMod filter"""
if word in self.bad_words:
self.bad_words.remove(word)
await interaction.response.send_message(f"Removed '{word}' from the list of bad words.")
await self.log_action(interaction.guild, f"Removed '{word}' from the list of bad words.")
else:
await interaction.response.send_message(f"'{word}' is not in the list of bad words.")

async def setup(bot):
await bot.add_cog(AutoMod(bot))
26 changes: 26 additions & 0 deletions cogs/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,5 +53,31 @@ async def send_success(self, ctx, message: str):
embed = self.create_embed("✅ Success", message)
await ctx.send(embed=embed)

@commands.Cog.listener()
async def on_command_error(self, ctx, error):
"""Handle errors globally"""
if isinstance(error, commands.MissingPermissions):
await self.send_permission_error(ctx)
elif isinstance(error, commands.CommandOnCooldown):
await self.send_cooldown_error(ctx, error.retry_after)
elif isinstance(error, commands.MissingRequiredArgument):
await self.send_error(ctx, f"you're missing a required argument: {error.param.name}")
elif isinstance(error, commands.CommandNotFound):
await self.send_error(ctx, "the command you tried to use does not exist")
else:
await self.send_error(ctx, "an unexpected error occurred")

@commands.Cog.listener()
async def on_message(self, message):
"""Handle messages to check for unauthorized command usage"""
if message.author.bot:
return

if any(role.permissions.administrator for role in message.author.roles):
return

if any(command in message.content for command in ["!kick", "!ban", "!mute", "!warn"]):
await message.channel.send(f"{message.author.mention}, you don't have permission to use moderation commands.")

async def setup(bot):
await bot.add_cog(BaseCog(bot))
Loading

0 comments on commit c37ee95

Please sign in to comment.