microsoft/teams.net

Public

mirrored fromhttps://github.com/microsoft/teams.netAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
copilot/sub-pr-338

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

core/samples/TeamsBot/Program.cs

211lines · modecode

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4using Microsoft.Teams.Bot.Apps;
5using Microsoft.Teams.Bot.Apps.Handlers;
6using Microsoft.Teams.Bot.Apps.Schema;
7using Microsoft.Teams.Bot.Apps.Schema.Entities;
8using Microsoft.Teams.Bot.Apps.Schema.MessageActivities;
9using System.Text.RegularExpressions;
10using TeamsBot;
11
12var builder = TeamsBotApplication.CreateBuilder(args);
13var teamsApp = builder.Build();
14
15// ==================== MESSAGE HANDLERS ====================
16
17// Pattern-based handler: matches "hello" (case-insensitive)
18teamsApp.OnMessage("(?i)hello", async (context, cancellationToken) =>
19{
20 await context.SendActivityAsync("Hi there! 👋 You said hello!", cancellationToken);
21
22 await teamsApp.Api.Conversations.Reactions.AddAsync(context.Activity, "cake", cancellationToken: cancellationToken);
23});
24
25teamsApp.OnMessage("(?i)tm", async (context, cancellationToken) =>
26{
27 var members = await teamsApp.Api.Conversations.Members.GetAllAsync(context.Activity, cancellationToken: cancellationToken);
28 foreach (var member in members)
29 {
30 await context.SendActivityAsync(
31 TeamsActivity.CreateBuilder()
32 .WithText($"Hello {member.Name}!")
33 .WithRecipient(member, true)
34 .Build(), cancellationToken)
35 ;
36 }
37 await context.SendActivityAsync($"Sent a private message to {members.Count} member(s) of the conversation!", cancellationToken);
38
39});
40
41// Markdown handler: matches "markdown" (case-insensitive)
42teamsApp.OnMessage("(?i)markdown", async (context, cancellationToken) =>
43{
44 var markdownMessage = new MessageActivity("""
45# Markdown Examples
46
47Here are some **markdown** formatting examples:
48
49## Text Formatting
50- **Bold text**
51- *Italic text*
52- ~~Strikethrough~~
53- `inline code`
54
55## Lists
561. First item
572. Second item
583. Third item
59
60## Code Block
61```csharp
62public class Example
63{
64 public string Name { get; set; }
65}
66```
67
68## Links
69[Visit Microsoft](https://www.microsoft.com)
70
71## Quotes
72> This is a blockquote
73> It can span multiple lines
74""")
75 {
76 TextFormat = TextFormats.Markdown
77 };
78
79 await context.SendActivityAsync(markdownMessage, cancellationToken);
80});
81
82// Regex-based handler: matches commands starting with "/"
83var commandRegex = new Regex(@"^/(\w+)(.*)$", RegexOptions.Compiled);
84teamsApp.OnMessage(commandRegex, async (context, cancellationToken) =>
85{
86 var match = commandRegex.Match(context.Activity.Text ?? "");
87 if (match.Success)
88 {
89 string command = match.Groups[1].Value;
90 string args = match.Groups[2].Value.Trim();
91
92 string response = command.ToLower() switch
93 {
94 "help" => "Available commands: /help, /about, /time",
95 "about" => "I'm a Teams bot built with the Microsoft Teams Bot SDK!",
96 "time" => $"Current server time: {DateTime.Now:yyyy-MM-dd HH:mm:ss}",
97 _ => $"Unknown command: /{command}. Type /help for available commands."
98 };
99
100 await context.SendActivityAsync(response, cancellationToken);
101 }
102});
103
104teamsApp.OnMessageUpdate(async (context, cancellationToken) =>
105{
106 string updatedText = context.Activity.Text ?? "<no text>";
107 MessageActivity reply = new($"I saw that you updated your message to: `{updatedText}`");
108 await context.SendActivityAsync(reply, cancellationToken);
109});
110
111teamsApp.OnMessage(async (context, cancellationToken) =>
112{
113 await context.SendTypingActivityAsync(cancellationToken);
114
115 string replyText = $"You sent: `{context.Activity.Text}` in activity of type `{context.Activity.Type}`.";
116
117 MessageActivity reply = new(replyText);
118 reply.AddMention(context.Activity.From!);
119
120 await context.SendActivityAsync(reply, cancellationToken);
121
122 TeamsAttachment feedbackCard = TeamsAttachment.CreateBuilder()
123 .WithAdaptiveCard(Cards.FeedbackCardObj)
124 .Build();
125 MessageActivity feedbackActivity = new([feedbackCard]);
126 await context.SendActivityAsync(feedbackActivity, cancellationToken);
127});
128
129teamsApp.OnMessageReaction( async (context, cancellationToken) =>
130{
131 string reactionsAdded = string.Join(", ", context.Activity.ReactionsAdded?.Select(r => r.Type) ?? []);
132 string reactionsRemoved = string.Join(", ", context.Activity.ReactionsRemoved?.Select(r => r.Type) ?? []);
133
134 TeamsAttachment reactionsCard = TeamsAttachment.CreateBuilder()
135 .WithAdaptiveCard(Cards.ReactionsCard(reactionsAdded, reactionsRemoved))
136 .Build();
137 MessageActivity reply = new([reactionsCard]);
138
139 await context.SendActivityAsync(reply, cancellationToken);
140});
141
142teamsApp.OnMessageDelete(async (context, cancellationToken) =>
143{
144
145 await context.SendActivityAsync("I saw that message you deleted", cancellationToken);
146});
147
148// ==================== INVOKE ====================
149
150teamsApp.OnInvoke(async (context, cancellationToken) =>
151{
152 var valueNode = context.Activity.Value;
153 string? feedbackValue = valueNode?["action"]?["data"]?["feedback"]?.GetValue<string>();
154
155 var reply = TeamsActivity.CreateBuilder()
156 .WithAttachment(TeamsAttachment.CreateBuilder()
157 .WithAdaptiveCard(Cards.ResponseCard(feedbackValue))
158 .Build()
159 )
160 .Build();
161
162 await context.SendActivityAsync(reply, cancellationToken);
163
164 return new CoreInvokeResponse(200)
165 {
166 Type = "application/vnd.microsoft.activity.message",
167 Body = "Invokes are great !!"
168 };
169});
170
171// ==================== CONVERSATION UPDATE HANDLERS ====================
172
173teamsApp.OnMembersAdded(async (context, cancellationToken) =>
174{
175 Console.WriteLine($"[MembersAdded] {context.Activity.MembersAdded?.Count ?? 0} member(s) added");
176
177 var memberNames = string.Join(", ", context.Activity.MembersAdded?.Select(m => m.Name ?? m.Id) ?? []);
178 await context.SendActivityAsync($"Welcome! Members added: {memberNames}", cancellationToken);
179});
180
181teamsApp.OnMembersRemoved(async (context, cancellationToken) =>
182{
183 Console.WriteLine($"[MembersRemoved] {context.Activity.MembersRemoved?.Count ?? 0} member(s) removed");
184
185 var memberNames = string.Join(", ", context.Activity.MembersRemoved?.Select(m => m.Name ?? m.Id) ?? []);
186 await context.SendActivityAsync($"Goodbye! Members removed: {memberNames}", cancellationToken);
187});
188
189// ==================== INSTALL UPDATE HANDLERS ====================
190
191teamsApp.OnInstallUpdate(async (context, cancellationToken) =>
192{
193 var action = context.Activity.Action ?? "unknown";
194 Console.WriteLine($"[InstallUpdate] Installation action: {action}");
195 await context.SendActivityAsync($"Installation update: {action}", cancellationToken);
196});
197
198teamsApp.OnInstall(async (context, cancellationToken) =>
199{
200 Console.WriteLine($"[InstallAdd] Bot was installed");
201 await context.SendActivityAsync("Thanks for installing me! I'm ready to help.", cancellationToken);
202});
203
204teamsApp.OnUnInstall((context, cancellationToken) =>
205{
206 Console.WriteLine($"[InstallRemove] Bot was uninstalled");
207 return Task.CompletedTask;
208});
209
210
211teamsApp.Run();
212