Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
|
|
| 1 |
import discord
|
| 2 |
from discord.ext import commands
|
| 3 |
import json
|
|
@@ -11,6 +12,7 @@ from gradio_client import Client
|
|
| 11 |
from concurrent.futures import ThreadPoolExecutor
|
| 12 |
from gtts import gTTS
|
| 13 |
import io
|
|
|
|
| 14 |
|
| 15 |
# Set up logging
|
| 16 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
|
@@ -56,13 +58,20 @@ You are GaurdineX, a futuristic next-generation AI guardian model built to act a
|
|
| 56 |
# Helper functions
|
| 57 |
def load_data(filename, default_data):
|
| 58 |
if os.path.exists(filename):
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
return default_data
|
| 62 |
|
| 63 |
def save_data(data, filename):
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
def log_action(guild_id, action, user_id, moderator_id, reason):
|
| 68 |
log_entry = {
|
|
@@ -121,7 +130,12 @@ async def timeout_check():
|
|
| 121 |
@bot.event
|
| 122 |
async def on_guild_join(guild):
|
| 123 |
try:
|
| 124 |
-
role = await guild.create_role(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
guild_id = str(guild.id)
|
| 126 |
config_data[guild_id] = {
|
| 127 |
'admin_role_id': role.id,
|
|
@@ -130,7 +144,7 @@ async def on_guild_join(guild):
|
|
| 130 |
'bad_words': ['fuck', 'shit', 'asshole'] # Add more bad words as needed
|
| 131 |
}
|
| 132 |
save_data(config_data, CONFIG_FILE)
|
| 133 |
-
logger.info(f"Created
|
| 134 |
except discord.Forbidden:
|
| 135 |
logger.error(f"Failed to create role in guild {guild.id}: Missing permissions")
|
| 136 |
except Exception as e:
|
|
@@ -195,27 +209,32 @@ async def process_ai_command(ctx, prompt: str):
|
|
| 195 |
return
|
| 196 |
|
| 197 |
# Default AI response
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
|
|
|
|
|
|
| 210 |
)
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
|
|
|
|
|
|
|
|
|
| 219 |
|
| 220 |
async def chat_with_ai(message: discord.Message):
|
| 221 |
guild_id = str(message.guild.id)
|
|
@@ -299,6 +318,8 @@ async def on_message(message):
|
|
| 299 |
admin_role = discord.utils.get(message.guild.roles, id=admin_role_id)
|
| 300 |
if admin_role and admin_role in message.author.roles:
|
| 301 |
is_admin = True
|
|
|
|
|
|
|
| 302 |
if is_admin and bot.user.mentioned_in(message):
|
| 303 |
clean_content = message.content.replace(f'<@!{bot.user.id}>', '').strip()
|
| 304 |
await process_ai_command(message.channel, clean_content)
|
|
@@ -352,7 +373,7 @@ async def addaccess(ctx, member: discord.Member):
|
|
| 352 |
if user_id not in config_data[guild_id]['allowed_users']:
|
| 353 |
config_data[guild_id]['allowed_users'].append(user_id)
|
| 354 |
save_data(config_data, CONFIG_FILE)
|
| 355 |
-
lang = config_data
|
| 356 |
msg = f"✅ Added moderation access to {member.mention}." if lang == 'en' else f"✅ تم إضافة صلاحية الإدارة لـ {member.mention}."
|
| 357 |
await ctx.send(msg)
|
| 358 |
log_action(guild_id, "add_access", member.id, ctx.author.id, "Added individual mod access")
|
|
@@ -366,7 +387,7 @@ async def removeaccess(ctx, member: discord.Member):
|
|
| 366 |
if user_id in config_data[guild_id]['allowed_users']:
|
| 367 |
config_data[guild_id]['allowed_users'].remove(user_id)
|
| 368 |
save_data(config_data, CONFIG_FILE)
|
| 369 |
-
lang = config_data
|
| 370 |
msg = f"✅ Removed moderation access from {member.mention}." if lang == 'en' else f"✅ تم إزالة صلاحية الإدارة من {member.mention}."
|
| 371 |
await ctx.send(msg)
|
| 372 |
log_action(guild_id, "remove_access", member.id, ctx.author.id, "Removed individual mod access")
|
|
@@ -578,30 +599,35 @@ async def chat(ctx, *, user_message: str):
|
|
| 578 |
memory.pop(0)
|
| 579 |
thinking_msg = await ctx.send("💭 Thinking..." if lang == 'en' else "💭 OS Bot is thinking...")
|
| 580 |
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
|
|
|
|
|
|
|
| 593 |
)
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
|
|
|
|
|
|
|
|
|
| 605 |
|
| 606 |
@bot.command(name='join')
|
| 607 |
async def join(ctx):
|
|
@@ -646,72 +672,97 @@ async def ask(ctx, *, text_query: str):
|
|
| 646 |
|
| 647 |
thinking_msg = await ctx.send("💭 Thinking..." if lang == 'en' else "💭 OS Bot is thinking...")
|
| 648 |
|
| 649 |
-
|
| 650 |
-
client = Client("amd/gpt-oss-120b-chatbot")
|
| 651 |
-
loop = asyncio.get_running_loop()
|
| 652 |
-
ai_output = await loop.run_in_executor(
|
| 653 |
-
executor,
|
| 654 |
-
lambda: client.predict(
|
| 655 |
-
message=text_query,
|
| 656 |
-
system_prompt=SYSTEM_PROMPT,
|
| 657 |
-
temperature=0.7,
|
| 658 |
-
reasoning_effort="medium",
|
| 659 |
-
enable_browsing=False,
|
| 660 |
-
api_name="/chat"
|
| 661 |
-
)
|
| 662 |
-
)
|
| 663 |
-
match = re.search(r'💬 Response:\s*(.+)', ai_output, re.DOTALL)
|
| 664 |
-
final_response = match.group(1).strip() if match else ai_output.strip()
|
| 665 |
-
|
| 666 |
-
# Save to chat history
|
| 667 |
-
user_id = str(ctx.author.id)
|
| 668 |
-
if user_id not in chat_history:
|
| 669 |
-
chat_history[user_id] = []
|
| 670 |
-
chat_history[user_id].append({"role": "user", "content": text_query})
|
| 671 |
-
chat_history[user_id].append({"role": "assistant", "content": final_response})
|
| 672 |
-
if len(chat_history[user_id]) > MAX_CHAT_HISTORY:
|
| 673 |
-
chat_history[user_id].pop(0)
|
| 674 |
-
|
| 675 |
-
# Convert AI response to voice
|
| 676 |
try:
|
| 677 |
-
|
| 678 |
-
|
| 679 |
-
|
| 680 |
-
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
|
| 685 |
-
|
| 686 |
-
|
| 687 |
-
|
| 688 |
-
|
| 689 |
-
pipe=True,
|
| 690 |
-
executable=FFMPEG_PATH,
|
| 691 |
-
**ffmpeg_options
|
| 692 |
)
|
|
|
|
|
|
|
| 693 |
|
| 694 |
-
|
| 695 |
-
|
| 696 |
-
|
| 697 |
-
|
| 698 |
-
|
|
|
|
|
|
|
|
|
|
| 699 |
|
| 700 |
-
|
| 701 |
-
|
| 702 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 703 |
|
| 704 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 705 |
|
| 706 |
except Exception as e:
|
| 707 |
-
logger.error(f"
|
| 708 |
-
|
| 709 |
-
|
| 710 |
-
|
| 711 |
-
|
| 712 |
-
|
| 713 |
-
|
| 714 |
-
await thinking_msg.edit(content=msg)
|
| 715 |
|
| 716 |
-
#
|
| 717 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
import discord
|
| 3 |
from discord.ext import commands
|
| 4 |
import json
|
|
|
|
| 12 |
from concurrent.futures import ThreadPoolExecutor
|
| 13 |
from gtts import gTTS
|
| 14 |
import io
|
| 15 |
+
import aiohttp
|
| 16 |
|
| 17 |
# Set up logging
|
| 18 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
|
|
|
| 58 |
# Helper functions
|
| 59 |
def load_data(filename, default_data):
|
| 60 |
if os.path.exists(filename):
|
| 61 |
+
try:
|
| 62 |
+
with open(filename, 'r', encoding='utf-8') as f:
|
| 63 |
+
return json.load(f)
|
| 64 |
+
except Exception as e:
|
| 65 |
+
logger.error(f"Error loading {filename}: {e}")
|
| 66 |
+
return default_data
|
| 67 |
return default_data
|
| 68 |
|
| 69 |
def save_data(data, filename):
|
| 70 |
+
try:
|
| 71 |
+
with open(filename, 'w', encoding='utf-8') as f:
|
| 72 |
+
json.dump(data, f, indent=4, ensure_ascii=False)
|
| 73 |
+
except Exception as e:
|
| 74 |
+
logger.error(f"Error saving {filename}: {e}")
|
| 75 |
|
| 76 |
def log_action(guild_id, action, user_id, moderator_id, reason):
|
| 77 |
log_entry = {
|
|
|
|
| 130 |
@bot.event
|
| 131 |
async def on_guild_join(guild):
|
| 132 |
try:
|
| 133 |
+
role = await guild.create_role(
|
| 134 |
+
name="🛡 Bot Moderation",
|
| 135 |
+
permissions=discord.Permissions(moderate_members=True, kick_members=True, ban_members=True, manage_messages=True),
|
| 136 |
+
hoist=True,
|
| 137 |
+
mentionable=True
|
| 138 |
+
)
|
| 139 |
guild_id = str(guild.id)
|
| 140 |
config_data[guild_id] = {
|
| 141 |
'admin_role_id': role.id,
|
|
|
|
| 144 |
'bad_words': ['fuck', 'shit', 'asshole'] # Add more bad words as needed
|
| 145 |
}
|
| 146 |
save_data(config_data, CONFIG_FILE)
|
| 147 |
+
logger.info(f"Created '🛡 Bot Moderation' role and set config for guild {guild_id}")
|
| 148 |
except discord.Forbidden:
|
| 149 |
logger.error(f"Failed to create role in guild {guild.id}: Missing permissions")
|
| 150 |
except Exception as e:
|
|
|
|
| 209 |
return
|
| 210 |
|
| 211 |
# Default AI response
|
| 212 |
+
for attempt in range(3): # Retry up to 3 times
|
| 213 |
+
try:
|
| 214 |
+
client = Client("amd/gpt-oss-120b-chatbot")
|
| 215 |
+
loop = asyncio.get_running_loop()
|
| 216 |
+
ai_output = await loop.run_in_executor(
|
| 217 |
+
executor,
|
| 218 |
+
lambda: client.predict(
|
| 219 |
+
message=prompt,
|
| 220 |
+
system_prompt=SYSTEM_PROMPT,
|
| 221 |
+
temperature=0.7,
|
| 222 |
+
reasoning_effort="medium",
|
| 223 |
+
enable_browsing=False,
|
| 224 |
+
api_name="/chat"
|
| 225 |
+
)
|
| 226 |
)
|
| 227 |
+
match = re.search(r'💬 Response:\s*(.+)', ai_output, re.DOTALL)
|
| 228 |
+
response = match.group(1).strip() if match else ai_output.strip()
|
| 229 |
+
await ctx.send(response)
|
| 230 |
+
return
|
| 231 |
+
except Exception as e:
|
| 232 |
+
logger.error(f"AI attempt {attempt + 1} failed: {e}")
|
| 233 |
+
if attempt < 2:
|
| 234 |
+
await asyncio.sleep(2) # Wait before retrying
|
| 235 |
+
else:
|
| 236 |
+
msg = f"Error communicating with AI after 3 attempts: {e}" if lang == 'en' else f"حصل خطأ أثناء التواصل مع الذكاء الاصطناعي بعد 3 محاولات: {e}"
|
| 237 |
+
await ctx.send(msg)
|
| 238 |
|
| 239 |
async def chat_with_ai(message: discord.Message):
|
| 240 |
guild_id = str(message.guild.id)
|
|
|
|
| 318 |
admin_role = discord.utils.get(message.guild.roles, id=admin_role_id)
|
| 319 |
if admin_role and admin_role in message.author.roles:
|
| 320 |
is_admin = True
|
| 321 |
+
if user_id in config.get('allowed_users', []):
|
| 322 |
+
is_admin = True
|
| 323 |
if is_admin and bot.user.mentioned_in(message):
|
| 324 |
clean_content = message.content.replace(f'<@!{bot.user.id}>', '').strip()
|
| 325 |
await process_ai_command(message.channel, clean_content)
|
|
|
|
| 373 |
if user_id not in config_data[guild_id]['allowed_users']:
|
| 374 |
config_data[guild_id]['allowed_users'].append(user_id)
|
| 375 |
save_data(config_data, CONFIG_FILE)
|
| 376 |
+
lang = config_data[guild_id].get('language', 'en')
|
| 377 |
msg = f"✅ Added moderation access to {member.mention}." if lang == 'en' else f"✅ تم إضافة صلاحية الإدارة لـ {member.mention}."
|
| 378 |
await ctx.send(msg)
|
| 379 |
log_action(guild_id, "add_access", member.id, ctx.author.id, "Added individual mod access")
|
|
|
|
| 387 |
if user_id in config_data[guild_id]['allowed_users']:
|
| 388 |
config_data[guild_id]['allowed_users'].remove(user_id)
|
| 389 |
save_data(config_data, CONFIG_FILE)
|
| 390 |
+
lang = config_data[guild_id].get('language', 'en')
|
| 391 |
msg = f"✅ Removed moderation access from {member.mention}." if lang == 'en' else f"✅ تم إزالة صلاحية الإدارة من {member.mention}."
|
| 392 |
await ctx.send(msg)
|
| 393 |
log_action(guild_id, "remove_access", member.id, ctx.author.id, "Removed individual mod access")
|
|
|
|
| 599 |
memory.pop(0)
|
| 600 |
thinking_msg = await ctx.send("💭 Thinking..." if lang == 'en' else "💭 OS Bot is thinking...")
|
| 601 |
|
| 602 |
+
for attempt in range(3):
|
| 603 |
+
try:
|
| 604 |
+
client = Client("amd/gpt-oss-120b-chatbot")
|
| 605 |
+
loop = asyncio.get_running_loop()
|
| 606 |
+
ai_output = await loop.run_in_executor(
|
| 607 |
+
executor,
|
| 608 |
+
lambda: client.predict(
|
| 609 |
+
message=user_message,
|
| 610 |
+
system_prompt=SYSTEM_PROMPT,
|
| 611 |
+
temperature=0.7,
|
| 612 |
+
reasoning_effort="medium",
|
| 613 |
+
enable_browsing=False,
|
| 614 |
+
api_name="/chat"
|
| 615 |
+
)
|
| 616 |
)
|
| 617 |
+
match = re.search(r'💬 Response:\s*(.+)', ai_output, re.DOTALL)
|
| 618 |
+
final_response = match.group(1).strip() if match else ai_output.strip()
|
| 619 |
+
memory.append({"role": "assistant", "content": final_response})
|
| 620 |
+
await thinking_msg.edit(content=final_response)
|
| 621 |
+
return
|
| 622 |
+
except Exception as e:
|
| 623 |
+
logger.error(f"AI attempt {attempt + 1} failed: {e}")
|
| 624 |
+
if attempt < 2:
|
| 625 |
+
await asyncio.sleep(2)
|
| 626 |
+
else:
|
| 627 |
+
msg = f"Error communicating with AI after 3 attempts: {e}" if lang == 'en' else f"حصل خطأ أثناء التواصل مع الذكاء الاصطناعي بعد 3 محاولات: {e}"
|
| 628 |
+
await thinking_msg.edit(content=msg)
|
| 629 |
+
if user_id in chat_history:
|
| 630 |
+
del chat_history[user_id]
|
| 631 |
|
| 632 |
@bot.command(name='join')
|
| 633 |
async def join(ctx):
|
|
|
|
| 672 |
|
| 673 |
thinking_msg = await ctx.send("💭 Thinking..." if lang == 'en' else "💭 OS Bot is thinking...")
|
| 674 |
|
| 675 |
+
for attempt in range(3):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 676 |
try:
|
| 677 |
+
client = Client("amd/gpt-oss-120b-chatbot")
|
| 678 |
+
loop = asyncio.get_running_loop()
|
| 679 |
+
ai_output = await loop.run_in_executor(
|
| 680 |
+
executor,
|
| 681 |
+
lambda: client.predict(
|
| 682 |
+
message=text_query,
|
| 683 |
+
system_prompt=SYSTEM_PROMPT,
|
| 684 |
+
temperature=0.7,
|
| 685 |
+
reasoning_effort="medium",
|
| 686 |
+
enable_browsing=False,
|
| 687 |
+
api_name="/chat"
|
| 688 |
+
)
|
|
|
|
|
|
|
|
|
|
| 689 |
)
|
| 690 |
+
match = re.search(r'💬 Response:\s*(.+)', ai_output, re.DOTALL)
|
| 691 |
+
final_response = match.group(1).strip() if match else ai_output.strip()
|
| 692 |
|
| 693 |
+
# Save to chat history
|
| 694 |
+
user_id = str(ctx.author.id)
|
| 695 |
+
if user_id not in chat_history:
|
| 696 |
+
chat_history[user_id] = []
|
| 697 |
+
chat_history[user_id].append({"role": "user", "content": text_query})
|
| 698 |
+
chat_history[user_id].append({"role": "assistant", "content": final_response})
|
| 699 |
+
if len(chat_history[user_id]) > MAX_CHAT_HISTORY:
|
| 700 |
+
chat_history[user_id].pop(0)
|
| 701 |
|
| 702 |
+
# Convert AI response to voice
|
| 703 |
+
try:
|
| 704 |
+
logger.info(f"Generating TTS for response: {final_response}")
|
| 705 |
+
tts = gTTS(text=final_response, lang='ar' if lang == 'ar' else 'en', slow=False)
|
| 706 |
+
voice_buffer = io.BytesIO()
|
| 707 |
+
tts.write_to_fp(voice_buffer)
|
| 708 |
+
voice_buffer.seek(0)
|
| 709 |
+
logger.info(f"TTS audio buffer created, size: {len(voice_buffer.getvalue())} bytes")
|
| 710 |
+
|
| 711 |
+
ffmpeg_options = {
|
| 712 |
+
'options': '-f s16le -ar 48000 -ac 2'
|
| 713 |
+
}
|
| 714 |
+
source = discord.FFmpegPCMAudio(
|
| 715 |
+
source=voice_buffer,
|
| 716 |
+
pipe=True,
|
| 717 |
+
executable=FFMPEG_PATH,
|
| 718 |
+
**ffmpeg_options
|
| 719 |
+
)
|
| 720 |
+
|
| 721 |
+
def after_playback(error):
|
| 722 |
+
if error:
|
| 723 |
+
logger.error(f"Playback error: {error}")
|
| 724 |
+
else:
|
| 725 |
+
logger.info("Audio playback completed successfully")
|
| 726 |
+
|
| 727 |
+
ctx.voice_client.play(source, after=after_playback)
|
| 728 |
+
while ctx.voice_client.is_playing():
|
| 729 |
+
await asyncio.sleep(1)
|
| 730 |
+
|
| 731 |
+
await thinking_msg.edit(content=f"Response: `{final_response}`" if lang == 'en' else f"الرد: `{final_response}`")
|
| 732 |
+
return
|
| 733 |
|
| 734 |
+
except Exception as e:
|
| 735 |
+
logger.error(f"TTS error: {e}")
|
| 736 |
+
msg = f"Error converting text to speech: {e}" if lang == 'en' else f"حصل خطأ أثناء تحويل النص إلى صوت: {e}"
|
| 737 |
+
await thinking_msg.edit(content=msg)
|
| 738 |
+
return
|
| 739 |
|
| 740 |
except Exception as e:
|
| 741 |
+
logger.error(f"AI attempt {attempt + 1} failed: {e}")
|
| 742 |
+
if attempt < 2:
|
| 743 |
+
await asyncio.sleep(2)
|
| 744 |
+
else:
|
| 745 |
+
msg = f"Error communicating with AI after 3 attempts: {e}" if lang == 'en' else f"حصل خطأ أثناء التواصل مع الذكاء الاصطناعي بعد 3 محاولات: {e}"
|
| 746 |
+
await thinking_msg.edit(content=msg)
|
| 747 |
+
return
|
|
|
|
| 748 |
|
| 749 |
+
# Retry-enabled bot start
|
| 750 |
+
async def start_bot():
|
| 751 |
+
for attempt in range(3):
|
| 752 |
+
try:
|
| 753 |
+
await bot.start(TOKEN)
|
| 754 |
+
return
|
| 755 |
+
except aiohttp.client_exceptions.ClientConnectorDNSError as e:
|
| 756 |
+
logger.error(f"Connection attempt {attempt + 1} failed: {e}")
|
| 757 |
+
if attempt < 2:
|
| 758 |
+
await asyncio.sleep(5)
|
| 759 |
+
else:
|
| 760 |
+
logger.error("Failed to connect to Discord after 3 attempts. Exiting.")
|
| 761 |
+
raise
|
| 762 |
+
|
| 763 |
+
# Run the bot with retry
|
| 764 |
+
if __name__ == "__main__":
|
| 765 |
+
try:
|
| 766 |
+
asyncio.run(start_bot())
|
| 767 |
+
except Exception as e:
|
| 768 |
+
logger.error(f"Fatal error: {e}")
|