about summary refs log tree commit diff
path: root/Utilities/LibMatrix.Utilities.Bot/BotCommandInstaller.cs
blob: 5a0b7add2ec689d076579d408d90ca17d86c3ae2 (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
58
59
60
61
62
63
64
65
66
67
68
using ArcaneLibs;
using LibMatrix.EventTypes.Spec.State;
using LibMatrix.Homeservers;
using LibMatrix.Responses;
using LibMatrix.Services;
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.AddSingleton<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!");
            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;
    }
}