Skip to main content

Send and list messages with XMTP

The message payload can be a plain string, but you can configure custom content types. To learn more, see Content types.

Send messages

To send a message, the recipient must have already started their client at least once and consequently advertised their key bundle on the network.

You might want to consider optimistically sending messages.

const conversation = await xmtp.conversations.newConversation(
"0x3F11b27F323b62B159D2642964fa27C46C841897",
);
await conversation.send("Hello world");

List messages in a conversation

You can receive the complete message history in a conversation.

for (const conversation of await xmtp.conversations.list()) {
// All parameters are optional and can be omitted
const opts = {
// Only show messages from last 24 hours
startTime: new Date(new Date().setDate(new Date().getDate() - 1)),
endTime: new Date(),
};
const messagesInConversation = await conversation.messages(opts);
}

List messages in a conversation with pagination

If a conversation has a lot of messages, it's more performant to retrieve and process the messages page by page instead of handling all of the messages at once.

Call conversation.messagesPaginated(), which will return an AsyncGenerator yielding one page of results at a time. conversation.messages() uses this under the hood internally to gather all messages.

const conversation = await xmtp.conversations.newConversation(
"0x3F11b27F323b62B159D2642964fa27C46C841897",
);

for await (const page of conversation.messagesPaginated({ pageSize: 25 })) {
for (const msg of page) {
// Breaking from the outer loop will stop the client from requesting any further pages
if (msg.content === "gm") {
return;
}
console.log(msg.content);
}
}

Decode a single message

You can decode a single Envelope from XMTP using the decode method:

let conversation = try await client.conversations.newConversation(
with: "0x3F11b27F323b62B159D2642964fa27C46C841897")

// Assume this function returns an Envelope that contains a message for the above conversation
let envelope = getEnvelopeFromXMTP()

let decodedMessage = try conversation.decode(envelope)

Was the information on this page helpful?
powered by XMTP