How to limit call duration and automatically disconnect

This question originally came up in our Slack community and the thread has been consolidated here for long-term reference.

How can I limit a call to only a certain time (e.g., 5 minutes) after which the call gets disconnected?

Implement a call monitor as a background asyncio task that tracks call duration. When the time limit is reached, use the LiveKit API to disconnect the participant:

async def call_monitor(session, room, participant, max_duration=300):
    call_start_time = time.time()
    
    while True:
        await asyncio.sleep(10)  # Check interval
        
        call_duration = time.time() - call_start_time
        if call_duration > max_duration:
            await session.say("We've reached the maximum call duration. Goodbye!")
            await asyncio.sleep(2)  # Let message play
            
            # Use RoomService API to remove participant
            async with aiohttp.ClientSession() as http_session:
                svc = room_service.RoomService(
                    http_session, livekit_url, api_key, api_secret
                )
                await svc.remove_participant(
                    room_service.RoomParticipantIdentity(
                        room=room.name,
                        identity=participant.identity
                    )
                )
            break

Start this as a background task when the session begins.