How do you receive text sent via the send_text api...
# ask-ai
w
How do you receive text sent via the send_text api in python?
t
Thanks for reaching out, Nathan. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To receive text messages sent via the
send_text
API in Python, you need to register a text stream handler for the topic you expect to receive messages on. Here’s how you can do it: 1. Register a handler for the topic using
room.register_text_stream_handler
. 2. The handler receives a
TextStreamReader
object and the sender's participant identity. 3. You can process the text incrementally as chunks arrive, or read the entire message after the stream completes.
Copy code
import asyncio
from livekit import rtc

async def main(room_name: str):
    room = rtc.Room()
    # Connect to room (token setup omitted for brevity)
    await room.connect(url, token)

    def on_text_received(reader: rtc.TextStreamReader, participant_identity: str):
        async def _on_text_received():
            # Process chunks as they arrive
            async for chunk in reader:
                print(f"Received chunk: {chunk}")
            # Or read all text at once
            # text = await reader.readAll()
            # print(f"Received complete text: {text}")
        task = asyncio.create_task(_on_text_received())

    room.register_text_stream_handler(
        topic='my-topic',
        handler=on_text_received
    )

    await asyncio.Event().wait()
• Replace
'my-topic'
with the topic you are using for
send_text
. • The handler will be called automatically whenever a text message is sent to that topic. You can process the message as it arrives in chunks, or wait for the entire message to be received before processing. Sources: Sending text | LiveKit Docs | examples/other/chat-stream-receiver.py