What’s the JS code for sending text stream in a li...
# ask-ai
p
What’s the JS code for sending text stream in a livekit room?
t
Thanks for reaching out, Ali. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'd love to help you with sending a text stream in a LiveKit room using JavaScript! Here are two friendly approaches you can try: 1. Sending Text All at Once: If you have the entire text ready, the
sendText
method is super handy. It takes care of chunking and streaming the text for you.
Copy code
const text = 'Lorem ipsum dolor sit amet...';
const info = await room.localParticipant.sendText(text, {
  topic: 'my-topic',
});

console.log(`Sent text with stream ID: ${info.id}`);
2. Streaming Text Incrementally: For cases where your content is generated bit by bit,
streamText
is perfect. It opens a writer so you can send text chunks as they come. Just remember to close the stream when you're done.
Copy code
const streamWriter = await room.localParticipant.streamText({
  topic: 'my-topic',
});

console.log(`Opened text stream with ID: ${streamWriter.info.id}`);

// Example text chunks
const textChunks = ["Lorem ", "ipsum ", "dolor ", "sit ", "amet..."];
for (const chunk of textChunks) {
  await streamWriter.write(chunk);
}

// Close the stream to signal completion
await streamWriter.close();

console.log(`Closed text stream with ID: ${streamWriter.info.id}`);
If you have any questions or want me to walk you through any part, just let me know—I'm here to help! Sources: Sending text | LiveKit Docs
p
and how can I receive texts from others in the room?
t
To receive texts from others in a LiveKit room, you can easily register a text stream handler using the
registerTextStreamHandler
method. This handler will help you process incoming text streams sent by other participants, making it simple to stay connected and informed. Here’s a friendly example to guide you:
Copy code
room.registerTextStreamHandler('my-topic', async (reader, participantInfo) => {
  const info = reader.info;
  console.log(
    `Received text stream from ${participantInfo.identity}\n` +
    `  Topic: ${info.topic}\n` +
    `  Timestamp: ${info.timestamp}\n` +
    `  ID: ${info.id}\n` +
    `  Size: ${info.size}` // Only available if sent via `sendText`
  );

  // Option 1: Process incrementally
  for await (const chunk of reader) {
    console.log(`Next chunk: ${chunk}`);
  }

  // Option 2: Read entire message at once
  const text = await reader.readAll();
  console.log(`Received text: ${text}`);
});
Whenever someone sends text using
sendText
or
streamText
, this handler will be triggered. You have the flexibility to process the text bit by bit as it arrives or all together once the stream finishes. If anything feels unclear or you’d like a hand with this, please don’t hesitate to reach out—I’m here to help! Sources: Realtime data | LiveKit Docs | packages/react/src/hooks/useTextStream.ts | Sending text | LiveKit Docs
p
give me python for the same receiving text
t
To receive texts from others in a LiveKit room using Python, let's walk through the steps together: 1. Define a callback function: This function will help you handle incoming text streams. You have the option to read the entire text once the stream finishes or to process it bit by bit as it comes in.
Copy code
async def on_text_received(reader: rtc.TextStreamReader, participant_identity: str):
    # Option 1: Read full text at once
    full_text = await reader.read_all()
    print(f"Received from {participant_identity}: {full_text}")

    # Option 2: Process incrementally
    print(f"Streaming text from {participant_identity}:")
    async for chunk in reader:
        print(chunk, end="", flush=True)
    print()  # New line after stream ends
2. Register the handler for a topic:
Copy code
room.register_text_stream_handler("chat", on_text_received)
3. Connect to the room:
Copy code
await room.connect("wss://your-room.livekit.cloud", "your-access-token")
4. Example Code:
Copy code
import asyncio
import logging
from livekit import rtc

async def main():
    room = rtc.Room()
    logging.basicConfig(level=logging.INFO)

    async def on_text_received(reader: rtc.TextStreamReader, participant_identity: str):
        text = await reader.read_all()
        logging.info(f"Message from {participant_identity}: {text}")

    room.register_text_stream_handler("chat", on_text_received)

    # Replace with your LiveKit URL and access token
    await room.connect("wss://your-room.livekit.cloud", "your-access-token")

    # Keep the connection alive
    await asyncio.Event().wait()

if __name__ == "__main__":
    asyncio.run(main())
Just make sure the sender is using the same topic (like "chat") so the receiver can catch those messages smoothly. If you run into any questions or need a hand with anything else, feel free to reach out—I'm here to help! Sources: Agents v0.x migration guide - Python | LiveKit Docs | examples/data-streams/data_streams.py | Sending text | LiveKit Docs
p
If a participant joins the room later after some chats were already done, is it possible for that new participant to see all the existing chats?
t
Hi there! I wanted to let you know that when a new participant joins a LiveKit room, they won’t be able to see the chat messages that were sent before they arrived. LiveKit doesn’t have built-in message persistence for text streams, so messages are shared in real-time only with those currently in the room. If it’s important for new participants to catch up on previous chats, a great approach would be to set up an external storage system, like a database, to save messages and then share the chat history when someone joins. I'd be more than happy to help you with ideas or steps on how to set this up—just let me know! Sources: Sending text | LiveKit Docs | Sending files & bytes | LiveKit Docs | packages/core/src/components/chat.ts
p
how about room.on(“text_received”, _on_text_received) Does that not work?
t
Hi there! I wanted to share a little tip about LiveKit's Room class. The
room.on('text_received', _on_text_received)
event listener isn't actually available for handling text streams. Instead, LiveKit uses a topic-based handler registration system to receive text, which works really well once you get the hang of it. To receive text, you’d want to use
registerTextStreamHandler
. Here’s a simple example to help you visualize it:
Copy code
room.registerTextStreamHandler('chat', async (reader, participantInfo) => {
  const text = await reader.readAll();
  console.log(`Received chat message: ${text}`);
});
This is the recommended way to handle text streams in LiveKit. If you have any questions or would like me to walk you through more examples tailored to your SDK, just let me know—I’m here to help! Sources: Sending text | LiveKit Docs | test/core/data_stream_test.dart | Agents v0.x migration guide - Node.js | LiveKit Docs | livekit-agents/livekit/agents/voice/room_io/room_io.py | Agents v0.x migration guide - Python | LiveKit Docs