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 code your app to listen for new conversations in real time. Listening for new conversations lets your app 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 code your app to listen for new incoming and outgoing messages in a conversation by calling conversation.streamMessages().

The stream returned by the stream methods is an asynchronous iterator. This means that the stream can be used by a for-await-of loop. However, note that by its nature, the stream is infinite. Therefore, any looping construct used with the stream won't terminate unless you explicitly initiate the termination. You can initiate the termination by breaking the loop or by making 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 that the stream can miss messages if multiple new conversations are received while the stream is being updated 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}`);
}

Listen for group chat updates

Monitor updates in group chats, including member management activities like adding and removing members as well as the creation of new group chats.

Code sample expected for Q2 2024

Was the information on this page helpful?
powered by XMTP