DomvsChatBot/Bot/ChatIABot.cs
2024-12-27 17:41:43 -03:00

172 lines
7.0 KiB
C#

using DomvsChatBot.Comm;
using DomvsChatBot.LocalData;
using DomvsChatBot.MSGraph;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Teams;
using Microsoft.Bot.Connector.Authentication;
using Microsoft.Bot.Connector;
using Microsoft.Bot.Schema;
using Microsoft.Extensions.Configuration;
using System.Net.Http.Headers;
using System.Web;
using System.Text;
namespace DomvsChatBot.Bot;
public class ChatIABot : TeamsActivityHandler
{
private readonly IConfigurationManager _configuration;
private readonly string _clientSecret;
private readonly string _clientId;
private readonly ApiService _apiService;
private readonly LocalStorage _localStorage;
private readonly TokenManager _tokenManager;
private readonly IHttpClientFactory _clientFactory;
public ChatIABot(IConfigurationManager configuration, ApiService apiService, LocalStorage localStorage, TokenManager tokenManager, IHttpClientFactory clientFactory)
{
_configuration = configuration;
_apiService = apiService;
_localStorage = localStorage;
_tokenManager = tokenManager;
_clientFactory = clientFactory;
_clientSecret = _configuration.GetSection("AppClientSecret").Value;
_clientId = _configuration.GetSection("AppClientID").Value;
}
protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
{
string messageText = turnContext.Activity.RemoveRecipientMention()?.Trim();
var userId = turnContext.Activity.From.Id;
var userName = turnContext.Activity.From.Name;
var tenantId = turnContext.Activity.Conversation.TenantId;
var aadObjectId = turnContext.Activity.From.AadObjectId;
//var token = turnContext.Activity.From.AadObjectId.ToString();
var credentials = new MicrosoftAppCredentials(_clientId, _clientSecret);
var connector = new ConnectorClient(new Uri(turnContext.Activity.ServiceUrl), credentials);
var sessionId = turnContext.Activity.Conversation.Id;
var localId = turnContext.Activity.Conversation.TenantId;
try
{
//var userInfo = await connector.Conversations.GetConversationMembersAsync(conversationId);
//var token = await TokenManager.ObterToken(userId);
//var replyText = await GetMessage(userId, turnContext.Activity.From.AadObjectId, turnContext.Activity.From.Name, messageText);
var token = await GetToken(userName, tenantId, userId);
await turnContext.SendActivityAsync(new Activity() { Type = ActivityTypes.Typing });
var taskResponse = _apiService.GetMessage(token, messageText, sessionId);
var waitTime = 1000;
while (!taskResponse.IsCompleted)
{
await Task.Delay(waitTime);
if (!taskResponse.IsCompleted) await turnContext.SendActivityAsync(new Activity() { Type = ActivityTypes.Typing });
waitTime = GetTime(waitTime);
};
var replyText = await taskResponse;
replyText = SepararCodigo(replyText);
await turnContext.SendActivityAsync(MessageFactory.Text(replyText), cancellationToken);
//await turnContext.SendActivityAsync(new Activity() { Type = ActivityTypes.Typing });
}
catch (Exception ex)
{
await turnContext.SendActivityAsync(MessageFactory.Text(ex.Message), cancellationToken);
}
}
private string SepararCodigo(string texto)
{
if (texto.Contains("```"))
{
return texto;
}
return texto.Replace("\n", "<br />");
}
private int GetTime(int waitTime)
{
return waitTime==1000 ? waitTime=2000 : waitTime == 2000 ? waitTime = 5000 : waitTime = 10000;
}
protected override async Task OnMembersAddedAsync(IList<ChannelAccount> membersAdded, ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
{
var welcomeText = "Olá! Eu sou a Domvs IA. A inteligência artificial da Domvs iT.\nSe perguntar algo sobre o conteúdo do SahePoint da Domvs, eu conseguirei responder.";
foreach (var member in membersAdded)
{
if (member.Id != turnContext.Activity.Recipient.Id)
{
await turnContext.SendActivityAsync(new Activity() { Type = ActivityTypes.Typing });
await turnContext.SendActivityAsync(MessageFactory.Text(welcomeText), cancellationToken);
//TODO: Verificar se o turnContext.Activity.Conversation.Id existe ou não bo BD do Bot (MongoDB localhost:27017)
var userId = turnContext.Activity.From.Id;
var userName = turnContext.Activity.From.Name;
var localId = turnContext.Activity.Conversation.TenantId;
await GetToken(userName, localId, userId);
//var token = await TokenManager.ObterToken(userId);
//var replyText = await GetMessage(token, messageText);
//await turnContext.SendActivityAsync(MessageFactory.Text(replyText), cancellationToken);
}
}
}
private async Task<string> GetToken(string name, string company, string id)
{
if (_localStorage?.Token != null && _tokenManager.CheckTokenIsValid(_localStorage.Token))
{
return _localStorage.Token;
}
var secret = await _apiService.GetSecret(id, company, name);
var token = await _apiService.GetToken(id, name, secret);
_localStorage.Secret = secret;
_localStorage.Token = token;
_localStorage.Name = name;
_localStorage.Company = company;
_localStorage.Id = id;
return token;
}
private async Task<string> GetMessage(string jwt, string message)
{
var httpClient = _clientFactory.CreateClient();
var content = "";
using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, $"http://localhost:5020/Chat?Message={HttpUtility.UrlEncode(message)}"))
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwt);
var responseGet = await httpClient.SendAsync(requestMessage);
content = responseGet.Content.ReadAsStringAsync().Result;
}
return content;
}
private async Task<string> GetMessage(string id, string email, string name, string message)
{
var httpClient = _clientFactory.CreateClient();
var content = "";
using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, $"http://localhost:5020/Chat?SessionId={HttpUtility.UrlEncode(id)}&Message={HttpUtility.UrlEncode(message)}&Email={HttpUtility.UrlEncode(email)}&Name={HttpUtility.UrlEncode(name)}"))
{
//requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwt);
var responseGet = await httpClient.SendAsync(requestMessage);
content = responseGet.Content.ReadAsStringAsync().Result;
}
return content;
}
}