Edit

Share via


Sending Messages

Sending messages is a core part of an agent's functionality. With all activity handlers, a send method is provided which allows your handlers to send a message back to the user to the relevant conversation.

app.on('message', async ({ activity, send }) => {
  await send(`You said: ${activity.text}`);
});
app.OnMessage(async context =>
{
    await context.Send($"you said: {context.activity.Text}");
});
@app.on_message
async def handle_message(ctx: ActivityContext[MessageActivity]):
    await ctx.send(f"You said '{ctx.activity.text}'")

In the above example, the handler gets a message activity, and uses the send method to send a reply to the user.

app.on('signin.verify-state', async ({ send }) => {
  await send('You have successfully signed in!');
});
  app.OnVerifyState(async context =>
  {
      await context.Send("You have successfully signed in!");
  });
@app.event("sign_in")
async def handle_sign_in(event: SignInEvent):
    """Handle sign-in events."""
    await event.activity_ctx.send("You are now signed in!")

You are not restricted to only replying to message activities. In the above example, the handler is listening to signin.verify-state events, which are sent when a user successfully signs in.

You are not restricted to only replying to message activities. In the above example, the handler is listening to SignIn.VerifyState events, which are sent when a user successfully signs in.

You are not restricted to only replying to message activities. In the above example, the handler is listening to sign_in events, which are sent when a user successfully signs in.

Tip

This shows an example of sending a text message. Additionally, you are able to send back things like adaptive cards by using the same send method. Look at the adaptive card section for more details.

Streaming

You may also stream messages to the user which can be useful for long messages, or AI generated messages. The SDK makes this simple for you by providing a stream function which you can use to send messages in chunks.

app.on('message', async ({ activity, stream }) => {
  stream.emit('hello');
  stream.emit(', ');
  stream.emit('world!');

  // result message: "hello, world!"
});
app.OnMessage(async context =>
{
    context.Stream.Emit("hello");
    context.Stream.Emit(", ");
    context.Stream.Emit("world!");
    // result message: "hello, world!"
    return Task.CompletedTask;
});
@app.on_message
async def handle_message(ctx: ActivityContext[MessageActivity]):
    ctx.stream.update("Stream starting...")
    await asyncio.sleep(1)

    # Stream messages with delays using ctx.stream.emit
    for message in STREAM_MESSAGES:
        # Add some randomness to timing
        await asyncio.sleep(random())

        ctx.stream.emit(message)

Note

Streaming is currently only supported in 1:1 conversations, not group chats or channels

Animated image showing agent response text incrementally appearing in the chat window.

@Mention

Sending a message at @mentions a user is as simple including the details of the user using the addMention method

Sending a message at @mentions a user is as simple including the details of the user using the AddMention method

Sending a message at @mentions a user is as simple including the details of the user using the add_mention method

app.on('message', async ({ send, activity }) => {
  await send(new MessageActivity('hi!').addMention(activity.from));
});
app.OnMessage(async context =>
{
    await context.Send(new MessageActivity("hi!").AddMention(activity.From));
});
@app.on_message
async def handle_message(ctx: ActivityContext[MessageActivity]):
  await ctx.send(MessageActivityInput(text='hi!').add_mention(account=ctx.activity.from_))

Targeted Messages

Note

Targeted messages are currently in preview.

Targeted messages, also known as ephemeral messages, are delivered to a specific user in a shared conversation. From a single user's perspective, they appear as regular inline messages in a conversation. Other participants won't see these messages, making them useful for authentication flows, help or error responses, personal reminders, or sharing contextual information without cluttering the group conversation.

To send a targeted message when responding to an incoming activity, use the withRecipient method with the recipient account and set the targeting flag to true.

To send a targeted message when responding to an incoming activity, use the WithRecipient method with the recipient account and set the targeting flag to true.

To send a targeted message when responding to an incoming activity, use the with_recipient method with the recipient account and set the targeting flag to true.

import { MessageActivity } from '@microsoft/teams.api';

app.on('message', async ({ send, activity }) => {
  // Using withRecipient with isTargeted=true explicitly targets the specified recipient
  await send(
    new MessageActivity('This message is only visible to you!')
      .withRecipient(activity.from, true)
  );
});
app.OnMessage(async context =>
{
    // Using WithRecipient with isTargeted=true explicitly targets the specified recipient
    await context.Send(
        new MessageActivity("This message is only visible to you!")
            .WithRecipient(context.Activity.From, isTargeted: true)
    );
});
from microsoft_teams.api import MessageActivity, MessageActivityInput
from microsoft_teams.apps import ActivityContext

@app.on_message
async def handle_message(ctx: ActivityContext[MessageActivity]):
    # Using with_recipient with is_targeted=True explicitly targets the specified recipient
    await ctx.send(
        MessageActivityInput(text="This message is only visible to you!")
            .with_recipient(ctx.activity.from_, is_targeted=True)
    )