about summary refs log tree commit diff
path: root/MatrixRoomUtils.Bot/Bot/Commands/CmdCommand.cs
blob: c267298eda7012dcda2f5f85cec210c54485ede2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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 = "";
            }
        }
    }
}