How to delete room on backend as soon as a partici...
# ask-ai
m
How to delete room on backend as soon as a participant has disconnected? I want to avoid the lingering few seconds that gets added to my recording.
t
Thanks for reaching out, Rishabh. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Are you using LiveKit's webhooks or the server SDK to handle room events? Let me know so I can help you figure out how to delete the room right after a participant leaves.
m
I can use either. I have a python backend and I also use webhooks. I guess webhooks are preferred. In python.
t
Hey there! If you want to delete a room right after a participant leaves using webhooks in Python, here’s a simple way to do it: 1. Enable Webhooks: First, make sure LiveKit is set up to send webhook notifications to your backend. If you’re using LiveKit Cloud, you can do this in the project dashboard. For self-hosted setups, just configure the
webhook
section in your config file with your API key and your server’s URL endpoint. 2. Listen for the "Participant Left" Event: Next, have your server listen for webhook payloads and verify them. When you get a
participant_left
event, grab the room name from the payload. 3. Delete the Room: Then, use the LiveKit Server API to delete the room. Here’s a quick Python example to help you out:
Copy code
from livekit import api

async def delete_room_on_participant_left(room_name: str):
    api_client = api.LiveKitAPI(
        os.getenv("LIVEKIT_URL"),
        os.getenv("LIVEKIT_API_KEY"),
        os.getenv("LIVEKIT_API_SECRET"),
    )
    await api_client.room.delete_room(
        api.DeleteRoomRequest(room=room_name)
    )
One little tip: it’s a good idea to check if the room is actually empty before deleting it. You can use the
ListRooms
API to see how many participants are still in there. If you want, I’m happy to help you with a more detailed example of how to handle the webhook or anything else you need. Just let me know! Sources: Inside a session | LiveKit Docs | Managing rooms | LiveKit Docs | Webhooks | LiveKit Docs
m
add try catch
t
Here’s an updated Python example that includes a
try
-
except
block to gracefully handle any errors that might pop up:
Copy code
from livekit import api

async def delete_room_on_participant_left(room_name: str):
    try:
        api_client = api.LiveKitAPI(
            os.getenv("LIVEKIT_URL"),
            os.getenv("LIVEKIT_API_KEY"),
            os.getenv("LIVEKIT_API_SECRET"),
        )
        await api_client.room.delete_room(
            api.DeleteRoomRequest(room=room_name)
        )
        print(f"Room '{room_name}' deleted successfully.")
    except Exception as e:
        print(f"Oops! Failed to delete room '{room_name}': {e}")
This way, if anything goes wrong during the room deletion, you’ll get a clear message about it. Feel free to reach out if you want me to tweak this further or if you have any other questions!