fix: include scheduled_time when logging medication intake from reminders

This commit is contained in:
2026-02-16 12:13:25 -06:00
parent 398e1ce334
commit 9cc2f19ce8
3 changed files with 1852 additions and 93 deletions

View File

@@ -3,10 +3,46 @@ Medications command handler - bot-side hooks for medication management
"""
import asyncio
import re
from bot.command_registry import register_module
import ai.parser as ai_parser
async def _get_scheduled_time_from_context(message, med_name):
"""Fetch recent messages and extract scheduled time from medication reminder.
Looks for bot messages in the last 5 messages that match the pattern:
"Time to take {med_name} (...) · HH:MM"
Returns the scheduled time string (e.g., "12:00") or None if not found.
"""
try:
# Get last 5 messages from channel history
async for msg in message.channel.history(limit=5):
# Skip the current message
if msg.id == message.id:
continue
# Check if this is a bot message
if not msg.author.bot:
continue
content = msg.content
# Look for reminder pattern: "Time to take {med_name} (...) · HH:MM"
# Use case-insensitive match for medication name
pattern = rf"Time to take {re.escape(med_name)}.*?·\s*(\d{{1,2}}:\d{{2}})"
match = re.search(pattern, content, re.IGNORECASE)
if match:
return match.group(1)
except Exception:
pass
return None
async def handle_medication(message, session, parsed):
action = parsed.get("action", "unknown")
token = session["token"]
@@ -19,10 +55,15 @@ async def handle_medication(message, session, parsed):
if not meds:
await message.channel.send("You don't have any medications yet.")
else:
lines = [f"- **{m['name']}**: {m['dosage']} {m['unit']} ({m.get('frequency', 'n/a')})" for m in meds]
lines = [
f"- **{m['name']}**: {m['dosage']} {m['unit']} ({m.get('frequency', 'n/a')})"
for m in meds
]
await message.channel.send("**Your medications:**\n" + "\n".join(lines))
else:
await message.channel.send(f"Error: {resp.get('error', 'Failed to fetch medications')}")
await message.channel.send(
f"Error: {resp.get('error', 'Failed to fetch medications')}"
)
elif action == "add":
name = parsed.get("name")
@@ -54,10 +95,12 @@ async def handle_medication(message, session, parsed):
"frequency": frequency,
"times": times,
"days_of_week": days_of_week,
"interval_days": interval_days
"interval_days": interval_days,
}
schedule_desc = _format_schedule(frequency, times, days_of_week, interval_days)
schedule_desc = _format_schedule(
frequency, times, days_of_week, interval_days
)
await message.channel.send(
f"{confirmation_prompt}\n\n"
f"**Details:**\n"
@@ -68,13 +111,25 @@ async def handle_medication(message, session, parsed):
)
return
await _add_medication(message, token, name, dosage, unit, frequency, times, days_of_week, interval_days)
await _add_medication(
message,
token,
name,
dosage,
unit,
frequency,
times,
days_of_week,
interval_days,
)
elif action == "take":
med_id = parsed.get("medication_id")
name = parsed.get("name")
med_id, name, found = await _find_medication_by_name(message, token, med_id, name)
med_id, name, found = await _find_medication_by_name(
message, token, med_id, name
)
if not found:
return
@@ -82,9 +137,26 @@ async def handle_medication(message, session, parsed):
await message.channel.send("Which medication did you take?")
return
resp, status = api_request("post", f"/api/medications/{med_id}/take", token, {})
# Try to get scheduled time from recent reminder context
scheduled_time = await _get_scheduled_time_from_context(message, name)
# Build request body with scheduled_time if found
request_body = {}
if scheduled_time:
request_body["scheduled_time"] = scheduled_time
resp, status = api_request(
"post", f"/api/medications/{med_id}/take", token, request_body
)
if status == 201:
await message.channel.send(f"Logged **{name}**! Great job staying on track.")
if scheduled_time:
await message.channel.send(
f"✅ Logged **{name}** for {scheduled_time}! Great job staying on track."
)
else:
await message.channel.send(
f"Logged **{name}**! Great job staying on track."
)
else:
await message.channel.send(f"Error: {resp.get('error', 'Failed to log')}")
@@ -93,7 +165,9 @@ async def handle_medication(message, session, parsed):
name = parsed.get("name")
reason = parsed.get("reason", "Skipped by user")
med_id, name, found = await _find_medication_by_name(message, token, med_id, name)
med_id, name, found = await _find_medication_by_name(
message, token, med_id, name
)
if not found:
return
@@ -101,7 +175,17 @@ async def handle_medication(message, session, parsed):
await message.channel.send("Which medication are you skipping?")
return
resp, status = api_request("post", f"/api/medications/{med_id}/skip", token, {"reason": reason})
# Try to get scheduled time from recent reminder context
scheduled_time = await _get_scheduled_time_from_context(message, name)
# Build request body with scheduled_time if found
request_body = {"reason": reason}
if scheduled_time:
request_body["scheduled_time"] = scheduled_time
resp, status = api_request(
"post", f"/api/medications/{med_id}/skip", token, request_body
)
if status == 201:
await message.channel.send(f"Skipped **{name}**. {reason}")
else:
@@ -127,7 +211,9 @@ async def handle_medication(message, session, parsed):
if is_prn:
status_icon = "💊"
lines.append(f"{status_icon} **{med_name}** {dosage} (as needed)")
lines.append(
f"{status_icon} **{med_name}** {dosage} (as needed)"
)
elif times:
for time in times:
if time in taken:
@@ -136,11 +222,15 @@ async def handle_medication(message, session, parsed):
status_icon = "⏭️"
else:
status_icon = ""
lines.append(f"{status_icon} **{med_name}** {dosage} at {time}")
lines.append(
f"{status_icon} **{med_name}** {dosage} at {time}"
)
else:
lines.append(f"💊 **{med_name}** {dosage}")
await message.channel.send("**Today's Medications:**\n" + "\n".join(lines))
await message.channel.send(
"**Today's Medications:**\n" + "\n".join(lines)
)
else:
error_msg = "Failed to fetch today's schedule"
await message.channel.send(f"Error: {resp.get('error', error_msg)}")
@@ -165,14 +255,18 @@ async def handle_medication(message, session, parsed):
await message.channel.send("**Refills Due:**\n" + "\n".join(lines))
else:
await message.channel.send(f"Error: {resp.get('error', 'Failed to fetch refills')}")
await message.channel.send(
f"Error: {resp.get('error', 'Failed to fetch refills')}"
)
elif action == "snooze":
med_id = parsed.get("medication_id")
name = parsed.get("name")
minutes = parsed.get("minutes", 15)
med_id, name, found = await _find_medication_by_name(message, token, med_id, name)
med_id, name, found = await _find_medication_by_name(
message, token, med_id, name
)
if not found:
return
@@ -180,11 +274,15 @@ async def handle_medication(message, session, parsed):
await message.channel.send("Which medication reminder should I snooze?")
return
resp, status = api_request("post", f"/api/medications/{med_id}/snooze", token, {"minutes": minutes})
resp, status = api_request(
"post", f"/api/medications/{med_id}/snooze", token, {"minutes": minutes}
)
if status == 200:
await message.channel.send(f"⏰ Snoozed **{name}** for {minutes} minutes.")
else:
await message.channel.send(f"Error: {resp.get('error', 'Failed to snooze')}")
await message.channel.send(
f"Error: {resp.get('error', 'Failed to snooze')}"
)
elif action == "adherence":
med_id = parsed.get("medication_id")
@@ -192,12 +290,16 @@ async def handle_medication(message, session, parsed):
if name and not med_id:
# Look up by name first
med_id, name, found = await _find_medication_by_name(message, token, None, name)
med_id, name, found = await _find_medication_by_name(
message, token, None, name
)
if not found:
return
if med_id:
resp, status = api_request("get", f"/api/medications/{med_id}/adherence", token)
resp, status = api_request(
"get", f"/api/medications/{med_id}/adherence", token
)
else:
resp, status = api_request("get", "/api/medications/adherence", token)
@@ -205,14 +307,18 @@ async def handle_medication(message, session, parsed):
if isinstance(resp, list):
lines = []
for m in resp:
adherence = m.get('adherence_percent')
adherence = m.get("adherence_percent")
if adherence is not None:
lines.append(f"- **{m['name']}**: {adherence}% adherence ({m.get('taken', 0)}/{m.get('expected', 0)} doses)")
lines.append(
f"- **{m['name']}**: {adherence}% adherence ({m.get('taken', 0)}/{m.get('expected', 0)} doses)"
)
else:
lines.append(f"- **{m['name']}**: PRN medication (no adherence tracking)")
lines.append(
f"- **{m['name']}**: PRN medication (no adherence tracking)"
)
await message.channel.send("**Adherence Stats:**\n" + "\n".join(lines))
else:
adherence = resp.get('adherence_percent')
adherence = resp.get("adherence_percent")
if adherence is not None:
await message.channel.send(
f"**{resp.get('name')}**:\n"
@@ -221,16 +327,22 @@ async def handle_medication(message, session, parsed):
f"- Skipped: {resp.get('skipped', 0)}"
)
else:
await message.channel.send(f"**{resp.get('name')}**: PRN medication (no adherence tracking)")
await message.channel.send(
f"**{resp.get('name')}**: PRN medication (no adherence tracking)"
)
else:
await message.channel.send(f"Error: {resp.get('error', 'Failed to fetch adherence')}")
await message.channel.send(
f"Error: {resp.get('error', 'Failed to fetch adherence')}"
)
elif action == "delete":
med_id = parsed.get("medication_id")
name = parsed.get("name")
needs_confirmation = parsed.get("needs_confirmation", True)
med_id, name, found = await _find_medication_by_name(message, token, med_id, name)
med_id, name, found = await _find_medication_by_name(
message, token, med_id, name
)
if not found:
return
@@ -249,7 +361,7 @@ async def handle_medication(message, session, parsed):
"interaction_type": "medication",
"medication_id": med_id,
"name": name,
"needs_confirmation": False # Skip confirmation next time
"needs_confirmation": False, # Skip confirmation next time
}
await message.channel.send(
@@ -264,20 +376,26 @@ async def handle_medication(message, session, parsed):
if status == 200:
await message.channel.send(f"🗑️ Deleted **{name}** and all its logs.")
else:
await message.channel.send(f"Error: {resp.get('error', 'Failed to delete medication')}")
await message.channel.send(
f"Error: {resp.get('error', 'Failed to delete medication')}"
)
else:
await message.channel.send(f"Unknown action: {action}. Try: list, add, delete, take, skip, today, refills, snooze, or adherence.")
await message.channel.send(
f"Unknown action: {action}. Try: list, add, delete, take, skip, today, refills, snooze, or adherence."
)
async def _add_medication(message, token, name, dosage, unit, frequency, times, days_of_week, interval_days):
async def _add_medication(
message, token, name, dosage, unit, frequency, times, days_of_week, interval_days
):
"""Helper to add a medication."""
data = {
"name": name,
"dosage": dosage,
"unit": unit,
"frequency": frequency,
"times": times
"times": times,
}
# Add optional fields if present
@@ -289,11 +407,15 @@ async def _add_medication(message, token, name, dosage, unit, frequency, times,
resp, status = api_request("post", "/api/medications", token, data)
if status == 201:
schedule_desc = _format_schedule(frequency, times, days_of_week, interval_days)
await message.channel.send(f"✅ Added **{name}** ({dosage} {unit}) - {schedule_desc}")
await message.channel.send(
f"✅ Added **{name}** ({dosage} {unit}) - {schedule_desc}"
)
else:
error_msg = resp.get('error', 'Failed to add medication')
error_msg = resp.get("error", "Failed to add medication")
if "invalid input syntax" in error_msg.lower():
await message.channel.send(f"Error: I couldn't understand the schedule format. Try saying it differently, like 'every day at 9am' or 'on Monday and Wednesday at 8pm'.")
await message.channel.send(
f"Error: I couldn't understand the schedule format. Try saying it differently, like 'every day at 9am' or 'on Monday and Wednesday at 8pm'."
)
else:
await message.channel.send(f"Error: {error_msg}")
@@ -315,28 +437,34 @@ async def _find_medication_by_name(message, token, med_id, name):
meds = resp if isinstance(resp, list) else []
# Try exact match first
matching = [m for m in meds if m['name'].lower() == name.lower()]
matching = [m for m in meds if m["name"].lower() == name.lower()]
# Then try partial match
if not matching:
matching = [m for m in meds if name.lower() in m['name'].lower() or m['name'].lower() in name.lower()]
matching = [
m
for m in meds
if name.lower() in m["name"].lower() or m["name"].lower() in name.lower()
]
if not matching:
await message.channel.send(f"❌ I couldn't find a medication called '{name}'.\n\nYour medications:\n" +
"\n".join([f"- {m['name']}" for m in meds[:10]]))
await message.channel.send(
f"❌ I couldn't find a medication called '{name}'.\n\nYour medications:\n"
+ "\n".join([f"- {m['name']}" for m in meds[:10]])
)
return None, None, False
if len(matching) > 1:
# Multiple matches - show list
lines = [f"{i + 1}. {m['name']}" for i, m in enumerate(matching[:5])]
await message.channel.send(
f"🔍 I found multiple medications matching '{name}':\n" +
"\n".join(lines) +
"\n\nPlease specify which one (e.g., 'take 1' or say the full name)."
f"🔍 I found multiple medications matching '{name}':\n"
+ "\n".join(lines)
+ "\n\nPlease specify which one (e.g., 'take 1' or say the full name)."
)
return None, None, False
return matching[0]['id'], matching[0]['name'], True
return matching[0]["id"], matching[0]["name"], True
def _format_schedule(frequency, times, days_of_week, interval_days):
@@ -346,7 +474,7 @@ def _format_schedule(frequency, times, days_of_week, interval_days):
elif frequency == "twice_daily":
return f"twice daily at {', '.join(times)}"
elif frequency == "specific_days":
days_str = ', '.join(days_of_week) if days_of_week else 'certain days'
days_str = ", ".join(days_of_week) if days_of_week else "certain days"
return f"on {days_str} at {', '.join(times)}"
elif frequency == "every_n_days":
return f"every {interval_days} days at {', '.join(times)}"
@@ -359,6 +487,7 @@ def _format_schedule(frequency, times, days_of_week, interval_days):
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}"}

File diff suppressed because it is too large Load Diff

View File

@@ -33,6 +33,7 @@ def check_medication_reminders():
"""Check for medications due now and send notifications."""
try:
from datetime import date as date_type
meds = postgres.select("medications", where={"active": True})
# Group by user so we only look up timezone once per user
@@ -68,8 +69,14 @@ def check_medication_reminders():
start = med.get("start_date")
interval = med.get("interval_days")
if start and interval:
start_d = start if isinstance(start, date_type) else datetime.strptime(str(start), "%Y-%m-%d").date()
if (today - start_d).days < 0 or (today - start_d).days % interval != 0:
start_d = (
start
if isinstance(start, date_type)
else datetime.strptime(str(start), "%Y-%m-%d").date()
)
if (today - start_d).days < 0 or (
today - start_d
).days % interval != 0:
continue
else:
continue
@@ -80,7 +87,9 @@ def check_medication_reminders():
continue
# Already taken today? Check by created_at date
logs = postgres.select("med_logs", where={"medication_id": med["id"], "action": "taken"})
logs = postgres.select(
"med_logs", where={"medication_id": med["id"], "action": "taken"}
)
already_taken = any(
log.get("scheduled_time") == current_time
and str(log.get("created_at", ""))[:10] == today_str
@@ -91,8 +100,10 @@ def check_medication_reminders():
user_settings = notifications.getNotificationSettings(user_uuid)
if user_settings:
msg = f"Time to take {med['name']} ({med['dosage']} {med['unit']})"
notifications._sendToEnabledChannels(user_settings, msg, user_uuid=user_uuid)
msg = f"Time to take {med['name']} ({med['dosage']} {med['unit']}) · {current_time}"
notifications._sendToEnabledChannels(
user_settings, msg, user_uuid=user_uuid
)
except Exception as e:
logger.error(f"Error checking medication reminders: {e}")
@@ -120,7 +131,9 @@ def check_routine_reminders():
user_settings = notifications.getNotificationSettings(routine["user_uuid"])
if user_settings:
msg = f"Time to start your routine: {routine['name']}"
notifications._sendToEnabledChannels(user_settings, msg, user_uuid=routine["user_uuid"])
notifications._sendToEnabledChannels(
user_settings, msg, user_uuid=routine["user_uuid"]
)
except Exception as e:
logger.error(f"Error checking routine reminders: {e}")
@@ -135,7 +148,9 @@ def check_refills():
user_settings = notifications.getNotificationSettings(med["user_uuid"])
if user_settings:
msg = f"Low on {med['name']}: only {qty} doses remaining. Time to refill!"
notifications._sendToEnabledChannels(user_settings, msg, user_uuid=med["user_uuid"])
notifications._sendToEnabledChannels(
user_settings, msg, user_uuid=med["user_uuid"]
)
except Exception as e:
logger.error(f"Error checking refills: {e}")