white-telephone-81843
10/20/2025, 12:53 PMtall-airline-16756
10/20/2025, 12:53 PMtall-airline-16756
10/20/2025, 12:54 PMimport 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.pywhite-telephone-81843
10/20/2025, 12:56 PMtall-airline-16756
10/20/2025, 12:57 PM.env file includes these lines:
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:
from dotenv import load_dotenv
load_dotenv()
1. If you prefer, you can also pass the credentials directly in your 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 projecttall-airline-16756
10/20/2025, 1:02 PMasync 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:
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:
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.pywhite-telephone-81843
10/20/2025, 1:02 PMtall-airline-16756
10/20/2025, 1:04 PMimport 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...white-telephone-81843
10/20/2025, 1:07 PMtall-airline-16756
10/20/2025, 1:09 PMroom_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:
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!white-telephone-81843
10/20/2025, 1:09 PMtall-airline-16756
10/20/2025, 1:10 PMimport 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!