microsoft/teams.net
Publicmirrored fromhttps://github.com/microsoft/teams.netAvailable
core/src/Microsoft.Teams.Bot.Apps/Handlers/AdaptiveCardHandler.cs
49lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. |
| 2 | // Licensed under the MIT License. |
| 3 | |
| 4 | using Microsoft.Teams.Bot.Apps.Routing; |
| 5 | using Microsoft.Teams.Bot.Apps.Schema; |
| 6 | |
| 7 | namespace Microsoft.Teams.Bot.Apps.Handlers; |
| 8 | |
| 9 | /// <summary> |
| 10 | /// Delegate for handling adaptive card action invoke activities. |
| 11 | /// </summary> |
| 12 | /// <param name="context">The context for the invoke activity, providing access to the activity data and bot application.</param> |
| 13 | /// <param name="cancellationToken">A cancellation token that can be used to cancel the operation.</param> |
| 14 | /// <returns>A task that represents the asynchronous operation. The task result contains the invoke response.</returns> |
| 15 | public delegate Task<InvokeResponse> AdaptiveCardActionHandler(Context<InvokeActivity<AdaptiveCardActionValue>> context, CancellationToken cancellationToken = default); |
| 16 | |
| 17 | /// <summary> |
| 18 | /// Extension methods for registering adaptive card action invoke handlers. |
| 19 | /// </summary> |
| 20 | public static class AdaptiveCardExtensions |
| 21 | { |
| 22 | /// <summary> |
| 23 | /// Registers a handler for adaptive card action invoke activities. |
| 24 | /// Cannot be combined with <see cref="InvokeExtensions.OnInvoke"/>. |
| 25 | /// </summary> |
| 26 | /// <remarks> |
| 27 | /// Breaking change: previously a catch-all invoke handler could be registered alongside specific invoke handlers. This combination now throws at registration time. |
| 28 | /// </remarks> |
| 29 | /// <param name="app">The Teams bot application.</param> |
| 30 | /// <param name="handler">The handler to register.</param> |
| 31 | /// <returns>The updated Teams bot application.</returns> |
| 32 | public static TeamsBotApplication OnAdaptiveCardAction(this TeamsBotApplication app, AdaptiveCardActionHandler handler) |
| 33 | { |
| 34 | ArgumentNullException.ThrowIfNull(app, nameof(app)); |
| 35 | app.Router.Register(new Route<InvokeActivity> |
| 36 | { |
| 37 | Name = string.Join("/", TeamsActivityType.Invoke, InvokeNames.AdaptiveCardAction), |
| 38 | Selector = activity => activity.Name == InvokeNames.AdaptiveCardAction, |
| 39 | HandlerWithReturn = async (ctx, cancellationToken) => |
| 40 | { |
| 41 | InvokeActivity<AdaptiveCardActionValue> typedActivity = new(ctx.Activity); |
| 42 | Context<InvokeActivity<AdaptiveCardActionValue>> typedContext = new(ctx.TeamsBotApplication, typedActivity); |
| 43 | return await handler(typedContext, cancellationToken).ConfigureAwait(false); |
| 44 | } |
| 45 | }); |
| 46 | |
| 47 | return app; |
| 48 | } |
| 49 | } |
| 50 | |