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

74 lines
2.4 KiB
C#
Raw Normal View History

2023-06-29 11:40:01 +00:00
using BotSharp.Abstraction.Agents;
2023-06-24 09:25:55 +00:00
using BotSharp.Abstraction.Conversations;
2023-06-27 18:31:13 +00:00
using BotSharp.Abstraction.Conversations.Models;
2023-06-24 09:25:55 +00:00
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-29 11:40:01 +00:00
private string WeChatAppId => Senparc.Weixin.Config.SenparcWeixinSetting.WeixinAppId;
2023-06-24 09:25:55 +00:00
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-27 18:31:13 +00:00
_service = service;
_logger = logger;
_queue = Channel.CreateUnbounded<WeChatMessage>();
2023-06-24 09:25:55 +00:00
}
private async Task HandleTextMessageAsync(string openid, string message)
{
2023-06-26 23:12:38 +00:00
var scoped = _service.CreateScope().ServiceProvider;
2023-06-29 11:40:01 +00:00
2023-06-26 23:12:38 +00:00
var conversationService = scoped.GetRequiredService<IConversationService>();
2023-06-29 11:40:01 +00:00
var result = await conversationService.SendMessage(WeChatAppId, openid, new RoleDialogModel
2023-06-24 09:25:55 +00:00
{
2023-06-27 18:31:13 +00:00
Role = "user",
2023-06-24 09:25:55 +00:00
Text = message,
});
2023-06-27 18:31:13 +00:00
await ReplyTextMessageAsync(openid, result);
2023-06-24 09:25:55 +00:00
}
private async Task ReplyTextMessageAsync(string openid, string content)
{
2023-06-29 11:40:01 +00:00
await Senparc.Weixin.MP.AdvancedAPIs.CustomApi.SendTextAsync(WeChatAppId, openid, content);
2023-06-24 09:25:55 +00:00
}
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");
}
}
}
}
}