Activities and handlers

An Activity is a data payload that represents user activity in Teams. As user activity occurs in Teams, Agent Communication Service sends activity payloads to your agent runtime in real time.

For most agents, activity handlers - particularly the chat message handler - are the main entrypoints for the agent's behavior. Register handlers for the activities your agent needs to process, such as messages, member changes, and channel lifecycle events. These activities occur in the conversation scopes where your agent is active.

Some events share a handler; inspect the activity payload to distinguish them rather than registering duplicate handlers.

Register activity handlers

Register handlers with the OnXXX() methods on your agent runtime's TeamsBotApplication instance before starting it. Handlers receive a typed context and a cancellation token.

The following example registers a message handler that echoes the user's message:

teams.OnMessage(async (context, cancellationToken) =>
{
    await context.SendAsync($"You said: {context.Activity.Text}", cancellationToken);
});

Register handlers with app.on(eventName, handler), where app is your agent runtime's main App instance, before starting it. The SDK infers the activity type from the event name. The handler context exposes the incoming activity and functions such as send() and reply() to respond.

The following example registers a message handler that echoes the user's message:

app.on('message', async ({ activity, send }) => {
    await send(`You said: ${activity.text}`);
});

Register an asynchronous function with one of the dedicated event-handler decorators on your agent runtime's App instance like @app.on_message. The handler receives an ActivityContext[TActivity] object. Use ctx.send() or ctx.reply() to respond.

The following example registers a message handler that echoes the user's message:

@app.on_message
async def handle_message(ctx: ActivityContext[MessageActivity]):
    await ctx.send(f"You said: {ctx.activity.text}")

If your agent takes more than 15 seconds to process an activity, Teams sends a retry request to the agent endpoint, so you might see duplicate requests.

For a complete listing of activity events, payload examples, and event-handling guidance, see the agent event reference.

Activity handler chaining

In Teams SDK for .NET, activity handlers do not form a next()-style processing chain. Instead, every handler that matches an activity is invoked in the order it was registered, and one handler cannot prevent subsequent matching handlers from running. If you need to intercept, short-circuit, or wrap request processing (for example, to stop execution when a condition is met), implement ITurnMiddleware and control whether to call nextTurn(...).

The event activity handlers (and attributes) follow a middleware pattern similar to how python middlewares work. This means that for each activity handler, a next function is passed in which can be called to pass control to the next handler. This allows you to build a chain of handlers that can process the same activity in different ways.

@app.on_message
async def handle_message(ctx: ActivityContext[MessageActivity]):
    """Handle message activities using the new generated handler system."""
    print(f"[GENERATED onMessage] Message received: {ctx.activity.text}")
    await ctx.next()
@app.on_message
async def handle_message(ctx: ActivityContext[MessageActivity]):
    """Handle message activities using the new generated handler system."""
    if ctx.activity.text == "/help":
        await ctx.send("Here are all the ways I can help you...")
    await ctx.next()
@app.on_message
async def handle_message(ctx: ActivityContext[MessageActivity]):
    await ctx.send(f"You said '{ctx.activity.text}'")

The on activity handlers follow a middleware pattern similar to how express middlewares work. This means that for each activity handler, a next function is passed in which can be called to pass control to the next handler. This allows you to build a chain of handlers that can process the same activity in different ways.

app.on('message', async ({ next }) => {
  console.log('global logger');
  next(); // pass control onward
});
app.on('message', async ({ activity, next }) => {
  if (activity.text === '/help') {
    await send('Here are all the ways I can help you...');
    return;
  }

  // Conditionally pass control to the next handler
  next();
});
app.on('message', async ({ activity }) => {
  // Fallthrough to the final handler
  await send(`Hello! you said ${activity.text}`);
});

Code sample

Sample name Description TypeScript C# Python
Teams conversation agent This app demonstrates conversation events, Adaptive Cards, read receipts, and message updates. It includes immersive reader support for accessibility. View View View

Next step