is there a way to send a custom event to a room?
# ask-ai
h
is there a way to send a custom event to a room?
t
Thanks for reaching out, Gabi. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! If you want to send a custom event (a little data packet) to a room in LiveKit, you can do that easily using either the server SDKs or the client SDKs: • Server SDK: Just use the
RoomServiceClient.sendData()
method to send data to everyone in the room. Here’s a quick example in Node.js:
Copy code
import { RoomServiceClient } from 'livekit-server-sdk';

const roomService = new RoomServiceClient(LIVEKIT_URL, API_KEY, API_SECRET);
await roomService.sendData(
  roomName,
  Buffer.from('Hello World'), // data as Uint8Array
  DataPacket_Kind.RELIABLE // delivery kind
);
• Client SDK: If you’re a participant in the room, you can use
LocalParticipant.publishData()
. Here’s how it looks in Rust:
Copy code
room.local_participant()
    .publish_data(DataPacket {
        payload: "Hello world".to_owned().into_bytes(),
        reliable: true,
        ..Default::default()
    })
    .await
    .unwrap();
You get to pick between reliable (which means in-order delivery) and lossy (best-effort delivery) options. Plus, if you want, you can add a topic or even target specific participants. Pretty flexible, right? Sources: src/main/kotlin/io/livekit/server/RoomServiceClient.kt | cmd/lk/room.go | agent-console/app/api/room/send-data/route.ts | examples/basic_room_async/src/main.rs | Data packets | LiveKit Docs
h
i need it in python, and also if you can show me how to handle this event in the entrypoint
t
Just to make sure I understand you correctly—are you trying to send the custom event from a server-side Python script, or from a participant using a Python client SDK? Also, when you talk about handling the event in the entrypoint, do you mean processing it on the server side or inside a participant’s application? I’m here to help clarify!
h
I'm trying to send the custom event from a server-side python script. by handling in the entrypoint i mean setting a handler for it after i instanciate the AgentSession
t
Hey there! If you want to send a custom event from a server-side Python script and catch it in the
AgentSession
entrypoint, here’s a friendly step-by-step guide for you: Sending a Custom Event You can use the
perform_rpc
method to send a nicely structured payload to a specific participant like this:
Copy code
import json

payload = {
    "action": "show",
    "id": "quiz_123",
    "questions": ["What is LiveKit?", "How do agents work?"]
}
json_payload = json.dumps(payload)

await room.local_participant.perform_rpc(
    destination_identity=participant.identity,
    method="client.quiz",
    payload=json_payload
)
This sends the event using the method name
client.quiz
directly to the participant you specify. Handling the Event in the Entrypoint To catch these incoming RPC calls, just register a handler with
register_rpc_method
like this:
Copy code
async def entrypoint(ctx):
    await ctx.connect()

    async def handle_flip_flash_card(rpc_data):
        payload = json.loads(rpc_data.payload)
        card_id = payload.get("id")
        if card_id:
            print(f"Flipping card with ID: {card_id}")
            return json.dumps({"status": "success", "id": card_id})

    ctx.room.local_participant.register_rpc_method(
        "agent.flipFlashCard",
        handle_flip_flash_card
    )

    session = AgentSession()
    await session.start(agent=agent, room=ctx.room)
This setup lets your agent respond to events sent from the client with the method name
agent.flipFlashCard
. Pretty neat, right? Some Friendly Reminders • Remember to use
json.dumps()
to turn your structured data into a string for
perform_rpc
. • Your handlers will get an
RpcInvocationData
object containing the payload and who called it. • Make sure your agent is connected to the room before sending or receiving any RPCs to keep things running smoothly. If anything’s unclear or you want me to walk you through more examples, just give me a shout—I’m here to help! Sources: metrics/send-metrics-to-3p/send_metrics_to_3p.py | Job lifecycle | LiveKit Docs | livekit-rtc/livekit/rtc/room.py
h
this is an event to a specific participant. i need a general event to the room (for example to start a video agent) and handle it as a room event
t
Just to make sure I’m on the right track—are you hoping to broadcast a general event to everyone in the room (like starting a video agent) so that each participant can respond to it as a room-wide event? Also, would you prefer this event to be managed by the server or by each participant’s client app?
h
i don't care for the participants to receive the event. i need to catch the event with @ctx.room.on or something simillar
t
Hey there! If you want to send a general event to a room and handle it using
@ctx.room.on
in LiveKit with Python, here’s a simple way to do it: Sending a General Event Just use the
publish_data
method on the
room.local_participant
object to send your data like this:
Copy code
await room.local_participant.publish_data("hello world", topic="general_event")
Feel free to specify a
topic
to keep things organized, and you can pick between reliable or lossy delivery depending on what you need. Handling the Event To listen for the event, register a listener for
data_received
using
@room.on("data_received")
like this:
Copy code
@room.on("data_received")
def on_data_received(data_packet):
    print(f"Received data from {data_packet.participant.identity}: {data_packet.data.decode()}")
    if data_packet.topic == "general_event":
        print("This is a general event")
Complete Example
Copy code
async def entrypoint(ctx):
    room = ctx.room

    @room.on("data_received")
    def on_data_received(data_packet):
        print(f"Message from {data_packet.participant.identity}: {data_packet.data.decode()}")

    # Connect to the room
    await ctx.connect()

    # Send a general event
    await room.local_participant.publish_data("hello world", topic="general_event")
And that’s it! This setup will help you send and handle room-wide events smoothly. If you have any questions or want to dive deeper, just let me know — I’m here to help! Sources: livekit-rtc/livekit/rtc/room.py | Data packets | LiveKit Docs
h
to run
await room.local_participant.publish_data("hello world", topic="general_event")
i need the room instance. how can i get it in a backend server?
t
If you want to grab a room instance on your backend server using Python, you can use the
list_rooms()
method from the LiveKit API and filter by the room name you’re interested in. Here’s a simple example to get you started:
Copy code
from livekit import api
import asyncio

async def get_room_instance(room_name: str):
    # Set up the API client
    lkapi = api.LiveKitAPI("https://your-livekit-server.com")
    
    try:
        # Fetch rooms filtered by the specific name
        room_list = await lkapi.room.list_rooms(
            api.ListRoomsRequest(names=[room_name])
        )
        
        if room_list.rooms:
            room_instance = room_list.rooms[0]
            print(f"Found room: {room_instance.name}")
            print(f"Participants: {room_instance.num_participants}")
            print(f"Created: {room_instance.creation_time}")
            return room_instance
        else:
            print(f"Room '{room_name}' not found")
            return None
            
    finally:
        await lkapi.aclose()

asyncio.run(get_room_instance("my-room"))
This way, you get all the room details you need! If anything’s unclear or you want to dive deeper, just give me a shout—I’m here to help! Sources: livekit-protocol/livekit/protocol/room.pyi
h
what room event can signal a video avatar participant turn end
t
Hey there! So, there isn’t a specific RoomEvent that signals when a video avatar participant’s turn ends. Usually, this is managed inside the
AgentSession
using things like Voice Activity Detection (VAD) or Speech-to-Text (STT) endpointing. Just curious—are you working on this within an AI agent using the LiveKit Agents framework, or are you trying to detect turn end in a client app without agents? I’m here to help either way! Sources: Pipeline nodes and hooks | LiveKit Docs | web/src/data/turn-end-types.ts | AI voice agents | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_session.py | livekit-rtc/livekit/rtc/_proto/room_pb2.py
h
I have a tavus avatar connecting to a room (tavus plugin). I want to remove it from a room (using the livekit api) but i want to do it only after it finishes his "turn" so i'm trying to find a way to identify its turn end
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!