# -*- coding: utf-8 -*- """ WhatsApp / SMS Delivery Service for Diabetes Dost. • If TWILIO_ACCOUNT_SID + TWILIO_AUTH_TOKEN are set → uses real Twilio API. • Otherwise → logs a mock delivery and saves PDF locally, returning a local URL. Gracefully degrades — no crash if twilio package is absent. """ import os import io import json import logging import urllib.request import urllib.parse import base64 from typing import Dict, Any, Optional from pathlib import Path from datetime import datetime logger = logging.getLogger("sehat_whatsapp") # ── Try Twilio ──────────────────────────────────────────────────────────────── try: from twilio.rest import Client as TwilioClient # type: ignore TWILIO_SDK_AVAILABLE = True except ImportError: TWILIO_SDK_AVAILABLE = False logger.info("twilio SDK not installed — using mock WhatsApp delivery.") PDF_DELIVERY_DIR = Path(__file__).resolve().parent.parent / "outputs" / "reports" / "pdf_reports" PDF_DELIVERY_DIR.mkdir(parents=True, exist_ok=True) # ── Follow-up / Reminder Message Templates ─────────────────────────────────── FOLLOWUP_TEMPLATES = { "hba1c_reminder": { "label": "HbA1c तपासणी स्मरण", "icon": "🩸", "mr": ( "🏥 *दीनानाथ मंगेशकर हॉस्पिटल — Diabetes Dost*\n\n" "नमस्कार {name} जी! 🙏\n\n" "🩸 *HbA1c तपासणीचे स्मरण*\n" "तुमची शेवटची Diabetes Dost सल्लामसलत: *{date}*\n\n" "तुम्हाला आठवण करून देतो की दर *3 महिन्यांनी* HbA1c तपासणी करणे आवश्यक आहे.\n" "HbA1c < 7% ठेवणे हे मधुमेह नियंत्रणाचे लक्षण आहे. ✅\n\n" "📍 तपासणी करा: DMH Pathology Lab, Pune\n" "📞 अपॉइंटमेंट: 020-66023000\n\n" "⚠️ हे AI-आधारित स्मरण आहे. डॉक्टरांचा सल्ला घ्या." ), "hi": ( "🏥 *दीनानाथ मंगेशकर अस्पताल — Diabetes Dost*\n\n" "नमस्ते {name} जी! 🙏\n\n" "🩸 *HbA1c जांच का रिमाइंडर*\n" "आपकी अंतिम Diabetes Dost परामर्श: *{date}*\n\n" "हर *3 महीने* में HbA1c जांच करवाना जरूरी है।\n" "HbA1c < 7% = अच्छा मधुमेह नियंत्रण ✅\n\n" "📍 जांच करें: DMH Pathology Lab, Pune\n" "📞 अपॉइंटमेंट: 020-66023000\n\n" "⚠️ यह AI रिमाइंडर है। डॉक्टर से परामर्श करें।" ) }, "medication_reminder": { "label": "औषध घेण्याची आठवण", "icon": "💊", "mr": ( "🏥 *Diabetes Dost — दीनानाथ मंगेशकर हॉस्पिटल*\n\n" "नमस्कार {name} जी! 🙏\n\n" "💊 *औषधांची आठवण (Medication Reminder)*\n\n" "तुमच्या डॉक्टरांनी सांगितलेली औषधे वेळेवर घेत आहात का?\n\n" "✅ *महत्त्वाचे:*\n" "• सकाळी जेवणापूर्वी Metformin / Glimepiride घ्या\n" "• इन्सुलिन असल्यास जेवणाच्या 15 मिनिटे आधी\n" "• औषध कधीही डॉक्टरांच्या सल्ल्याशिवाय बंद करू नका\n\n" "📞 DMH Helpline: 020-66023000\n" "💬 Session ID: {session_id}" ), "hi": ( "🏥 *Diabetes Dost — दीनानाथ मंगेशकर अस्पताल*\n\n" "नमस्ते {name} जी! 🙏\n\n" "💊 *दवा लेने का रिमाइंडर*\n\n" "क्या आप अपनी दवाएं समय पर ले रहे हैं?\n\n" "✅ *ध्यान रखें:*\n" "• सुबह खाने से पहले Metformin / Glimepiride\n" "• इंसुलिन हो तो खाने से 15 मिनट पहले\n" "• बिना डॉक्टर की सलाह दवा बंद न करें\n\n" "📞 DMH Helpline: 020-66023000" ) }, "diet_reminder": { "label": "आहार व व्यायाम स्मरण", "icon": "🥗", "mr": ( "🏥 *Diabetes Dost — दीनानाथ मंगेशकर हॉस्पिटल*\n\n" "नमस्कार {name} जी! 🙏\n\n" "🥗 *आहार व जीवनशैली स्मरण*\n\n" "तुमच्या IDRS Score नुसार या गोष्टी लक्षात ठेवा:\n\n" "🌿 *आहार:*\n" "• मेथी दाण्यांचे पाणी — सकाळी रिकाम्या पोटी\n" "• ज्वारी / बाजरी भाकरी — पांढऱ्या तांदळाऐवजी\n" "• मूग डाळ, पालेभाज्या — रोज\n" "• साखर, मैदा, बटाटा — टाळा\n\n" "🚶 *व्यायाम:*\n" "रोज 30–45 मिनिटे चालणे किंवा योगा करा.\n\n" "📞 DMH: 020-66023000 | 💬 Session: {session_id}" ), "hi": ( "🏥 *Diabetes Dost — दीनानाथ मंगेशकर अस्पताल*\n\n" "नमस्ते {name} जी! 🙏\n\n" "🥗 *आहार और जीवनशैली रिमाइंडर*\n\n" "आपके IDRS Score के अनुसार ये बातें याद रखें:\n\n" "🌿 *खान-पान:*\n" "• मेथी का पानी — सुबह खाली पेट\n" "• ज्वार/बाजरा रोटी — सफेद चावल की जगह\n" "• मूंग दाल, हरी सब्जियां — रोज\n" "• चीनी, मैदा, आलू — कम करें\n\n" "🚶 *व्यायाम:*\n" "रोज 30–45 मिनट चलें या योगा करें।\n\n" "📞 DMH: 020-66023000" ) }, "followup_appointment": { "label": "Follow-up अपॉइंटमेंट रिमाइंडर", "icon": "📅", "mr": ( "🏥 *दीनानाथ मंगेशकर हॉस्पिटल — Diabetes Dost*\n\n" "नमस्कार {name} जी! 🙏\n\n" "📅 *Follow-up भेटीची आठवण*\n\n" "तुमची Diabetes Dost AI pre-screening झाली आहे.\n" "आता डॉक्टरांशी प्रत्यक्ष भेट घेणे महत्त्वाचे आहे!\n\n" "🏥 *DMH OPD — Diabetes & Endocrinology*\n" "📞 अपॉइंटमेंट बुक करा: 020-66023000\n" "🌐 ऑनलाईन: www.rubyhall.com\n\n" "Session ID: `{session_id}`\n\n" "⚕️ हा अहवाल डॉक्टरांना दाखवा." ), "hi": ( "🏥 *दीनानाथ मंगेशकर अस्पताल — Diabetes Dost*\n\n" "नमस्ते {name} जी! 🙏\n\n" "📅 *Follow-up अपॉइंटमेंट रिमाइंडर*\n\n" "आपकी Diabetes Dost AI pre-screening हो गई है।\n" "अब डॉक्टर से मिलना जरूरी है!\n\n" "🏥 *DMH OPD — Diabetes & Endocrinology*\n" "📞 अपॉइंटमेंट: 020-66023000\n" "🌐 Online: www.rubyhall.com\n\n" "Session ID: `{session_id}`\n\n" "⚕️ यह रिपोर्ट डॉक्टर को दिखाएं।" ) }, "sugar_control_alert": { "label": "Blood Sugar नियंत्रण Alert", "icon": "🚨", "mr": ( "🚨 *DIABETES DOST — Blood Sugar Alert*\n\n" "नमस्कार {name} जी! 🙏\n\n" "तुमच्या शेवटच्या तपासणीनुसार Blood Sugar नियंत्रण महत्त्वाचे आहे.\n\n" "⚠️ *लक्षणे आढळल्यास लगेच डॉक्टरांशी संपर्क करा:*\n" "• जास्त तहान / वारंवार लघवी\n" "• अत्यंत थकवा / चक्कर\n" "• हात-पाय थरथरणे (Hypoglycemia)\n" "• दृष्टी धुसर होणे\n\n" "🚑 *Emergency: 020-66023000*\n" "📞 DMH ICU Direct: 020-66023001\n\n" "Session: {session_id}" ), "hi": ( "🚨 *DIABETES DOST — Blood Sugar Alert*\n\n" "नमस्ते {name} जी! 🙏\n\n" "आपकी जांच के अनुसार Blood Sugar नियंत्रण जरूरी है।\n\n" "⚠️ *ये लक्षण हों तो तुरंत डॉक्टर से मिलें:*\n" "• ज्यादा प्यास / बार-बार पेशाब\n" "• बहुत थकान / चक्कर\n" "• हाथ-पैर कांपना (Hypoglycemia)\n" "• धुंधली नजर\n\n" "🚑 *Emergency: 020-66023000*" ) }, "custom": { "label": "Custom Message (स्वत: लिहा)", "icon": "✏️", "mr": "{custom_message}", "hi": "{custom_message}" } } class WhatsAppDeliveryService: """ Sends clinical PDF reports via WhatsApp/SMS. Gracefully falls back to local PDF save + URL if Twilio is unconfigured. """ def __init__(self): self.account_sid = os.getenv("TWILIO_ACCOUNT_SID", "").strip() self.auth_token = os.getenv("TWILIO_AUTH_TOKEN", "").strip() self.from_number = os.getenv("TWILIO_WHATSAPP_FROM", "whatsapp:+17372508034").strip() self.from_sms = os.getenv("TWILIO_SMS_FROM", "").strip() self.content_sid = os.getenv("TWILIO_CONTENT_SID", "").strip() self.doctor_phone = os.getenv("DOCTOR_WHATSAPP_NUMBER", "").strip() self._twilio_client = None @property def is_twilio_configured(self) -> bool: return bool(self.account_sid and self.auth_token) def _get_client(self): if self._twilio_client is None and self.is_twilio_configured and TWILIO_SDK_AVAILABLE: try: self._twilio_client = TwilioClient(self.account_sid, self.auth_token) except Exception as e: logger.warning(f"Twilio SDK init fallback: {e}") return self._twilio_client # ───────────────────────────────────────────────────────────────────────── # FOLLOWUP REMINDER — NEW # ───────────────────────────────────────────────────────────────────────── def send_followup_reminder( self, phone_number: str, patient_name: str, session_id: str, template_key: str = "followup_appointment", language: str = "mr", custom_message: str = "", consultation_date: str = "" ) -> Dict[str, Any]: """ Send a pre-built follow-up / reminder message via WhatsApp. Supports multiple template types and custom messages. """ clean_phone = self._format_phone(phone_number) tmpl = FOLLOWUP_TEMPLATES.get(template_key, FOLLOWUP_TEMPLATES["followup_appointment"]) # Build message from template date_str = consultation_date or datetime.now().strftime("%d %b %Y") raw_msg = tmpl.get(language, tmpl.get("mr", "")) message_body = raw_msg.format( name=patient_name, session_id=session_id, date=date_str, custom_message=custom_message or "" ) logger.info(f"Sending follow-up '{template_key}' to {clean_phone} for patient {patient_name}") if self.is_twilio_configured: return self._send_via_twilio_whatsapp(clean_phone, message_body) else: return self._mock_delivery(clean_phone, message_body, None, "whatsapp_followup") # ───────────────────────────────────────────────────────────────────────── # PUBLIC API # ───────────────────────────────────────────────────────────────────────── def save_pdf_locally(self, pdf_bytes: bytes, session_id: str, patient_name: str = "Patient") -> str: import re safe_name = re.sub(r"[^\w\-_]", "_", patient_name.strip()) or "Patient" filename = f"Report_{safe_name}_{session_id}.pdf" filepath = PDF_DELIVERY_DIR / filename with open(filepath, "wb") as f: f.write(pdf_bytes) local_url = f"/api/reports/pdf/{filename}" logger.info(f"PDF saved locally: {filepath}") return local_url def send_whatsapp_report( self, phone_number: str, patient_name: str, pdf_bytes: bytes, session_id: str, pdf_url: Optional[str] = None, language: str = "mr" ) -> Dict[str, Any]: local_url = self.save_pdf_locally(pdf_bytes, session_id, patient_name) final_pdf_url = pdf_url or local_url clean_phone = self._format_phone(phone_number) if language == "mr": message_body = ( f"🏥 *दीनानाथ मंगेशकर हॉस्पिटल — Diabetes Dost*\n\n" f"नमस्कार {patient_name} जी! 🙏\n" f"तुमचा मधुमेह पूर्व-तपासणी अहवाल तयार आहे.\n\n" f"📄 *अहवाल डाउनलोड करा:*\n" f"Session ID: `{session_id}`\n\n" f"⚠️ हा अहवाल AI-आधारित आहे. कृपया डॉक्टरांचा सल्ला घ्या.\n" f"📞 DMH हेल्पलाईन: 020-66023000" ) else: message_body = ( f"🏥 *Ruby Hospital — Diabetes Dost*\n\n" f"Hello {patient_name}! 🙏\n" f"Your diabetes pre-screening report is ready.\n\n" f"📄 *Download Report:*\n" f"Session ID: `{session_id}`\n\n" f"⚠️ This is an AI-assisted pre-screening. Please consult your doctor.\n" f"📞 DMH Helpline: 020-66023000" ) if self.is_twilio_configured: return self._send_via_twilio_whatsapp(clean_phone, message_body, final_pdf_url) else: return self._mock_delivery(clean_phone, message_body, local_url, "whatsapp") def send_sms_alert( self, phone_number: str, patient_name: str, alert_type: str = "emergency", session_id: str = "" ) -> Dict[str, Any]: clean_phone = self._format_phone(phone_number) if alert_type == "emergency": message = ( f"🚨 EMERGENCY ALERT — Diabetes Dost\n" f"Patient: {patient_name}\n" f"Possible Hypoglycemia/DKA symptoms detected.\n" f"Session: {session_id}\n" f"Please contact DMH ICU: 020-66023000 immediately." ) else: message = ( f"📋 Diabetes Dost Report Ready\n" f"Patient: {patient_name} | Session: {session_id}\n" f"Consult your doctor with this report.\n" f"DMH: 020-66023000" ) if self.is_twilio_configured: return self._send_via_twilio_sms(clean_phone, message) else: return self._mock_delivery(clean_phone, message, None, "sms") def send_doctor_alert( self, doctor_phone: str, patient_name: str, urgency: str, session_id: str, summary_snippet: str = "" ) -> Dict[str, Any]: clean_phone = self._format_phone(doctor_phone) message = ( f"🩺 Diabetes Dost — Doctor Alert\n" f"Patient: {patient_name}\n" f"Urgency: {urgency.upper()}\n" f"Session: {session_id}\n" f"{summary_snippet[:200] if summary_snippet else ''}\n" f"Review at DMH Admin Portal." ) if self.is_twilio_configured: return self._send_via_twilio_sms(clean_phone, message) return self._mock_delivery(clean_phone, message, None, "sms_doctor") def build_whatsapp_direct_url(self, phone: str, message: str) -> str: """ Builds a direct click-to-chat WhatsApp URL (wa.me) that immediately opens WhatsApp Web (Desktop) or the WhatsApp App (Android/iOS) with the pre-filled summary. Zero Twilio token dependencies, zero template approval delays, works 100% reliably. """ digits = "".join(c for c in str(phone) if c.isdigit()) if len(digits) == 10: digits = "91" + digits return f"https://wa.me/{digits}?text={urllib.parse.quote(message)}" def format_doctor_summary_message(self, summary: Dict[str, Any], pdf_url: Optional[str] = None) -> str: """Format a comprehensive, structured clinical pre-screening summary for WhatsApp delivery to the physician.""" p = summary.get("patient") or {} p_name = p.get("name") or "Unknown Patient" p_age = p.get("age") or "N/A" p_sex = p.get("sex") or "N/A" session_id = summary.get("session_id", "N/A") branch = (summary.get("branch") or "pre_screening").replace("_", " ").title() urgency = (summary.get("recommended_urgency") or "routine").upper() urgency_emoji = "🚨" if "EMERG" in urgency else ("⚠️" if "URGENT" in urgency else "🟢") idrs_score = summary.get("idrs_risk_score", "N/A") idrs_cat = summary.get("idrs_risk_category", "N/A") symptoms = summary.get("symptoms_reported") or [] sym_str = ", ".join(symptoms) if symptoms else "None reported" meds = summary.get("medications") or [] if meds: med_list = [] for m in meds: if isinstance(m, dict): m_name = m.get("name", "") m_dose = m.get("dosage", "") med_list.append(f"{m_name} ({m_dose})".strip()) else: med_list.append(str(m)) meds_str = ", ".join(med_list) else: meds_str = "None logged" sugars = summary.get("blood_sugar_readings") or {} sugar_items = [] if isinstance(sugars, dict): if sugars.get("fasting"): sugar_items.append(f"FBS: {sugars['fasting']} mg/dL") if sugars.get("post_prandial"): sugar_items.append(f"PPBS: {sugars['post_prandial']} mg/dL") if sugars.get("hba1c"): sugar_items.append(f"HbA1c: {sugars['hba1c']}%") if sugars.get("random"): sugar_items.append(f"RBS: {sugars['random']} mg/dL") sugars_str = ", ".join(sugar_items) if sugar_items else "No direct values recorded" emergency_block = "" if summary.get("emergency_escalation"): details = summary.get("emergency_details") or {} sigs = details.get("detected_signals") or [] emergency_block = f"\n\n🚨 *RED-FLAG EMERGENCY DETECTED:*\nImmediate evaluation needed: {', '.join(sigs)}" narrative = summary.get("summary_narrative") or summary.get("clinical_summary_en") or summary.get("clinical_summary_mr") or "" if len(narrative) > 700: narrative = narrative[:697] + "..." pdf_block = f"\n📄 *Clinical PDF Report:* {pdf_url}" if pdf_url else "" msg = ( f"🏥 *RUBY HOSPITAL*\n" f"🩺 *DIABETES DOST — PRE-SCREENING SUMMARY*\n" f"━━━━━━━━━━━━━━━━━━━━━━━━\n" f"👤 *Patient:* {p_name} | {p_age} yrs | {p_sex}\n" f"🆔 *Session:* `{session_id}`\n" f"📋 *Consultation Branch:* {branch}\n" f"{urgency_emoji} *Triage Urgency:* *{urgency}*\n" f"📊 *IDRS Risk Score:* *{idrs_score}/100* ({idrs_cat})\n\n" f"🩺 *Clinical Findings:*\n" f"• *Symptoms:* {sym_str}\n" f"• *Blood Sugar:* {sugars_str}\n" f"• *Medications:* {meds_str}\n" f"{emergency_block}\n\n" f"📝 *Clinician Handover Note:*\n" f"{narrative}{pdf_block}\n\n" f"━━━━━━━━━━━━━━━━━━━━━━━━\n" f"⚕️ *DMH Clinical Triage Desk: 020-66023000*\n" f"🔗 Full EHR Record available in Hospital Admin Portal" ) return msg def get_doctor_summary_preview( self, doctor_phone: str, summary: Dict[str, Any], host_url: str = "" ) -> Dict[str, Any]: """Returns pre-calculated summary text, PDF URL, and 1-click WhatsApp URL for UI display.""" clean_phone = self._format_phone(doctor_phone or self.doctor_phone or "+918830578295") session_id = summary.get("session_id", "session") patient_name = (summary.get("patient") or {}).get("name") or "Patient" filename = f"Report_{session_id}.pdf" local_pdf_url = f"/api/reports/pdf/{filename}" full_pdf_url = (host_url.rstrip("/") + local_pdf_url) if host_url else local_pdf_url msg = self.format_doctor_summary_message(summary, full_pdf_url) wa_url = self.build_whatsapp_direct_url(clean_phone, msg) return { "session_id": session_id, "patient_name": patient_name, "doctor_phone": clean_phone, "message_text": msg, "whatsapp_url": wa_url, "pdf_url": local_pdf_url, "urgency": summary.get("recommended_urgency", "routine"), "idrs_score": summary.get("idrs_risk_score", "N/A"), "idrs_cat": summary.get("idrs_risk_category", "N/A") } def send_doctor_summary_whatsapp( self, doctor_phone: str, summary: Dict[str, Any], pdf_bytes: Optional[bytes] = None, host_url: str = "" ) -> Dict[str, Any]: """ Dual-delivery method: 1. Generates instant 1-Click WhatsApp direct link (wa.me) with complete clinical summary and PDF. 2. Tries background Twilio Cloud API dispatch if configured. 3. If Twilio fails (due to trial sandbox templates or restrictions), gracefully falls back to Direct WhatsApp so the doctor / assistant is NEVER blocked. """ target_phone = doctor_phone or self.doctor_phone or "+918830578295" clean_phone = self._format_phone(target_phone) session_id = summary.get("session_id", "session") patient_name = (summary.get("patient") or {}).get("name") or "Patient" local_pdf_url = None if pdf_bytes: local_pdf_url = self.save_pdf_locally(pdf_bytes, session_id, patient_name) else: filename = f"Report_{session_id}.pdf" local_pdf_url = f"/api/reports/pdf/{filename}" full_pdf_url = (host_url.rstrip("/") + local_pdf_url) if (host_url and local_pdf_url) else local_pdf_url message_body = self.format_doctor_summary_message(summary, full_pdf_url) whatsapp_url = self.build_whatsapp_direct_url(clean_phone, message_body) logger.info(f"Preparing doctor summary WhatsApp for {clean_phone} (Session: {session_id})") response_data: Dict[str, Any] = { "session_id": session_id, "doctor_phone": clean_phone, "message_text": message_body, "whatsapp_url": whatsapp_url, "pdf_url": local_pdf_url } # Attempt background Twilio Cloud Dispatch if configured if self.is_twilio_configured: content_vars = { "1": patient_name, "2": str(session_id), "3": str(summary.get("recommended_urgency", "Routine")).upper(), "4": f"IDRS: {summary.get('idrs_risk_score', 'N/A')}/100" } cloud_res = self._send_via_twilio_whatsapp( clean_phone, message_body, local_pdf_url, content_sid=self.content_sid, content_variables=content_vars ) response_data["twilio"] = cloud_res if cloud_res.get("status") == "sent": response_data["status"] = "sent" response_data["delivery_type"] = "twilio_cloud" response_data["message_sid"] = cloud_res.get("message_sid") response_data["message"] = "✅ Twilio Cloud द्वारे संदेश थेट डॉक्टरांच्या WhatsApp वर पाठवला गेला!" return response_data # Twilio error: gracefully fallback to direct WhatsApp err_detail = cloud_res.get("error", "Twilio dispatch issue") logger.warning(f"Twilio dispatch notice ({err_detail}). Direct WhatsApp fallback ready.") response_data["status"] = "ready_direct" response_data["delivery_type"] = "whatsapp_direct" response_data["twilio_error"] = err_detail response_data["message"] = ( "Twilio Cloud चाचणी मर्यादा (Sandbox Template). " "खालील 1-Click WhatsApp बटनावर क्लिक करून थेट डॉक्टरांना पाठवा." ) return response_data # Twilio not configured: Mock/Direct delivery mock_res = self._mock_delivery(clean_phone, message_body, local_pdf_url, "whatsapp_doctor_summary") response_data["status"] = "ready_direct" response_data["delivery_type"] = "whatsapp_direct" response_data["twilio"] = mock_res response_data["message"] = "सारांश तयार आहे. खालील WhatsApp बटनावर क्लिक करा." return response_data # ───────────────────────────────────────────────────────────────────────── # INTERNALS # ───────────────────────────────────────────────────────────────────────── def _format_phone(self, phone: str) -> str: phone = str(phone).strip().replace(" ", "").replace("-", "") if not phone.startswith("+"): if phone.startswith("0"): phone = "+91" + phone[1:] elif len(phone) == 10: phone = "+91" + phone else: phone = "+" + phone return phone def _send_via_twilio_whatsapp( self, to_phone: str, body: str, media_url: Optional[str] = None, content_sid: Optional[str] = None, content_variables: Optional[Dict[str, Any]] = None ) -> Dict[str, Any]: """ Sends WhatsApp message directly via Twilio REST API. Supports both Content Template (ContentSid + ContentVariables) and Session (Body) messaging. Works across all operating systems without requiring external C/binary libraries. """ clean_to = self._format_phone(to_phone) url = f"https://api.twilio.com/2010-04-01/Accounts/{self.account_sid}/Messages.json" auth_bytes = f"{self.account_sid}:{self.auth_token}".encode("utf-8") auth_str = base64.b64encode(auth_bytes).decode("utf-8") headers = { "Authorization": f"Basic {auth_str}", "Content-Type": "application/x-www-form-urlencoded" } from_val = self.from_number if self.from_number.startswith("whatsapp:") else f"whatsapp:{self.from_number}" target_content_sid = content_sid or self.content_sid payload = { "From": from_val, "To": f"whatsapp:{clean_to}" } if target_content_sid: # Twilio Content Template mode: do NOT pass Body or MediaUrl payload["ContentSid"] = target_content_sid if content_variables: payload["ContentVariables"] = json.dumps(content_variables) else: # Standard / Session WhatsApp mode payload["Body"] = body if media_url and media_url.startswith("http"): payload["MediaUrl"] = media_url try: encoded_payload = urllib.parse.urlencode(payload).encode("utf-8") req = urllib.request.Request(url, data=encoded_payload, headers=headers, method="POST") with urllib.request.urlopen(req, timeout=15.0) as resp: res_data = json.loads(resp.read().decode("utf-8")) sid = res_data.get("sid") status = res_data.get("status") logger.info(f"✅ Twilio WhatsApp message sent: SID={sid}, Status={status} to {clean_to}") return { "status": "sent", "provider": "twilio_whatsapp_rest", "message_sid": sid, "to": clean_to, "twilio_status": status, "delivery": "real" } except urllib.error.HTTPError as he: err_text = he.read().decode("utf-8") if he.fp else str(he) logger.error(f"❌ Twilio WhatsApp HTTP Error {he.code}: {err_text}") err_msg = err_text err_code = he.code try: err_j = json.loads(err_text) err_msg = err_j.get("message", err_text) err_code = err_j.get("code", he.code) except Exception: pass if err_code == 21654 or "ContentSid Required" in str(err_msg): err_msg = ( "ContentSid Required (Twilio WhatsApp): WhatsApp restricts business-initiated messages " "outside a 24-hr window unless an approved template is used. " "Quick solution: (1) Send 'Hi' from your doctor phone to WhatsApp number +17372508034 " "to open the freeform 24-hr session, OR (2) In Twilio Console > Messaging > Content Template Builder, " "copy your template SID (starts with HX) and set TWILIO_CONTENT_SID in .env." ) return { "status": "failed", "provider": "twilio_whatsapp", "error": err_msg, "code": err_code, "http_status": he.code } except Exception as e: logger.error(f"❌ Twilio WhatsApp send error: {e}") return {"status": "failed", "provider": "twilio_whatsapp", "error": str(e)} def _send_via_twilio_sms(self, to_phone: str, body: str) -> Dict[str, Any]: """Send standard SMS via direct Twilio REST API.""" clean_to = self._format_phone(to_phone) url = f"https://api.twilio.com/2010-04-01/Accounts/{self.account_sid}/Messages.json" auth_bytes = f"{self.account_sid}:{self.auth_token}".encode("utf-8") auth_str = base64.b64encode(auth_bytes).decode("utf-8") headers = { "Authorization": f"Basic {auth_str}", "Content-Type": "application/x-www-form-urlencoded" } from_val = self.from_sms or self.from_number.replace("whatsapp:", "") payload = { "From": from_val, "To": clean_to, "Body": body } try: encoded_payload = urllib.parse.urlencode(payload).encode("utf-8") req = urllib.request.Request(url, data=encoded_payload, headers=headers, method="POST") with urllib.request.urlopen(req, timeout=15.0) as resp: res_data = json.loads(resp.read().decode("utf-8")) sid = res_data.get("sid") return { "status": "sent", "provider": "twilio_sms_rest", "message_sid": sid, "to": clean_to, "delivery": "real" } except urllib.error.HTTPError as he: err_text = he.read().decode("utf-8") if he.fp else str(he) return {"status": "failed", "provider": "twilio_sms", "error": err_text} except Exception as e: return {"status": "failed", "provider": "twilio_sms", "error": str(e)} def _mock_delivery(self, phone: str, message: str, pdf_url: Optional[str], channel: str) -> Dict[str, Any]: logger.info( f"[MOCK {channel.upper()}] To: {phone}\n" f"Message: {message[:120]}...\n" f"PDF URL: {pdf_url or 'N/A'}" ) return { "status": "mock_sent", "provider": "mock", "channel": channel, "to": phone, "pdf_url": pdf_url, "delivery": "simulated", "note": "Configure TWILIO_ACCOUNT_SID + TWILIO_AUTH_TOKEN for real delivery.", "message_preview": message[:200] } GLOBAL_WHATSAPP_SERVICE = WhatsAppDeliveryService()