about summary refs log tree commit diff
path: root/Utilities/LibMatrix.Utilities.Bot/BotCommandInstaller.cs
blob: 16e144422d21671071737396862e1954b40f1ecd (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
using ArcaneLibs;
using ArcaneLibs.Extensions;
using LibMatrix.Helpers;
using LibMatrix.Homeservers;
using LibMatrix.Services;
using LibMatrix.Utilities.Bot.Interfaces;
using LibMatrix.Utilities.Bot.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace LibMatrix.Utilities.Bot;

public static class BotCommandInstaller {
    public static IServiceCollection AddBotCommands(this IServiceCollection services) {
        foreach (var commandClass in new ClassCollector<ICommand>().ResolveFromAllAccessibleAssemblies()) {
            Console.WriteLine($"Adding command {commandClass.Name}");
            services.AddScoped(typeof(ICommand), commandClass);
        }

        return services;
    }

    public static IServiceCollection AddBot(this IServiceCollection services, bool withCommands = true, bool isAppservice = false) {
        services.AddSingleton<LibMatrixBotConfiguration>();

        services.AddScoped<AuthenticatedHomeserverGeneric>(x => {
            var config = x.GetService<LibMatrixBotConfiguration>();
            var hsProvider = x.GetService<HomeserverProviderService>();
            var hs = hsProvider.GetAuthenticatedWithToken(config.Homeserver, config.AccessToken).Result;

            return hs;
        });

        if (withCommands) {
            Console.WriteLine("Adding command handler...");
            services.AddBotCommands();
            services.AddHostedService<CommandListenerHostedService>();
            // services.AddSingleton<IHostedService, CommandListenerHostedService>();
        }
        return services;
    }
}