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
|