Skip to main content

Stream conversations and messages with XMTP

XMTP supports real-time message delivery and retrieval. Once you initially retrieve existing conversations, you can listen for a real-time stream of new conversations and messages.

Listen for new conversations

You can listen for new conversations being started in real-time. This enables apps to display incoming messages from new contacts.

const stream = await xmtp.conversations.stream();
for await (const conversation of stream) {
console.log(`New conversation started with ${conversation.peerAddress}`);
// Say hello to your new friend
await conversation.send("Hi there!");
// Break from the loop to stop listening
//This stream will continue infinitely. To end the stream,
//You can either break from the loop, or call `await stream.return()`.
break;
}

Listen for new messages in a conversation

You can listen for any new messages (incoming or outgoing) in a conversation by calling conversation.streamMessages().

The Stream returned by the stream methods is an asynchronous iterator and as such usable by a for-await-of loop. Note however that it is by its nature infinite, so any looping construct used with it will not terminate, unless the termination is explicitly initiated (by breaking the loop or by an external call to return).

const conversation = await xmtp.conversations.newConversation(
"0x3F11b27F323b62B159D2642964fa27C46C841897",
);
for await (const message of await conversation.streamMessages()) {
if (message.senderAddress === xmtp.address) {
// This message was sent from me
continue;
}
console.log(`New message from ${message.senderAddress}: ${message.content}`);
}

Listen for new messages in all conversations

info

There is a chance this stream can miss messages if multiple new conversations are received in the time it takes to update the stream to include a new conversation.

for await (const message of await xmtp.conversations.streamAllMessages()) {
if (message.senderAddress === xmtp.address) {
// This message was sent from me
continue;
}
console.log(`New message from ${message.senderAddress}: ${message.content}`);
}

Was the information on this page helpful?
powered by XMTP