Verwenden Sie Nachrichtenerweiterungen in Microsoft Teams

Nachrichtenerweiterungen erscheinen als Befehle im Teams Compose-Box, im Aktionsmenü in Nachrichten oder in Link-Vorschauen. Im Teams-App-Manifest wird jeder Befehl durch die id Eigenschaft im Array composeExtensions[].commands[] identifiziert. Geben Sie diesen Wert an den commandId Parameter der SDK-Route weiter, wie zum Beispiel das Konstruktorargument in [TeamsQueryRoute("searchQuery")].

Die Beispiele erstellen Karten-Payloads als JSON. Für Hinweise zur Kartenstruktur und anderen C#-Konstruktionsoptionen siehe Building Adaptive Karten.

Abfrage und SelectItem

Nutzer können Ihren Service abfragen und Ergebnisse auswählen, die sie in eine Nachricht einfügen.

Fügen Sie diesen Befehl dem Teams-Manifest hinzu:

"composeExtensions": [
  {
    "commands": [
      {
        "id": "searchQuery",
        "type": "query",
        "title": "searchQuery",
        "description": "searchQuery",
        "initialRun": true,
        "fetchTask": false,
        "context": ["commandBox", "compose"],
        "parameters": [
          {
            "name": "searchQuery",
            "title": "Search Query",
            "description": "Search Query",
            "inputType": "text"
          }
        ]
      }
    ]
  }
]
using Microsoft.Teams.Apps.MessageExtensions;
using Microsoft.Teams.Apps.Schema;
using System.Text.Json;

[TeamsExtension]
public partial class SearchAgent(AgentApplicationOptions options) : AgentApplication(options)
{
    [TeamsQueryRoute("searchQuery")]
    public Task<MessageExtensionResponse> OnSearchAsync(
        ITeamsTurnContext turnContext,
        ITurnState turnState,
        MessageExtensionQuery query,
        CancellationToken cancellationToken)
    {
        bool initialRun = query.Parameters?
            .FirstOrDefault(p => p.Name == "initialRun")?
            .Value?.ToString() == "true";

        if (initialRun)
        {
            return Task.FromResult(CreateMessageResponse("Enter search query"));
        }

        string searchText = query.Parameters?
            .FirstOrDefault(p => p.Name == "searchQuery")?.Value?.ToString() ?? "";

        var attachments = new List<TeamsAttachment>();
        for (int i = 1; i <= 5; i++)
        {
            var cardJson = $$"""
            {
              "type": "AdaptiveCard",
              "version": "1.4",
              "body": [
                {
                  "type": "TextBlock",
                  "text": {{$"Search Result {i}"}},
                  "size": "Large",
                  "weight": "Bolder"
                },
                {
                  "type": "TextBlock",
                  "text": {{$"Query: '{searchQuery}' - Result description for item {i}"}},
                  "wrap": true,
                  "isSubtle": true
                }
              ]
            }
            """;

            var previewJson = $$"""
            {
              "title": {{$"Result {i}"}},
              "text": {{$"This is a preview of result {i} for query '{searchQuery}'."}},
              "tap": {
                "type": "invoke",
                "value": {
                  "index": {{$"{i}"}},
                  "query": {{$"{searchQuery}"}}
                }
              }
            }
            """;

            attachments.Add(CreateAdaptiveCardAttachment(cardJson, previewJson));
        }

        return Task.FromResult(CreateResultResponse([.. attachments]));
    }

    [TeamsSelectItemRoute]
    public Task<MessageExtensionResponse> OnSelectItemAsync(
        ITeamsTurnContext turnContext,
        ITurnState turnState,
        Dictionary<string, string> items,
        CancellationToken cancellationToken)
    {
        var index = items.TryGetValue("index", out string? value) ? value : "No Index";
        var query = items.TryGetValue("query", out string? queryValue) ? queryValue : "No Query";

        var cardJson = $$"""
        {
          "type": "AdaptiveCard",
          "version": "1.4",
          "body": [
            {
              "type": "TextBlock",
              "text": "Item Selected",
              "size": "Large",
              "weight": "Bolder",
              "color": "Good"
            },
            {
              "type": "TextBlock",
              "text": {{$"You selected item: {index} for query: '{query}'"}},
              "wrap": true,
              "separator": true,
              "fontType": "Monospace"
            }
          ]
        }
        """;

        return Task.FromResult(
            CreateResultResponse(CreateAdaptiveCardAttachment(cardJson)));
    }

    private static MessageExtensionResponse CreateMessageResponse(string text)
    {
        return MessageExtensionResponse.CreateBuilder()
            .WithType(MessageExtensionResponseTypes.Message)
            .WithText(text)
            .Build()
            .Body
            ?? throw new InvalidOperationException("The message extension response builder returned no body.");
    }

    private static MessageExtensionResponse CreateResultResponse(params TeamsAttachment[] attachments)
    {
        return MessageExtensionResponse.CreateBuilder()
            .WithType(MessageExtensionResponseTypes.Result)
            .WithAttachmentLayout(AttachmentLayoutType.List)
            .WithAttachments(attachments)
            .Build()
            .Body
            ?? throw new InvalidOperationException("The message extension response builder returned no body.");
    }

    private static TeamsAttachment CreateAdaptiveCardAttachment(
        string cardJson,
        string? previewJson = null)
    {
        var attachment = new TeamsAttachment
        {
            ContentType = AttachmentContentTypes.AdaptiveCard,
            Content = JsonSerializer.Deserialize<JsonElement>(cardJson)
        };

        if (previewJson is not null)
        {
            attachment.Properties = new()
            {
                ["preview"] = new TeamsAttachment
                {
                    ContentType = AttachmentContentTypes.ThumbnailCard,
                    Content = JsonSerializer.Deserialize<JsonElement>(previewJson)
                }
            };
        }

        return attachment;
    }
}
teams.messageExtensions
  .onQuery('searchQuery', async (context, state, query) => {
    const initialRun = query.parameters
      ?.find((parameter) => parameter.name === 'initialRun')
      ?.value?.toString() === 'true'

    if (initialRun) {
      return {
        composeExtension: {
          type: 'message',
          text: 'Enter search query'
        }
      }
    }

    const searchText = query.parameters
      ?.find((parameter) => parameter.name === 'searchQuery')
      ?.value?.toString() ?? ''

    const attachments = []
    for (let i = 1; i <= 5; i++) {
      attachments.push({
        contentType: 'application/vnd.microsoft.card.adaptive',
        content: {
          $schema: 'https://adaptivecards.io/schemas/adaptive-card.json',
          type: 'AdaptiveCard',
          version: '1.4',
          body: [
            {
              type: 'TextBlock',
              text: `Search Result ${i}`,
              size: 'Large',
              weight: 'Bolder'
            },
            {
              type: 'TextBlock',
              text: `Query: '${searchText}' - Result description for item ${i}`,
              wrap: true,
              isSubtle: true
            }
          ]
        },
        preview: {
          contentType: 'application/vnd.microsoft.card.thumbnail',
          content: {
            title: `Result ${i}`,
            text: `This is a preview of result ${i} for query '${searchText}'.`,
            tap: {
              type: 'invoke',
              value: { index: i.toString(), query: searchText }
            }
          }
        }
      })
    }

    return {
      composeExtension: {
        attachmentLayout: 'list',
        type: 'result',
        attachments
      }
    }
  })
  .onSelectItem(async (context, state, item) => {
    const index = item?.index ?? 'No Index'
    const query = item?.query ?? 'No Query'

    return {
      composeExtension: {
        attachmentLayout: 'list',
        type: 'result',
        attachments: [{
          contentType: 'application/vnd.microsoft.card.adaptive',
          content: {
            $schema: 'https://adaptivecards.io/schemas/adaptive-card.json',
            type: 'AdaptiveCard',
            version: '1.4',
            body: [
              {
                type: 'TextBlock',
                text: 'Item Selected',
                size: 'Large',
                weight: 'Bolder',
                color: 'Good'
              },
              {
                type: 'TextBlock',
                text: `You selected item: ${index} for query: '${query}'`,
                wrap: true,
                separator: true,
                fontType: 'Monospace'
              }
            ]
          }
        }]
      }
    }
  })
from microsoft_teams.api.models import (
    MessagingExtensionQuery,
    MessagingExtensionResponse,
    MessagingExtensionResult,
    MessagingExtensionResultType,
    MessagingExtensionAttachment,
    MessagingExtensionAttachmentLayout,
)

@teams.message_extensions.query("searchQuery")
async def on_search(context, state, query: MessagingExtensionQuery) -> MessagingExtensionResponse:
    params = {p.name: p.value for p in (query.parameters or [])}
    if str(params.get("initialRun", "")).lower() == "true":
        return MessagingExtensionResponse(
            compose_extension=MessagingExtensionResult(
                type=MessagingExtensionResultType.MESSAGE,
                text="Enter search query",
            )
        )

    search_text = str(params.get("searchQuery", "") or "")

    attachments = []
    for i in range(1, 6):
        card = {
            "$schema": "https://adaptivecards.io/schemas/adaptive-card.json",
            "type": "AdaptiveCard",
            "version": "1.4",
            "body": [
                {
                    "type": "TextBlock",
                    "text": f"Search Result {i}",
                    "size": "Large",
                    "weight": "Bolder",
                },
                {
                    "type": "TextBlock",
                    "text": f"Query: '{search_text}' - Result description for item {i}",
                    "wrap": True,
                    "isSubtle": True,
                },
            ],
        }
        preview = {
            "title": f"Result {i}",
            "text": f"This is a preview of result {i} for query '{search_text}'.",
            "tap": {"type": "invoke", "value": {"index": str(i), "query": search_text}},
        }
        attachments.append(
            MessagingExtensionAttachment(
                content_type="application/vnd.microsoft.card.adaptive",
                content=card,
                preview=MessagingExtensionAttachment(
                    content_type="application/vnd.microsoft.card.thumbnail",
                    content=preview,
                ),
            )
        )

    return MessagingExtensionResponse(
        compose_extension=MessagingExtensionResult(
            type=MessagingExtensionResultType.RESULT,
            attachment_layout=MessagingExtensionAttachmentLayout.LIST,
            attachments=attachments,
        )
    )

@teams.message_extensions.select_item
async def on_select_item(context, state, item) -> MessagingExtensionResponse:
    item = item or {}
    index = item.get("index", "No Index")
    query = item.get("query", "No Query")
    card = {
        "$schema": "https://adaptivecards.io/schemas/adaptive-card.json",
        "type": "AdaptiveCard",
        "version": "1.4",
        "body": [
            {
                "type": "TextBlock",
                "text": "Item Selected",
                "size": "Large",
                "weight": "Bolder",
                "color": "Good",
            },
            {
                "type": "TextBlock",
                "text": f"You selected item: {index} for query: '{query}'",
                "wrap": True,
                "separator": True,
                "fontType": "Monospace",
            },
        ],
    }
    return MessagingExtensionResponse(
        compose_extension=MessagingExtensionResult(
            type=MessagingExtensionResultType.RESULT,
            attachment_layout=MessagingExtensionAttachmentLayout.LIST,
            attachments=[
                MessagingExtensionAttachment(
                    content_type="application/vnd.microsoft.card.adaptive",
                    content=card,
                )
            ],
        )
    )

Aktionsbefehle

Ein Befehl „Aktion absenden“ öffnet ein Formular, sammelt Eingaben und gibt eine Karte zurück, die in die Unterhaltung eingeladen wird.

Das Teams-Manifest muss folgenden Befehl enthalten:

"composeExtensions": [
  {
    "commands": [
      {
        "id": "createCard",
        "type": "action",
        "title": "Create Card",
        "description": "Create Card",
        "initialRun": false,
        "fetchTask": false,
        "context": ["commandBox", "compose", "message"],
        "parameters": [
          { "name": "title", "title": "Title", "inputType": "text" },
          { "name": "description", "title": "Description", "inputType": "text" }
        ]
      }
    ]
  }
]
using Microsoft.Teams.Apps.MessageExtensions;
using Microsoft.Teams.Apps.Schema;
using System.Text.Json;

[TeamsSubmitActionRoute("createCard")]
public Task<MessageExtensionResponse> OnCreateCardAsync(
    ITeamsTurnContext turnContext,
    ITurnState turnState,
    MessageExtensionAction action,
    CancellationToken cancellationToken)
{
    var data = action.GetDataAs<JsonElement>();
    var title = data.GetDataString("title", "Default Title");
    var description = data.GetDataString("description", "Default Description");

    var cardJson = $$"""
    {
        "type": "AdaptiveCard",
        "version": "1.4",
        "body": [
            { "type": "TextBlock", "text": "Custom Card Created", "size": "Large", "weight": "Bolder", "color": "Good" },
            { "type": "TextBlock", "text": {{title}}, "size": "Medium", "weight": "Bolder" },
            { "type": "TextBlock", "text": {{description}}, "wrap": true, "isSubtle": true }
        ]
    }
    """;

    var attachment = new TeamsAttachment
    {
        ContentType = AttachmentContentTypes.AdaptiveCard,
        Content = JsonSerializer.Deserialize<JsonElement>(cardJson)
    };

    var response = MessageExtensionResponse.CreateBuilder()
        .WithType(MessageExtensionResponseTypes.Result)
        .WithAttachmentLayout(AttachmentLayoutType.List)
        .WithAttachments([attachment])
        .Build()
        .Body
        ?? throw new InvalidOperationException("The message extension response builder returned no body.");

    return Task.FromResult(response);
}
teams.messageExtensions
  .onSubmitAction('createCard', async (context, state, action) => {
    const title = action.data?.title ?? 'Default Title'
    const description = action.data?.description ?? 'Default Description'

    return {
      composeExtension: {
        type: 'result',
        attachmentLayout: 'list',
        attachments: [{
          contentType: 'application/vnd.microsoft.card.adaptive',
          content: {
            $schema: 'https://adaptivecards.io/schemas/adaptive-card.json',
            type: 'AdaptiveCard',
            version: '1.4',
            body: [
              { type: 'TextBlock', text: 'Custom Card Created', size: 'Large', weight: 'Bolder', color: 'Good' },
              { type: 'TextBlock', text: title, size: 'Medium', weight: 'Bolder' },
              { type: 'TextBlock', text: description, wrap: true, isSubtle: true }
            ]
          }
        }]
      }
    }
  })

Der Sendaktionshandler erhält ein MessagingExtensionAction. Lesen Sie die Formularfelder aus action.data:

from microsoft_teams.api.models import (
    MessagingExtensionAction,
    MessagingExtensionResponse,
    MessagingExtensionResult,
    MessagingExtensionResultType,
    MessagingExtensionAttachment,
    MessagingExtensionAttachmentLayout,
)

@teams.message_extensions.submit_action("createCard")
async def on_create_card(context, state, action: MessagingExtensionAction) -> MessagingExtensionResponse:
    data = action.data if isinstance(action.data, dict) else {}
    title = data.get("title") or "Default Title"
    description = data.get("description") or "Default Description"

    card = {
        "$schema": "https://adaptivecards.io/schemas/adaptive-card.json",
        "type": "AdaptiveCard",
        "version": "1.4",
        "body": [
            {"type": "TextBlock", "text": "Custom Card Created", "size": "Large", "weight": "Bolder", "color": "Good"},
            {"type": "TextBlock", "text": title, "size": "Medium", "weight": "Bolder"},
            {"type": "TextBlock", "text": description, "wrap": True, "isSubtle": True},
        ],
    }
    return MessagingExtensionResponse(
        compose_extension=MessagingExtensionResult(
            type=MessagingExtensionResultType.RESULT,
            attachment_layout=MessagingExtensionAttachmentLayout.LIST,
            attachments=[
                MessagingExtensionAttachment(
                    content_type="application/vnd.microsoft.card.adaptive",
                    content=card,
                )
            ],
        )
    )

Link-Entfaltung generiert eine reiche Vorschaukarte, wenn Benutzende eine URL in das Compose-Feld einfügen. Teams ruft Ihren Agenten an, wenn die URL-Domain mit einem messageHandlers Eintrag in Ihrem App-Manifest übereinstimmt:

"composeExtensions": [{
  "botId": "...",
  "messageHandlers": [{
    "type": "link",
    "value": { "domains": ["*.contoso.com"] }
  }]
}]
using Microsoft.Teams.Apps.MessageExtensions;
using Microsoft.Teams.Apps.Schema;
using System.Text.Json;

[TeamsQueryLinkRoute]
public Task<MessageExtensionResponse> OnQueryLinkAsync(
    ITeamsTurnContext turnContext,
    ITurnState turnState,
    MessageExtensionQueryLink? query,
    CancellationToken cancellationToken)
{
    var url = query?.Url?.ToString();
    if (string.IsNullOrWhiteSpace(url))
    {
        return Task.FromResult(CreateMessageResponse("No URL provided"));
    }

    var cardJson = $$"""
    {
      "type": "AdaptiveCard",
      "version": "1.4",
      "body": [
        {
          "type": "TextBlock",
          "text": "Link Preview",
          "size": "Medium",
          "weight": "Bolder"
        },
        {
          "type": "TextBlock",
          "text": {{$"URL: {url}"}},
          "wrap": true,
          "isSubtle": true
        },
        {
          "type": "TextBlock",
          "text": "This is a preview of the linked content generated by the message extension.",
          "wrap": true,
          "size": "Small"
        }
      ]
    }
    """;

    var previewJson = $$"""
    {
      "title": "Link Preview",
      "text": {{url}}
    }
    """;

    var attachment = new TeamsAttachment
    {
        ContentType = AttachmentContentTypes.AdaptiveCard,
        Content = JsonSerializer.Deserialize<JsonElement>(cardJson),
        Properties = new()
        {
            ["preview"] = new TeamsAttachment
            {
                ContentType = AttachmentContentTypes.ThumbnailCard,
                Content = JsonSerializer.Deserialize<JsonElement>(previewJson)
            }
        }
    };

    var response = MessageExtensionResponse.CreateBuilder()
        .WithType(MessageExtensionResponseTypes.Result)
        .WithAttachmentLayout(AttachmentLayoutType.List)
        .WithAttachments([attachment])
        .Build()
        .Body
        ?? throw new InvalidOperationException("The message extension response builder returned no body.");

    return Task.FromResult(response);
}

Durch das Entfalten von Zero-Install-/anonymen Links kann Teams Ihren Agent bereits anrufen, noch bevor Benutzer die App installiert haben. Verwenden Sie [TeamsAnonQueryLinkRoute]. Die Handler-Signatur ist identisch. Der Agent kann keine proaktiven Nachrichten senden oder auf Mitgliederdaten im anonymen Kontext zugreifen.

teams.messageExtensions
  .onQueryLink(async (context, state, query) => {
    const url = query?.url
    if (!url) {
      return {
        composeExtension: {
          type: 'message',
          text: 'No URL provided'
        }
      }
    }

    return {
      composeExtension: {
        attachmentLayout: 'list',
        type: 'result',
        attachments: [{
          contentType: 'application/vnd.microsoft.card.adaptive',
          content: {
            $schema: 'https://adaptivecards.io/schemas/adaptive-card.json',
            type: 'AdaptiveCard',
            version: '1.4',
            body: [
              { type: 'TextBlock', text: 'Link Preview', size: 'Medium', weight: 'Bolder' },
              { type: 'TextBlock', text: `URL: ${url}`, wrap: true, isSubtle: true },
              {
                type: 'TextBlock',
                text: 'This is a preview of the linked content generated by the message extension.',
                wrap: true,
                size: 'Small'
              }
            ]
          },
          preview: {
            contentType: 'application/vnd.microsoft.card.thumbnail',
            content: { title: 'Link Preview', text: url }
          }
        }]
      }
    }
  })

Durch das Entfalten von Zero-Install-/anonymen Links kann Teams Ihren Agent bereits anrufen, noch bevor Benutzer die App installiert haben. Verwenden Sie onAnonymousQueryLink. Die Handler-Signatur ist identisch.

Der Handler erhält ein AppBasedLinkQuery. Lesen Sie die eingefügte URL von query.url:

from microsoft_teams.api.models import (
    AppBasedLinkQuery,
    MessagingExtensionResponse,
    MessagingExtensionResult,
    MessagingExtensionResultType,
    MessagingExtensionAttachment,
    MessagingExtensionAttachmentLayout,
)

@teams.message_extensions.query_link
async def on_query_link(context, state, query: AppBasedLinkQuery) -> MessagingExtensionResponse:
    url = query.url or ""
    if not url:
        return MessagingExtensionResponse(
            compose_extension=MessagingExtensionResult(
                type=MessagingExtensionResultType.MESSAGE,
                text="No URL provided",
            )
        )

    card = {
        "$schema": "https://adaptivecards.io/schemas/adaptive-card.json",
        "type": "AdaptiveCard",
        "version": "1.4",
        "body": [
            {"type": "TextBlock", "text": "Link Preview", "size": "Medium", "weight": "Bolder"},
            {"type": "TextBlock", "text": f"URL: {url}", "isSubtle": True, "wrap": True},
            {
                "type": "TextBlock",
                "text": "This is a preview of the linked content generated by the message extension.",
                "wrap": True,
                "size": "Small",
            },
        ],
    }
    return MessagingExtensionResponse(
        compose_extension=MessagingExtensionResult(
            type=MessagingExtensionResultType.RESULT,
            attachment_layout=MessagingExtensionAttachmentLayout.LIST,
            attachments=[
                MessagingExtensionAttachment(
                    content_type="application/vnd.microsoft.card.adaptive",
                    content=card,
                    preview=MessagingExtensionAttachment(
                        content_type="application/vnd.microsoft.card.thumbnail",
                        content={"title": "Link Preview", "text": url},
                    ),
                )
            ],
        )
    )

Durch das Entfalten von Zero-Install-/anonymen Links kann Teams Ihren Agent bereits anrufen, noch bevor Benutzer die App installiert haben. Verwendung @teams.message_extensions.anonymous_query_link – die Handler-Signatur ist identisch.

Nachrichtenvorschau

Wenn Sie eine Compose-Erweiterung mit botMessagePreviewActionkonfigurieren, zeigt Teams dem Benutzer eine Vorschau der Karte, bevor sie gesendet wird.

using Microsoft.Teams.Apps.MessageExtensions;
using Microsoft.Teams.Apps.Schema;
using System.Text.Json;

[TeamsMessagePreviewEditRoute("myCommand")]
public Task<MessageExtensionResponse> OnPreviewEditAsync(
    ITeamsTurnContext turnContext,
    ITurnState turnState,
    MessageExtensionActivityPreview previewActivity,
    CancellationToken cancellationToken)
{
    const string editCardJson = """
    {
      "type": "AdaptiveCard",
      "version": "1.4",
      "body": [
        {
          "type": "TextBlock",
          "text": "Edit card",
          "size": "Large",
          "weight": "Bolder"
        }
      ]
    }
    """;

    var attachment = new TeamsAttachment
    {
        ContentType = AttachmentContentTypes.AdaptiveCard,
        Content = JsonSerializer.Deserialize<JsonElement>(editCardJson)
    };

    var response = MessageExtensionResponse.CreateBuilder()
        .WithType(MessageExtensionResponseTypes.Result)
        .WithAttachmentLayout(AttachmentLayoutType.List)
        .WithAttachments([attachment])
        .Build()
        .Body
        ?? throw new InvalidOperationException("The message extension response builder returned no body.");

    return Task.FromResult(response);
}

[TeamsMessagePreviewSendRoute("myCommand")]
public async Task OnPreviewSendAsync(
    ITeamsTurnContext turnContext,
    ITurnState turnState,
    MessageExtensionActivityPreview previewActivity,
    CancellationToken cancellationToken)
{
    await turnContext.SendActivityAsync("Card sent!", cancellationToken: cancellationToken);
}
import { Activity } from '@microsoft/agents-activity'
import { MessagingExtensionActionResponse } from '@microsoft/teams.api'

teams.messageExtensions
  .onMessagePreviewEdit('myCommand', async (context, state, activity) => {
    return {
      composeExtension: {
        type: 'result',
        attachmentLayout: 'list',
        attachments: [{
          contentType: 'application/vnd.microsoft.card.adaptive',
          content: {
            $schema: 'https://adaptivecards.io/schemas/adaptive-card.json',
            type: 'AdaptiveCard',
            version: '1.4',
            body: [
              {
                type: 'TextBlock',
                text: 'Edit card',
                size: 'Large',
                weight: 'Bolder'
              }
            ]
          }
        }]
      }
    }
  })
  .onMessagePreviewSend('myCommand', async (context, state, activity) => {
    await context.sendActivity('Card sent!')
  })

Die Preview-Handler erhalten die analysierte Vorschau Activity. Verwenden Sie message_preview_edit, um eine bearbeitbare Karte zurückzugeben, und message_preview_send, um sie zu senden:

from microsoft_agents.activity import Activity
from microsoft_teams.api.models import (
    MessagingExtensionResponse,
    MessagingExtensionResult,
    MessagingExtensionResultType,
    MessagingExtensionAttachment,
    MessagingExtensionAttachmentLayout,
)

@teams.message_extensions.message_preview_edit("myCommand")
async def on_preview_edit(context, state, activity_preview: Activity) -> MessagingExtensionResponse:
    return MessagingExtensionResponse(
        compose_extension=MessagingExtensionResult(
            type=MessagingExtensionResultType.RESULT,
            attachment_layout=MessagingExtensionAttachmentLayout.LIST,
            attachments=[
                MessagingExtensionAttachment(
                    content_type="application/vnd.microsoft.card.adaptive",
                    content={
                        "$schema": "https://adaptivecards.io/schemas/adaptive-card.json",
                        "type": "AdaptiveCard",
                        "version": "1.4",
                        "body": [
                            {
                                "type": "TextBlock",
                                "text": "Edit card",
                                "size": "Large",
                                "weight": "Bolder",
                            }
                        ],
                    },
                )
            ],
        )
    )

@teams.message_extensions.message_preview_send("myCommand")
async def on_preview_send(context, state, activity_preview: Activity):
    await context.send_activity("Card sent!")

Settings

Erstelle eine Einstellungsseite, auf die Nutzer über das Zahnrad-Symbol im Flyout der Nachrichtenerweiterung zugreifen können.

using Microsoft.Teams.Apps.MessageExtensions;
using Microsoft.Teams.Apps.Schema;

[TeamsQuerySettingUrlRoute]
public Task<MessageExtensionResponse> OnQuerySettingsUrlAsync(
    ITeamsTurnContext turnContext,
    ITurnState turnState,
    CancellationToken cancellationToken)
{
    var response = MessageExtensionResponse.CreateBuilder()
        .WithType(MessageExtensionResponseTypes.Config)
        .WithSuggestedActions(new Microsoft.Teams.Apps.Schema.SuggestedActions
        {
            Actions =
            [
                new SuggestedAction(
                    ActionType.OpenUrl,
                    "Configure",
                    "https://your-agent-host/settings")
            ]
        })
        .Build()
        .Body
        ?? throw new InvalidOperationException("The message extension response builder returned no body.");

    return Task.FromResult(response);
}

[TeamsSettingRoute]
public Task<MessageExtensionResponse> OnConfigureSettingsAsync(
    ITeamsTurnContext turnContext,
    ITurnState turnState,
    MessageExtensionQuery settings,
    CancellationToken cancellationToken)
{
    // Persist settings.State or settings.Parameters as needed
    return Task.FromResult(new MessageExtensionResponse());
}
import { MessagingExtensionResponse } from '@microsoft/teams.api'

teams.messageExtensions
  .onQuerySettingUrl(async (context, state) => {
    return {
      composeExtension: {
        type: 'config',
        suggestedActions: {
          actions: [{
            type: 'openUrl',
            value: 'https://your-agent-host/settings',
            title: 'Configure'
          }]
        }
      }
    }
  })
  .onSetting(async (context, state, settings) => {
    // Persist the user's settings
    console.log('Settings saved:', settings)
  })

Verwenden Sie query_setting_url, um die URL der Einstellungsseite zurückzugeben, und setting, um die übermittelten Einstellungen anzuwenden:

from microsoft_teams.api.models import (
    MessagingExtensionQuery,
    MessagingExtensionResponse,
    MessagingExtensionResult,
    MessagingExtensionResultType,
)

@teams.message_extensions.query_setting_url
async def on_query_settings_url(context, state, query: MessagingExtensionQuery) -> MessagingExtensionResponse:
    return MessagingExtensionResponse(
        compose_extension=MessagingExtensionResult(
            type=MessagingExtensionResultType.CONFIG,
            suggested_actions={
                "actions": [
                    {"type": "openUrl", "title": "Configure", "value": "https://your-agent-host/settings"}
                ]
            },
        )
    )

@teams.message_extensions.setting
async def on_configure_settings(context, state, query: MessagingExtensionQuery):
    # Persist query.state or query.parameters as needed
    return MessagingExtensionResponse()