-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathProgram.cs
More file actions
229 lines (182 loc) · 9.37 KB
/
Copy pathProgram.cs
File metadata and controls
229 lines (182 loc) · 9.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Text.Json;
using MessageExtensionBot;
using Microsoft.Teams.Apps;
using Microsoft.Teams.Apps.Schema;
using Microsoft.Teams.Apps.TaskModules;
using Microsoft.Teams.Apps.MessageExtensions;
WebApplicationBuilder webAppBuilder = WebApplication.CreateSlimBuilder(args);
webAppBuilder.Services.AddTeamsBotApplication();
WebApplication webApp = webAppBuilder.Build();
webApp.UseStaticFiles();
webApp.MapGet("/tabs/settings", async context =>
{
string html = await File.ReadAllTextAsync("wwwroot/settings.html");
context.Response.ContentType = "text/html";
await context.Response.WriteAsync(html);
});
TeamsBotApplication bot = webApp.UseTeamsBotApplication();
// ==================== MESSAGE EXTENSION QUERY ====================
bot.OnQuery(async (context, cancellationToken) =>
{
Console.WriteLine("✓ OnQuery");
MessageExtensionQuery? query = context.Activity.Value;
string commandId = query?.CommandId ?? "unknown";
string searchText = query?.Parameters
.FirstOrDefault(p => !p.Name.Equals("initialRun"))?
.Value ?? "default";
if (searchText.Equals("help", StringComparison.OrdinalIgnoreCase))
{
return MessageExtensionResponse.CreateBuilder()
.WithType(MessageExtensionResponseTypes.Message)
.WithText("💡 Search for any keyword to see results.")
.Build();
}
// Create results with tap actions to trigger OnSelectItem
object[] cards = Cards.CreateQueryResultCards(searchText);
TeamsAttachment[] attachments = [.. cards.Select(card => TeamsAttachment.CreateBuilder().WithContent(card)
.WithContentType(AttachmentContentTypes.ThumbnailCard).Build())];
return MessageExtensionResponse.CreateBuilder()
.WithType(MessageExtensionResponseTypes.Result)
.WithAttachmentLayout(TeamsAttachmentLayouts.List)
.WithAttachments(attachments)
.Build();
});
// ==================== MESSAGE EXTENSION SELECT ITEM ====================
bot.OnSelectItem(async (context, cancellationToken) =>
{
Console.WriteLine("✓ OnSelectItem");
JsonElement selectedItem = context.Activity.Value;
JsonElement? itemData = selectedItem;
string? itemId = itemData.Value.TryGetProperty("itemId", out JsonElement id) ? id.GetString() : "unknown";
string? title = itemData.Value.TryGetProperty("title", out JsonElement t) ? t.GetString() : "Selected Item";
string? description = itemData.Value.TryGetProperty("description", out JsonElement d) ? d.GetString() : "No description";
object card = Cards.CreateSelectItemCard(itemId, title, description);
TeamsAttachment attachment = TeamsAttachment.CreateBuilder().WithAdaptiveCard(card).Build();
return MessageExtensionResponse.CreateBuilder()
.WithType(MessageExtensionResponseTypes.Result)
.WithAttachmentLayout(TeamsAttachmentLayouts.List)
.WithAttachments(attachment)
.Build();
});
// ==================== MESSAGE EXTENSION CARD BUTTON CLICKED ====================
bot.OnCardButtonClicked(async (context, cancellationToken) =>
{
Console.WriteLine("✓ OnCardButtonClicked");
return new InvokeResponse(200);
});
// ==================== MESSAGE EXTENSION FETCH TASK ====================
bot.OnFetchTask(async (context, cancellationToken) =>
{
Console.WriteLine("✓ OnFetchTask");
MessageExtensionAction? action = context.Activity.Value;
object fetchTaskCard = Cards.CreateFetchTaskCard(action?.CommandId ?? "unknown");
TeamsAttachment fetchTaskCardResponse = TeamsAttachment.CreateBuilder()
.WithAdaptiveCard(fetchTaskCard).Build();
return MessageExtensionActionResponse.CreateBuilder()
.WithTask(TaskModuleResponse.CreateBuilder()
.WithType(TaskModuleResponseTypes.Continue)
.WithTitle("Task Module")
.WithCard(fetchTaskCardResponse))
.Build();
});
// Helper: Extract title and description from preview card
static (string?, string?) GetDataFromPreview(MessageExtensionActivityPreview? preview)
{
if (preview?.Attachments == null) return (null, null);
JsonElement cardData = JsonSerializer.Deserialize<JsonElement>(
JsonSerializer.Serialize(preview.Attachments[0].Content));
if (!cardData.TryGetProperty("body", out JsonElement body) || body.ValueKind != JsonValueKind.Array)
return (null, null);
string? title = body.GetArrayLength() > 0 && body[0].TryGetProperty("text", out JsonElement t) ? t.GetString() : null;
string? description = body.GetArrayLength() > 1 && body[1].TryGetProperty("text", out JsonElement d) ? d.GetString() : null;
return (title, description);
}
// ==================== MESSAGE EXTENSION SUBMIT ACTION ====================
bot.OnSubmitAction(async (context, cancellationToken) =>
{
Console.WriteLine("✓ OnSubmitAction");
MessageExtensionAction? action = context.Activity.Value;
// Handle "edit" - user clicked edit on the preview, show the form again
if (action?.BotMessagePreviewAction == BotMessagePreviewActionTypes.Edit)
{
Console.WriteLine("Handling EDIT action - returning to form");
(string? previewTitle, string? previewDescription) = GetDataFromPreview(action.BotActivityPreview?.FirstOrDefault());
object editFormCard = Cards.CreateEditFormCard(previewTitle, previewDescription);
TeamsAttachment editFormCardResponse = TeamsAttachment.CreateBuilder()
.WithAdaptiveCard(editFormCard).Build();
return MessageExtensionActionResponse.CreateBuilder()
.WithTask(TaskModuleResponse.CreateBuilder()
.WithType(TaskModuleResponseTypes.Continue)
.WithTitle("Edit Card")
.WithCard(editFormCardResponse))
.Build();
}
// Handle "send" - user clicked send on the preview, finalize the card
//TODO : when I start from the compose box or message, i get an error at this point but seems to be a teams issue ( no activity is sent on clicking send)
if (action?.BotMessagePreviewAction == BotMessagePreviewActionTypes.Send)
{
Console.WriteLine("Handling SEND action - finalizing card");
(string? previewTitle, string? previewDescription) = GetDataFromPreview(action.BotActivityPreview?.FirstOrDefault());
object card = Cards.CreateSubmitActionCard(previewTitle, previewDescription);
TeamsAttachment attachment2 = TeamsAttachment.CreateBuilder().WithAdaptiveCard(card).Build();
return MessageExtensionActionResponse.CreateBuilder()
.WithComposeExtension(MessageExtensionResponse.CreateBuilder()
.WithType(MessageExtensionResponseTypes.Result)
.WithAttachmentLayout(TeamsAttachmentLayouts.List)
.WithAttachments(attachment2))
.Build();
}
JsonElement? data = action?.Data as JsonElement?;
string? title = data != null && data.Value.TryGetProperty("title", out JsonElement t) ? t.GetString() : "Untitled";
string? description = data != null && data.Value.TryGetProperty("description", out JsonElement d) ? d.GetString() : "No description";
object previewCard = Cards.CreateSubmitActionCard(title, description);
TeamsAttachment attachment = TeamsAttachment.CreateBuilder().WithAdaptiveCard(previewCard).Build();
return MessageExtensionActionResponse.CreateBuilder()
.WithComposeExtension(MessageExtensionResponse.CreateBuilder()
.WithType(MessageExtensionResponseTypes.BotMessagePreview)
.WithActivityPreview(new MessageExtensionActivityPreview().AddAttachment(attachment))
)
.Build();
});
// ==================== MESSAGE EXTENSION QUERY LINK ====================
bot.OnQueryLink(async (context, cancellationToken) =>
{
Console.WriteLine("✓ OnQueryLink");
MessageExtensionQueryLink? queryLink = context.Activity.Value;
object card = Cards.CreateLinkUnfurlCard(queryLink?.Url?.ToString());
TeamsAttachment attachment = TeamsAttachment.CreateBuilder()
.WithContent(card).WithContentType(AttachmentContentTypes.ThumbnailCard).Build();
return MessageExtensionResponse.CreateBuilder()
.WithType(MessageExtensionResponseTypes.Result)
.WithAttachmentLayout(TeamsAttachmentLayouts.List)
.WithAttachments(attachment)
.Build();
});
// ==================== MESSAGE EXTENSION QUERY SETTING URL ====================
bot.OnQuerySettingUrl(async (context, cancellationToken) =>
{
Console.WriteLine("✓ OnQuerySettingUrl");
string botEndpoint = webAppBuilder.Configuration["BotEndpoint"] ?? "";
string settingsUrl = $"{botEndpoint}/tabs/settings";
var action = new SuggestedAction(ActionTypes.OpenUrl, "Settings", settingsUrl);
return MessageExtensionResponse.CreateBuilder()
.WithType(MessageExtensionResponseTypes.Config)
.WithSuggestedActions(new SuggestedActions().AddAction(action))
.Build();
});
// ==================== MESSAGE EXTENSION SETTINGS SAVED ====================
bot.OnSetting(async (context, cancellationToken) =>
{
string? state = context.Activity.Value?.State;
Console.WriteLine($"✓ OnSettings - state: {state}");
if (state == "CancelledByUser")
{
Console.WriteLine("User cancelled settings.");
return new InvokeResponse(200);
}
Console.WriteLine($"User saved setting: {state}");
return new InvokeResponse(200);
});
webApp.Run();