white-telephone-81843
10/17/2025, 7:43 AMtall-airline-16756
10/17/2025, 7:43 AMtall-airline-16756
10/17/2025, 7:44 AMimport asyncio
import os
from livekit import api, rtc
# Create a room instance
loop = asyncio.get_event_loop()
room = rtc.Room(loop=loop)
# Create an access token
token = (
api.AccessToken()
.with_identity("python-bot")
.with_name("Python Bot")
.with_grants(
api.VideoGrants(
room_join=True,
room="my-room",
)
)
.to_jwt()
)
# Connect to the room
await room.connect(os.getenv("LIVEKIT_URL"), token)
2. Set Up Event Handlers:
It's helpful to set up event handlers before connecting so you can listen to the room's activity as it happens:
@room.on("participant_connected")
def on_participant_connected(participant: rtc.RemoteParticipant):
print(f"Participant connected: {participant.identity}")
@room.on("track_subscribed")
def on_track_subscribed(track: rtc.Track, publication: rtc.RemoteTrackPublication, participant: rtc.RemoteParticipant):
print(f"Track subscribed: {publication.sid}")
3. Complete Example:
async def main():
# Set up event handlers
@room.on("connected")
def on_connected():
print("Connected to room")
# Connect to the room
await room.connect(os.getenv("LIVEKIT_URL"), token)
loop.run_until_complete(main())
Just a quick reminder to make sure your environment variables LIVEKIT_URL, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET are all set up properly. If you run into any questions or need more help, please feel free to ask—I'm here to support you!
Sources: Handling events | LiveKit Docs | Connecting to LiveKit | LiveKit Docs | examples/participant_attributes.pywhite-telephone-81843
10/17/2025, 8:07 AMtall-airline-16756
10/17/2025, 8:08 AMawait room.connect(LIVEKIT_URL, token)
If you’d like, I’m here to guide you through generating the access token or connecting to the room—just let me know!
Sources: Connecting to LiveKit | LiveKit Docs | room.go | examples/rpc/index.ts | livekit/tests/common/e2e/mod.rswhite-telephone-81843
10/17/2025, 10:24 AMtall-airline-16756
10/17/2025, 10:26 AMfrom livekit import api
import asyncio
async def main():
# This will automatically use your LIVEKIT_URL, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET environment variables
lkapi = api.LiveKitAPI()
room_info = await lkapi.room.create_room(
api.CreateRoomRequest(name="my-room"),
)
print(room_info)
await lkapi.aclose()
if __name__ == "__main__":
asyncio.run(main())
2. Advanced Room Configuration:
room_info = await lkapi.room.create_room(
api.CreateRoomRequest(
name="my-configured-room",
empty_timeout=300, # How many seconds to keep the room open when it’s empty
departure_timeout=60, # Seconds to wait after a participant leaves
max_participants=50, # Maximum number of participants allowed
metadata="Custom room metadata"
)
)
3. Authentication: Just make sure you have your environment variables LIVEKIT_URL, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET set up correctly. If you prefer, you can also configure the API client manually like this:
lkapi = api.LiveKitAPI(url=os.getenv("LIVEKIT_URL"), api_key=os.getenv("LIVEKIT_API_KEY"), api_secret=os.getenv("LIVEKIT_API_SECRET"))
4. Implicit Room Creation: A neat feature is that rooms can be created automatically when the first participant joins with a valid token:
token = (
api.AccessToken()
.with_identity("participant-1")
.with_grants(api.VideoGrants(room_join=True, room="auto-created-room"))
.to_jwt()
)
If you have any questions or would like me to walk you through a more detailed example, just let me know. I’m here to help!
Sources: examples/agent_dispatch.py | Rooms, participants, and tracks | LiveKit Docs | Core Platform Architecture & Authentication | livekit/livekit_composite | D... | CreateRoom() is Taking Too Longwhite-telephone-81843
10/17/2025, 10:54 AMtall-airline-16756
10/17/2025, 10:55 AMimport asyncio
import os
import aiohttp
from livekit import api
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
class LiveKitRoomManager:
def __init__(self):
self.api_key = os.getenv('LIVEKIT_API_KEY')
self.api_secret = os.getenv('LIVEKIT_API_SECRET')
self.livekit_url = os.getenv('LIVEKIT_URL')
if not all([self.api_key, self.api_secret, self.livekit_url]):
raise ValueError("Missing required environment variables: LIVEKIT_API_KEY, LIVEKIT_API_SECRET, LIVEKIT_URL")
async def create_room(self, room_name: str, **kwargs):
async with aiohttp.ClientSession() as session:
lkapi = api.LiveKitAPI(session=session)
create_request = api.CreateRoomRequest(name=room_name, **kwargs)
room_info = await lkapi.room.create_room(create_request)
return room_info
async def list_rooms(self):
async with aiohttp.ClientSession() as session:
lkapi = api.LiveKitAPI(session=session)
rooms_response = await lkapi.room.list_rooms(api.ListRoomsRequest())
return rooms_response.rooms
async def delete_room(self, room_name: str):
async with aiohttp.ClientSession() as session:
lkapi = api.LiveKitAPI(session=session)
await lkapi.room.delete_room(api.DeleteRoomRequest(room=room_name))
return True
def generate_access_token(self, identity: str, name: str, room: str):
token = api.AccessToken(self.api_key, self.api_secret)
token = token.with_identity(identity).with_name(name).with_grants(api.VideoGrants(room_join=True, room=room))
return token.to_jwt()
async def main():
manager = LiveKitRoomManager()
room_name = "test-room"
# Create a room
print("Creating room...")
room_info = await manager.create_room(room_name, empty_timeout=300, max_participants=10)
print(f"Room created: {room_info.name}")
# List rooms
print("\nListing rooms...")
rooms = await manager.list_rooms()
for room in rooms:
print(f"Room: {room.name}, Participants: {room.num_participants}")
# Generate access token
print("\nGenerating access token...")
token = manager.generate_access_token("user123", "Test User", room_name)
print(f"Access token: {token}")
# Delete the room
print("\nDeleting room...")
await manager.delete_room(room_name)
print("Room deleted.")
if __name__ == "__main__":
asyncio.run(main())
Setup:
• First, create a .env file with your LiveKit credentials like this:
LIVEKIT_URL=wss://your-livekit-server.com
LIVEKIT_API_KEY=your-api-key
LIVEKIT_API_SECRET=your-api-secret
• Then, make sure to install the necessary dependencies:
pip install livekit-api python-dotenv aiohttp
If you have any questions or need help along the way, please don’t hesitate to ask — I’m here to support you!
Sources: examples/api.py | mcp/server.pywhite-telephone-81843
10/17/2025, 10:57 AMtall-airline-16756
10/17/2025, 10:58 AMempty_timeout period (which is usually 300 seconds by default).
• There might be a permissions issue with listing rooms. Could you please check if your API key has the roomList permissions enabled?
• If you’re using the names parameter in the ListRooms API, it’s worth double-checking that the correct room name is included.
• Sometimes, creating and deleting rooms quickly with the same name can lead to race conditions, which might cause this behavior.
To help us get to the bottom of this, could you please confirm a few things for me?
• Did any participants join the room after it was created?
• Are you using any filters, like the names parameter, when listing rooms?
• How long after creating the room did you try to list it?
Once we have this info, I’ll be better equipped to assist you and find the best solution. Thanks so much for your patience!
Sources: Avoiding Room ID Reuse When Re-Creating Rooms With the Same Name | packages/livekit-server-sdk/README.md | test/scenarios.go | Rooms, participants, and tracks | LiveKit Docs