microsoft/teams.net
Publicmirrored fromhttps://github.com/microsoft/teams.netAvailable
core/samples/MigrationBot/Program.cs
63lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. |
| 2 | // Licensed under the MIT License. |
| 3 | |
| 4 | using System.Text.Json; |
| 5 | using Microsoft.Bot.Builder; |
| 6 | using Microsoft.Bot.Builder.Integration.AspNet.Core; |
| 7 | using Microsoft.Teams.Bot.Compat; |
| 8 | using MigrationBot; |
| 9 | |
| 10 | // ───────────────────────────────────────────────────────────────────────────── |
| 11 | // MIGRATION BOT — Phased migration from Bot Framework to the Teams SDK |
| 12 | // |
| 13 | // Routing on POST /api/messages: |
| 14 | // message whose text starts with "bf" → Bot Framework (LegacyEchoBot) |
| 15 | // everything else → Teams SDK (NewSdkBot) |
| 16 | // ───────────────────────────────────────────────────────────────────────────── |
| 17 | |
| 18 | WebApplicationBuilder builder = WebApplication.CreateBuilder(args); |
| 19 | |
| 20 | builder.AddCompatAdapter(); |
| 21 | builder.Services.AddTransient<IBot, LegacyEchoBot>(); |
| 22 | builder.AddNewSdkBot(); |
| 23 | |
| 24 | WebApplication app = builder.Build(); |
| 25 | |
| 26 | NewSdkBot newSdkBot = app.Services.GetRequiredService<NewSdkBot>(); |
| 27 | |
| 28 | app.MapPost("/api/messages", async ( |
| 29 | IBotFrameworkHttpAdapter adapter, |
| 30 | IBot bot, |
| 31 | HttpRequest req, |
| 32 | HttpResponse res, |
| 33 | CancellationToken ct) => |
| 34 | { |
| 35 | // Buffer the body so it can be read once for routing and again by the adapter. |
| 36 | req.EnableBuffering(); |
| 37 | |
| 38 | bool useBotFramework = false; |
| 39 | try |
| 40 | { |
| 41 | using JsonDocument doc = await JsonDocument.ParseAsync(req.Body, cancellationToken: ct); |
| 42 | |
| 43 | string? type = doc.RootElement.TryGetProperty("type", out JsonElement typeProp) |
| 44 | ? typeProp.GetString() : null; |
| 45 | string? text = doc.RootElement.TryGetProperty("text", out JsonElement textProp) |
| 46 | ? textProp.GetString() : null; |
| 47 | |
| 48 | // Message activities whose text starts with "bf" go to the Bot Framework path. |
| 49 | useBotFramework = string.Equals(type, "message", StringComparison.OrdinalIgnoreCase) |
| 50 | && text?.StartsWith("bf", StringComparison.OrdinalIgnoreCase) == true; |
| 51 | } |
| 52 | catch { /* malformed body – fall through to Teams SDK */ } |
| 53 | |
| 54 | req.Body.Position = 0; |
| 55 | |
| 56 | if (useBotFramework) |
| 57 | await adapter.ProcessAsync(req, res, bot, ct); |
| 58 | else |
| 59 | await newSdkBot.ProcessAsync(req.HttpContext, ct); |
| 60 | |
| 61 | }).RequireAuthorization(); |
| 62 | |
| 63 | app.Run(); |
| 64 | |