From 2e271e1de75b8fe27dfdaa459f5b04f66b9be5c0 Mon Sep 17 00:00:00 2001 From: xbotter Date: Sat, 24 Jun 2023 17:25:55 +0800 Subject: [PATCH 1/5] feat: add WeChat Plugin --- .../BotSharp.Plugin.WeChat.csproj | 7 +- .../BotSharpMessageHandler.cs | 50 +++++++++++ .../BotSharp.Plugin.WeChat/IMessageQueue.cs | 12 +++ .../WeChatBackgroundService.cs | 90 +++++++++++++++++++ .../BotSharp.Plugin.WeChat/WeChatMessage.cs | 13 +++ .../BotSharp.Plugin.WeChat/WeChatPlugin.cs | 34 +++++++ src/WebStarter/appsettings.json | 2 +- 7 files changed, 206 insertions(+), 2 deletions(-) create mode 100644 src/Plugins/BotSharp.Plugin.WeChat/BotSharpMessageHandler.cs create mode 100644 src/Plugins/BotSharp.Plugin.WeChat/IMessageQueue.cs create mode 100644 src/Plugins/BotSharp.Plugin.WeChat/WeChatBackgroundService.cs create mode 100644 src/Plugins/BotSharp.Plugin.WeChat/WeChatMessage.cs create mode 100644 src/Plugins/BotSharp.Plugin.WeChat/WeChatPlugin.cs diff --git a/src/Plugins/BotSharp.Plugin.WeChat/BotSharp.Plugin.WeChat.csproj b/src/Plugins/BotSharp.Plugin.WeChat/BotSharp.Plugin.WeChat.csproj index d1ee4dc0..4dc14bdf 100644 --- a/src/Plugins/BotSharp.Plugin.WeChat/BotSharp.Plugin.WeChat.csproj +++ b/src/Plugins/BotSharp.Plugin.WeChat/BotSharp.Plugin.WeChat.csproj @@ -20,7 +20,12 @@ - + + + + + + diff --git a/src/Plugins/BotSharp.Plugin.WeChat/BotSharpMessageHandler.cs b/src/Plugins/BotSharp.Plugin.WeChat/BotSharpMessageHandler.cs new file mode 100644 index 00000000..f25c882d --- /dev/null +++ b/src/Plugins/BotSharp.Plugin.WeChat/BotSharpMessageHandler.cs @@ -0,0 +1,50 @@ +using BotSharp.Abstraction.Conversations; +using BotSharp.Abstraction.Infrastructures.ContentTransmitters; +using BotSharp.Abstraction.Models; +using Microsoft.Extensions.DependencyInjection; +using Senparc.NeuChar.App.AppStore; +using Senparc.NeuChar.Entities; +using Senparc.Weixin.MP.Entities; +using Senparc.Weixin.MP.Entities.Request; +using Senparc.Weixin.MP.MessageContexts; +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace BotSharp.Plugin.WeChat +{ + public class BotSharpMessageHandler : Senparc.Weixin.MP.MessageHandlers.MessageHandler + { + public BotSharpMessageHandler(Stream inputStream, PostModel postModel, int maxRecordCount = 0, bool onlyAllowEncryptMessage = false, DeveloperInfo developerInfo = null, IServiceProvider serviceProvider = null) : base(inputStream, postModel, maxRecordCount, onlyAllowEncryptMessage, developerInfo, serviceProvider) + { + } + + public BotSharpMessageHandler(XDocument requestDocument, PostModel postModel, int maxRecordCount = 0, bool onlyAllowEncryptMessage = false, DeveloperInfo developerInfo = null, IServiceProvider serviceProvider = null) : base(requestDocument, postModel, maxRecordCount, onlyAllowEncryptMessage, developerInfo, serviceProvider) + { + } + + public BotSharpMessageHandler(RequestMessageBase requestMessageBase, PostModel postModel, int maxRecordCount = 0, bool onlyAllowEncryptMessage = false, DeveloperInfo developerInfo = null, IServiceProvider serviceProvider = null) : base(requestMessageBase, postModel, maxRecordCount, onlyAllowEncryptMessage, developerInfo, serviceProvider) + { + } + + public override IResponseMessageBase DefaultResponseMessage(IRequestMessageBase requestMessage) + { + return null; + } + + public async override Task OnTextRequestAsync(RequestMessageText requestMessage) + { + var messageQueue = ServiceProvider.GetRequiredService(); + await messageQueue.EnqueueAsync(new WeChatMessage() + { + OpenId = OpenId, + Message = requestMessage.Content, + Type = "text" + }); + return await base.OnTextRequestAsync(requestMessage); + } + } +} diff --git a/src/Plugins/BotSharp.Plugin.WeChat/IMessageQueue.cs b/src/Plugins/BotSharp.Plugin.WeChat/IMessageQueue.cs new file mode 100644 index 00000000..b7d31cf6 --- /dev/null +++ b/src/Plugins/BotSharp.Plugin.WeChat/IMessageQueue.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; + +namespace BotSharp.Plugin.WeChat +{ + public interface IMessageQueue + { + Task EnqueueAsync(WeChatMessage message); + } +} diff --git a/src/Plugins/BotSharp.Plugin.WeChat/WeChatBackgroundService.cs b/src/Plugins/BotSharp.Plugin.WeChat/WeChatBackgroundService.cs new file mode 100644 index 00000000..83a7092f --- /dev/null +++ b/src/Plugins/BotSharp.Plugin.WeChat/WeChatBackgroundService.cs @@ -0,0 +1,90 @@ +using BotSharp.Abstraction.Conversations; +using BotSharp.Abstraction.Infrastructures.ContentTransmitters; +using BotSharp.Abstraction.Models; +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 +{ + public class WeChatBackgroundService : IHostedService, IMessageQueue + { + private readonly Channel _queue; + private readonly IConversationService _conversationService; + private readonly IContentTransfer _contentTransfer; + private readonly ILogger _logger; + + public WeChatBackgroundService(IConversationService conversationService, + IContentTransfer contentTransfer, + ILogger logger) + { + this._conversationService = conversationService; + this._contentTransfer = contentTransfer; + this._logger = logger; + this._queue = Channel.CreateUnbounded(); + } + + private async Task HandleTextMessageAsync(string openid, string message) + { + var conversations = _conversationService.GetDialogHistory(openid); + conversations.Add(new RoleDialogModel + { + Role = "User", + Text = message, + }); + + var container = new ContentContainer + { + Conversations = conversations + }; + + var result = await _contentTransfer.Transport(container); + + if (result.IsSuccess) + { + var output = container.Output.Text.Trim(); + await ReplyTextMessageAsync(openid, output); + _conversationService.AddDialog(new RoleDialogModel() + { + 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); + } + + public async Task StartAsync(CancellationToken cancellationToken) + { + 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"); + } + } + } + + public Task StopAsync(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } + + public async Task EnqueueAsync(WeChatMessage message) + { + await _queue.Writer.WriteAsync(message); + } + } +} diff --git a/src/Plugins/BotSharp.Plugin.WeChat/WeChatMessage.cs b/src/Plugins/BotSharp.Plugin.WeChat/WeChatMessage.cs new file mode 100644 index 00000000..944c2fce --- /dev/null +++ b/src/Plugins/BotSharp.Plugin.WeChat/WeChatMessage.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace BotSharp.Plugin.WeChat +{ + public class WeChatMessage + { + public string OpenId { get; set; } + public string Type { get; set; } + public string Message { get; set; } + } +} diff --git a/src/Plugins/BotSharp.Plugin.WeChat/WeChatPlugin.cs b/src/Plugins/BotSharp.Plugin.WeChat/WeChatPlugin.cs new file mode 100644 index 00000000..f5b24a1c --- /dev/null +++ b/src/Plugins/BotSharp.Plugin.WeChat/WeChatPlugin.cs @@ -0,0 +1,34 @@ +using BotSharp.Abstraction.Plugins; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Hosting; +using Senparc.Weixin.AspNet; +using Senparc.Weixin.RegisterServices; +using System; +using System.Collections.Generic; +using System.Text; + +namespace BotSharp.Plugin.WeChat +{ + + public class WeChatPlugin : IBotSharpPlugin + { + public void RegisterDI(IServiceCollection services, IConfiguration config) + { + services.AddMemoryCache(); + + services.AddSenparcWeixinServices(config); + + services.AddHostedService(); + + services.TryAddSingleton(s => s.GetRequiredService()); + } + + public void ConfigurateApplication(IApplicationBuilder app) + { + // TODO: app.UseSenparcWeixin + } + } +} diff --git a/src/WebStarter/appsettings.json b/src/WebStarter/appsettings.json index 90f666a2..d3bd76f2 100644 --- a/src/WebStarter/appsettings.json +++ b/src/WebStarter/appsettings.json @@ -48,7 +48,7 @@ "Master": "mongodb://localhost:27017/chat-ui" }, "Agent": { - "Master": "Data Source=(localdb)\\ProjectModels;Initial Catalog=Agent;Integrated Security=True;Connect Timeout=30;Encrypt=False;Trust Server Certificate=False;Application Intent=ReadWrite;Multi Subnet Failover=False", + "Master": "Data Source=(localdb)\\mssqllocaldb;Initial Catalog=Agent;Integrated Security=True;Connect Timeout=30;Encrypt=False;Trust Server Certificate=False;Application Intent=ReadWrite;Multi Subnet Failover=False", "Slavers": [] }, "UseCamelCase": true, From 3a7b3aa0570df5cde80289fd7aa05d852dcc63e2 Mon Sep 17 00:00:00 2001 From: xbotter Date: Sat, 24 Jun 2023 17:28:52 +0800 Subject: [PATCH 2/5] reset appsettings.json --- src/WebStarter/appsettings.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/WebStarter/appsettings.json b/src/WebStarter/appsettings.json index d3bd76f2..90f666a2 100644 --- a/src/WebStarter/appsettings.json +++ b/src/WebStarter/appsettings.json @@ -48,7 +48,7 @@ "Master": "mongodb://localhost:27017/chat-ui" }, "Agent": { - "Master": "Data Source=(localdb)\\mssqllocaldb;Initial Catalog=Agent;Integrated Security=True;Connect Timeout=30;Encrypt=False;Trust Server Certificate=False;Application Intent=ReadWrite;Multi Subnet Failover=False", + "Master": "Data Source=(localdb)\\ProjectModels;Initial Catalog=Agent;Integrated Security=True;Connect Timeout=30;Encrypt=False;Trust Server Certificate=False;Application Intent=ReadWrite;Multi Subnet Failover=False", "Slavers": [] }, "UseCamelCase": true, From 8b680203dd4356aea0a53feb8d56ef5ace295b30 Mon Sep 17 00:00:00 2001 From: xbotter Date: Tue, 27 Jun 2023 06:16:21 +0800 Subject: [PATCH 3/5] adapt to IApplicationBuilder configure --- .../Plugins/IBotSharpAppPlugin.cs | 12 ++++++++++ .../BotSharpServiceCollectionExtensions.cs | 4 ++++ .../BotSharp.Core/Plugins/PluginLoader.cs | 19 ++++++++++++++- .../BotSharp.Plugin.WeChat.csproj | 2 +- .../BotSharpMessageHandler.cs | 3 +++ .../BotSharp.Plugin.WeChat/WeChatPlugin.cs | 23 +++++++++++++++---- 6 files changed, 57 insertions(+), 6 deletions(-) create mode 100644 src/Infrastructure/BotSharp.Abstraction/Plugins/IBotSharpAppPlugin.cs diff --git a/src/Infrastructure/BotSharp.Abstraction/Plugins/IBotSharpAppPlugin.cs b/src/Infrastructure/BotSharp.Abstraction/Plugins/IBotSharpAppPlugin.cs new file mode 100644 index 00000000..d4106b7a --- /dev/null +++ b/src/Infrastructure/BotSharp.Abstraction/Plugins/IBotSharpAppPlugin.cs @@ -0,0 +1,12 @@ +using Microsoft.AspNetCore.Builder; +using System; +using System.Collections.Generic; +using System.Text; + +namespace BotSharp.Abstraction.Plugins +{ + public interface IBotSharpAppPlugin: IBotSharpPlugin + { + void Configure(IApplicationBuilder app); + } +} diff --git a/src/Infrastructure/BotSharp.Core/BotSharpServiceCollectionExtensions.cs b/src/Infrastructure/BotSharp.Core/BotSharpServiceCollectionExtensions.cs index cf65850d..40e994b1 100644 --- a/src/Infrastructure/BotSharp.Core/BotSharpServiceCollectionExtensions.cs +++ b/src/Infrastructure/BotSharp.Core/BotSharpServiceCollectionExtensions.cs @@ -40,6 +40,8 @@ public static class BotSharpServiceCollectionExtensions throw new ArgumentNullException(nameof(app)); } + app.ApplicationServices.GetRequiredService().Configure(app); + return app; } @@ -77,5 +79,7 @@ public static class BotSharpServiceCollectionExtensions var loader = new PluginLoader(services, config, pluginSettings); loader.Load(); + + services.AddSingleton(loader); } } diff --git a/src/Infrastructure/BotSharp.Core/Plugins/PluginLoader.cs b/src/Infrastructure/BotSharp.Core/Plugins/PluginLoader.cs index 79cdd134..6e79dc03 100644 --- a/src/Infrastructure/BotSharp.Core/Plugins/PluginLoader.cs +++ b/src/Infrastructure/BotSharp.Core/Plugins/PluginLoader.cs @@ -1,3 +1,4 @@ +using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Configuration; using System.Drawing; using System.IO; @@ -13,7 +14,7 @@ public class PluginLoader private readonly PluginLoaderSettings _settings; private static List _modules = new List(); - public PluginLoader(IServiceCollection services, + public PluginLoader(IServiceCollection services, IConfiguration config, PluginLoaderSettings settings) { @@ -59,4 +60,20 @@ public class PluginLoader } }); } + + public void Configure(IApplicationBuilder app) + { + if(_modules.Count == 0) + { + Console.WriteLine($"No plugin loaded. Please check whether the Load() method is called.", Color.Yellow); + } + + _modules.ForEach(module => + { + if (module.GetType().GetInterface(nameof(IBotSharpAppPlugin)) != null) + { + (module as IBotSharpAppPlugin).Configure(app); + } + }); + } } diff --git a/src/Plugins/BotSharp.Plugin.WeChat/BotSharp.Plugin.WeChat.csproj b/src/Plugins/BotSharp.Plugin.WeChat/BotSharp.Plugin.WeChat.csproj index 4dc14bdf..611146dd 100644 --- a/src/Plugins/BotSharp.Plugin.WeChat/BotSharp.Plugin.WeChat.csproj +++ b/src/Plugins/BotSharp.Plugin.WeChat/BotSharp.Plugin.WeChat.csproj @@ -24,7 +24,7 @@ - + diff --git a/src/Plugins/BotSharp.Plugin.WeChat/BotSharpMessageHandler.cs b/src/Plugins/BotSharp.Plugin.WeChat/BotSharpMessageHandler.cs index f25c882d..d12a6f45 100644 --- a/src/Plugins/BotSharp.Plugin.WeChat/BotSharpMessageHandler.cs +++ b/src/Plugins/BotSharp.Plugin.WeChat/BotSharpMessageHandler.cs @@ -18,6 +18,9 @@ namespace BotSharp.Plugin.WeChat { public class BotSharpMessageHandler : Senparc.Weixin.MP.MessageHandlers.MessageHandler { + public static Func GenerateMessageHandler = (stream, postModel, maxRecordCount, serviceProvider) + => new BotSharpMessageHandler(stream, postModel, maxRecordCount, false /* 是否只允许处理加密消息,以提高安全性 */, serviceProvider: serviceProvider); + public BotSharpMessageHandler(Stream inputStream, PostModel postModel, int maxRecordCount = 0, bool onlyAllowEncryptMessage = false, DeveloperInfo developerInfo = null, IServiceProvider serviceProvider = null) : base(inputStream, postModel, maxRecordCount, onlyAllowEncryptMessage, developerInfo, serviceProvider) { } diff --git a/src/Plugins/BotSharp.Plugin.WeChat/WeChatPlugin.cs b/src/Plugins/BotSharp.Plugin.WeChat/WeChatPlugin.cs index f5b24a1c..6ed9fb72 100644 --- a/src/Plugins/BotSharp.Plugin.WeChat/WeChatPlugin.cs +++ b/src/Plugins/BotSharp.Plugin.WeChat/WeChatPlugin.cs @@ -4,16 +4,20 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; -using Senparc.Weixin.AspNet; +using Senparc.CO2NET.AspNet; +using Senparc.CO2NET; using Senparc.Weixin.RegisterServices; using System; using System.Collections.Generic; using System.Text; +using Senparc.Weixin; +using Senparc.Weixin.MP; +using Senparc.Weixin.MP.MessageHandlers.Middleware; namespace BotSharp.Plugin.WeChat { - public class WeChatPlugin : IBotSharpPlugin + public class WeChatPlugin : IBotSharpAppPlugin { public void RegisterDI(IServiceCollection services, IConfiguration config) { @@ -26,9 +30,20 @@ namespace BotSharp.Plugin.WeChat services.TryAddSingleton(s => s.GetRequiredService()); } - public void ConfigurateApplication(IApplicationBuilder app) + public void Configure(IApplicationBuilder app) { - // TODO: app.UseSenparcWeixin + var env = app.ApplicationServices.GetRequiredService(); + var register = app.UseSenparcGlobal(env); + register.UseSenparcWeixin(null, (svc, settings) => + { + svc.RegisterMpAccount(settings, "WeChat"); + }, app.ApplicationServices); + + app.UseMessageHandlerForMp("/WeixinAsync", BotSharpMessageHandler.GenerateMessageHandler, options => + { + options.AccountSettingFunc = context => Senparc.Weixin.Config.SenparcWeixinSetting; + }); + } } } From 62e833d6b8c7acf14d5d5b0f1f611bac5b7e9758 Mon Sep 17 00:00:00 2001 From: xbotter Date: Tue, 27 Jun 2023 07:12:38 +0800 Subject: [PATCH 4/5] add webstarter setting --- .../WeChatBackgroundService.cs | 22 +++++++++++-------- .../BotSharp.Plugin.WeChat/WeChatPlugin.cs | 17 ++++++++++++-- src/WebStarter/WebStarter.csproj | 1 + src/WebStarter/appsettings.json | 13 +++++++++-- 4 files changed, 40 insertions(+), 13 deletions(-) diff --git a/src/Plugins/BotSharp.Plugin.WeChat/WeChatBackgroundService.cs b/src/Plugins/BotSharp.Plugin.WeChat/WeChatBackgroundService.cs index 83a7092f..b7948f03 100644 --- a/src/Plugins/BotSharp.Plugin.WeChat/WeChatBackgroundService.cs +++ b/src/Plugins/BotSharp.Plugin.WeChat/WeChatBackgroundService.cs @@ -1,6 +1,7 @@ using BotSharp.Abstraction.Conversations; using BotSharp.Abstraction.Infrastructures.ContentTransmitters; using BotSharp.Abstraction.Models; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; @@ -13,23 +14,26 @@ namespace BotSharp.Plugin.WeChat public class WeChatBackgroundService : IHostedService, IMessageQueue { private readonly Channel _queue; - private readonly IConversationService _conversationService; - private readonly IContentTransfer _contentTransfer; + private readonly IServiceProvider _service; private readonly ILogger _logger; - public WeChatBackgroundService(IConversationService conversationService, - IContentTransfer contentTransfer, + public WeChatBackgroundService( + IServiceProvider service, ILogger logger) { - this._conversationService = conversationService; - this._contentTransfer = contentTransfer; + + this._service = service; this._logger = logger; this._queue = Channel.CreateUnbounded(); } private async Task HandleTextMessageAsync(string openid, string message) { - var conversations = _conversationService.GetDialogHistory(openid); + var scoped = _service.CreateScope().ServiceProvider; + var conversationService = scoped.GetRequiredService(); + var contentTransfer = scoped.GetRequiredService(); + + var conversations = conversationService.GetDialogHistory(openid); conversations.Add(new RoleDialogModel { Role = "User", @@ -41,13 +45,13 @@ namespace BotSharp.Plugin.WeChat Conversations = conversations }; - var result = await _contentTransfer.Transport(container); + var result = await contentTransfer.Transport(container); if (result.IsSuccess) { var output = container.Output.Text.Trim(); await ReplyTextMessageAsync(openid, output); - _conversationService.AddDialog(new RoleDialogModel() + conversationService.AddDialog(new RoleDialogModel() { Role = "Assistant", Text = output, diff --git a/src/Plugins/BotSharp.Plugin.WeChat/WeChatPlugin.cs b/src/Plugins/BotSharp.Plugin.WeChat/WeChatPlugin.cs index 6ed9fb72..bd8caa27 100644 --- a/src/Plugins/BotSharp.Plugin.WeChat/WeChatPlugin.cs +++ b/src/Plugins/BotSharp.Plugin.WeChat/WeChatPlugin.cs @@ -13,6 +13,10 @@ using System.Text; using Senparc.Weixin; using Senparc.Weixin.MP; using Senparc.Weixin.MP.MessageHandlers.Middleware; +using Senparc.Weixin.Entities; +using Senparc.CO2NET.RegisterServices; +using Microsoft.Extensions.Logging; +using Microsoft.AspNetCore.Http; namespace BotSharp.Plugin.WeChat { @@ -23,7 +27,12 @@ namespace BotSharp.Plugin.WeChat { services.AddMemoryCache(); - services.AddSenparcWeixinServices(config); + services.Configure(config.GetSection("WeChat")); + + if (!Senparc.CO2NET.RegisterServices.RegisterServiceExtension.SenparcGlobalServicesRegistered) + { + services = services.AddSenparcGlobalServices(config); + } services.AddHostedService(); @@ -33,17 +42,21 @@ namespace BotSharp.Plugin.WeChat public void Configure(IApplicationBuilder app) { var env = app.ApplicationServices.GetRequiredService(); + var logger = app.ApplicationServices.GetRequiredService>(); + var register = app.UseSenparcGlobal(env); register.UseSenparcWeixin(null, (svc, settings) => { svc.RegisterMpAccount(settings, "WeChat"); }, app.ApplicationServices); - app.UseMessageHandlerForMp("/WeixinAsync", BotSharpMessageHandler.GenerateMessageHandler, options => + app.UseMessageHandlerForMp("/WeChatAsync", BotSharpMessageHandler.GenerateMessageHandler, options => { options.AccountSettingFunc = context => Senparc.Weixin.Config.SenparcWeixinSetting; }); + logger.LogInformation("WeChat Message Handler is running on /WeChatAsync."); + } } } diff --git a/src/WebStarter/WebStarter.csproj b/src/WebStarter/WebStarter.csproj index 7991ff98..e2abd70d 100644 --- a/src/WebStarter/WebStarter.csproj +++ b/src/WebStarter/WebStarter.csproj @@ -42,6 +42,7 @@ + diff --git a/src/WebStarter/appsettings.json b/src/WebStarter/appsettings.json index 90f666a2..bd849f57 100644 --- a/src/WebStarter/appsettings.json +++ b/src/WebStarter/appsettings.json @@ -14,7 +14,7 @@ }, "Conversation": { - + }, "LlamaSharp": { @@ -60,6 +60,13 @@ "ApiKey": "" }, + "WeChat": { + "Token": "#{Token}#", + "EncodingAESKey": "#{EncodingAESKey}#", + "WeixinAppId": "#{WeixinAppId}#", + "WeixinAppSecret": "#{WeixinAppSecret}#" + }, + "PluginLoader": { "Assemblies": [ "BotSharp.Core", @@ -67,13 +74,15 @@ "BotSharp.Plugin.MetaAI", "BotSharp.Plugin.Qdrant", "BotSharp.Plugin.PaddleSharp" + "BotSharp.Plugin.WeChat" ], "Plugins": [ // "LLamaSharpPlugin", "AzureOpenAiPlugin", "MetaAiPlugin", "QdrantPlugin", - "PaddleSharpPlugin" + "PaddleSharpPlugin", + "WeChatPlugin" ] } } From d143e0292794ca5ae7820e4bd327512dad36233d Mon Sep 17 00:00:00 2001 From: xbotter Date: Tue, 27 Jun 2023 10:23:30 +0800 Subject: [PATCH 5/5] fix BackgroundService --- .../BotSharp.Core/Plugins/PluginLoader.cs | 5 ++++- .../WeChatBackgroundService.cs | 21 +++++++------------ .../BotSharp.Plugin.WeChat/WeChatPlugin.cs | 6 +++++- src/WebStarter/appsettings.json | 2 +- 4 files changed, 18 insertions(+), 16 deletions(-) diff --git a/src/Infrastructure/BotSharp.Core/Plugins/PluginLoader.cs b/src/Infrastructure/BotSharp.Core/Plugins/PluginLoader.cs index 6e79dc03..516b906f 100644 --- a/src/Infrastructure/BotSharp.Core/Plugins/PluginLoader.cs +++ b/src/Infrastructure/BotSharp.Core/Plugins/PluginLoader.cs @@ -72,7 +72,10 @@ public class PluginLoader { if (module.GetType().GetInterface(nameof(IBotSharpAppPlugin)) != null) { - (module as IBotSharpAppPlugin).Configure(app); + if (_settings.Plugins.Contains(module.GetType().Name)) + { + (module as IBotSharpAppPlugin).Configure(app); + } } }); } diff --git a/src/Plugins/BotSharp.Plugin.WeChat/WeChatBackgroundService.cs b/src/Plugins/BotSharp.Plugin.WeChat/WeChatBackgroundService.cs index b7948f03..09aac562 100644 --- a/src/Plugins/BotSharp.Plugin.WeChat/WeChatBackgroundService.cs +++ b/src/Plugins/BotSharp.Plugin.WeChat/WeChatBackgroundService.cs @@ -11,7 +11,7 @@ using System.Threading.Tasks; namespace BotSharp.Plugin.WeChat { - public class WeChatBackgroundService : IHostedService, IMessageQueue + public class WeChatBackgroundService : BackgroundService, IMessageQueue { private readonly Channel _queue; private readonly IServiceProvider _service; @@ -21,7 +21,7 @@ namespace BotSharp.Plugin.WeChat IServiceProvider service, ILogger logger) { - + this._service = service; this._logger = logger; this._queue = Channel.CreateUnbounded(); @@ -65,7 +65,12 @@ namespace BotSharp.Plugin.WeChat await Senparc.Weixin.MP.AdvancedAPIs.CustomApi.SendTextAsync(appId, openid, content); } - public async Task StartAsync(CancellationToken cancellationToken) + public async Task EnqueueAsync(WeChatMessage message) + { + await _queue.Writer.WriteAsync(message); + } + + protected override async Task ExecuteAsync(CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { @@ -80,15 +85,5 @@ namespace BotSharp.Plugin.WeChat } } } - - public Task StopAsync(CancellationToken cancellationToken) - { - return Task.CompletedTask; - } - - public async Task EnqueueAsync(WeChatMessage message) - { - await _queue.Writer.WriteAsync(message); - } } } diff --git a/src/Plugins/BotSharp.Plugin.WeChat/WeChatPlugin.cs b/src/Plugins/BotSharp.Plugin.WeChat/WeChatPlugin.cs index bd8caa27..38c6592f 100644 --- a/src/Plugins/BotSharp.Plugin.WeChat/WeChatPlugin.cs +++ b/src/Plugins/BotSharp.Plugin.WeChat/WeChatPlugin.cs @@ -34,7 +34,9 @@ namespace BotSharp.Plugin.WeChat services = services.AddSenparcGlobalServices(config); } - services.AddHostedService(); + services.AddSingleton(); + + services.AddHostedService(s => s.GetRequiredService()); services.TryAddSingleton(s => s.GetRequiredService()); } @@ -53,6 +55,8 @@ namespace BotSharp.Plugin.WeChat app.UseMessageHandlerForMp("/WeChatAsync", BotSharpMessageHandler.GenerateMessageHandler, options => { options.AccountSettingFunc = context => Senparc.Weixin.Config.SenparcWeixinSetting; + options.EnbleResponseLog = false; + options.EnableRequestLog = false; }); logger.LogInformation("WeChat Message Handler is running on /WeChatAsync."); diff --git a/src/WebStarter/appsettings.json b/src/WebStarter/appsettings.json index c7f705b8..10509e05 100644 --- a/src/WebStarter/appsettings.json +++ b/src/WebStarter/appsettings.json @@ -77,7 +77,7 @@ "BotSharp.Plugin.AzureOpenAI", "BotSharp.Plugin.MetaAI", "BotSharp.Plugin.Qdrant", - "BotSharp.Plugin.PaddleSharp" + "BotSharp.Plugin.PaddleSharp", "BotSharp.Plugin.WeChat" ], "Plugins": [