289 lines
13 KiB
Python
289 lines
13 KiB
Python
"""
|
|
Routines command handler - bot-side hooks for routine management
|
|
"""
|
|
|
|
from bot.command_registry import register_module
|
|
import ai.parser as ai_parser
|
|
|
|
|
|
async def handle_routine(message, session, parsed):
|
|
action = parsed.get("action", "unknown")
|
|
token = session["token"]
|
|
user_uuid = session["user_uuid"]
|
|
|
|
if action == "list":
|
|
resp, status = api_request("get", "/api/routines", token)
|
|
if status == 200:
|
|
routines = resp if isinstance(resp, list) else []
|
|
if not routines:
|
|
await message.channel.send("You don't have any routines yet.")
|
|
else:
|
|
lines = [f"- **{r['name']}**: {r.get('description', 'No description')}" for r in routines]
|
|
await message.channel.send("**Your routines:**\n" + "\n".join(lines))
|
|
else:
|
|
await message.channel.send(f"Error: {resp.get('error', 'Failed to fetch routines')}")
|
|
|
|
elif action == "create":
|
|
name = parsed.get("name")
|
|
description = parsed.get("description")
|
|
|
|
if not name:
|
|
await message.channel.send("Please provide a routine name.")
|
|
return
|
|
|
|
data = {"name": name, "description": description or ""}
|
|
resp, status = api_request("post", "/api/routines", token, data)
|
|
if status == 201:
|
|
await message.channel.send(f"Created routine **{name}**!")
|
|
else:
|
|
await message.channel.send(f"Error: {resp.get('error', 'Failed to create routine')}")
|
|
|
|
elif action == "start":
|
|
routine_id = parsed.get("routine_id")
|
|
if not routine_id:
|
|
await message.channel.send("Which routine would you like to start?")
|
|
return
|
|
|
|
resp, status = api_request("post", f"/api/routines/{routine_id}/start", token)
|
|
if status == 201:
|
|
step = resp.get("current_step", {})
|
|
await message.channel.send(f"Started! First step: **{step.get('name', 'Unknown')}**")
|
|
elif status == 409:
|
|
await message.channel.send(f"You already have an active session: {resp.get('error', '')}")
|
|
else:
|
|
await message.channel.send(f"Error: {resp.get('error', 'Failed to start routine')}")
|
|
|
|
elif action == "complete":
|
|
session_resp, _ = api_request("get", "/api/sessions/active", token)
|
|
if "session" not in session_resp:
|
|
await message.channel.send("No active routine session.")
|
|
return
|
|
session_id = session_resp["session"]["id"]
|
|
resp, status = api_request("post", f"/api/sessions/{session_id}/complete-step", token)
|
|
if status == 200:
|
|
if resp.get("next_step"):
|
|
await message.channel.send(f"Done! Next: **{resp['next_step'].get('name', 'Unknown')}**")
|
|
else:
|
|
await message.channel.send("Completed all steps! Great job!")
|
|
else:
|
|
await message.channel.send(f"Error: {resp.get('error', 'Failed to complete step')}")
|
|
|
|
elif action == "skip":
|
|
session_resp, _ = api_request("get", "/api/sessions/active", token)
|
|
if "session" not in session_resp:
|
|
await message.channel.send("No active routine session.")
|
|
return
|
|
session_id = session_resp["session"]["id"]
|
|
resp, status = api_request("post", f"/api/sessions/{session_id}/skip-step", token)
|
|
if status == 200:
|
|
if resp.get("next_step"):
|
|
await message.channel.send(f"Skipped! Next: **{resp['next_step'].get('name', 'Unknown')}**")
|
|
else:
|
|
await message.channel.send("All steps skipped! Routine ended.")
|
|
else:
|
|
await message.channel.send(f"Error: {resp.get('error', 'Failed to skip step')}")
|
|
|
|
elif action == "cancel":
|
|
session_resp, _ = api_request("get", "/api/sessions/active", token)
|
|
if "session" not in session_resp:
|
|
await message.channel.send("No active routine session to cancel.")
|
|
return
|
|
session_id = session_resp["session"]["id"]
|
|
resp, status = api_request("post", f"/api/sessions/{session_id}/cancel", token)
|
|
if status == 200:
|
|
await message.channel.send("Routine cancelled.")
|
|
else:
|
|
await message.channel.send(f"Error: {resp.get('error', 'Failed to cancel')}")
|
|
|
|
elif action == "history":
|
|
routine_id = parsed.get("routine_id")
|
|
if not routine_id:
|
|
await message.channel.send("Which routine's history?")
|
|
return
|
|
resp, status = api_request("get", f"/api/routines/{routine_id}/history", token)
|
|
if status == 200:
|
|
sessions = resp if isinstance(resp, list) else []
|
|
if not sessions:
|
|
await message.channel.send("No history yet.")
|
|
else:
|
|
lines = [f"- {s.get('status', 'unknown')} on {s.get('created_at', '')}" for s in sessions[:5]]
|
|
await message.channel.send("**Recent sessions:**\n" + "\n".join(lines))
|
|
else:
|
|
await message.channel.send(f"Error: {resp.get('error', 'Failed to fetch history')}")
|
|
|
|
elif action == "pause":
|
|
session_resp, _ = api_request("get", "/api/sessions/active", token)
|
|
if "session" not in session_resp:
|
|
await message.channel.send("No active routine session to pause.")
|
|
return
|
|
session_id = session_resp["session"]["id"]
|
|
resp, status = api_request("post", f"/api/sessions/{session_id}/pause", token)
|
|
if status == 200:
|
|
await message.channel.send("Routine paused. Say 'resume' when ready to continue.")
|
|
else:
|
|
await message.channel.send(f"Error: {resp.get('error', 'Failed to pause')}")
|
|
|
|
elif action == "resume":
|
|
session_resp, _ = api_request("get", "/api/sessions/active", token)
|
|
if "session" not in session_resp:
|
|
await message.channel.send("You don't have a paused session.")
|
|
return
|
|
resp, status = api_request("post", f"/api/sessions/{session_resp['session']['id']}/resume", token)
|
|
if status == 200:
|
|
await message.channel.send("Resumed! Let's keep going.")
|
|
else:
|
|
await message.channel.send(f"Error: {resp.get('error', 'Failed to resume')}")
|
|
|
|
elif action == "abort":
|
|
session_resp, _ = api_request("get", "/api/sessions/active", token)
|
|
if "session" not in session_resp:
|
|
await message.channel.send("No active routine session to abort.")
|
|
return
|
|
session_id = session_resp["session"]["id"]
|
|
reason = parsed.get("reason", "Aborted by user")
|
|
resp, status = api_request("post", f"/api/sessions/{session_id}/abort", token, {"reason": reason})
|
|
if status == 200:
|
|
await message.channel.send("Routine aborted. No worries, you can try again later!")
|
|
else:
|
|
await message.channel.send(f"Error: {resp.get('error', 'Failed to abort')}")
|
|
|
|
elif action == "note":
|
|
session_resp, _ = api_request("get", "/api/sessions/active", token)
|
|
if "session" not in session_resp:
|
|
await message.channel.send("No active routine session.")
|
|
return
|
|
session_id = session_resp["session"]["id"]
|
|
note = parsed.get("note")
|
|
if not note:
|
|
await message.channel.send("What note would you like to add?")
|
|
return
|
|
step_index = session_resp.get("session", {}).get("current_step_index", 0)
|
|
resp, status = api_request("post", f"/api/sessions/{session_id}/note", token, {"step_index": step_index, "note": note})
|
|
if status == 201:
|
|
await message.channel.send(f"Note saved: {note}")
|
|
else:
|
|
await message.channel.send(f"Error: {resp.get('error', 'Failed to save note')}")
|
|
|
|
elif action == "stats":
|
|
routine_id = parsed.get("routine_id")
|
|
if routine_id:
|
|
resp, status = api_request("get", f"/api/routines/{routine_id}/stats", token)
|
|
else:
|
|
await message.channel.send("Which routine's stats? (Please specify routine)")
|
|
return
|
|
if status == 200:
|
|
await message.channel.send(
|
|
f"**{resp.get('routine_name')} Stats:**\n"
|
|
f"- Completion rate: {resp.get('completion_rate_percent')}%\n"
|
|
f"- Completed: {resp.get('completed')}/{resp.get('total_sessions')}\n"
|
|
f"- Avg duration: {resp.get('avg_duration_minutes')} min"
|
|
)
|
|
else:
|
|
await message.channel.send(f"Error: {resp.get('error', 'Failed to fetch stats')}")
|
|
|
|
elif action == "streak":
|
|
routine_id = parsed.get("routine_id")
|
|
if routine_id:
|
|
resp, status = api_request("get", f"/api/routines/{routine_id}/streak", token)
|
|
else:
|
|
resp, status = api_request("get", "/api/routines/streaks", token)
|
|
if status == 200:
|
|
streaks = resp if isinstance(resp, list) else []
|
|
if not streaks:
|
|
await message.channel.send("No streaks yet. Complete routines to build streaks!")
|
|
else:
|
|
lines = [f"- {s.get('routine_name')}: {s.get('current_streak')} day streak" for s in streaks]
|
|
await message.channel.send("**Your streaks:**\n" + "\n".join(lines))
|
|
return
|
|
else:
|
|
await message.channel.send(f"Error: {resp.get('error', 'Failed to fetch streaks')}")
|
|
return
|
|
if status == 200:
|
|
await message.channel.send(
|
|
f"**{resp.get('routine_name')}**\n"
|
|
f"Current streak: {resp.get('current_streak')} days\n"
|
|
f"Longest streak: {resp.get('longest_streak')} days"
|
|
)
|
|
else:
|
|
await message.channel.send(f"Error: {resp.get('error', 'Failed to fetch streak')}")
|
|
|
|
elif action == "templates":
|
|
resp, status = api_request("get", "/api/templates", token)
|
|
if status == 200:
|
|
templates = resp if isinstance(resp, list) else []
|
|
if not templates:
|
|
await message.channel.send("No templates available yet.")
|
|
else:
|
|
lines = [f"- **{t['name']}**: {t.get('description', 'No description')}" for t in templates[:10]]
|
|
await message.channel.send("**Available templates:**\n" + "\n".join(lines))
|
|
else:
|
|
await message.channel.send(f"Error: {resp.get('error', 'Failed to fetch templates')}")
|
|
|
|
elif action == "clone":
|
|
template_id = parsed.get("template_id")
|
|
if not template_id:
|
|
await message.channel.send("Which template would you like to clone?")
|
|
return
|
|
resp, status = api_request("post", f"/api/templates/{template_id}/clone", token)
|
|
if status == 201:
|
|
await message.channel.send(f"Cloned! Created routine: **{resp.get('name')}**")
|
|
else:
|
|
await message.channel.send(f"Error: {resp.get('error', 'Failed to clone template')}")
|
|
|
|
elif action == "tag":
|
|
routine_id = parsed.get("routine_id")
|
|
tag_name = parsed.get("tag")
|
|
if not routine_id or not tag_name:
|
|
await message.channel.send("Please specify routine and tag.")
|
|
return
|
|
tags_resp, _ = api_request("get", "/api/tags", token)
|
|
existing_tag = next((t for t in tags_resp if t.get("name", "").lower() == tag_name.lower()), None)
|
|
if existing_tag:
|
|
tag_id = existing_tag["id"]
|
|
else:
|
|
tag_resp, tag_status = api_request("post", "/api/tags", token, {"name": tag_name})
|
|
if tag_status == 201:
|
|
tag_id = tag_resp["id"]
|
|
else:
|
|
await message.channel.send(f"Error creating tag: {tag_resp.get('error')}")
|
|
return
|
|
resp, status = api_request("post", f"/api/routines/{routine_id}/tags", token, {"tag_ids": [tag_id]})
|
|
if status == 200:
|
|
await message.channel.send(f"Added tag **{tag_name}** to routine!")
|
|
else:
|
|
await message.channel.send(f"Error: {resp.get('error', 'Failed to add tag')}")
|
|
|
|
else:
|
|
await message.channel.send(f"Unknown action: {action}. Try: list, create, start, complete, skip, cancel, history, pause, resume, abort, note, stats, streak, templates, clone, or tag.")
|
|
|
|
|
|
def api_request(method, endpoint, token, data=None):
|
|
import requests
|
|
import os
|
|
API_URL = os.getenv("API_URL", "http://app:5000")
|
|
url = f"{API_URL}{endpoint}"
|
|
headers = {"Content-Type": "application/json", "Authorization": f"Bearer {token}"}
|
|
try:
|
|
resp = getattr(requests, method)(url, headers=headers, json=data, timeout=10)
|
|
try:
|
|
return resp.json(), resp.status_code
|
|
except ValueError:
|
|
return {}, resp.status_code
|
|
except requests.RequestException:
|
|
return {"error": "API unavailable"}, 503
|
|
|
|
|
|
def validate_routine_json(data):
|
|
errors = []
|
|
if not isinstance(data, dict):
|
|
return ["Response must be a JSON object"]
|
|
if "error" in data:
|
|
return []
|
|
if "action" not in data:
|
|
errors.append("Missing required field: action")
|
|
return errors
|
|
|
|
|
|
register_module("routine", handle_routine)
|
|
ai_parser.register_validator("routine", validate_routine_json)
|