Add logic to only forward the first on_dialin_ready event

This commit is contained in:
Mark Backman
2025-04-27 14:21:14 -04:00
parent 53887b7c98
commit f24a85cc94
3 changed files with 15 additions and 4 deletions

View File

@@ -39,6 +39,8 @@ async def run_bot(room_url: str, token: str, call_id: str, sip_uri: str) -> None
logger.info(f"Starting bot with room: {room_url}") logger.info(f"Starting bot with room: {room_url}")
logger.info(f"SIP endpoint: {sip_uri}") logger.info(f"SIP endpoint: {sip_uri}")
call_already_forwarded = False
# Setup the Daily transport # Setup the Daily transport
transport = DailyTransport( transport = DailyTransport(
room_url, room_url,
@@ -113,6 +115,14 @@ async def run_bot(room_url: str, token: str, call_id: str, sip_uri: str) -> None
# Handle call ready to forward # Handle call ready to forward
@transport.event_handler("on_dialin_ready") @transport.event_handler("on_dialin_ready")
async def on_dialin_ready(transport, cdata): async def on_dialin_ready(transport, cdata):
nonlocal call_already_forwarded
# We only want to forward the call once
# The on_dialin_ready event will be triggered for each sip endpoint provisioned
if call_already_forwarded:
logger.warning("Call already forwarded, ignoring this event.")
return
logger.info(f"Forwarding call {call_id} to {sip_uri}") logger.info(f"Forwarding call {call_id} to {sip_uri}")
try: try:
@@ -121,6 +131,7 @@ async def run_bot(room_url: str, token: str, call_id: str, sip_uri: str) -> None
twiml=f"<Response><Dial><Sip>{sip_uri}</Sip></Dial></Response>" twiml=f"<Response><Dial><Sip>{sip_uri}</Sip></Dial></Response>"
) )
logger.info("Call forwarded successfully") logger.info("Call forwarded successfully")
call_already_forwarded = True
except Exception as e: except Exception as e:
logger.error(f"Failed to forward call: {str(e)}") logger.error(f"Failed to forward call: {str(e)}")
raise raise

View File

@@ -21,10 +21,10 @@ load_dotenv()
@asynccontextmanager @asynccontextmanager
async def lifespan(app: FastAPI): async def lifespan(app: FastAPI):
# Create aiohttp session to be used for Daily API calls # Create aiohttp session to be used for Daily API calls
app.session = aiohttp.ClientSession() app.state.session = aiohttp.ClientSession()
yield yield
# Close session when shutting down # Close session when shutting down
await app.session.close() await app.state.session.close()
app = FastAPI(lifespan=lifespan) app = FastAPI(lifespan=lifespan)
@@ -51,7 +51,7 @@ async def handle_call(request: Request):
# Create a Daily room with SIP capabilities # Create a Daily room with SIP capabilities
try: try:
room_details = await create_sip_room(request.app.session, caller_phone) room_details = await create_sip_room(request.app.state.session, caller_phone)
except Exception as e: except Exception as e:
print(f"Error creating Daily room: {e}") print(f"Error creating Daily room: {e}")
raise HTTPException(status_code=500, detail=f"Failed to create Daily room: {str(e)}") raise HTTPException(status_code=500, detail=f"Failed to create Daily room: {str(e)}")

View File

@@ -1,7 +1,7 @@
"""Helper functions for interacting with the Daily API.""" """Helper functions for interacting with the Daily API."""
import os import os
from typing import Any, Dict, Optional from typing import Dict, Optional
import aiohttp import aiohttp
from dotenv import load_dotenv from dotenv import load_dotenv