Files
.gitignore
bot.py
config.json
README.md
requirements.txt
Code
5 398
bot.py
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
import json
import logging
from openai import OpenAI
load_dotenv()
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# Verifică dacă există tokenul Discord
if not os.getenv('DISCORD_TOKEN'):
logger.error('❌ DISCORD_TOKEN nu este setat în fișierul .env!')
logger.error('Creează un fișier .env (copiază .env.example) și adaugă tokenul Discord.')
exit(1)
# Verifică dacă există cheia OpenAI
if not os.getenv('OPENAI_API_KEY'):
logger.error('❌ OPENAI_API_KEY nu este setat în fișierul .env!')
logger.error('Adaugă cheia ta OpenAI în fișierul .env pentru a folosi AI.')
logger.error('Obține o cheie de la: https://platform.openai.com/api-keys')
exit(1)
with open('config.json', 'r', encoding='utf-8') as f:
config = json.load(f)
if config['ai_channel_id'] == 0:
logger.warning('⚠️ ai_channel_id este 0 în config.json!')
logger.warning(f'Folosește comanda !setchannel #nume-canal pentru a seta canalul AI.')
intents = discord.Intents.default()
intents.message_content = True
intents.messages = True
bot = commands.Bot(command_prefix=config['prefix'], intents=intents)
# Configurează OpenAI
client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
conversation_history = {}
@bot.event
async def on_ready():
logger.info(f'Bot-ul este activ! Conectat ca {bot.user}')
await bot.change_presence(activity=discord.Game(name=config['status']))
@bot.event
async def on_message(message):
if message.author.bot:
return
if message.channel.id != config['ai_channel_id']:
await bot.process_commands(message)
return
if message.content.startswith(config['prefix']):
await bot.process_commands(message)
return
async with message.channel.typing():
try:
user_id = message.author.id
if user_id not in conversation_history:
conversation_history[user_id] = [
{"role": "system", "content": config['system_prompt']}
]
conversation_history[user_id].append(
{"role": "user", "content": message.content}
)
response = client.chat.completions.create(
model=config['ai_model'],
messages=conversation_history[user_id],
max_tokens=config['max_tokens'],
temperature=config['temperature']
)
ai_response = response.choices[0].message.content
conversation_history[user_id].append(
{"role": "assistant", "content": ai_response}
)
# Limitează istoricul
if len(conversation_history[user_id]) > config['max_history'] * 2 + 1:
conversation_history[user_id] = [
conversation_history[user_id][0]
] + conversation_history[user_id][-(config['max_history'] * 2):]
if len(ai_response) > 2000:
chunks = [ai_response[i:i+2000] for i in range(0, len(ai_response), 2000)]
for chunk in chunks:
await message.reply(chunk)
else:
await message.reply(ai_response)
logger.info(f'Răspuns generat pentru {message.author.name}: {ai_response[:50]}...')
except Exception as e:
logger.error(f'Eroare la generarea răspunsului: {e}')
await message.reply(f'❌ Scuze, a apărut o eroare: {str(e)}')
await bot.process_commands(message)
@bot.command(name='clear')
async def clear_history(ctx):
"""Șterge istoricul conversației tale cu AI-ul"""
user_id = ctx.author.id
if user_id in conversation_history:
del conversation_history[user_id]
await ctx.send('✅ Istoricul conversației a fost șters!')
else:
await ctx.send('ℹ️ Nu ai niciun istoric de conversație.')
@bot.command(name='setprompt')
@commands.has_permissions(administrator=True)
async def set_prompt(ctx, *, new_prompt: str):
"""Schimbă promptul de sistem al AI-ului (doar admini)"""
config['system_prompt'] = new_prompt
with open('config.json', 'w', encoding='utf-8') as f:
json.dump(config, f, indent=4, ensure_ascii=False)
await ctx.send(f'✅ Promptul de sistem a fost actualizat!')
@bot.command(name='setchannel')
@commands.has_permissions(administrator=True)
async def set_channel(ctx, channel: discord.TextChannel):
"""Setează canalul pentru AI (doar admini)"""
config['ai_channel_id'] = channel.id
with open('config.json', 'w', encoding='utf-8') as f:
json.dump(config, f, indent=4, ensure_ascii=False)
await ctx.send(f'✅ Canalul AI a fost setat la {channel.mention}')
@bot.command(name='info')
async def info(ctx):
"""Informații despre bot"""
embed = discord.Embed(
title="🤖 Informații Bot AI Românesc",
description=config['bot_description'],
color=discord.Color.blue()
)
embed.add_field(name="Model AI", value=config['ai_model'], inline=True)
embed.add_field(name="Canal AI", value=f"<#{config['ai_channel_id']}>", inline=True)
embed.add_field(name="Prefix", value=config['prefix'], inline=True)
embed.add_field(name="Comenzi", value=f"`{config['prefix']}clear` - Șterge istoricul\n`{config['prefix']}info` - Informații bot", inline=False)
embed.set_footer(text=f"Solicitat de {ctx.author.name}")
await ctx.send(embed=embed)
@bot.command(name='ajutor')
async def help_command(ctx):
"""Afișează lista de comenzi"""
embed = discord.Embed(
title="📋 Comenzi Disponibile",
description="Lista comenzilor disponibile pentru bot:",
color=discord.Color.green()
)
embed.add_field(
name=f"{config['prefix']}ajutor",
value="Afișează acest mesaj de ajutor",
inline=False
)
embed.add_field(
name=f"{config['prefix']}info",
value="Informații despre bot și configurația AI",
inline=False
)
embed.add_field(
name=f"{config['prefix']}clear",
value="Șterge istoricul conversației tale cu AI-ul",
inline=False
)
embed.add_field(
name=f"{config['prefix']}setprompt <prompt>",
value="Schimbă promptul de sistem (doar admini)",
inline=False
)
embed.add_field(
name=f"{config['prefix']}setchannel <canal>",
value="Setează canalul pentru AI (doar admini)",
inline=False
)
embed.add_field(
name="💬 Conversație AI",
value=f"Scrie orice mesaj în <#{config['ai_channel_id']}> pentru a vorbi cu AI-ul!",
inline=False
)
embed.set_footer(text=f"Solicitat de {ctx.author.name}")
await ctx.send(embed=embed)
@set_prompt.error
@set_channel.error
async def admin_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send('❌ Nu ai permisiunea de administrator pentru această comandă!')
bot.run(os.getenv('DISCORD_TOKEN'))