microsoft/teams.net

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
next/oauth-card-null-ref-bug

Branches

Tags

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

Clone

HTTPS

Download ZIP

core/samples/PABot/Bots/TeamsBot.cs

126lines · modecode

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4using Microsoft.Bot.Builder;
5using Microsoft.Bot.Builder.Dialogs;
6using Microsoft.Bot.Connector;
7using Microsoft.Bot.Schema;
8using Microsoft.Bot.Schema.Teams;
9
10namespace PABot.Bots
11{
12 /// <summary>
13 /// This bot is derived from the TeamsActivityHandler class and handles Teams-specific activities.
14 /// </summary>
15 /// <typeparam name="T">The type of the dialog.</typeparam>
16 public class TeamsBot<T> : DialogBot<T> where T : Dialog
17 {
18 /// <summary>
19 /// Initializes a new instance of the <see cref="TeamsBot{T}"/> class.
20 /// </summary>
21 /// <param name="conversationState">The conversation state.</param>
22 /// <param name="userState">The user state.</param>
23 /// <param name="dialog">The dialog.</param>
24 /// <param name="logger">The logger.</param>
25 public TeamsBot(ConversationState conversationState, UserState userState, T dialog, ILogger<DialogBot<T>> logger)
26 : base(conversationState, userState, dialog, logger)
27 {
28 }
29
30 /// <summary>
31 /// Handles the event when members are added to the conversation.
32 /// </summary>
33 /// <param name="membersAdded">The list of members added.</param>
34 /// <param name="turnContext">The turn context.</param>
35 /// <param name="cancellationToken">The cancellation token.</param>
36 /// <returns>A task that represents the work queued to execute.</returns>
37 protected override async Task OnMembersAddedAsync(IList<ChannelAccount> membersAdded, ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
38 {
39 foreach (ChannelAccount member in membersAdded)
40 {
41 if (member.Id != turnContext.Activity.Recipient.Id)
42 {
43 await turnContext.SendActivityAsync(MessageFactory.Text("Welcome to AuthenticationBot. Type anything to get logged in. Type 'logout' to sign-out."), cancellationToken);
44 }
45 }
46 }
47
48 /// <summary>
49 /// Handles the Teams sign-in verification state.
50 /// </summary>
51 /// <param name="turnContext">The turn context.</param>
52 /// <param name="cancellationToken">The cancellation token.</param>
53 /// <returns>A task that represents the work queued to execute.</returns>
54 protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
55 {
56 string text = System.Text.RegularExpressions.Regex.Replace(
57 turnContext.Activity.Text ?? string.Empty, @"<at>[^<]*<\/at>", string.Empty).Trim();
58
59 if (text.Equals("/create-conversation", StringComparison.OrdinalIgnoreCase))
60 {
61 if (turnContext.Activity.Conversation.IsGroup != true)
62 {
63 await turnContext.SendActivityAsync(MessageFactory.Text("This command can only be used in a group chat."), cancellationToken);
64 return;
65 }
66
67 TeamsChannelData channelData = turnContext.Activity.GetChannelData<TeamsChannelData>();
68 ChannelAccount userChannel = turnContext.Activity.From;
69
70 ConversationParameters conversationParameters = new ConversationParameters
71 {
72 IsGroup = false,
73 Bot = new ChannelAccount { Id = turnContext.Activity.Recipient.Id },
74 Members = [userChannel],
75 TenantId = channelData.Tenant.Id,
76 };
77
78 _logger.LogInformation("Creating 1:1 conversation with user {UserId} in tenant {TenantId}",
79 userChannel.Id, conversationParameters.TenantId);
80
81 IConnectorClient connectorClient = turnContext.TurnState.Get<IConnectorClient>();
82 ConversationResourceResponse conv = await connectorClient.Conversations.CreateConversationAsync(conversationParameters, cancellationToken);
83
84 _logger.LogInformation("Created conversation {ConversationId}", conv.Id);
85
86 Activity message = MessageFactory.Text("Hello! I've started a 1:1 conversation with you from the group chat.");
87 message.ServiceUrl = turnContext.Activity.ServiceUrl;
88 await connectorClient.Conversations.SendToConversationAsync(conv.Id, message, cancellationToken);
89
90 await turnContext.SendActivityAsync(MessageFactory.Text("Done! Check your personal chat."), cancellationToken);
91 return;
92 }
93
94 await base.OnMessageActivityAsync(turnContext, cancellationToken);
95 }
96
97 protected override async Task OnTeamsSigninVerifyStateAsync(ITurnContext<IInvokeActivity> turnContext, CancellationToken cancellationToken)
98 {
99 _logger.LogInformation("Running dialog with sign-in/verify state from an Invoke Activity.");
100
101 // The OAuth Prompt needs to see the Invoke Activity in order to complete the login process.
102 // Run the Dialog with the new Invoke Activity.
103 await _dialog.RunAsync(turnContext, _conversationState.CreateProperty<DialogState>(nameof(DialogState)), cancellationToken);
104 }
105
106 /// <summary>
107 /// Handles invoke activities, including signin/failure events.
108 /// </summary>
109 /// <param name="turnContext">The turn context.</param>
110 /// <param name="cancellationToken">The cancellation token.</param>
111 /// <returns>An invoke response.</returns>
112 protected override async Task<InvokeResponse> OnInvokeActivityAsync(ITurnContext<IInvokeActivity> turnContext, CancellationToken cancellationToken)
113 {
114 if (turnContext.Activity.Name == "signin/failure")
115 {
116 _logger.LogWarning("Sign-in failure detected. Activity Name: {ActivityName}", turnContext.Activity.Name);
117 _logger.LogWarning("Sign-in failure details - ConversationId: {ConversationId}, From: {FromId}, Value: {Value}",
118 turnContext.Activity.Conversation?.Id,
119 turnContext.Activity.From?.Id,
120 Newtonsoft.Json.JsonConvert.SerializeObject(turnContext.Activity));
121 }
122
123 return await base.OnInvokeActivityAsync(turnContext, cancellationToken);
124 }
125 }
126}
127