about summary refs log tree commit diff
path: root/Utilities/LibMatrix.Utilities.Bot/Services/CommandListenerHostedService.cs
blob: f56f9c12064fde2a4d32ada5830c036243f96d1b (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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
using LibMatrix.EventTypes.Spec;
using LibMatrix.Helpers;
using LibMatrix.Homeservers;
using LibMatrix.Utilities.Bot.Interfaces;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace LibMatrix.Utilities.Bot.Services;

public class CommandListenerHostedService : IHostedService {
    private readonly AuthenticatedHomeserverGeneric _hs;
    private readonly ILogger<CommandListenerHostedService> _logger;
    private readonly IEnumerable<ICommand> _commands;
    private readonly LibMatrixBotConfiguration _config;

    private Task? _listenerTask;

    public CommandListenerHostedService(AuthenticatedHomeserverGeneric hs, ILogger<CommandListenerHostedService> logger, IServiceProvider services,
        LibMatrixBotConfiguration config) {
        logger.LogInformation("{} instantiated!", this.GetType().Name);
        _hs = hs;
        _logger = logger;
        _config = config;
        _logger.LogInformation("Getting commands...");
        _commands = services.GetServices<ICommand>();
        _logger.LogInformation("Got {} commands!", _commands.Count());
    }

    /// <summary>Triggered when the application host is ready to start the service.</summary>
    /// <param name="cancellationToken">Indicates that the start process has been aborted.</param>
    public Task StartAsync(CancellationToken cancellationToken) {
        _listenerTask = Run(cancellationToken);
        _logger.LogInformation("Command listener started (StartAsync)!");
        return Task.CompletedTask;
    }

    private async Task? Run(CancellationToken cancellationToken) {
        _logger.LogInformation("Starting command listener!");
        var syncHelper = new SyncHelper(_hs);
        syncHelper.TimelineEventHandlers.Add(async @event => {
            try {
                var room = _hs.GetRoom(@event.RoomId);
                // _logger.LogInformation(eventResponse.ToJson(indent: false));
                if (@event is { Type: "m.room.message", TypedContent: RoomMessageEventContent message }) {
                    if (message is { MessageType: "m.text" }) {
                        var messageContentWithoutReply =
                            message.Body.Split('\n', StringSplitOptions.RemoveEmptyEntries).SkipWhile(x => x.StartsWith(">")).Aggregate((x, y) => $"{x}\n{y}");
                        if (messageContentWithoutReply.StartsWith(_config.Prefix)) {
                            var command = _commands.FirstOrDefault(x => x.Name == messageContentWithoutReply.Split(' ')[0][_config.Prefix.Length..]);
                            if (command == null) {
                                await room.SendMessageEventAsync(
                                    new RoomMessageEventContent(messageType: "m.notice", body: "Command not found!"));
                                return;
                            }

                            var ctx = new CommandContext {
                                Room = room,
                                MessageEvent = @event,
                                Homeserver = _hs
                            };

                            if (await command.CanInvoke(ctx)) {
                                try {
                                    await command.Invoke(ctx);
                                }
                                catch (Exception e) {
                                    await room.SendMessageEventAsync(
                                        MessageFormatter.FormatException("An error occurred during the execution of this command", e));
                                }
                            }
                            else {
                                await room.SendMessageEventAsync(
                                    new RoomMessageEventContent(messageType: "m.notice", body: "You do not have permission to run this command!"));
                            }
                        }
                    }
                }
            }
            catch (Exception e) {
                _logger.LogError(e, "Error in command listener!");
            }
        });
        await new SyncHelper(_hs){Timeout = 2500}.RunSyncLoopAsync(cancellationToken: cancellationToken);
    }

    /// <summary>Triggered when the application host is performing a graceful shutdown.</summary>
    /// <param name="cancellationToken">Indicates that the shutdown process should no longer be graceful.</param>
    public Task StopAsync(CancellationToken cancellationToken) {
        _logger.LogInformation("Shutting down command listener!");
        _listenerTask.Wait(cancellationToken);
        return Task.CompletedTask;
    }
}