about summary refs log tree commit diff
path: root/ExampleBots/PluralContactBotPoC/Bot/Commands/CreateSystemCommand.cs
blob: 6d2cb3a0b4c1eb27d45a2bbd85f30bacf6d76fc2 (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
50
51
52
53
54
55
56
57
using LibMatrix;
using LibMatrix.EventTypes.Spec.State;
using LibMatrix.Helpers;
using LibMatrix.Services;
using LibMatrix.Utilities.Bot.Interfaces;
using PluralContactBotPoC.Bot.AccountData;
using PluralContactBotPoC.Bot.StateEventTypes;

namespace PluralContactBotPoC.Bot.Commands;

public class CreateSystemCommand(IServiceProvider services, HomeserverProviderService hsProvider, HomeserverResolverService hsResolver) : ICommand {
    public string Name { get; } = "createsystem";
    public string Description { get; } = "Create a new system";

    public async Task<bool> CanInvoke(CommandContext ctx) {
        return true;
    }

    public async Task Invoke(CommandContext ctx) {
        if (ctx.Args.Length != 1) {
            await ctx.Reply(MessageFormatter.FormatError("Only one argument is allowed: system name!"));
            return;
        }

        var sysName = ctx.Args[0];
        try {
            try {
                await ctx.Homeserver.GetAccountDataAsync<BotData>("gay.rory.plural_contact_bot.system_data");
                await ctx.Reply(MessageFormatter.FormatError($"System {sysName} already exists!"));
            }
            catch (MatrixException e) {
                if (e is { ErrorCode: "M_NOT_FOUND" }) {
                    var sysData = new SystemData() {
                        ControlRoom = ctx.Room.RoomId,
                        Members = new(),
                    };

                    var state = ctx.Room.GetMembersAsync();
                    await foreach (var member in state) {
                        sysData.Members.Add(member.StateKey);
                    }

                    await ctx.Room.SendStateEventAsync("m.room.name", new RoomNameEventContent() {
                        Name = sysName + " control room"
                    });

                    return;
                }

                throw;
            }
        }
        catch (Exception e) {
            await ctx.Reply(MessageFormatter.FormatException("Something went wrong!", e));
        }
    }
}