BotSharp/src/Plugins/BotSharp.Plugin.WeChat/WeChatBackgroundService.cs

90 lines
3 KiB
C#
Raw Normal View History

2023-06-24 09:25:55 +00:00
using BotSharp.Abstraction.Conversations;
using BotSharp.Abstraction.Infrastructures.ContentTransmitters;
using BotSharp.Abstraction.Models;
2023-06-26 23:12:38 +00:00
using Microsoft.Extensions.DependencyInjection;
2023-06-24 09:25:55 +00:00
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
namespace BotSharp.Plugin.WeChat
{
2023-06-27 02:23:30 +00:00
public class WeChatBackgroundService : BackgroundService, IMessageQueue
2023-06-24 09:25:55 +00:00
{
private readonly Channel<WeChatMessage> _queue;
2023-06-26 23:12:38 +00:00
private readonly IServiceProvider _service;
2023-06-24 09:25:55 +00:00
private readonly ILogger<WeChatBackgroundService> _logger;
2023-06-26 23:12:38 +00:00
public WeChatBackgroundService(
IServiceProvider service,
2023-06-24 09:25:55 +00:00
ILogger<WeChatBackgroundService> logger)
{
2023-06-27 02:23:30 +00:00
2023-06-26 23:12:38 +00:00
this._service = service;
2023-06-24 09:25:55 +00:00
this._logger = logger;
this._queue = Channel.CreateUnbounded<WeChatMessage>();
}
private async Task HandleTextMessageAsync(string openid, string message)
{
2023-06-26 23:12:38 +00:00
var scoped = _service.CreateScope().ServiceProvider;
var conversationService = scoped.GetRequiredService<IConversationService>();
var contentTransfer = scoped.GetRequiredService<IContentTransfer>();
var conversations = conversationService.GetDialogHistory(openid);
2023-06-24 09:25:55 +00:00
conversations.Add(new RoleDialogModel
{
Role = "User",
Text = message,
});
var container = new ContentContainer
{
Conversations = conversations
};
2023-06-26 23:12:38 +00:00
var result = await contentTransfer.Transport(container);
2023-06-24 09:25:55 +00:00
if (result.IsSuccess)
{
var output = container.Output.Text.Trim();
await ReplyTextMessageAsync(openid, output);
2023-06-26 23:12:38 +00:00
conversationService.AddDialog(new RoleDialogModel()
2023-06-24 09:25:55 +00:00
{
Role = "Assistant",
Text = output,
});
}
}
private async Task ReplyTextMessageAsync(string openid, string content)
{
var appId = Senparc.Weixin.Config.SenparcWeixinSetting.WeixinAppId;
await Senparc.Weixin.MP.AdvancedAPIs.CustomApi.SendTextAsync(appId, openid, content);
}
2023-06-27 02:23:30 +00:00
public async Task EnqueueAsync(WeChatMessage message)
{
await _queue.Writer.WriteAsync(message);
}
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
2023-06-24 09:25:55 +00:00
{
while (!cancellationToken.IsCancellationRequested)
{
try
{
var message = await _queue.Reader.ReadAsync(cancellationToken);
await HandleTextMessageAsync(message.OpenId, message.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error occurred Handle Message");
}
}
}
}
}