From ce2b168b6fb73c3ff8b9d160625ee21252db5945 Mon Sep 17 00:00:00 2001 From: Slipstream Date: Sat, 3 May 2025 19:52:52 -0600 Subject: [PATCH] vvd --- api_service/api_server.py | 175 +++++++++++++++++++++++-- api_service/dashboard_api_endpoints.py | 63 +++------ discord_bot_sync_api.py | 5 +- main.py | 8 +- 4 files changed, 188 insertions(+), 63 deletions(-) diff --git a/api_service/api_server.py b/api_service/api_server.py index f36a11f..8a71493 100644 --- a/api_service/api_server.py +++ b/api_service/api_server.py @@ -10,6 +10,7 @@ from fastapi.staticfiles import StaticFiles from starlette.middleware.base import BaseHTTPMiddleware from starlette.middleware.sessions import SessionMiddleware import aiohttp +import discord from database import Database # Existing DB import logging from pydantic_settings import BaseSettings, SettingsConfigDict @@ -1558,19 +1559,92 @@ async def dashboard_test_welcome_message( detail="Welcome channel not configured" ) - # In a real implementation, this would send a test message to the welcome channel - # For now, we'll just return a success message with the formatted message + # Format the message formatted_message = welcome_message_template.format( user="@TestUser", username="TestUser", server=f"Server {guild_id}" ) - return { - "message": "Test welcome message sent", - "channel_id": welcome_channel_id_str, - "formatted_message": formatted_message - } + # Import the bot instance from discord_bot_sync_api + from discord_bot_sync_api import bot_instance + + # Check if bot instance is available + if not bot_instance: + log.error(f"Bot instance not available for sending test welcome message to guild {guild_id}") + return { + "message": "Test welcome message could not be sent (bot instance not available)", + "channel_id": welcome_channel_id_str, + "formatted_message": formatted_message + } + + # Try to get the channel and send the message + try: + welcome_channel_id = int(welcome_channel_id_str) + channel = bot_instance.get_channel(welcome_channel_id) + + if not channel: + # Try fetching if not in cache + try: + channel = await bot_instance.fetch_channel(welcome_channel_id) + except discord.NotFound: + log.warning(f"Welcome channel ID {welcome_channel_id} not found for guild {guild_id}") + return { + "message": "Test welcome message could not be sent (channel not found)", + "channel_id": welcome_channel_id_str, + "formatted_message": formatted_message + } + except discord.Forbidden: + log.warning(f"Bot does not have permission to access channel {welcome_channel_id} in guild {guild_id}") + return { + "message": "Test welcome message could not be sent (no permission to access channel)", + "channel_id": welcome_channel_id_str, + "formatted_message": formatted_message + } + + # Check if channel is a text channel + if not hasattr(channel, 'send'): + log.warning(f"Channel {welcome_channel_id} in guild {guild_id} is not a text channel") + return { + "message": "Test welcome message could not be sent (channel is not a text channel)", + "channel_id": welcome_channel_id_str, + "formatted_message": formatted_message + } + + # Check permissions if it's a guild channel + if hasattr(channel, 'guild') and hasattr(channel.guild, 'me'): + bot_member = channel.guild.me + if not channel.permissions_for(bot_member).send_messages: + log.warning(f"Bot does not have permission to send messages in channel {welcome_channel_id} in guild {guild_id}") + return { + "message": "Test welcome message could not be sent (no permission to send messages)", + "channel_id": welcome_channel_id_str, + "formatted_message": formatted_message + } + + # Send the message + await channel.send(formatted_message) + log.info(f"Sent test welcome message to channel {welcome_channel_id} in guild {guild_id}") + + return { + "message": "Test welcome message sent successfully", + "channel_id": welcome_channel_id_str, + "formatted_message": formatted_message + } + except ValueError: + log.error(f"Invalid welcome channel ID '{welcome_channel_id_str}' for guild {guild_id}") + return { + "message": "Test welcome message could not be sent (invalid channel ID)", + "channel_id": welcome_channel_id_str, + "formatted_message": formatted_message + } + except Exception as e: + log.error(f"Error sending test welcome message to channel {welcome_channel_id_str} in guild {guild_id}: {e}") + return { + "message": f"Test welcome message could not be sent: {str(e)}", + "channel_id": welcome_channel_id_str, + "formatted_message": formatted_message + } except HTTPException: # Re-raise HTTP exceptions raise @@ -1600,18 +1674,91 @@ async def dashboard_test_goodbye_message( detail="Goodbye channel not configured" ) - # In a real implementation, this would send a test message to the goodbye channel - # For now, we'll just return a success message with the formatted message + # Format the message formatted_message = goodbye_message_template.format( username="TestUser", server=f"Server {guild_id}" ) - return { - "message": "Test goodbye message sent", - "channel_id": goodbye_channel_id_str, - "formatted_message": formatted_message - } + # Import the bot instance from discord_bot_sync_api + from discord_bot_sync_api import bot_instance + + # Check if bot instance is available + if not bot_instance: + log.error(f"Bot instance not available for sending test goodbye message to guild {guild_id}") + return { + "message": "Test goodbye message could not be sent (bot instance not available)", + "channel_id": goodbye_channel_id_str, + "formatted_message": formatted_message + } + + # Try to get the channel and send the message + try: + goodbye_channel_id = int(goodbye_channel_id_str) + channel = bot_instance.get_channel(goodbye_channel_id) + + if not channel: + # Try fetching if not in cache + try: + channel = await bot_instance.fetch_channel(goodbye_channel_id) + except discord.NotFound: + log.warning(f"Goodbye channel ID {goodbye_channel_id} not found for guild {guild_id}") + return { + "message": "Test goodbye message could not be sent (channel not found)", + "channel_id": goodbye_channel_id_str, + "formatted_message": formatted_message + } + except discord.Forbidden: + log.warning(f"Bot does not have permission to access channel {goodbye_channel_id} in guild {guild_id}") + return { + "message": "Test goodbye message could not be sent (no permission to access channel)", + "channel_id": goodbye_channel_id_str, + "formatted_message": formatted_message + } + + # Check if channel is a text channel + if not hasattr(channel, 'send'): + log.warning(f"Channel {goodbye_channel_id} in guild {guild_id} is not a text channel") + return { + "message": "Test goodbye message could not be sent (channel is not a text channel)", + "channel_id": goodbye_channel_id_str, + "formatted_message": formatted_message + } + + # Check permissions if it's a guild channel + if hasattr(channel, 'guild') and hasattr(channel.guild, 'me'): + bot_member = channel.guild.me + if not channel.permissions_for(bot_member).send_messages: + log.warning(f"Bot does not have permission to send messages in channel {goodbye_channel_id} in guild {guild_id}") + return { + "message": "Test goodbye message could not be sent (no permission to send messages)", + "channel_id": goodbye_channel_id_str, + "formatted_message": formatted_message + } + + # Send the message + await channel.send(formatted_message) + log.info(f"Sent test goodbye message to channel {goodbye_channel_id} in guild {guild_id}") + + return { + "message": "Test goodbye message sent successfully", + "channel_id": goodbye_channel_id_str, + "formatted_message": formatted_message + } + except ValueError: + log.error(f"Invalid goodbye channel ID '{goodbye_channel_id_str}' for guild {guild_id}") + return { + "message": "Test goodbye message could not be sent (invalid channel ID)", + "channel_id": goodbye_channel_id_str, + "formatted_message": formatted_message + } + except Exception as e: + log.error(f"Error sending test goodbye message to channel {goodbye_channel_id_str} in guild {guild_id}: {e}") + return { + "message": f"Test goodbye message could not be sent: {str(e)}", + "channel_id": goodbye_channel_id_str, + "formatted_message": formatted_message + } except HTTPException: # Re-raise HTTP exceptions raise diff --git a/api_service/dashboard_api_endpoints.py b/api_service/dashboard_api_endpoints.py index c7f1368..b636354 100644 --- a/api_service/dashboard_api_endpoints.py +++ b/api_service/dashboard_api_endpoints.py @@ -537,31 +537,17 @@ async def test_welcome_message( _admin: bool = Depends(verify_dashboard_guild_admin) ): """Test the welcome message for a guild.""" + # This endpoint is now handled by the main API server + # We'll just redirect to the main API server endpoint try: - # Get welcome settings - welcome_channel_id_str = await settings_manager.get_setting(guild_id, 'welcome_channel_id') - welcome_message_template = await settings_manager.get_setting(guild_id, 'welcome_message', default="Welcome {user} to {server}!") + # Import the main API server endpoint + try: + from api_server import dashboard_test_welcome_message + except ImportError: + from .api_server import dashboard_test_welcome_message - # Check if welcome channel is set - if not welcome_channel_id_str or welcome_channel_id_str == "__NONE__": - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Welcome channel not configured" - ) - - # In a real implementation, this would send a test message to the welcome channel - # For now, we'll just return a success message with the formatted message - formatted_message = welcome_message_template.format( - user="@TestUser", - username="TestUser", - server=f"Server {guild_id}" - ) - - return { - "message": "Test welcome message sent", - "channel_id": welcome_channel_id_str, - "formatted_message": formatted_message - } + # Call the main API server endpoint + return await dashboard_test_welcome_message(guild_id, _user, _admin) except HTTPException: # Re-raise HTTP exceptions raise @@ -579,30 +565,17 @@ async def test_goodbye_message( _admin: bool = Depends(verify_dashboard_guild_admin) ): """Test the goodbye message for a guild.""" + # This endpoint is now handled by the main API server + # We'll just redirect to the main API server endpoint try: - # Get goodbye settings - goodbye_channel_id_str = await settings_manager.get_setting(guild_id, 'goodbye_channel_id') - goodbye_message_template = await settings_manager.get_setting(guild_id, 'goodbye_message', default="{username} has left the server.") + # Import the main API server endpoint + try: + from api_server import dashboard_test_goodbye_message + except ImportError: + from .api_server import dashboard_test_goodbye_message - # Check if goodbye channel is set - if not goodbye_channel_id_str or goodbye_channel_id_str == "__NONE__": - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Goodbye channel not configured" - ) - - # In a real implementation, this would send a test message to the goodbye channel - # For now, we'll just return a success message with the formatted message - formatted_message = goodbye_message_template.format( - username="TestUser", - server=f"Server {guild_id}" - ) - - return { - "message": "Test goodbye message sent", - "channel_id": goodbye_channel_id_str, - "formatted_message": formatted_message - } + # Call the main API server endpoint + return await dashboard_test_goodbye_message(guild_id, _user, _admin) except HTTPException: # Re-raise HTTP exceptions raise diff --git a/discord_bot_sync_api.py b/discord_bot_sync_api.py index 52118fb..668c02a 100644 --- a/discord_bot_sync_api.py +++ b/discord_bot_sync_api.py @@ -17,10 +17,11 @@ from typing import Optional # Added for GurtCog type hint # This file contains the API endpoints for syncing conversations between # the Flutter app and the Discord bot, AND the Gurt stats endpoint. -# --- Placeholder for GurtCog instance --- -# This needs to be set by the script that starts the bot and API server +# --- Placeholder for GurtCog instance and bot instance --- +# These need to be set by the script that starts the bot and API server from discordbot.gurt.cog import GurtCog # Import GurtCog for type hint and access gurt_cog_instance: Optional[GurtCog] = None +bot_instance = None # Will be set to the Discord bot instance # ============= Models ============= diff --git a/main.py b/main.py index c5be06e..9c87e4b 100644 --- a/main.py +++ b/main.py @@ -447,7 +447,7 @@ async def main(args): # Pass parsed args # This should now include WelcomeCog and SettingsCog if they are in the cogs dir await load_all_cogs(bot, skip_cogs=ai_cogs_to_skip) - # --- Share GurtCog instance with the sync API --- + # --- Share GurtCog instance and bot instance with the sync API --- try: gurt_cog = bot.get_cog("Gurt") # Get the loaded GurtCog instance if gurt_cog: @@ -455,8 +455,12 @@ async def main(args): # Pass parsed args print("Successfully shared GurtCog instance with discord_bot_sync_api.") else: print("Warning: GurtCog not found after loading cogs. Stats API might not work.") + + # Share the bot instance with the sync API + discord_bot_sync_api.bot_instance = bot + print("Successfully shared bot instance with discord_bot_sync_api.") except Exception as e: - print(f"Error sharing GurtCog instance: {e}") + print(f"Error sharing instances with discord_bot_sync_api: {e}") # ------------------------------------------------ # --- Manually Load FreakTetoCog (only if AI is NOT disabled) ---