microsoft/teams.net

Public

mirrored from https://github.com/microsoft/teams.netAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
c9613c042b5302aa50b0e4a195512cab276ef100

Branches

Tags

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

Clone

HTTPS

Download ZIP

core/src/Microsoft.Bot.Core/ConversationClient.cs

53lines · modecode

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4using System.Net.Mime;
5using System.Text;
6using Microsoft.Bot.Core.Hosting;
7using Microsoft.Bot.Core.Schema;
8
9namespace Microsoft.Bot.Core;
10
11/// <summary>
12/// Provides methods for sending activities to a conversation endpoint using HTTP requests.
13/// </summary>
14/// <param name="httpClient">The HTTP client instance used to send requests to the conversation service. Must not be null.</param>
15public class ConversationClient(HttpClient httpClient)
16{
17 internal const string ConversationHttpClientName = "BotConversationClient";
18
19 internal AgenticIdentity? AgenticIdentity { get; set; }
20
21 /// <summary>
22 /// Sends the specified activity to the conversation endpoint asynchronously.
23 /// </summary>
24 /// <param name="activity">The activity to send. Cannot be null. The activity must contain valid conversation and service URL information.</param>
25 /// <param name="cancellationToken">A cancellation token that can be used to cancel the send operation.</param>
26 /// <returns>A task that represents the asynchronous operation. The task result contains the response content as a string if
27 /// the activity is sent successfully.</returns>
28 /// <exception cref="Exception">Thrown if the activity could not be sent successfully. The exception message includes the HTTP status code and
29 /// response content.</exception>
30 public async Task<string> SendActivityAsync(CoreActivity activity, CancellationToken cancellationToken = default)
31 {
32 ArgumentNullException.ThrowIfNull(activity);
33 ArgumentNullException.ThrowIfNull(activity.Conversation);
34 ArgumentNullException.ThrowIfNullOrWhiteSpace(activity.Conversation.Id);
35 ArgumentNullException.ThrowIfNull(activity.ServiceUrl);
36
37 string url = $"{activity.ServiceUrl.ToString().TrimEnd('/')}/v3/conversations/{activity.Conversation.Id}/activities/";
38
39 using StringContent content = new(activity.ToJson(), Encoding.UTF8, MediaTypeNames.Application.Json);
40
41 using HttpRequestMessage request = new(HttpMethod.Post, url) { Content = content };
42
43 request.Options.Set(BotAuthenticationHandler.AgenticIdentityKey, AgenticIdentity);
44
45 using HttpResponseMessage resp = await httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
46
47 string respContent = await resp.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
48
49 return resp.IsSuccessStatusCode ?
50 respContent :
51 throw new HttpRequestException($"Error sending activity: {resp.StatusCode} - {respContent}");
52 }
53}
54