forked from toprmrproducer/InboundAIVoice
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnotify.py
More file actions
205 lines (176 loc) · 7.68 KB
/
Copy pathnotify.py
File metadata and controls
205 lines (176 loc) · 7.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import os
import logging
import requests
import httpx
from datetime import datetime
logger = logging.getLogger("notify")
TELEGRAM_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN", "")
TELEGRAM_CHAT_ID = os.environ.get("TELEGRAM_CHAT_ID", "")
TELEGRAM_URL = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
# ─── Telegram ──────────────────────────────────────────────────────────────────
def send_telegram(message: str) -> bool:
"""Fire a single POST to Telegram. Supports Markdown formatting."""
if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CHAT_ID:
logger.warning("[TELEGRAM] Token or Chat ID not set — skipping.")
return False
try:
resp = requests.post(
TELEGRAM_URL,
json={"chat_id": TELEGRAM_CHAT_ID, "text": message, "parse_mode": "Markdown"},
timeout=5,
)
resp.raise_for_status()
logger.info("[TELEGRAM] Message sent.")
return True
except Exception as e:
logger.error(f"[TELEGRAM] Failed: {e}")
return False
# ─── WhatsApp via Twilio (#16) ────────────────────────────────────────────────
def send_whatsapp(to_phone: str, message: str) -> bool:
"""
Send a WhatsApp message via Twilio.
Requires env vars: TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, TWILIO_WHATSAPP_NUMBER
The Twilio sandbox number is whatsapp:+14155238886 (for testing).
Production: use your approved Twilio WhatsApp sender number.
"""
account_sid = os.environ.get("TWILIO_ACCOUNT_SID", "")
auth_token = os.environ.get("TWILIO_AUTH_TOKEN", "")
from_number = os.environ.get("TWILIO_WHATSAPP_NUMBER", "whatsapp:+14155238886")
if not account_sid or not auth_token:
logger.debug("[WHATSAPP] Twilio credentials not set — skipping.")
return False
# Normalise destination number
to_wa = f"whatsapp:{to_phone}" if not to_phone.startswith("whatsapp:") else to_phone
try:
resp = httpx.post(
f"https://api.twilio.com/2010-04-01/Accounts/{account_sid}/Messages.json",
auth=(account_sid, auth_token),
data={"From": from_number, "To": to_wa, "Body": message},
timeout=8.0,
)
resp.raise_for_status()
logger.info(f"[WHATSAPP] Sent to {to_phone}: {resp.status_code}")
return True
except Exception as e:
logger.error(f"[WHATSAPP] Failed to send to {to_phone}: {e}")
return False
def send_whatsapp_booking_confirmation(
caller_phone: str,
caller_name: str,
booking_time_iso: str,
) -> bool:
"""Send WhatsApp confirmation after a booking is made."""
try:
dt = datetime.fromisoformat(booking_time_iso)
readable = dt.strftime("%A, %d %B %Y at %I:%M %p IST")
except Exception:
readable = booking_time_iso
message = (
f"✅ Hi {caller_name or 'there'}! Your appointment is *confirmed*.\n\n"
f"📅 *Date & Time:* {readable}\n\n"
f"If you need to reschedule or cancel, just call us back.\n\n"
f"— RapidX AI 🤖"
)
return send_whatsapp(caller_phone, message)
# ─── Message Templates ─────────────────────────────────────────────────────────
def notify_booking_confirmed(
caller_name: str,
caller_phone: str,
booking_time_iso: str,
booking_id: str,
notes: str = "",
tts_voice: str = "",
ai_summary: str = "",
) -> bool:
"""Sends Telegram + WhatsApp when a booking is confirmed."""
try:
dt = datetime.fromisoformat(booking_time_iso)
readable = dt.strftime("%A, %d %B %Y at %-I:%M %p IST")
except Exception:
readable = booking_time_iso
message = (
f"✅ *New Booking Confirmed!*\n"
f"━━━━━━━━━━━━━━━━━━━━━━\n"
f"👤 *Name:* {caller_name}\n"
f"📞 *Phone:* `{caller_phone}`\n"
f"📅 *Time:* {readable}\n"
f"🔖 *Booking ID:* `{booking_id}`\n"
f"📝 *Notes:* {notes or '—'}\n"
f"🎙️ *Voice Model:* {tts_voice or '—'}\n"
f"━━━━━━━━━━━━━━━━━━━━━━\n"
+ (f"💬 *AI Summary:*\n_{ai_summary}_\n\n" if ai_summary else "")
+ f"_Booked via RapidX AI Voice Agent_ 🤖"
)
tg_ok = send_telegram(message)
# Also send WhatsApp confirmation to caller (#16)
send_whatsapp_booking_confirmation(caller_phone, caller_name, booking_time_iso)
return tg_ok
def notify_booking_cancelled(
caller_name: str,
caller_phone: str,
booking_id: str,
reason: str = "",
) -> bool:
message = (
f"❌ *Booking Cancelled*\n"
f"━━━━━━━━━━━━━━━━━━━━━━\n"
f"👤 *Name:* {caller_name}\n"
f"📞 *Phone:* `{caller_phone}`\n"
f"🔖 *Booking ID:* `{booking_id}`\n"
f"💬 *Reason:* {reason or 'Caller changed mind'}\n"
f"━━━━━━━━━━━━━━━━━━━━━━\n"
f"_RapidX AI Voice Agent_ 🤖"
)
return send_telegram(message)
def notify_call_no_booking(
caller_name: str,
caller_phone: str,
call_summary: str = "",
tts_voice: str = "",
ai_summary: str = "",
duration_seconds: int = 0,
) -> bool:
message = (
f"📵 *Call Ended — No Booking*\n"
f"━━━━━━━━━━━━━━━━━━━━━━\n"
f"👤 *Name:* {caller_name or 'Unknown'}\n"
f"📞 *Phone:* `{caller_phone}`\n"
f"⏱️ *Duration:* {duration_seconds}s\n"
f"🎙️ *Voice Model:* {tts_voice or '—'}\n"
f"━━━━━━━━━━━━━━━━━━━━━━\n"
+ f"💬 *Summary:*\n_{ai_summary or call_summary or 'Caller did not schedule.'}_\n\n"
+ f"_Consider a manual follow-up call_ 📲\n"
f"_RapidX AI Voice Agent_ 🤖"
)
return send_telegram(message)
def notify_agent_error(caller_phone: str, error: str) -> bool:
message = (
f"⚠️ *Agent Error During Call*\n"
f"━━━━━━━━━━━━━━━━━━━━━━\n"
f"📞 *Phone:* `{caller_phone}`\n"
f"🔴 *Error:* `{error}`\n"
f"━━━━━━━━━━━━━━━━━━━━━━\n"
f"_RapidX AI Voice Agent_ 🤖"
)
return send_telegram(message)
# ─── n8n / Custom Webhook (#35) ──────────────────────────────────────────────
async def send_webhook(webhook_url: str, event_type: str, payload: dict) -> bool:
"""Deliver an event to a configurable webhook URL (for CRM embeds)."""
if not webhook_url:
return False
try:
async with httpx.AsyncClient(timeout=5.0) as client:
resp = await client.post(
webhook_url,
json={
"event": event_type,
"timestamp": datetime.utcnow().isoformat(),
"data": payload,
},
headers={"Content-Type": "application/json"},
)
logger.info(f"[WEBHOOK] Delivered {event_type} → {resp.status_code}")
return resp.status_code < 300
except Exception as e:
logger.warning(f"[WEBHOOK] Failed to deliver {event_type}: {e}")
return False