Skip to content

Commit 557bf61

Browse files
authored
Merge pull request #280 from Tanzania-AI-Community/feature/send_reminder_message_to_user_on_demand
feat: Send Reminder To Users via Template
2 parents 987b557 + 9c9ae56 commit 557bf61

13 files changed

Lines changed: 810 additions & 16 deletions
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
{
2+
"name": "twiga_inactive_reminder",
3+
"category": "UTILITY",
4+
"language": "en_US",
5+
"allow_category_change": true,
6+
"components": [
7+
{
8+
"type": "BODY",
9+
"text": "📚 Friendly reminder from Twiga 🦒: if you're planning lessons this week, I can help you prepare in minutes."
10+
}
11+
]
12+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
{
2+
"name": "twiga_inactive_reminder_with_name",
3+
"category": "UTILITY",
4+
"language": "en_US",
5+
"allow_category_change": true,
6+
"components": [
7+
{
8+
"type": "BODY",
9+
"text": "👋 Hi {{1}}! Twiga 🦒 is here whenever you need quick lesson support, activities, or class explanations.",
10+
"example": {
11+
"body_text": [
12+
[
13+
"Teacher"
14+
]
15+
]
16+
}
17+
}
18+
]
19+
}

‎app/database/db.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,7 @@ async def create_new_message_by_fields(
300300
tool_calls: list[dict] | None = None,
301301
tool_call_id: str | None = None,
302302
tool_name: str | None = None,
303+
cron_name: enums.MessageCronName | None = None,
303304
) -> Message:
304305
message = Message(
305306
user_id=user_id,
@@ -310,6 +311,7 @@ async def create_new_message_by_fields(
310311
tool_calls=tool_calls,
311312
tool_call_id=tool_call_id,
312313
tool_name=tool_name,
314+
cron_name=cron_name,
313315
)
314316
return await create_new_message(message)
315317

‎app/database/enums.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,10 @@ class MessageRole(str, Enum):
2424
system = "system"
2525

2626

27+
class MessageCronName(str, Enum):
28+
send_reminder_messages_cron = "send_reminder_messages_cron"
29+
30+
2731
class GradeLevel(str, Enum):
2832
p1 = "p1"
2933
p2 = "p2"

‎app/database/models.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,7 @@ class Message(SQLModel, table=True):
211211
tool_calls: Optional[list[dict]] = Field(default=None, sa_column=Column(JSON))
212212
tool_call_id: Optional[str] = Field(default=None)
213213
tool_name: Optional[str] = Field(default=None, max_length=50)
214+
cron_name: Optional[enums.MessageCronName] = Field(default=None, max_length=100)
214215
created_at: Optional[datetime] = Field(
215216
default_factory=lambda: datetime.now(timezone.utc),
216217
sa_type=DateTime(timezone=True), # type: ignore

‎app/utils/string_manager.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ class StringCategory(str, Enum):
2222
SETTINGS = "settings"
2323
FLOWS = "flows"
2424
RATE_LIMIT = "rate_limit"
25+
REMINDER = "reminder"
2526

2627

2728
class StringResources:
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""Add cron_name to messages
2+
3+
Revision ID: a1f4c7e2d3b9
4+
Revises: 9a7d3f1c2b44
5+
Create Date: 2026-04-22 00:00:00.000000
6+
7+
"""
8+
9+
from typing import Sequence, Union
10+
11+
import sqlalchemy as sa
12+
from alembic import op
13+
14+
# revision identifiers, used by Alembic.
15+
revision: str = "a1f4c7e2d3b9"
16+
down_revision: Union[str, None] = "9a7d3f1c2b44"
17+
branch_labels: Union[str, Sequence[str], None] = None
18+
depends_on: Union[str, Sequence[str], None] = None
19+
20+
21+
MESSAGE_CRON_ENUM_NAME = "messagecronname"
22+
MESSAGE_CRON_VALUES = ("send_reminder_messages_cron",)
23+
24+
25+
def upgrade() -> None:
26+
message_cron_enum = sa.Enum(*MESSAGE_CRON_VALUES, name=MESSAGE_CRON_ENUM_NAME)
27+
message_cron_enum.create(op.get_bind(), checkfirst=True)
28+
29+
op.add_column(
30+
"messages",
31+
sa.Column("cron_name", message_cron_enum, nullable=True),
32+
)
33+
34+
35+
def downgrade() -> None:
36+
op.drop_column("messages", "cron_name")
37+
38+
message_cron_enum = sa.Enum(*MESSAGE_CRON_VALUES, name=MESSAGE_CRON_ENUM_NAME)
39+
message_cron_enum.drop(op.get_bind(), checkfirst=True)

‎scripts/crons/helpers/__init__.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,11 @@
77

88
from .database import (
99
create_message,
10+
create_messages,
1011
get_database_url,
1112
get_session,
1213
get_users_by_state,
14+
get_users_for_reminder,
1315
get_users_to_mark_inactive,
1416
initialize_db,
1517
update_user,
@@ -23,8 +25,10 @@
2325
"get_session",
2426
"get_users_by_state",
2527
"get_users_to_mark_inactive",
28+
"get_users_for_reminder",
2629
"update_user",
2730
"create_message",
31+
"create_messages",
2832
"WhatsAppClient",
2933
"setup_logging",
3034
]

‎scripts/crons/helpers/database.py‎

Lines changed: 85 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,16 @@
1010
# Import from app directory
1111
import sys
1212
from contextlib import asynccontextmanager
13-
from datetime import datetime, timedelta
13+
from datetime import datetime, timedelta, timezone
1414
from urllib.parse import urlparse
1515

1616
from sqlalchemy import func, text
1717
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
18-
from sqlmodel import and_, select
18+
from sqlmodel import and_, or_, select
1919

2020
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", ".."))
2121

22-
from app.database.enums import UserState
22+
from app.database.enums import MessageCronName, MessageRole, UserState
2323
from app.database.models import Message, User
2424

2525

@@ -181,6 +181,69 @@ async def get_users_to_mark_inactive(hours_threshold: int) -> list[User]:
181181
return list(result.scalars().all())
182182

183183

184+
async def get_users_for_reminder(
185+
inactivity_days: int,
186+
reminder_cooldown_days: int,
187+
) -> list[User]:
188+
"""
189+
Get users eligible for reminder messages.
190+
191+
A user is eligible when:
192+
- Their state is active, inactive or onboarding
193+
- They have a non-null last_message_at timestamp
194+
- Their last_message_at is older than inactivity_days
195+
- They have not received a reminder in the last reminder_cooldown_days
196+
197+
Reminder messages are tracked by assistant messages with
198+
cron_name == "send_reminder_messages_cron".
199+
"""
200+
async with get_session() as session:
201+
inactivity_threshold = datetime.now(timezone.utc) - timedelta(
202+
days=inactivity_days
203+
)
204+
cooldown_threshold = datetime.now(timezone.utc) - timedelta(
205+
days=reminder_cooldown_days
206+
)
207+
208+
reminder_history_subquery = (
209+
select(
210+
Message.user_id.label("user_id"),
211+
func.max(Message.created_at).label("last_reminder_at"),
212+
)
213+
.where(
214+
and_(
215+
Message.role == MessageRole.assistant,
216+
Message.cron_name == MessageCronName.send_reminder_messages_cron,
217+
)
218+
)
219+
.group_by(Message.user_id)
220+
.subquery()
221+
)
222+
223+
statement = (
224+
select(User)
225+
.outerjoin(
226+
reminder_history_subquery,
227+
User.id == reminder_history_subquery.c.user_id,
228+
)
229+
.where(
230+
and_(
231+
User.state.in_([UserState.active, UserState.inactive, UserState.onboarding]), # type: ignore
232+
User.last_message_at.is_not(None),
233+
User.last_message_at < inactivity_threshold,
234+
or_(
235+
reminder_history_subquery.c.last_reminder_at.is_(None),
236+
reminder_history_subquery.c.last_reminder_at
237+
< cooldown_threshold,
238+
),
239+
)
240+
)
241+
)
242+
243+
result = await session.execute(statement)
244+
return list(result.scalars().all())
245+
246+
184247
async def update_user(user: User) -> User:
185248
"""
186249
Update a user in the database.
@@ -213,3 +276,22 @@ async def create_message(message: Message) -> Message:
213276
await session.commit()
214277
await session.refresh(message)
215278
return message
279+
280+
281+
async def create_messages(*, messages: list[Message]) -> list[Message]:
282+
"""
283+
Create multiple messages in one database operation.
284+
285+
Args:
286+
messages: Message objects to create
287+
288+
Returns:
289+
list[Message]: Created message objects
290+
"""
291+
if len(messages) == 0:
292+
return []
293+
294+
async with get_session() as session:
295+
session.add_all(messages)
296+
await session.flush()
297+
return messages

‎scripts/crons/helpers/whatsapp.py‎

Lines changed: 35 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,8 @@ async def send_template_message(
7171
wa_id: str,
7272
template_name: str,
7373
language_code: str = "en_US",
74+
body_text_params: list[str] | None = None,
75+
include_image_header: bool = True,
7476
) -> None:
7577
"""
7678
Send a WhatsApp template message.
@@ -79,6 +81,8 @@ async def send_template_message(
7981
wa_id: WhatsApp ID (phone number) of recipient
8082
template_name: Name of the approved template message
8183
language_code: Language code for the template (default: "en_US")
84+
body_text_params: Optional body text placeholders for template variables
85+
include_image_header: Whether to include the default image header component
8286
8387
Raises:
8488
httpx.HTTPStatusError: If API request fails
@@ -89,29 +93,47 @@ async def send_template_message(
8993
return
9094

9195
try:
96+
components: list[dict] = []
97+
98+
if include_image_header:
99+
components.append(
100+
{
101+
"type": "header",
102+
"parameters": [
103+
{
104+
"type": "image",
105+
"image": {
106+
"link": "https://twiga.ai.or.tz/external/classroom-image.jpeg"
107+
},
108+
}
109+
],
110+
}
111+
)
112+
113+
if body_text_params:
114+
components.append(
115+
{
116+
"type": "body",
117+
"parameters": [
118+
{"type": "text", "text": value}
119+
for value in body_text_params
120+
],
121+
}
122+
)
123+
92124
payload = {
93125
"messaging_product": "whatsapp",
94126
"to": wa_id,
95127
"type": "template",
96128
"template": {
97129
"name": template_name,
98130
"language": {"code": language_code},
99-
"components": [
100-
{
101-
"type": "header",
102-
"parameters": [
103-
{
104-
"type": "image",
105-
"image": {
106-
"link": "https://twiga.ai.or.tz/external/classroom-image.jpeg"
107-
},
108-
}
109-
],
110-
}
111-
],
112131
},
113132
}
114133

134+
if components:
135+
payload["template"]["components"] = components
136+
115137
response = await self.client.post(
116138
"/messages",
117139
json=payload,

0 commit comments

Comments
 (0)