From 6bd02248ccfbcb46960a6f39eaad23888d190eb5 Mon Sep 17 00:00:00 2001 From: TheArcaneBrony Date: Fri, 15 Sep 2023 09:50:45 +0200 Subject: Some refactoring --- .../PluralContactBotPoC/Bot/PluralContactBot.cs | 99 ++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 ExampleBots/PluralContactBotPoC/Bot/PluralContactBot.cs (limited to 'ExampleBots/PluralContactBotPoC/Bot/PluralContactBot.cs') diff --git a/ExampleBots/PluralContactBotPoC/Bot/PluralContactBot.cs b/ExampleBots/PluralContactBotPoC/Bot/PluralContactBot.cs new file mode 100644 index 0000000..2136b42 --- /dev/null +++ b/ExampleBots/PluralContactBotPoC/Bot/PluralContactBot.cs @@ -0,0 +1,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 logger, LibMatrixBotConfiguration botConfiguration, + PluralContactBotConfiguration configuration, + HomeserverResolverService hsResolver) : IHostedService { + private readonly IEnumerable _commands; + + private Task _listenerTask; + + private GenericRoom? _logRoom; + + /// Triggered when the application host is ready to start the service. + /// Indicates that the start process has been aborted. + 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($"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); + } + }); + } + + /// Triggered when the application host is performing a graceful shutdown. + /// Indicates that the shutdown process should no longer be graceful. + public async Task StopAsync(CancellationToken cancellationToken) { + logger.LogInformation("Shutting down bot!"); + } +} -- cgit 1.4.1