MCPcopy Create free account
hub / github.com/Roy3838/Observer / voice_callback

Function voice_callback

api/messaging.py:932–980  ·  view source on GitHub ↗

Webhook endpoint that Twilio calls when a voice call connects. Handles both incoming calls (whitelist them) and outgoing calls (speak message). Returns TwiML instructions. Validates Twilio signature to prevent spoofing attacks.

(
    request: Request,
    form_data: dict = Depends(validate_twilio_request)
)

Source from the content-addressed store, hash-verified

930
931@messaging_router.post("/webhooks/voice-callback", tags=["Webhooks"])
932async def voice_callback(
933 request: Request,
934 form_data: dict = Depends(validate_twilio_request)
935):
936 """
937 Webhook endpoint that Twilio calls when a voice call connects.
938 Handles both incoming calls (whitelist them) and outgoing calls (speak message).
939 Returns TwiML instructions.
940 Validates Twilio signature to prevent spoofing attacks.
941 """
942 try:
943 # Extract call info (form_data already validated and parsed)
944 call_sid = form_data.get("CallSid", "")
945 call_status = form_data.get("CallStatus", "")
946 direction = form_data.get("Direction", "")
947 from_number = form_data.get("From", "")
948
949 logger.info(f"Voice callback received: SID={call_sid}, Status={call_status}, Direction={direction}")
950
951 # Create TwiML response
952 response = VoiceResponse()
953
954 if direction == "inbound":
955 # A call can't carry a code, so it pairs nothing: point the caller at WhatsApp.
956 logger.info(f"Inbound call from {from_number}; pointed at WhatsApp pairing")
957 response.say(
958 "This is the Observer bot. To get alerts from your Observer agents, "
959 "send your four word code to the Observer bot on WhatsApp.",
960 voice='alice',
961 language='en-US'
962 )
963 else:
964 # Outgoing call - speak the message from AI, looked up by the token
965 # we minted when the call was created (see stash_voice_message).
966 message_text = await pop_voice_message(request.query_params.get("token", ""))
967 if message_text is None:
968 logger.warning(f"No stashed message for call {call_sid}; using default")
969 message_text = DEFAULT_VOICE_MESSAGE
970 response.say(message_text, voice='alice', language='en-US')
971
972 # Return TwiML as XML
973 return FastAPIResponse(content=str(response), media_type="application/xml")
974
975 except Exception as e:
976 logger.error(f"Error processing voice callback: {str(e)}")
977 # Return a fallback TwiML response
978 response = VoiceResponse()
979 response.say("An error occurred.", voice='alice')
980 return FastAPIResponse(content=str(response), media_type="application/xml")
981
982@messaging_router.post("/webhooks/voice-status", tags=["Webhooks"])
983async def voice_status_callback(

Callers

nothing calls this directly

Calls 3

pop_voice_messageFunction · 0.85
infoMethod · 0.80
errorMethod · 0.80

Tested by

no test coverage detected