im making a timer to disconnect all participants a...
# ask-ai
m
im making a timer to disconnect all participants after 60 minutes
t
Thanks for reaching out, Jack. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
m
class TimedAgent(Agent): async def on_room_started(self, ctx: JobContext, session: AgentSession): # Start the 60-minute timer asyncio.create_task(self.end_room_after_timeout(ctx)) async def end_room_after_timeout(self, ctx: JobContext, session: AgentSession): await asyncio.sleep(60 * 60) print("Ending room after 60 minutes") for participant in ctx.participants: await participant.disconnect(reason="Session timeout") await ctx.disconnect()
please improve my code to work with 1.2 agents SDK python
t
To improve your code for compatibility with the LiveKit 1.2 Python SDK, you can use the following approach:
Copy code
import asyncio
from livekit import api, rtc

async def entrypoint(ctx: rtc.JobContext):
    # Initialize the room and connect
    room = ctx.room
    await ctx.connect(auto_subscribe=rtc.AutoSubscribe.AUDIO_ONLY)

    # Create a LiveKit API client
    api_client = api.LiveKitAPI(
        os.getenv("LIVEKIT_URL"),
        os.getenv("LIVEKIT_API_KEY"),
        os.getenv("LIVEKIT_API_SECRET"),
    )

    try:
        # Set up a timer to disconnect everyone after 60 minutes
        async def disconnect_everyone_after_delay():
            await asyncio.sleep(60 * 60)  # Wait for 60 minutes
            await api_client.room.delete_room(
                api.DeleteRoomRequest(room=ctx.job.room.name)
            )

        # Create and start the timer task
        timer_task = asyncio.create_task(disconnect_everyone_after_delay())

        # Keep the agent running to maintain presence in the room
        while True:
            await asyncio.sleep(1)

    except asyncio.CancelledError:
        # Cleanup task on shutdown
        if timer_task.done():
            print("Timer already completed")
        else:
            timer_task.cancel()
            print("Timer cancelled during shutdown")

    finally:
        # Disconnect the agent
        ctx.shutdown("Timer session ended")
Key Improvements: • Uses the LiveKit API client to delete the room after 60 minutes, ensuring all participants are disconnected. • Handles task cancellation gracefully during shutdown. • Maintains agent presence in the room with a loop. Ensure your agent has the necessary permissions to delete rooms via the API, and replace environment variables with actual credentials or configuration. Sources: Job lifecycle | LiveKit Docs | Inside a session | LiveKit Docs