Implement prompt handling for web interface; validate API key and JSON input
This commit is contained in:
Binary file not shown.
@@ -82,6 +82,41 @@ class DiscordBot:
|
||||
self._initialized = False
|
||||
raise
|
||||
|
||||
async def _handle_prompt(self, request: web.Request) -> web.Response:
|
||||
"""Handle incoming prompt requests from the web interface."""
|
||||
try:
|
||||
# Validate API key if provided in environment
|
||||
expected_key = os.getenv('BACKEND_API_KEY')
|
||||
if expected_key:
|
||||
provided_key = request.headers.get('X-API-Key')
|
||||
if not provided_key or provided_key != expected_key:
|
||||
return web.json_response({"error": "Invalid API key"}, status=401)
|
||||
|
||||
# Parse request body
|
||||
try:
|
||||
body = await request.json()
|
||||
except ValueError:
|
||||
return web.json_response({"error": "Invalid JSON"}, status=400)
|
||||
|
||||
# Validate required fields
|
||||
prompt = body.get('prompt')
|
||||
if not prompt:
|
||||
return web.json_response({"error": "Missing required field: prompt"}, status=400)
|
||||
|
||||
# Use provided channel_id or default
|
||||
channel_id = body.get('channel_id', AUTO_RESPONSE_CHANNEL_ID)
|
||||
|
||||
# Have the event handler process the prompt
|
||||
if self.event_handler:
|
||||
await self.event_handler.send_prompt_to_channel(prompt, channel_id)
|
||||
return web.json_response({"status": "processing"})
|
||||
else:
|
||||
return web.json_response({"error": "Event handler not initialized"}, status=503)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error handling prompt request: {e}")
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
async def _handle_connection(self, token: str) -> None:
|
||||
"""Handle bot connection with retries."""
|
||||
retry_count = 0
|
||||
|
||||
@@ -32,7 +32,7 @@ def send_prompt():
|
||||
headers['X-API-Key'] = BACKEND_API_KEY
|
||||
|
||||
response = requests.post(
|
||||
f'http://localhost:{API_PORT}/api/prompt',
|
||||
'http://127.0.0.1:8000/api/prompt', # Use fixed internal API port
|
||||
json=data,
|
||||
headers=headers
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user