This commit is contained in:
Slipstream 2025-05-03 19:52:52 -06:00
parent d526eefe81
commit ce2b168b6f
Signed by: slipstream
GPG Key ID: 13E498CE010AC6FD
4 changed files with 188 additions and 63 deletions

View File

@ -10,6 +10,7 @@ from fastapi.staticfiles import StaticFiles
from starlette.middleware.base import BaseHTTPMiddleware from starlette.middleware.base import BaseHTTPMiddleware
from starlette.middleware.sessions import SessionMiddleware from starlette.middleware.sessions import SessionMiddleware
import aiohttp import aiohttp
import discord
from database import Database # Existing DB from database import Database # Existing DB
import logging import logging
from pydantic_settings import BaseSettings, SettingsConfigDict from pydantic_settings import BaseSettings, SettingsConfigDict
@ -1558,19 +1559,92 @@ async def dashboard_test_welcome_message(
detail="Welcome channel not configured" detail="Welcome channel not configured"
) )
# In a real implementation, this would send a test message to the welcome channel # Format the message
# For now, we'll just return a success message with the formatted message
formatted_message = welcome_message_template.format( formatted_message = welcome_message_template.format(
user="@TestUser", user="@TestUser",
username="TestUser", username="TestUser",
server=f"Server {guild_id}" server=f"Server {guild_id}"
) )
return { # Import the bot instance from discord_bot_sync_api
"message": "Test welcome message sent", from discord_bot_sync_api import bot_instance
"channel_id": welcome_channel_id_str,
"formatted_message": formatted_message # 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: except HTTPException:
# Re-raise HTTP exceptions # Re-raise HTTP exceptions
raise raise
@ -1600,18 +1674,91 @@ async def dashboard_test_goodbye_message(
detail="Goodbye channel not configured" detail="Goodbye channel not configured"
) )
# In a real implementation, this would send a test message to the goodbye channel # Format the message
# For now, we'll just return a success message with the formatted message
formatted_message = goodbye_message_template.format( formatted_message = goodbye_message_template.format(
username="TestUser", username="TestUser",
server=f"Server {guild_id}" server=f"Server {guild_id}"
) )
return { # Import the bot instance from discord_bot_sync_api
"message": "Test goodbye message sent", from discord_bot_sync_api import bot_instance
"channel_id": goodbye_channel_id_str,
"formatted_message": formatted_message # 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: except HTTPException:
# Re-raise HTTP exceptions # Re-raise HTTP exceptions
raise raise

View File

@ -537,31 +537,17 @@ async def test_welcome_message(
_admin: bool = Depends(verify_dashboard_guild_admin) _admin: bool = Depends(verify_dashboard_guild_admin)
): ):
"""Test the welcome message for a guild.""" """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: try:
# Get welcome settings # Import the main API server endpoint
welcome_channel_id_str = await settings_manager.get_setting(guild_id, 'welcome_channel_id') try:
welcome_message_template = await settings_manager.get_setting(guild_id, 'welcome_message', default="Welcome {user} to {server}!") from api_server import dashboard_test_welcome_message
except ImportError:
from .api_server import dashboard_test_welcome_message
# Check if welcome channel is set # Call the main API server endpoint
if not welcome_channel_id_str or welcome_channel_id_str == "__NONE__": return await dashboard_test_welcome_message(guild_id, _user, _admin)
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
}
except HTTPException: except HTTPException:
# Re-raise HTTP exceptions # Re-raise HTTP exceptions
raise raise
@ -579,30 +565,17 @@ async def test_goodbye_message(
_admin: bool = Depends(verify_dashboard_guild_admin) _admin: bool = Depends(verify_dashboard_guild_admin)
): ):
"""Test the goodbye message for a guild.""" """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: try:
# Get goodbye settings # Import the main API server endpoint
goodbye_channel_id_str = await settings_manager.get_setting(guild_id, 'goodbye_channel_id') try:
goodbye_message_template = await settings_manager.get_setting(guild_id, 'goodbye_message', default="{username} has left the server.") from api_server import dashboard_test_goodbye_message
except ImportError:
from .api_server import dashboard_test_goodbye_message
# Check if goodbye channel is set # Call the main API server endpoint
if not goodbye_channel_id_str or goodbye_channel_id_str == "__NONE__": return await dashboard_test_goodbye_message(guild_id, _user, _admin)
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
}
except HTTPException: except HTTPException:
# Re-raise HTTP exceptions # Re-raise HTTP exceptions
raise raise

View File

@ -17,10 +17,11 @@ from typing import Optional # Added for GurtCog type hint
# This file contains the API endpoints for syncing conversations between # This file contains the API endpoints for syncing conversations between
# the Flutter app and the Discord bot, AND the Gurt stats endpoint. # the Flutter app and the Discord bot, AND the Gurt stats endpoint.
# --- Placeholder for GurtCog instance --- # --- Placeholder for GurtCog instance and bot instance ---
# This needs to be set by the script that starts the bot and API server # 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 from discordbot.gurt.cog import GurtCog # Import GurtCog for type hint and access
gurt_cog_instance: Optional[GurtCog] = None gurt_cog_instance: Optional[GurtCog] = None
bot_instance = None # Will be set to the Discord bot instance
# ============= Models ============= # ============= Models =============

View File

@ -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 # 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) 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: try:
gurt_cog = bot.get_cog("Gurt") # Get the loaded GurtCog instance gurt_cog = bot.get_cog("Gurt") # Get the loaded GurtCog instance
if gurt_cog: if gurt_cog:
@ -455,8 +455,12 @@ async def main(args): # Pass parsed args
print("Successfully shared GurtCog instance with discord_bot_sync_api.") print("Successfully shared GurtCog instance with discord_bot_sync_api.")
else: else:
print("Warning: GurtCog not found after loading cogs. Stats API might not work.") 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: 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) --- # --- Manually Load FreakTetoCog (only if AI is NOT disabled) ---