microsoft/teams.net
Publicmirrored from https://github.com/microsoft/teams.netAvailable
core/src/Microsoft.Teams.Bot.Apps/Handlers/InvokeHandler.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 | /// Represents a method that handles an invocation request and returns a response asynchronously. |
| 11 | /// </summary> |
| 12 | /// <param name="context">The context for the invocation, containing request data and metadata required to process the operation. Cannot be |
| 13 | /// null.</param> |
| 14 | /// <param name="cancellationToken">A cancellation token that can be used to cancel the operation. The default value is <see |
| 15 | /// cref="CancellationToken.None"/>.</param> |
| 16 | /// <returns>A task that represents the asynchronous operation. The task result contains the response to the invocation.</returns> |
| 17 | public delegate Task<InvokeResponse> InvokeHandler(Context<InvokeActivity> context, CancellationToken cancellationToken = default); |
| 18 | |
| 19 | /// <summary> |
| 20 | /// Provides extension methods for registering handlers for invoke activities in a Teams bot application. |
| 21 | /// </summary> |
| 22 | public static class InvokeExtensions |
| 23 | { |
| 24 | /// <summary> |
| 25 | /// Registers a catch-all handler for all invoke activities. |
| 26 | /// Cannot be combined with specific invoke handlers such as <see cref="AdaptiveCardExtensions.OnAdaptiveCardAction"/>, |
| 27 | /// <see cref="TaskExtensions.OnTaskFetch"/>, etc. |
| 28 | /// </summary> |
| 29 | /// <remarks> |
| 30 | /// Breaking change: previously a catch-all invoke handler could be registered alongside specific invoke handlers. This combination now throws at registration time. |
| 31 | /// </remarks> |
| 32 | /// <param name="app">The Teams bot application.</param> |
| 33 | /// <param name="handler">The invoke handler to register.</param> |
| 34 | /// <returns>The updated Teams bot application.</returns> |
| 35 | public static TeamsBotApplication OnInvoke(this TeamsBotApplication app, InvokeHandler handler) |
| 36 | { |
| 37 | ArgumentNullException.ThrowIfNull(app, nameof(app)); |
| 38 | app.Router.Register(new Route<InvokeActivity> |
| 39 | { |
| 40 | Name = TeamsActivityType.Invoke, |
| 41 | Selector = _ => true, |
| 42 | HandlerWithReturn = async (ctx, cancellationToken) => |
| 43 | { |
| 44 | return await handler(ctx, cancellationToken).ConfigureAwait(false); |
| 45 | } |
| 46 | }); |
| 47 | return app; |
| 48 | } |
| 49 | } |
| 50 | |