about summary refs log tree commit diff
path: root/MatrixRoomUtils.Bot
diff options
context:
space:
mode:
authorTheArcaneBrony <myrainbowdash949@gmail.com>2023-06-26 02:43:54 +0200
committerTheArcaneBrony <myrainbowdash949@gmail.com>2023-06-27 17:43:00 +0200
commit3ed00f732a284b5a3e96e52d4e3a71869135869b (patch)
tree308cdd5c9891a676dc55cbf0e0e998ab5a74b2d2 /MatrixRoomUtils.Bot
parentWorking state, refactored Rory&::LibMatrix (diff)
downloadMatrixUtils-3ed00f732a284b5a3e96e52d4e3a71869135869b.tar.xz
Dependency injection stuff
Diffstat (limited to 'MatrixRoomUtils.Bot')
-rw-r--r--MatrixRoomUtils.Bot/Bot/Commands/CmdCommand.cs49
-rw-r--r--MatrixRoomUtils.Bot/Bot/Commands/HelpCommand.cs28
-rw-r--r--MatrixRoomUtils.Bot/Bot/Commands/PingCommand.cs19
-rw-r--r--MatrixRoomUtils.Bot/Bot/FileStorageProvider.cs (renamed from MatrixRoomUtils.Bot/FileStorageProvider.cs)0
-rw-r--r--MatrixRoomUtils.Bot/Bot/Interfaces/CommandContext.cs11
-rw-r--r--MatrixRoomUtils.Bot/Bot/Interfaces/ICommand.cs12
-rw-r--r--MatrixRoomUtils.Bot/Bot/MRUBot.cs (renamed from MatrixRoomUtils.Bot/MRUBot.cs)56
-rw-r--r--MatrixRoomUtils.Bot/Bot/MRUBotConfiguration.cs (renamed from MatrixRoomUtils.Bot/MRUBotConfiguration.cs)1
-rw-r--r--MatrixRoomUtils.Bot/MatrixRoomUtils.Bot.csproj5
-rw-r--r--MatrixRoomUtils.Bot/Program.cs6
10 files changed, 173 insertions, 14 deletions
diff --git a/MatrixRoomUtils.Bot/Bot/Commands/CmdCommand.cs b/MatrixRoomUtils.Bot/Bot/Commands/CmdCommand.cs
new file mode 100644
index 0000000..c267298
--- /dev/null
+++ b/MatrixRoomUtils.Bot/Bot/Commands/CmdCommand.cs
@@ -0,0 +1,49 @@
+using System.Runtime.InteropServices;
+using System.Text;
+using MatrixRoomUtils.Bot.Interfaces;
+using Microsoft.Extensions.DependencyInjection;
+
+namespace MatrixRoomUtils.Bot.Commands;
+
+public class CmdCommand : ICommand {
+    public string Name { get; } = "cmd";
+    public string Description { get; } = "Runs a command on the host system";
+
+    public async Task<bool> CanInvoke(CommandContext ctx) {
+        return ctx.MessageEvent.Sender.EndsWith(":rory.gay");
+    }
+
+    public async Task Invoke(CommandContext ctx) {
+        var cmd = "\"";
+        foreach (var arg in ctx.Args) cmd += arg + " ";
+
+        cmd = cmd.Trim();
+        cmd += "\"";
+
+        await ctx.Room.SendMessageEventAsync("m.room.message", new() {
+            Body = $"Command being executed: `{cmd}`"
+        });
+
+        var output = ArcaneLibs.Util.GetCommandOutputSync(
+                Environment.OSVersion.Platform == PlatformID.Unix ? "/bin/sh" : "cmd.exe",
+                (Environment.OSVersion.Platform == PlatformID.Unix ? "-c " : "/c ") + cmd)
+            .Replace("`", "\\`")
+            .Split("\n").ToList();
+        foreach (var _out in output) Console.WriteLine($"{_out.Length:0000} {_out}");
+
+        var msg = "";
+        while (output.Count > 0) {
+            Console.WriteLine("Adding: " + output[0]);
+            msg += output[0] + "\n";
+            output.RemoveAt(0);
+            if ((output.Count > 0 && (msg + output[0]).Length > 64000) || output.Count == 0) {
+                await ctx.Room.SendMessageEventAsync("m.room.message", new() {
+                    FormattedBody = $"```ansi\n{msg}\n```",
+                    Body = Markdig.Markdown.ToHtml(msg),
+                    Format = "org.matrix.custom.html"
+                });
+                msg = "";
+            }
+        }
+    }
+}
\ No newline at end of file
diff --git a/MatrixRoomUtils.Bot/Bot/Commands/HelpCommand.cs b/MatrixRoomUtils.Bot/Bot/Commands/HelpCommand.cs
new file mode 100644
index 0000000..af41563
--- /dev/null
+++ b/MatrixRoomUtils.Bot/Bot/Commands/HelpCommand.cs
@@ -0,0 +1,28 @@
+using System.Text;
+using MatrixRoomUtils.Bot.Interfaces;
+using Microsoft.Extensions.DependencyInjection;
+
+namespace MatrixRoomUtils.Bot.Commands; 
+
+public class HelpCommand : ICommand {
+    private readonly IServiceProvider _services;
+    public HelpCommand(IServiceProvider services) {
+        _services = services;
+    }
+
+    public string Name { get; } = "help";
+    public string Description { get; } = "Displays this help message";
+
+    public async Task Invoke(CommandContext ctx) {
+        var sb = new StringBuilder();
+        sb.AppendLine("Available commands:");
+        var commands = _services.GetServices<ICommand>().ToList();
+        foreach (var command in commands) {
+            sb.AppendLine($"- {command.Name}: {command.Description}");
+        }
+
+        await ctx.Room.SendMessageEventAsync("m.room.message", new() {
+            Body = sb.ToString(),
+        });
+    }
+}
\ No newline at end of file
diff --git a/MatrixRoomUtils.Bot/Bot/Commands/PingCommand.cs b/MatrixRoomUtils.Bot/Bot/Commands/PingCommand.cs
new file mode 100644
index 0000000..a00cc8b
--- /dev/null
+++ b/MatrixRoomUtils.Bot/Bot/Commands/PingCommand.cs
@@ -0,0 +1,19 @@
+using System.Text;
+using MatrixRoomUtils.Bot.Interfaces;
+using Microsoft.Extensions.DependencyInjection;
+
+namespace MatrixRoomUtils.Bot.Commands; 
+
+public class PingCommand : ICommand {
+    public PingCommand() {
+    }
+
+    public string Name { get; } = "ping";
+    public string Description { get; } = "Pong!";
+
+    public async Task Invoke(CommandContext ctx) {
+        await ctx.Room.SendMessageEventAsync("m.room.message", new() {
+            Body = "pong!"
+        });
+    }
+}
\ No newline at end of file
diff --git a/MatrixRoomUtils.Bot/FileStorageProvider.cs b/MatrixRoomUtils.Bot/Bot/FileStorageProvider.cs
index 8d99828..8d99828 100644
--- a/MatrixRoomUtils.Bot/FileStorageProvider.cs
+++ b/MatrixRoomUtils.Bot/Bot/FileStorageProvider.cs
diff --git a/MatrixRoomUtils.Bot/Bot/Interfaces/CommandContext.cs b/MatrixRoomUtils.Bot/Bot/Interfaces/CommandContext.cs
new file mode 100644
index 0000000..ab29554
--- /dev/null
+++ b/MatrixRoomUtils.Bot/Bot/Interfaces/CommandContext.cs
@@ -0,0 +1,11 @@
+using MatrixRoomUtils.Core;
+using MatrixRoomUtils.Core.Responses;
+
+namespace MatrixRoomUtils.Bot.Interfaces;
+
+public class CommandContext {
+    public GenericRoom Room { get; set; }
+    public StateEventResponse MessageEvent { get; set; }
+    public string CommandName => (MessageEvent.TypedContent as MessageEventData).Body.Split(' ')[0][1..];
+    public string[] Args => (MessageEvent.TypedContent as MessageEventData).Body.Split(' ')[1..];
+}
\ No newline at end of file
diff --git a/MatrixRoomUtils.Bot/Bot/Interfaces/ICommand.cs b/MatrixRoomUtils.Bot/Bot/Interfaces/ICommand.cs
new file mode 100644
index 0000000..b57d8c9
--- /dev/null
+++ b/MatrixRoomUtils.Bot/Bot/Interfaces/ICommand.cs
@@ -0,0 +1,12 @@
+namespace MatrixRoomUtils.Bot.Interfaces; 
+
+public interface ICommand {
+    public string Name { get; }
+    public string Description { get; }
+
+    public Task<bool> CanInvoke(CommandContext ctx) {
+        return Task.FromResult(true);
+    }
+    
+    public Task Invoke(CommandContext ctx);
+}
\ No newline at end of file
diff --git a/MatrixRoomUtils.Bot/MRUBot.cs b/MatrixRoomUtils.Bot/Bot/MRUBot.cs
index 157673d..81123e0 100644
--- a/MatrixRoomUtils.Bot/MRUBot.cs
+++ b/MatrixRoomUtils.Bot/Bot/MRUBot.cs
@@ -1,11 +1,13 @@
 using System.Diagnostics;
 using System.Diagnostics.CodeAnalysis;
 using MatrixRoomUtils.Bot;
+using MatrixRoomUtils.Bot.Interfaces;
 using MatrixRoomUtils.Core;
 using MatrixRoomUtils.Core.Extensions;
 using MatrixRoomUtils.Core.Helpers;
 using MatrixRoomUtils.Core.Services;
 using MatrixRoomUtils.Core.StateEventTypes;
+using Microsoft.Extensions.DependencyInjection;
 using Microsoft.Extensions.Hosting;
 using Microsoft.Extensions.Logging;
 
@@ -13,13 +15,17 @@ public class MRUBot : IHostedService {
     private readonly HomeserverProviderService _homeserverProviderService;
     private readonly ILogger<MRUBot> _logger;
     private readonly MRUBotConfiguration _configuration;
+    private readonly IEnumerable<ICommand> _commands;
 
     public MRUBot(HomeserverProviderService homeserverProviderService, ILogger<MRUBot> logger,
-        MRUBotConfiguration configuration) {
+        MRUBotConfiguration configuration, IServiceProvider services) {
         Console.WriteLine("MRUBot hosted service instantiated!");
         _homeserverProviderService = homeserverProviderService;
         _logger = logger;
         _configuration = configuration;
+        Console.WriteLine("Getting commands...");
+        _commands = services.GetServices<ICommand>();
+        Console.WriteLine($"Got {_commands.Count()} commands!");
     }
 
     /// <summary>Triggered when the application host is ready to start the service.</summary>
@@ -39,18 +45,20 @@ public class MRUBot : IHostedService {
 
         await (await hs.GetRoom("!DoHEdFablOLjddKWIp:rory.gay")).JoinAsync();
 
-        hs.SyncHelper.InviteReceived += async (_, args) => {
-            // Console.WriteLine($"Got invite to {args.Key}:");
-            // foreach (var stateEvent in args.Value.InviteState.Events) {
-            // Console.WriteLine($"[{stateEvent.Sender}: {stateEvent.StateKey}::{stateEvent.Type}] " +
-            // ObjectExtensions.ToJson(stateEvent.Content, indent: false, ignoreNull: true));
-            // }
+        // foreach (var room in await hs.GetJoinedRooms()) {
+        //     if(room.RoomId is "!OGEhHVWSdvArJzumhm:matrix.org") continue;
+        //     foreach (var stateEvent in await room.GetStateAsync<List<StateEvent>>("")) {
+        //         var _ = stateEvent.GetType;
+        //     }
+        //     Console.WriteLine($"Got room state for {room.RoomId}!");
+        // }
 
+        hs.SyncHelper.InviteReceived += async (_, args) => {
             var inviteEvent =
                 args.Value.InviteState.Events.FirstOrDefault(x =>
                     x.Type == "m.room.member" && x.StateKey == hs.WhoAmI.UserId);
             Console.WriteLine(
-                $"Got invite to {args.Key} by {inviteEvent.Sender} with reason: {(inviteEvent.TypedContent as MemberEventData).Reason}");
+                $"Got invite to {args.Key} by {inviteEvent.Sender} with reason: {(inviteEvent.TypedContent as RoomMemberEventData).Reason}");
             if (inviteEvent.Sender == "@emma:rory.gay") {
                 try {
                     await (await hs.GetRoom(args.Key)).JoinAsync(reason: "I was invited by Emma (Rory&)!");
@@ -65,17 +73,37 @@ public class MRUBot : IHostedService {
             Console.WriteLine(
                 $"Got timeline event in {@event.RoomId}: {@event.ToJson(indent: false, ignoreNull: true)}");
 
+            var room = await hs.GetRoom(@event.RoomId);
             // Console.WriteLine(eventResponse.ToJson(indent: false));
             if (@event is { Type: "m.room.message", TypedContent: MessageEventData message }) {
-                if (message is { MessageType: "m.text", Body: "!ping" }) {
-                    Console.WriteLine(
-                        $"Got ping from {@event.Sender} in {@event.RoomId} with message id {@event.EventId}!");
-                    await (await hs.GetRoom(@event.RoomId)).SendMessageEventAsync("m.room.message",
-                        new MessageEventData() { MessageType = "m.text", Body = "pong!" });
+                if (message is { MessageType: "m.text" } && message.Body.StartsWith(_configuration.Prefix)) {
+                    
+                        var command = _commands.FirstOrDefault(x => x.Name == message.Body.Split(' ')[0][_configuration.Prefix.Length..]);
+                        if (command == null) {
+                            await room.SendMessageEventAsync("m.room.message",
+                                new MessageEventData() {
+                                    MessageType = "m.text",
+                                    Body = "Command not found!"
+                                });
+                            return;
+                        }
+                        var ctx = new CommandContext() {
+                            Room = room,
+                            MessageEvent = @event
+                        };
+                        if (await command.CanInvoke(ctx)) {
+                            await command.Invoke(ctx);
+                        }
+                        else {
+                            await room.SendMessageEventAsync("m.room.message",
+                                new MessageEventData() {
+                                    MessageType = "m.text",
+                                    Body = "You do not have permission to run this command!"
+                                });
+                        }
                 }
             }
         };
-
         await hs.SyncHelper.RunSyncLoop(cancellationToken);
     }
 
diff --git a/MatrixRoomUtils.Bot/MRUBotConfiguration.cs b/MatrixRoomUtils.Bot/Bot/MRUBotConfiguration.cs
index 14d9b60..c91698a 100644
--- a/MatrixRoomUtils.Bot/MRUBotConfiguration.cs
+++ b/MatrixRoomUtils.Bot/Bot/MRUBotConfiguration.cs
@@ -8,4 +8,5 @@ public class MRUBotConfiguration {
     }
     public string Homeserver { get; set; } = "";
     public string AccessToken { get; set; } = "";
+    public string Prefix { get; set; }
 }
\ No newline at end of file
diff --git a/MatrixRoomUtils.Bot/MatrixRoomUtils.Bot.csproj b/MatrixRoomUtils.Bot/MatrixRoomUtils.Bot.csproj
index a82b6aa..7012647 100644
--- a/MatrixRoomUtils.Bot/MatrixRoomUtils.Bot.csproj
+++ b/MatrixRoomUtils.Bot/MatrixRoomUtils.Bot.csproj
@@ -21,11 +21,16 @@
   </ItemGroup>

   

   <ItemGroup>

+    <PackageReference Include="ArcaneLibs" Version="1.0.0-preview3020494760.012ed3f" />

+    <PackageReference Include="Markdig" Version="0.31.0" />

     <PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0-preview.5.23280.8" />

   </ItemGroup>

   <ItemGroup>

     <Content Include="appsettings*.json">

       <CopyToOutputDirectory>Always</CopyToOutputDirectory>

     </Content>

+    <Content Update="appsettings.Local.json">

+      <CopyToOutputDirectory>Always</CopyToOutputDirectory>

+    </Content>

   </ItemGroup>

 </Project>

diff --git a/MatrixRoomUtils.Bot/Program.cs b/MatrixRoomUtils.Bot/Program.cs
index e8a5b96..0e27286 100644
--- a/MatrixRoomUtils.Bot/Program.cs
+++ b/MatrixRoomUtils.Bot/Program.cs
@@ -1,6 +1,8 @@
 // See https://aka.ms/new-console-template for more information

 

 using MatrixRoomUtils.Bot;

+using MatrixRoomUtils.Bot.Interfaces;

+using MatrixRoomUtils.Core.Extensions;

 using MatrixRoomUtils.Core.Services;

 using Microsoft.Extensions.DependencyInjection;

 using Microsoft.Extensions.Hosting;

@@ -16,6 +18,10 @@ var host = Host.CreateDefaultBuilder(args).ConfigureServices((_, services) => {
     );

     services.AddScoped<MRUBotConfiguration>();

     services.AddRoryLibMatrixServices();

+    foreach (var commandClass in new ClassCollector<ICommand>().ResolveFromAllAccessibleAssemblies()) {

+        Console.WriteLine($"Adding command {commandClass.Name}");

+        services.AddScoped(typeof(ICommand), commandClass);

+    }

     services.AddHostedService<MRUBot>();

 }).UseConsoleLifetime().Build();