Give me a python script that tells me when a room ...
# ask-ai
w
Give me a python script that tells me when a room is created, finished and when participants join and leave
t
Thanks for reaching out, Marius. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm happy to share a Python script that helps you track room creation, completion, and participant join/leave events in LiveKit. This should make managing your sessions a bit easier:
Copy code
import asyncio
import logging
import os
from datetime import datetime
from livekit import api, rtc

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class LiveKitEventTracker:
    def __init__(self):
        self.room = None
        self.participants = {}
        self.room_start_time = None

    async def connect_and_track(self, room_name, participant_identity):
        self.room = rtc.Room()
        self._setup_event_handlers()

        token = (
            api.AccessToken()
            .with_identity(participant_identity)
            .with_grants(api.VideoGrants(room_join=True, room=room_name))
            .to_jwt()
        )

        await self.room.connect(os.getenv("LIVEKIT_URL"), token)
        logger.info(f"Connected to room: {room_name}")

    def _setup_event_handlers(self):
        @self.room.on("connected")
        def on_connected():
            self.room_start_time = datetime.now()
            logger.info(f"Room created at {self.room_start_time}")

        @self.room.on("disconnected")
        def on_disconnected():
            logger.info("Room disconnected")

        @self.room.on("participant_connected")
        def on_participant_connected(participant):
            self.participants[participant.sid] = {
                'identity': participant.identity,
                'join_time': datetime.now()
            }
            logger.info(f"Participant joined: {participant.identity}")

        @self.room.on("participant_disconnected")
        def on_participant_disconnected(participant):
            leave_time = datetime.now()
            join_time = self.participants[participant.sid]['join_time']
            logger.info(f"Participant left: {participant.identity}, Duration: {leave_time - join_time}")

async def main():
    tracker = LiveKitEventTracker()
    await tracker.connect_and_track("room_name", "participant_identity")

if __name__ == "__main__":
    asyncio.run(main())
Just a quick reminder: be sure to replace
room_name
and
participant_identity
with the values that fit your setup. Also, don't forget to set your
LIVEKIT_URL
,
LIVEKIT_API_KEY
, and
LIVEKIT_API_SECRET
environment variables before running the script. If you have any questions or need further help, feel free to ask—I'm here to support you! Sources: examples/room_example.py
w
(voice-ai-agent) mariusrodderbjornoy@X-JFX09Q5GKY voice-ai-agent % /Users/mariusrodderbjornoy/Documents/GMG/voice-ai-agent/.ve nv/bin/python /Users/mariusrodderbjornoy/Documents/GMG/voice-ai-agent/telephony/notifications.py Traceback (most recent call last): File "/Users/mariusrodderbjornoy/Documents/GMG/voice-ai-agent/telephony/notifications.py", line 60, in <module> asyncio.run(main()) File "/Users/mariusrodderbjornoy/.local/share/uv/python/cpython-3.12.11-macos-aarch64-none/lib/python3.12/asyncio/runners.py", line 195, in run return runner.run(main) ^^^^^^^^^^^^^^^^ File "/Users/mariusrodderbjornoy/.local/share/uv/python/cpython-3.12.11-macos-aarch64-none/lib/python3.12/asyncio/runners.py", line 118, in run return self._loop.run_until_complete(task) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/mariusrodderbjornoy/.local/share/uv/python/cpython-3.12.11-macos-aarch64-none/lib/python3.12/asyncio/base_events.py", line 691, in run_until_complete return future.result() ^^^^^^^^^^^^^^^ File "/Users/mariusrodderbjornoy/Documents/GMG/voice-ai-agent/telephony/notifications.py", line 57, in main await tracker.connect_and_track("my-room", "python-user-my-room") File "/Users/mariusrodderbjornoy/Documents/GMG/voice-ai-agent/telephony/notifications.py", line 22, in connect_and_track api.AccessToken() File "/Users/mariusrodderbjornoy/Documents/GMG/voice-ai-agent/.venv/lib/python3.12/site-packages/livekit/api/access_token.py", line 124, in init raise ValueError("api_key and api_secret must be set") ValueError: api_key and api_secret must be set URL, Secret and key are all in my .env
t
It looks like the LiveKit Python SDK is having trouble finding your API credentials. No worries—let’s work through this together! Here are some friendly steps to help you get it sorted: 1. First, double-check that your
.env
file includes these lines:
Copy code
LIVEKIT_API_KEY=your_api_key_here
LIVEKIT_API_SECRET=your_api_secret_here
1. Next, make sure you’re loading those environment variables in your script like this:
Copy code
from dotenv import load_dotenv
load_dotenv()
1. If you prefer, you can also pass the credentials directly in your code:
Copy code
from livekit import api

# Pass credentials directly
token = api.AccessToken(
    api_key="your_api_key",
    api_secret="your_api_secret"
)
Just confirm that
LIVEKIT_API_KEY
and
LIVEKIT_API_SECRET
are correctly set and accessible in your environment. If you hit any bumps or want me to walk you through any part, I’m here to help! Sources: Secrets management | LiveKit Docs | livekit-api/livekit/api/__init__.py | auth.py | Mini tutorial: setting up a LiveKit Cloud project
It looks like you're encountering the "Event loop is closed" error, which usually happens when the asyncio event loop is closed before all operations have finished. Don’t worry, I’m here to help you work through this! Here are some friendly steps to guide you: 1. Make Sure to Disconnect from the Room Properly: It’s important to always disconnect from the room before closing the event loop. Here’s a simple way to do that:
Copy code
async def cleanup():
    await room.disconnect()  # Disconnect first
    loop.stop()

# Handle shutdown signals
for signal in [signal.SIGINT, signal.SIGTERM]:
    loop.add_signal_handler(signal, lambda: asyncio.ensure_future(cleanup()))

try:
    loop.run_forever()
finally:
    loop.close()
1. Double-Check the Event Loop Status: Before you perform any queue operations, it’s a good idea to verify that the event loop is still running to avoid any surprises:
Copy code
if loop and not loop.is_closed():
    loop.call_soon_threadsafe(queue.put_nowait, item)
else:
    logger.error("Event loop is closed")
1. Stop Background Threads Properly: If you’re working with audio streaming, make sure all audio devices and threads are stopped before closing the loop to keep things tidy:
Copy code
def stop_audio_devices():
    if input_stream:
        input_stream.stop()
        input_stream.close()
Following these steps should help ensure everything cleans up nicely and prevent that pesky error from popping up. If anything isn’t clear or you want to dive deeper, just let me know—I’m happy to help! Sources: livekit-protocol/livekit/protocol/models.py | stream_audio.py
w
fix the current script: import asyncio import logging import os from dotenv import load_dotenv from datetime import datetime from livekit import api, rtc load_dotenv() # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(name) class LiveKitEventTracker: def __init__(self): self.room = None self.participants = {} self.room_start_time = None async def connect_and_track(self, room_name, participant_identity): self.room = rtc.Room() self._setup_event_handlers() token = ( api.AccessToken( api_key=os.environ.get("LIVEKIT_API_KEY"), api_secret=os.environ.get("LIVEKIT_API_SECRET") ) .with_identity(participant_identity) .with_grants(api.VideoGrants(room_join=True, room=room_name)) .to_jwt() ) await self.room.connect(os.getenv("LIVEKIT_URL"), token) logger.info(*f*"Connected to room: {room_name}") def _setup_event_handlers(self): @self.room.on("connected") def on_connected(): self.room_start_time = datetime.now() logger.info(*f*"Room created at {self.room_start_time}") @self.room.on("disconnected") def on_disconnected(): logger.info("Room disconnected") @self.room.on("participant_connected") def on_participant_connected(participant): self.participants[participant.sid] = { 'identity': participant.identity, 'join_time': datetime.now() } logger.info(*f*"Participant joined: {participant.identity}") @self.room.on("participant_disconnected") def on_participant_disconnected(participant): leave_time = datetime.now() join_time = self.participants[participant.sid]['join_time'] logger.info(*f*"Participant left: {participant.identity}, Duration: {leave_time - join_time}") async def main(): tracker = LiveKitEventTracker() await tracker.connect_and_track("my-room", "python-user-my-room") if name == "__main__": asyncio.run(main())
t
Let's work together to fix the script and get rid of the "Event loop is closed" error by managing the event loop properly and ensuring cleanup is handled smoothly. Here's an updated version of your script that should help:
Copy code
import asyncio
import logging
import os
from dotenv import load_dotenv
from datetime import datetime
from livekit import api, rtc

load_dotenv()

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class LiveKitEventTracker:
    def __init__(self):
        self.room = None
        self.participants = {}
        self.room_start_time = None

    async def connect_and_track(self, room_name, participant_identity):
        self.room = rtc.Room()
        self._setup_event_handlers()

        token = (
            api.AccessToken(
                api_key=os.environ.get("LIVEKIT_API_KEY"),
                api_secret=os.environ.get("LIVEKIT_API_SECRET")
            )
            .with_identity(participant_identity)
            .with_grants(api.VideoGrants(room_join=True, room=room_name))
            .to_jwt()
        )

        await self.room.connect(os.getenv("LIVEKIT_URL"), token)
        logger.info(f"Connected to room: {room_name}")

    def _setup_event_handlers(self):
        @self.room.on("connected")
        def on_connected():
            self.room_start_time = datetime.now()
            logger.info(f"Room created at {self.room_start_time}")

        @self.room.on("disconnected")
        def on_disconnected():
            logger.info("Room disconnected")

        @self.room.on("participant_connected")
        def on_participant_connected(participant):
            self.participants[participant.sid] = {
                'identity': participant.identity,
                'join_time': datetime.now()
            }
            logger.info(f"Participant joined: {participant.identity}")

        @self.room.on("participant_disconnected")
        def on_participant_disconnected(participant):
            leave_time = datetime.now()
            join_time = self.participants[participant.sid]['join_time']
            logger.info(f"Participant left: {participant.identity}, Duration: {leave_time - join_time}")

async def main():
    tracker = LiveKitEventTracker()
    try:
        await tracker.connect_and_track("my-room", "python-user-my-room")
    finally:
        if tracker.room:
            await tracker.room.disconnect()

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("Program terminated by user")
This version carefully ensures the room disconnects in a
finally
block, so cleanup happens no matter what, and also gracefully handles
KeyboardInterrupt
so your program can shut down nicely. If anything else comes up or you have questions, please don’t hesitate to reach out—I’m here to help! Sources: livekit-rtc/livekit/rtc/room.py | stream_audio.py | livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real...
w
I get this output now: INFOlivekitlivekit_ffi:server139livekit ffi:server - initializing ffi server v0.12.30 INFOlivekitlivekit_ffi:cabi36livekit ffi:cabi - initializing ffi server v0.12.30 INFOlivekitlivekit_api:signal clientsignal stream106livekit apisignal client:signal_stream - connecting to INFO main Connected to room: my-room Although What I want is to be able to track when new rooms are created. Meaning I would get some sort of print statement as soon as a room is created.
t
To help you keep track of when new rooms are created in LiveKit, you have a couple of great options to choose from: 1. Webhooks: You can set up LiveKit to send a webhook event every time a room is created. The
room_started
event will give your server all the details about the new room. Here’s a simple example of how a webhook handler might look:
Copy code
app.post('/webhook', (req, res) => {
  const event = req.body;

  if (event.event === 'room_started') {
    console.log(`New room created: ${event.room.name}`);
    console.log(`Room SID: ${event.room.sid}`);
    console.log(`Created at: ${new Date(event.created_at * 1000)}`);
  }

  res.status(200).send('OK');
});
1. Agents Framework: Another handy approach is using the LiveKit Agents framework, which can automatically detect and manage new room creation events. This is especially useful if you want to dispatch agents to rooms as soon as they’re created. If you’d like, I’m here to help you set up either the webhooks or the Agents framework—just let me know what fits your needs best, and we can get started together!
w
give me the full python script. just change my current one: import asyncio import logging import os from dotenv import load_dotenv from datetime import datetime from livekit import api, rtc load_dotenv() # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(name) class LiveKitEventTracker: def __init__(self): self.room = None self.participants = {} self.room_start_time = None async def connect_and_track(self, room_name, participant_identity): self.room = rtc.Room() self._setup_event_handlers() token = ( api.AccessToken( api_key=os.environ.get("LIVEKIT_API_KEY"), api_secret=os.environ.get("LIVEKIT_API_SECRET") ) .with_identity(participant_identity) .with_grants(api.VideoGrants(room_join=True, room=room_name)) .to_jwt() ) await self.room.connect(os.getenv("LIVEKIT_URL"), token) logger.info(*f*"Connected to room: {room_name}") def _setup_event_handlers(self): @self.room.on("connected") def on_connected(): self.room_start_time = datetime.now() logger.info(*f*"Room created at {self.room_start_time}") @self.room.on("disconnected") def on_disconnected(): logger.info("Room disconnected") @self.room.on("participant_connected") def on_participant_connected(participant): self.participants[participant.sid] = { 'identity': participant.identity, 'join_time': datetime.now() } logger.info(*f*"Participant joined: {participant.identity}") @self.room.on("participant_disconnected") def on_participant_disconnected(participant): leave_time = datetime.now() join_time = self.participants[participant.sid]['join_time'] logger.info(*f*"Participant left: {participant.identity}, Duration: {leave_time - join_time}") async def main(): tracker = LiveKitEventTracker() try: await tracker.connect_and_track("my-room", "python-user-my-room") finally: if tracker.room: await tracker.room.disconnect() if name == "__main__": try: asyncio.run(main()) except KeyboardInterrupt: print("Program terminated by user")
t
I’m glad you’re looking to track when new rooms are created! To do this, using LiveKit webhooks is the way to go. I understand the current Python SDK doesn’t offer a direct method to catch room creation events in real-time, but no worries—we can set up a webhook to notify your server whenever a room is created. Here’s an updated version of your script that includes webhook handling:
Copy code
import asyncio
import logging
import os
from flask import Flask, request, jsonify
from dotenv import load_dotenv

load_dotenv()

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Flask app for webhook handling
app = Flask(__name__)

@app.route("/webhook", methods=["POST"])
def webhook():
    event = request.json

    if event["event"] == "room_started":
        room_name = event["room"]["name"]
        created_at = event["created_at"]
        logger.info(f"New room created: {room_name} at {created_at}")

    return jsonify({"status": "success"}), 200

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)
Here are some simple steps to get you started: 1. Deploy this script on a server that LiveKit can reach. 2. Set up your LiveKit project to send webhooks to your server’s URL (like
<WEBHOOK_SERVER_URL>/webhook
). 3. Make sure your server is ready to handle incoming POST requests with JSON payloads. This setup will help you keep track of room creation events as they happen. If you have any questions or want me to walk you through any part of this, just let me know—I’m here to help!