Skip to content

Stream conversations and messages

Stream messages

With the agent-sdk, you can listen for different types of messages using event handlers. The agent automatically handles streaming and provides simple event-based APIs.

Node
// Listen for text messages
agent.on('text', async (ctx) => {
  console.log(`New text message: ${ctx.message.content}`);
  await ctx.sendText('Got your message!');
});
 
// Listen for reactions
agent.on('reaction', async (ctx) => {
  console.log(`New reaction: ${ctx.message.content}`);
});
 
// Listen for replies
agent.on('reply', async (ctx) => {
  console.log(`New reply: ${ctx.message.content}`);
});

Stream all messages

Node
import { filter } from '@xmtp/agent-sdk';
 
const agent = await Agent.createFromEnv();
 
agent.on('message', async (ctx) => {
  // Filter for specific message types
  if (filter.isText(ctx.message)) {
    await ctx.sendText(`Echo: ${ctx.message.content}`);
  }
});
 
// Listen for unknown messages
agent.on('unknownMessage', (ctx) => {
  // handle the unknown message
});

Stream conversations

You can listen to new conversations using the dm and group events.

Node
// Listen to new conversations
agent.on('dm', async (ctx) => {
  // received when you create a new dm
  console.log('New dm created:', ctx.conversation.id);
});
 
agent.on('group', async (ctx) => {
  // received when you create a new group
  console.log('Added to group:', ctx.conversation.id);
});

Handle errors and failures

The agent-sdk automatically handles connection failures and reconnections. You can listen for errors using the error handler:

Node
// Handle uncaught errors
agent.on('unhandledError', (error) => {
  console.error(`Agent error: ${error}`);
  // Handle the error appropriately
});