Refactor web interface and bot initialization; enhance error handling for channel ID and update queue state

This commit is contained in:
pacnpal
2025-02-12 09:05:21 -05:00
parent 9efd4454fe
commit 4fe1505d92
9 changed files with 4604 additions and 29 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -166,6 +166,32 @@ class DiscordBot:
self.bot, self.queue_manager, self.db_manager, self.api_manager
)
# Debug available channels
# Debug bot permissions
for guild in self.bot.guilds:
me = guild.me
logger.info(f"Bot permissions in guild {guild.name}:")
logger.info(f"Bot roles: {[role.name for role in me.roles]}")
logger.info(f"Bot permissions: {me.guild_permissions}")
for channel in guild.text_channels:
perms = channel.permissions_for(me)
logger.info(f"Channel #{channel.name} ({channel.id}) - Can send messages: {perms.send_messages}")
# Initialize and start web interface with event handler
from discord_glhf.web.app import init_app
from hypercorn.config import Config
from hypercorn.asyncio import serve
web_port = int(os.getenv('WEB_PORT', '8080'))
config = Config()
config.bind = [f"0.0.0.0:{web_port}"]
self.web_app = init_app(self.event_handler)
# Start web interface in background task
loop = asyncio.get_event_loop()
loop.create_task(serve(self.web_app, config))
logger.info(f"Web interface starting at http://localhost:{web_port}")
# Start API manager
if not self.api_manager.is_running:
await self.api_manager.start()
@@ -192,11 +218,6 @@ class DiscordBot:
await internal_site.start()
logger.info("Internal API server started")
# Initialize and start web interface
from discord_glhf.web.app import init_app
self.web_app = init_app(self.event_handler)
logger.info("Web interface initialized with event handler")
# Set bot status
activity = Game(name="with roller coasters")
await self.bot.change_presence(activity=activity)

View File

@@ -2,3 +2,15 @@
2025-02-11 20:23:21 - INFO - discord_bot - load_responses:250 - Loaded responses from file
2025-02-11 20:23:21 - DEBUG - asyncio - __init__:64 - Using selector: KqueueSelector
2025-02-11 20:23:21 - INFO - hypercorn.error - info:106 - Running on http://0.0.0.0:8080 (CTRL + C to quit)
2025-02-11 22:07:35 - INFO - discord_bot - <module>:211 - Using database path: conversation_history.db
2025-02-11 22:07:35 - INFO - discord_bot - load_responses:250 - Loaded responses from file
2025-02-11 22:07:35 - DEBUG - asyncio - __init__:64 - Using selector: KqueueSelector
2025-02-11 22:07:35 - INFO - hypercorn.error - info:106 - Running on http://0.0.0.0:8080 (CTRL + C to quit)
2025-02-11 22:30:35 - INFO - discord_bot - <module>:211 - Using database path: conversation_history.db
2025-02-11 22:30:35 - INFO - discord_bot - load_responses:250 - Loaded responses from file
2025-02-11 22:30:35 - DEBUG - asyncio - __init__:64 - Using selector: KqueueSelector
2025-02-11 22:30:35 - INFO - hypercorn.error - info:106 - Running on http://0.0.0.0:8080 (CTRL + C to quit)
2025-02-11 22:56:25 - INFO - discord_bot - <module>:211 - Using database path: conversation_history.db
2025-02-11 22:56:25 - INFO - discord_bot - load_responses:250 - Loaded responses from file
2025-02-11 22:56:25 - DEBUG - asyncio - __init__:64 - Using selector: KqueueSelector
2025-02-11 22:56:25 - INFO - hypercorn.error - info:106 - Running on http://0.0.0.0:8080 (CTRL + C to quit)

View File

@@ -26,12 +26,18 @@ python3 -m discord_glhf &
# Wait a moment for bot to initialize
sleep 2
# Start the web interface
echo "Starting web interface on port ${WEB_PORT}..."
# Start the bot with the web interface
echo "Starting Discord bot and web interface..."
cd $(dirname "$0")
# Run web interface with proper Python path and virtualenv
PYTHONPATH=/Volumes/macminissd/Projects/discord_glhf /Users/talor/Projects/discord_glhf/.venv/bin/python3 web/app.py &
WEB_PID=$!
# Ensure virtualenv is activated
source /Users/talor/Projects/discord_glhf/.venv/bin/activate
# Set Python path
export PYTHONPATH=/Volumes/macminissd/Projects/discord_glhf
# Run bot
cd /Volumes/macminissd/Projects/discord_glhf && python -m discord_glhf
# Wait a moment for web interface to start
sleep 2

View File

@@ -35,13 +35,31 @@ async def send_prompt():
if not event_handler:
return jsonify({'error': 'Bot not initialized'}), 503
data = request.get_json()
data = await request.get_json()
if not data or 'prompt' not in data:
return jsonify({'error': 'Missing prompt'}), 400
channel_id = data.get('channel_id', AUTO_RESPONSE_CHANNEL_ID)
await event_handler.send_prompt_to_channel(data['prompt'], channel_id)
return jsonify({'status': 'processing'}), 200
try:
channel_id = int(str(data.get('channel_id', '1198637345701285999')))
except (ValueError, TypeError):
return jsonify({'error': 'Invalid channel ID format'}), 400
if not channel_id:
return jsonify({'error': 'Channel ID is required'}), 400
try:
# Attempt to send prompt to channel
await event_handler.send_prompt_to_channel(data['prompt'], channel_id)
return jsonify({
'status': 'processing',
'message': f'Prompt sent to channel {channel_id}'
}), 200
except Exception as e:
if 'Could not find channel' in str(e):
return jsonify({
'error': f'Invalid channel ID: {channel_id}. Please verify the channel ID is correct.'
}), 404
raise
except Exception as e:
return jsonify({'error': str(e)}), 500

View File

@@ -28,15 +28,18 @@
<div>
<label for="channelId" class="block text-sm font-medium text-gray-700 mb-1">
Channel ID (optional)
Channel ID (required)
</label>
<input
type="text"
id="channelId"
name="channelId"
<input
type="text"
id="channelId"
name="channelId"
class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500"
placeholder="Enter channel ID..."
value="743661026050048040"
required
>
<p class="mt-1 text-sm text-gray-500">Default: #shock_space (743661026050048040)</p>
</div>
<div>
@@ -75,7 +78,7 @@
},
body: JSON.stringify({
prompt: prompt,
...(channelId && { channel_id: parseInt(channelId) })
channel_id: channelId ? String(channelId) : "1198637345701285999"
})
});
@@ -87,12 +90,14 @@
resultMessage.textContent = 'Prompt sent successfully! Check Discord for the response.';
} else {
resultDiv.firstElementChild.className = 'p-4 rounded-md bg-red-100 text-red-700';
resultMessage.textContent = `Error: ${data.error}`;
resultMessage.innerHTML = `Error: ${data.error}<br>
<span class="text-sm text-gray-500">Make sure the channel ID exists and the bot has access to it.</span>`;
}
} catch (error) {
resultDiv.className = 'mt-6 block';
resultDiv.firstElementChild.className = 'p-4 rounded-md bg-red-100 text-red-700';
resultMessage.textContent = `Error: ${error.message}`;
resultMessage.innerHTML = `Error: ${error.message}<br>
<span class="text-sm text-gray-500">There was a problem connecting to the bot. Please try again.</span>`;
}
});
</script>

View File

@@ -1,11 +1,11 @@
{
"total_processed": 1859,
"failed_messages": 46,
"last_processed_time": 1739323467.1755688,
"total_processed": 0,
"failed_messages": 0,
"last_processed_time": 1739369077.797861,
"user_queues": {},
"last_save": 1739323467.1755688,
"processor_id": null,
"active": false,
"last_save": 1739369077.797876,
"processor_id": "8cbb203b",
"active": true,
"pending_messages": [],
"last_channel_id": "743661026050048040"
"last_channel_id": null
}