about summary refs log tree commit diff
path: root/Utilities/LibMatrix.Utilities.Bot
diff options
context:
space:
mode:
authorRory& <root@rory.gay>2025-03-09 18:34:53 +0100
committerRory& <root@rory.gay>2025-03-09 18:34:53 +0100
commit9659093fcd9745f7030418998ca1cf886ff820b3 (patch)
treee7223357f7deb85738c195fa5bbca30d9e4cc548 /Utilities/LibMatrix.Utilities.Bot
parentWell known resolver work, synapse admin work (diff)
Error reading parent commit
downloadLibMatrix-unpacked-9659093fcd9745f7030418998ca1cf886ff820b3.tar.xz
Merge remote-tracking branch 'origin/dev/moderationclient-changes'
Diffstat (limited to 'Utilities/LibMatrix.Utilities.Bot')
-rw-r--r--Utilities/LibMatrix.Utilities.Bot/BotCommandInstaller.cs81
-rw-r--r--Utilities/LibMatrix.Utilities.Bot/Services/CommandListenerHostedService.cs49
2 files changed, 36 insertions, 94 deletions
diff --git a/Utilities/LibMatrix.Utilities.Bot/BotCommandInstaller.cs b/Utilities/LibMatrix.Utilities.Bot/BotCommandInstaller.cs

index ca6a4d8..8501d41 100644 --- a/Utilities/LibMatrix.Utilities.Bot/BotCommandInstaller.cs +++ b/Utilities/LibMatrix.Utilities.Bot/BotCommandInstaller.cs
@@ -1,81 +0,0 @@ -using ArcaneLibs; -using LibMatrix.Homeservers; -using LibMatrix.Services; -using LibMatrix.Utilities.Bot.AppServices; -using LibMatrix.Utilities.Bot.Interfaces; -using LibMatrix.Utilities.Bot.Services; -using Microsoft.Extensions.DependencyInjection; - -namespace LibMatrix.Utilities.Bot; - -public static class BotCommandInstaller { - public static BotInstaller AddMatrixBot(this IServiceCollection services) { - return new BotInstaller(services).AddMatrixBot(); - } -} - -public class BotInstaller(IServiceCollection services) { - public BotInstaller AddMatrixBot() { - services.AddSingleton<LibMatrixBotConfiguration>(); - - services.AddScoped<AuthenticatedHomeserverGeneric>(x => { - var config = x.GetService<LibMatrixBotConfiguration>() ?? throw new Exception("No configuration found!"); - var hsProvider = x.GetService<HomeserverProviderService>() ?? throw new Exception("No homeserver provider found!"); - - if (x.GetService<AppServiceConfiguration>() is AppServiceConfiguration appsvcConfig) - config.AccessToken = appsvcConfig.AppserviceToken; - else if (Environment.GetEnvironmentVariable("LIBMATRIX_ACCESS_TOKEN_PATH") is string path) - config.AccessTokenPath = path; - - if(string.IsNullOrWhiteSpace(config.AccessToken) && string.IsNullOrWhiteSpace(config.AccessTokenPath)) - throw new Exception("Unable to add bot service without an access token or access token path!"); - - if(!string.IsNullOrWhiteSpace(config.AccessTokenPath)) { - var token = File.ReadAllText(config.AccessTokenPath); - config.AccessToken = token; - } - - var hs = hsProvider.GetAuthenticatedWithToken(config.Homeserver, config.AccessToken).Result; - - return hs; - }); - - return this; - } - - public BotInstaller AddCommandHandler() { - Console.WriteLine("Adding command handler..."); - services.AddHostedService<CommandListenerHostedService>(); - return this; - } - - public BotInstaller DiscoverAllCommands() { - foreach (var commandClass in ClassCollector<ICommand>.ResolveFromAllAccessibleAssemblies()) { - Console.WriteLine($"Adding command {commandClass.Name}"); - services.AddScoped(typeof(ICommand), commandClass); - } - - return this; - } - public BotInstaller AddCommands(IEnumerable<Type> commandClasses) { - foreach (var commandClass in commandClasses) { - if(!commandClass.IsAssignableTo(typeof(ICommand))) - throw new Exception($"Type {commandClass.Name} is not assignable to ICommand!"); - Console.WriteLine($"Adding command {commandClass.Name}"); - services.AddScoped(typeof(ICommand), commandClass); - } - - return this; - } - - public BotInstaller WithInviteHandler(Func<InviteHandlerHostedService.InviteEventArgs, Task> inviteHandler) { - services.AddSingleton(inviteHandler); - services.AddHostedService<InviteHandlerHostedService>(); - return this; - } - - public BotInstaller WithCommandResultHandler(Func<CommandResult, Task> commandResultHandler) { - services.AddSingleton(commandResultHandler); - return this; - } -} \ No newline at end of file diff --git a/Utilities/LibMatrix.Utilities.Bot/Services/CommandListenerHostedService.cs b/Utilities/LibMatrix.Utilities.Bot/Services/CommandListenerHostedService.cs
index b5b5a2b..d07090f 100644 --- a/Utilities/LibMatrix.Utilities.Bot/Services/CommandListenerHostedService.cs +++ b/Utilities/LibMatrix.Utilities.Bot/Services/CommandListenerHostedService.cs
@@ -1,3 +1,4 @@ +using ArcaneLibs.Extensions; using LibMatrix.EventTypes.Spec; using LibMatrix.EventTypes.Spec.State.RoomInfo; using LibMatrix.Filters; @@ -57,22 +58,44 @@ public class CommandListenerHostedService : IHostedService { FilterId = filter }; - syncHelper.TimelineEventHandlers.Add(async @event => { - try { - var room = _hs.GetRoom(@event.RoomId); - // _logger.LogInformation(eventResponse.ToJson(indent: false)); - if (@event is { Type: "m.room.message", TypedContent: RoomMessageEventContent message }) - if (message is { MessageType: "m.text" }) { - var usedPrefix = await GetUsedPrefix(@event); - if (usedPrefix is null) return; - var res = await InvokeCommand(@event, usedPrefix); - await (_commandResultHandler?.Invoke(res) ?? HandleResult(res)); + syncHelper.SyncReceivedHandlers.Add(async sync => { + _logger.LogInformation("Sync received!"); + foreach (var roomResp in sync.Rooms?.Join ?? []) { + if (roomResp.Value.Timeline?.Events is null or { Count: > 5 }) continue; + foreach (var @event in roomResp.Value.Timeline.Events) { + @event.RoomId = roomResp.Key; + try { + // var room = _hs.GetRoom(@event.RoomId); + // _logger.LogInformation(eventResponse.ToJson(indent: false)); + if (@event is { Type: "m.room.message", TypedContent: RoomMessageEventContent message }) + if (message is { MessageType: "m.text" }) { + var usedPrefix = await GetUsedPrefix(@event); + if (usedPrefix is null) return; + var res = await InvokeCommand(@event, usedPrefix); + await (_commandResultHandler?.Invoke(res) ?? HandleResult(res)); + } } - } - catch (Exception e) { - _logger.LogError(e, "Error in command listener!"); + catch (Exception e) { + _logger.LogError(e, "Error in command listener!"); + Console.WriteLine(@event.ToJson(ignoreNull: false, indent: true)); + var fakeResult = new CommandResult() { + Result = CommandResult.CommandResultType.Failure_Exception, + Exception = e, + Success = false, + Context = new() { + Homeserver = _hs, + CommandName = "[CommandListener.SyncHandler]", + Room = _hs.GetRoom(roomResp.Key), + Args = [], + MessageEvent = @event + } + }; + await (_commandResultHandler?.Invoke(fakeResult) ?? HandleResult(fakeResult)); + } + } } }); + await syncHelper.RunSyncLoopAsync(cancellationToken: cancellationToken); }