64 lines
2.5 KiB
Python
64 lines
2.5 KiB
Python
import logging
|
|
from typing import Optional
|
|
from twilio.rest import Client
|
|
from twilio.base.exceptions import TwilioException
|
|
from app.core.config import settings
|
|
from app.models.task import Task
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class WhatsAppService:
|
|
def __init__(self):
|
|
if settings.TWILIO_ACCOUNT_SID and settings.TWILIO_AUTH_TOKEN:
|
|
self.client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN)
|
|
else:
|
|
self.client = None
|
|
logger.warning("Twilio credentials not configured. WhatsApp functionality disabled.")
|
|
|
|
def send_message(self, to_number: str, message: str) -> bool:
|
|
if not self.client:
|
|
logger.error("WhatsApp service not configured")
|
|
return False
|
|
|
|
try:
|
|
# Ensure phone number is in WhatsApp format
|
|
if not to_number.startswith("whatsapp:"):
|
|
to_number = f"whatsapp:{to_number}"
|
|
|
|
message = self.client.messages.create(
|
|
body=message,
|
|
from_=settings.TWILIO_WHATSAPP_FROM,
|
|
to=to_number
|
|
)
|
|
logger.info(f"WhatsApp message sent successfully. SID: {message.sid}")
|
|
return True
|
|
except TwilioException as e:
|
|
logger.error(f"Failed to send WhatsApp message: {str(e)}")
|
|
return False
|
|
except Exception as e:
|
|
logger.error(f"Unexpected error sending WhatsApp message: {str(e)}")
|
|
return False
|
|
|
|
|
|
whatsapp_service = WhatsAppService()
|
|
|
|
|
|
def send_task_reminder(phone_number: str, task: Task) -> bool:
|
|
due_info = f" (Due: {task.due_date.strftime('%Y-%m-%d %H:%M')})" if task.due_date else ""
|
|
message = f"🔔 Task Reminder: {task.title}\n\n{task.description or 'No description provided'}{due_info}\n\nPriority: {task.priority.value.upper()}"
|
|
|
|
return whatsapp_service.send_message(phone_number, message)
|
|
|
|
|
|
def send_task_completion(phone_number: str, task: Task) -> bool:
|
|
message = f"✅ Task Completed: {task.title}\n\nCongratulations! You've successfully completed this task."
|
|
|
|
return whatsapp_service.send_message(phone_number, message)
|
|
|
|
|
|
def send_task_overdue(phone_number: str, task: Task) -> bool:
|
|
overdue_days = (task.due_date - task.created_at).days if task.due_date else 0
|
|
message = f"⚠️ Task Overdue: {task.title}\n\nThis task is overdue by {overdue_days} days. Please complete it as soon as possible.\n\nPriority: {task.priority.value.upper()}"
|
|
|
|
return whatsapp_service.send_message(phone_number, message) |