BotSharp/src/Plugins/BotSharp.Plugin.ChatHub/Hooks/WelcomeHook.cs

81 lines
2.9 KiB
C#
Raw Normal View History

2024-03-07 18:27:29 +00:00
using Microsoft.AspNetCore.SignalR;
namespace BotSharp.Plugin.ChatHub.Hooks;
public class WelcomeHook : ConversationHookBase
{
private readonly IServiceProvider _services;
private readonly IHubContext<SignalRHub> _chatHub;
private readonly IUserIdentity _user;
private readonly IConversationStorage _storage;
2024-03-18 19:36:41 +00:00
private readonly BotSharpOptions _options;
2024-03-07 18:27:29 +00:00
public WelcomeHook(IServiceProvider services,
IHubContext<SignalRHub> chatHub,
IUserIdentity user,
2024-03-18 19:36:41 +00:00
IConversationStorage storage,
BotSharpOptions options)
2024-03-07 18:27:29 +00:00
{
_services = services;
_chatHub = chatHub;
_user = user;
_storage = storage;
2024-03-18 19:36:41 +00:00
_options = options;
2024-03-07 18:27:29 +00:00
}
public override async Task OnUserAgentConnectedInitially(Conversation conversation)
{
var agentService = _services.GetRequiredService<IAgentService>();
var agent = await agentService.LoadAgent(conversation.AgentId);
// Check if the Welcome template exists.
var welcomeTemplate = agent.Templates?.FirstOrDefault(x => x.Name == ".welcome");
if (welcomeTemplate != null)
{
// Render template
var templating = _services.GetRequiredService<ITemplateRender>();
var user = _services.GetRequiredService<IUserIdentity>();
2024-09-16 22:04:08 +00:00
var content = templating.Render(welcomeTemplate.Content, new Dictionary<string, object>
2024-03-07 18:27:29 +00:00
{
{ "user", user }
});
var richContentService = _services.GetRequiredService<IRichContentService>();
2024-09-16 22:04:08 +00:00
var messages = richContentService.ConvertToMessages(content);
2024-03-07 18:27:29 +00:00
foreach (var message in messages)
{
2024-09-16 22:04:08 +00:00
var richContent = new RichContent<IRichMessage>(message)
{
Editor = message.RichType == RichTypeEnum.QuickReply ? EditorTypeEnum.None : EditorTypeEnum.Text,
};
2024-03-07 18:27:29 +00:00
var json = JsonSerializer.Serialize(new ChatResponseModel()
{
ConversationId = conversation.Id,
Text = message.Text,
2024-09-16 22:04:08 +00:00
RichContent = richContent,
2024-03-07 18:27:29 +00:00
Sender = new UserViewModel()
{
FirstName = agent.Name,
LastName = "",
Role = AgentRole.Assistant
}
2024-03-18 19:36:41 +00:00
}, _options.JsonSerializerOptions);
2024-03-07 18:27:29 +00:00
await Task.Delay(300);
_storage.Append(conversation.Id, new RoleDialogModel(AgentRole.Assistant, message.Text)
{
MessageId = conversation.Id,
CurrentAgentId = agent.Id,
2024-09-16 22:04:08 +00:00
RichContent = richContent
2024-03-07 18:27:29 +00:00
});
await _chatHub.Clients.User(_user.Id).SendAsync("OnMessageReceivedFromAssistant", json);
}
}
await base.OnUserAgentConnectedInitially(conversation);
}
}