about summary refs log tree commit diff
path: root/ExampleBots/PluralContactBotPoC/Bot/PluralContactBot.cs
blob: 2136b42f9af51e0e691c270cfbc2c05a68f93446 (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
95
96
97
98
99
using System.Text;
using ArcaneLibs.Extensions;
using LibMatrix.Helpers;
using LibMatrix.Homeservers;
using LibMatrix.RoomTypes;
using LibMatrix.Services;
using LibMatrix.StateEventTypes.Spec;
using LibMatrix.Utilities.Bot;
using MediaModeratorPoC.Bot.Interfaces;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using PluralContactBotPoC.Bot.AccountData;
using PluralContactBotPoC.Bot.StateEventTypes;

namespace PluralContactBotPoC.Bot;

public class PluralContactBot(AuthenticatedHomeserverGeneric hs, ILogger<PluralContactBot> logger, LibMatrixBotConfiguration botConfiguration,
    PluralContactBotConfiguration configuration,
    HomeserverResolverService hsResolver) : IHostedService {
    private readonly IEnumerable<ICommand> _commands;

    private Task _listenerTask;

    private GenericRoom? _logRoom;

    /// <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 async Task StartAsync(CancellationToken cancellationToken) {
        _listenerTask = Run(cancellationToken);
        logger.LogInformation("Bot started!");
    }

    private async Task Run(CancellationToken cancellationToken) {
        Directory.GetFiles("bot_data/cache").ToList().ForEach(File.Delete);

        BotData botData;

        _logRoom = await hs.GetRoom(botConfiguration.LogRoom);

        hs.SyncHelper.InviteReceivedHandlers.Add(async Task (args) => {
            var inviteEvent =
                args.Value.InviteState.Events.FirstOrDefault(x =>
                    x.Type == "m.room.member" && x.StateKey == hs.WhoAmI.UserId);
            logger.LogInformation("Got invite to {} by {} with reason: {}", args.Key, inviteEvent.Sender, (inviteEvent.TypedContent as RoomMemberEventContent).Reason);

            try {
                var accountData = await hs.GetAccountData<SystemData>($"gay.rory.plural_contact_bot.system_data#{inviteEvent.StateKey}");
                if (accountData.Members.Contains(inviteEvent.Sender)) {
                    await (await hs.GetRoom(args.Key)).JoinAsync(reason: "I was invited by a system member!");

                    await _logRoom.SendMessageEventAsync("m.room.message",
                        MessageFormatter.FormatSuccess(
                            $"I was invited by a system member ({MessageFormatter.HtmlFormatMention(inviteEvent.Sender)}) to {MessageFormatter.HtmlFormatMention(args.Key)}"));

                    return;
                }
            }
            catch (Exception e) {
                await _logRoom.SendMessageEventAsync("m.room.message",
                    MessageFormatter.FormatException(
                        $"Exception handling event {inviteEvent.EventId} by {inviteEvent.Sender} in {MessageFormatter.HtmlFormatMention(inviteEvent.RoomId)}", e));
            }

            if (inviteEvent.Sender.EndsWith(":rory.gay") || inviteEvent.Sender.EndsWith(":conduit.rory.gay")) {
                try {
                    var senderProfile = await hs.GetProfile(inviteEvent.Sender);
                    await (await hs.GetRoom(args.Key)).JoinAsync(reason: $"I was invited by {senderProfile.DisplayName ?? inviteEvent.Sender}!");
                }
                catch (Exception e) {
                    logger.LogError("{}", e.ToString());
                    await (await hs.GetRoom(args.Key)).LeaveAsync(reason: "I was unable to join the room: " + e);
                }
            }
        });

        hs.SyncHelper.TimelineEventHandlers.Add(async @event => {
            var room = await hs.GetRoom(@event.RoomId);
            try {
                logger.LogInformation(
                    "Got timeline event in {}: {}", @event.RoomId, @event.ToJson(indent: true, ignoreNull: true));

                if (@event is { Type: "m.room.message", TypedContent: RoomMessageEventContent message }) { }
            }
            catch (Exception e) {
                logger.LogError("{}", e.ToString());
                await _logRoom.SendMessageEventAsync("m.room.message",
                    MessageFormatter.FormatException($"Exception handling event {@event.EventId} by {@event.Sender} in {MessageFormatter.HtmlFormatMention(room.RoomId)}", e));
                await using var stream = new MemoryStream(Encoding.UTF8.GetBytes(e.ToString()));
                await _logRoom.SendFileAsync("m.file", "error.log.cs", stream);
            }
        });
    }

    /// <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 async Task StopAsync(CancellationToken cancellationToken) {
        logger.LogInformation("Shutting down bot!");
    }
}