about summary refs log tree commit diff
path: root/ExampleBots/MediaModeratorPoC
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--ExampleBots/MediaModeratorPoC/MediaModBot.cs339
-rw-r--r--ExampleBots/MediaModeratorPoC/MediaModBotConfiguration.cs10
-rw-r--r--ExampleBots/MediaModeratorPoC/PolicyEngine.cs86
-rw-r--r--ExampleBots/ModerationBot/AccountData/BotData.cs (renamed from ExampleBots/MediaModeratorPoC/AccountData/BotData.cs)7
-rw-r--r--ExampleBots/ModerationBot/Commands/BanMediaCommand.cs (renamed from ExampleBots/MediaModeratorPoC/Commands/BanMediaCommand.cs)28
-rw-r--r--ExampleBots/ModerationBot/ModerationBot.csproj (renamed from ExampleBots/MediaModeratorPoC/MediaModeratorPoC.csproj)2
-rw-r--r--ExampleBots/ModerationBot/PolicyList.cs (renamed from ExampleBots/MediaModeratorPoC/PolicyList.cs)6
-rw-r--r--ExampleBots/ModerationBot/Program.cs (renamed from ExampleBots/MediaModeratorPoC/Program.cs)8
-rw-r--r--ExampleBots/ModerationBot/Properties/launchSettings.json (renamed from ExampleBots/MediaModeratorPoC/Properties/launchSettings.json)0
-rw-r--r--ExampleBots/ModerationBot/StateEventTypes/Policies/BasePolicy.cs (renamed from ExampleBots/MediaModeratorPoC/StateEventTypes/BasePolicy.cs)15
-rw-r--r--ExampleBots/ModerationBot/StateEventTypes/Policies/Implementations/MediaPolicyFile.cs (renamed from ExampleBots/MediaModeratorPoC/StateEventTypes/MediaPolicyStateEventData.cs)9
-rw-r--r--ExampleBots/ModerationBot/appsettings.Development.json (renamed from ExampleBots/MediaModeratorPoC/appsettings.Development.json)2
-rw-r--r--ExampleBots/ModerationBot/appsettings.json (renamed from ExampleBots/MediaModeratorPoC/appsettings.json)0
13 files changed, 46 insertions, 466 deletions
diff --git a/ExampleBots/MediaModeratorPoC/MediaModBot.cs b/ExampleBots/MediaModeratorPoC/MediaModBot.cs
deleted file mode 100644
index 0aacf61..0000000
--- a/ExampleBots/MediaModeratorPoC/MediaModBot.cs
+++ /dev/null
@@ -1,339 +0,0 @@
-using System.Security.Cryptography;
-using System.Text.RegularExpressions;
-using ArcaneLibs.Extensions;
-using LibMatrix;
-using LibMatrix.EventTypes.Spec;
-using LibMatrix.EventTypes.Spec.State;
-using LibMatrix.Helpers;
-using LibMatrix.Homeservers;
-using LibMatrix.Responses;
-using LibMatrix.RoomTypes;
-using LibMatrix.Services;
-using LibMatrix.Utilities.Bot.Interfaces;
-using MediaModeratorPoC.AccountData;
-using MediaModeratorPoC.StateEventTypes;
-using Microsoft.Extensions.Hosting;
-using Microsoft.Extensions.Logging;
-
-namespace MediaModeratorPoC;
-
-public class MediaModBot(AuthenticatedHomeserverGeneric hs, ILogger<MediaModBot> logger, MediaModBotConfiguration configuration,
-    HomeserverResolverService hsResolver) : IHostedService {
-    private readonly IEnumerable<ICommand> _commands;
-
-    private Task _listenerTask;
-
-    private GenericRoom _policyRoom;
-    private GenericRoom _logRoom;
-    private GenericRoom _controlRoom;
-
-
-
-    /// <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;
-
-        try {
-            botData = await hs.GetAccountDataAsync<BotData>("gay.rory.modbot_data");
-        }
-        catch (Exception e) {
-            if (e is not MatrixException { ErrorCode: "M_NOT_FOUND" }) {
-                logger.LogError("{}", e.ToString());
-                throw;
-            }
-
-            botData = new BotData();
-            var creationContent = CreateRoomRequest.CreatePrivate(hs, name: "Media Moderator PoC - Control room", roomAliasName: "media-moderator-poc-control-room");
-            creationContent.Invite = configuration.Admins;
-            creationContent.CreationContent["type"] = "gay.rory.media_moderator_poc.control_room";
-
-            botData.ControlRoom = (await hs.CreateRoom(creationContent)).RoomId;
-
-            //set access rules to allow joining via control room
-            creationContent.InitialState.Add(new StateEvent {
-                Type = "m.room.join_rules",
-                StateKey = "",
-                TypedContent = new RoomJoinRulesEventContent {
-                    JoinRule = "knock_restricted",
-                    Allow = new() {
-                        new RoomJoinRulesEventContent.AllowEntry {
-                            Type = "m.room_membership",
-                            RoomId = botData.ControlRoom
-                        }
-                    }
-                }
-            });
-
-            creationContent.Name = "Media Moderator PoC - Log room";
-            creationContent.RoomAliasName = "media-moderator-poc-log-room";
-            creationContent.CreationContent["type"] = "gay.rory.media_moderator_poc.log_room";
-            botData.LogRoom = (await hs.CreateRoom(creationContent)).RoomId;
-
-            creationContent.Name = "Media Moderator PoC - Policy room";
-            creationContent.RoomAliasName = "media-moderator-poc-policy-room";
-            creationContent.CreationContent["type"] = "gay.rory.media_moderator_poc.policy_room";
-            botData.PolicyRoom = (await hs.CreateRoom(creationContent)).RoomId;
-
-            await hs.SetAccountData("gay.rory.modbot_data", botData);
-        }
-
-        _policyRoom = hs.GetRoom(botData.PolicyRoom ?? botData.ControlRoom);
-        _logRoom = hs.GetRoom(botData.LogRoom ?? botData.ControlRoom);
-        _controlRoom = hs.GetRoom(botData.ControlRoom);
-        var syncHelper = new SyncHelper(hs);
-
-        List<string> admins = new();
-
-#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
-        Task.Run(async () => {
-            while (!cancellationToken.IsCancellationRequested) {
-                var controlRoomMembers = _controlRoom.GetMembersAsync();
-                await foreach (var member in controlRoomMembers) {
-                    if ((member.TypedContent as RoomMemberEventContent)?
-
-                        .Membership == "join") admins.Add(member.UserId);
-                }
-
-                await Task.Delay(TimeSpan.FromSeconds(30), cancellationToken);
-            }
-        }, cancellationToken);
-#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
-
-        syncHelper.InviteReceivedHandlers.Add(async Task (args) => {
-            var inviteEvent =
-                args.Value.InviteState.Events.FirstOrDefault(x =>
-                    x.Type == "m.room.member" && x.StateKey == hs.UserId);
-            logger.LogInformation("Got invite to {RoomId} by {Sender} with reason: {Reason}", args.Key, inviteEvent!.Sender, (inviteEvent.TypedContent as RoomMemberEventContent)!.Reason);
-            if (inviteEvent.Sender.EndsWith(":rory.gay") || inviteEvent!.Sender.EndsWith(":conduit.rory.gay")) {
-                try {
-                    var senderProfile = await hs.GetProfileAsync(inviteEvent.Sender);
-                    await hs.GetRoom(args.Key).JoinAsync(reason: $"I was invited by {senderProfile.DisplayName ?? inviteEvent.Sender}!");
-                }
-                catch (Exception e) {
-                    logger.LogError("{}", e.ToString());
-                    await hs.GetRoom(args.Key).LeaveAsync(reason: "I was unable to join the room: " + e);
-                }
-            }
-        });
-
-        syncHelper.TimelineEventHandlers.Add(async @event => {
-            var room = 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 }) {
-                    if (message is { MessageType: "m.image" }) {
-                        //check media
-                        var matchedPolicy = await CheckMedia(@event);
-                        if (matchedPolicy is null) return;
-                        var matchedpolicyData = matchedPolicy.TypedContent as MediaPolicyEventContent;
-                        var recommendation = matchedpolicyData.Recommendation;
-                        await _logRoom.SendMessageEventAsync(
-                            new RoomMessageEventContent(
-                                body:
-                                $"User {MessageFormatter.HtmlFormatMention(@event.Sender)} posted an image in {MessageFormatter.HtmlFormatMention(room.RoomId)} that matched rule {matchedPolicy.StateKey}, applying action {matchedpolicyData.Recommendation}, as described in rule: {matchedPolicy.RawContent!.ToJson(ignoreNull: true)}",
-                                messageType: "m.text") {
-                                Format = "org.matrix.custom.html",
-                                FormattedBody =
-                                    $"<font color=\"#FFFF00\">User {MessageFormatter.HtmlFormatMention(@event.Sender)} posted an image in {MessageFormatter.HtmlFormatMention(room.RoomId)} that matched rule {matchedPolicy.StateKey}, applying action {matchedpolicyData.Recommendation}, as described in rule: <pre>{matchedPolicy.RawContent!.ToJson(ignoreNull: true)}</pre></font>"
-                            });
-                        switch (recommendation) {
-                            case "warn_admins": {
-                                await _controlRoom.SendMessageEventAsync(
-                                    new RoomMessageEventContent(
-                                        body: $"{string.Join(' ', admins)}\nUser {MessageFormatter.HtmlFormatMention(@event.Sender)} posted a banned image {message.Url}",
-                                        messageType: "m.text") {
-                                        Format = "org.matrix.custom.html",
-                                        FormattedBody = $"{string.Join(' ', admins.Select(u => MessageFormatter.HtmlFormatMention(u)))}\n" +
-                                                        $"<font color=\"#FF0000\">User {MessageFormatter.HtmlFormatMention(@event.Sender)} posted a banned image <a href=\"{message.Url}\">{message.Url}</a></font>"
-                                    });
-                                break;
-                            }
-                            case "warn": {
-                                await room.SendMessageEventAsync(
-                                    new RoomMessageEventContent(
-                                        body: $"Please be careful when posting this image: {matchedpolicyData.Reason ?? "No reason specified"}",
-                                        messageType: "m.text") {
-                                        Format = "org.matrix.custom.html",
-                                        FormattedBody =
-                                            $"<font color=\"#FFFF00\">Please be careful when posting this image: {matchedpolicyData.Reason ?? "No reason specified"}</a></font>"
-                                    });
-                                break;
-                            }
-                            case "redact": {
-                                await room.RedactEventAsync(@event.EventId, matchedpolicyData.Reason ?? "No reason specified");
-                                break;
-                            }
-                            case "spoiler": {
-                                // <blockquote>
-                                //  <a href=\"https://matrix.to/#/@emma:rory.gay\">@emma:rory.gay</a><br>
-                                //  <a href=\"https://codeberg.org/crimsonfork/CN\"></a>
-                                //  <font color=\"#dc143c\" data-mx-color=\"#dc143c\">
-                                //      <b>CN</b>
-                                //  </font>:
-                                //  <a href=\"https://the-apothecary.club/_matrix/media/v3/download/rory.gay/sLkdxUhipiQaFwRkXcPSRwdg\">test</a><br>
-                                //  <span data-mx-spoiler=\"\"><a href=\"https://the-apothecary.club/_matrix/media/v3/download/rory.gay/sLkdxUhipiQaFwRkXcPSRwdg\">
-                                //      <img src=\"mxc://rory.gay/sLkdxUhipiQaFwRkXcPSRwdg\" height=\"69\"></a>
-                                //  </span>
-                                // </blockquote>
-                                await room.SendMessageEventAsync(
-                                    new RoomMessageEventContent(
-                                        body:
-                                        $"Please be careful when posting this image: {matchedpolicyData.Reason}, I have spoilered it for you:",
-                                        messageType: "m.text") {
-                                        Format = "org.matrix.custom.html",
-                                        FormattedBody =
-                                            $"<font color=\"#FFFF00\">Please be careful when posting this image: {matchedpolicyData.Reason}, I have spoilered it for you:</a></font>"
-                                    });
-                                var imageUrl = message.Url;
-                                await room.SendMessageEventAsync(
-                                    new RoomMessageEventContent(body: $"CN: {imageUrl}",
-                                        messageType: "m.text") {
-                                        Format = "org.matrix.custom.html",
-                                        FormattedBody = $"""
-                                                             <blockquote>
-                                                                <font color=\"#dc143c\" data-mx-color=\"#dc143c\">
-                                                                    <b>CN</b>
-                                                                </font>:
-                                                                <a href=\"{imageUrl}\">{matchedpolicyData.Reason}</a><br>
-                                                                <span data-mx-spoiler=\"\">
-                                                                    <a href=\"{imageUrl}\">
-                                                                        <img src=\"{imageUrl}\" height=\"69\">
-                                                                    </a>
-                                                                </span>
-                                                             </blockquote>
-                                                         """
-                                    });
-                                await room.RedactEventAsync(@event.EventId, "Automatically spoilered: " + matchedpolicyData.Reason);
-                                break;
-                            }
-                            case "mute": {
-                                await room.RedactEventAsync(@event.EventId, matchedpolicyData.Reason);
-                                //change powerlevel to -1
-                                var currentPls = await room.GetPowerLevelsAsync();
-                                if(currentPls is null) {
-                                    logger.LogWarning("Unable to get power levels for {room}", room.RoomId);
-                                    await _logRoom.SendMessageEventAsync(
-                                        MessageFormatter.FormatError($"Unable to get power levels for {MessageFormatter.HtmlFormatMention(room.RoomId)}"));
-                                    return;
-                                }
-                                currentPls.Users ??= new();
-                                currentPls.Users[@event.Sender] = -1;
-                                await room.SendStateEventAsync("m.room.power_levels", currentPls);
-                                break;
-                            }
-                            case "kick": {
-                                await room.RedactEventAsync(@event.EventId, matchedpolicyData.Reason);
-                                await room.KickAsync(@event.Sender, matchedpolicyData.Reason);
-                                break;
-                            }
-                            case "ban": {
-                                await room.RedactEventAsync(@event.EventId, matchedpolicyData.Reason);
-                                await room.BanAsync(@event.Sender, matchedpolicyData.Reason);
-                                break;
-                            }
-                            default: {
-                                throw new ArgumentOutOfRangeException("recommendation",
-                                    $"Unknown response type {matchedpolicyData.Recommendation}!");
-                            }
-                        }
-                    }
-                }
-            }
-            catch (Exception e) {
-                logger.LogError("{}", e.ToString());
-                await _controlRoom.SendMessageEventAsync(
-                    MessageFormatter.FormatException($"Unable to ban user in {MessageFormatter.HtmlFormatMention(room.RoomId)}", e));
-                await _logRoom.SendMessageEventAsync(
-                    MessageFormatter.FormatException($"Unable to ban user in {MessageFormatter.HtmlFormatMention(room.RoomId)}", e));
-                await using var stream = new MemoryStream(e.ToString().AsBytes().ToArray());
-                await _controlRoom.SendFileAsync("error.log.cs", stream);
-                await _logRoom.SendFileAsync("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!");
-    }
-
-    private async Task<StateEventResponse?> CheckMedia(StateEventResponse @event) {
-        var stateList = _policyRoom.GetFullStateAsync();
-        var hashAlgo = SHA3_256.Create();
-
-        var mxcUri = @event.RawContent["url"].GetValue<string>();
-        var resolvedUri = await hsResolver.ResolveMediaUri(mxcUri.Split('/')[2], mxcUri);
-        var uriHash = hashAlgo.ComputeHash(mxcUri.AsBytes().ToArray());
-        byte[]? fileHash = null;
-
-        try {
-            fileHash = await hashAlgo.ComputeHashAsync(await hs._httpClient.GetStreamAsync(resolvedUri));
-        }
-        catch (Exception ex) {
-            await _logRoom.SendMessageEventAsync(
-                MessageFormatter.FormatException($"Error calculating file hash for {mxcUri} via {mxcUri.Split('/')[2]} ({resolvedUri}), retrying via {hs.BaseUrl}...",
-                    ex));
-            try {
-                resolvedUri = await hsResolver.ResolveMediaUri(hs.BaseUrl, mxcUri);
-                fileHash = await hashAlgo.ComputeHashAsync(await hs._httpClient.GetStreamAsync(resolvedUri));
-            }
-            catch (Exception ex2) {
-                await _logRoom.SendMessageEventAsync(
-                    MessageFormatter.FormatException($"Error calculating file hash via {hs.BaseUrl} ({resolvedUri})!", ex2));
-            }
-        }
-
-        logger.LogInformation("Checking media {url} with hash {hash}", resolvedUri, fileHash);
-
-        await foreach (var state in stateList) {
-            if (state.Type != "gay.rory.media_moderator_poc.rule.media" && state.Type != "gay.rory.media_moderator_poc.rule.server") continue;
-            if (!state.RawContent.ContainsKey("entity")) {
-                logger.LogWarning("Rule {rule} has no entity, this event was probably redacted!", state.StateKey);
-                continue;
-            }
-
-            logger.LogInformation("Checking rule {rule}: {data}", state.StateKey, state.TypedContent.ToJson(ignoreNull: true, indent: false));
-            var rule = state.TypedContent as MediaPolicyEventContent;
-            if (state.Type == "gay.rory.media_moderator_poc.rule.server" && rule.ServerEntity is not null) {
-                rule.ServerEntity = rule.ServerEntity.Replace("\\*", ".*").Replace("\\?", ".");
-                var regex = new Regex($"mxc://({rule.ServerEntity})/.*", RegexOptions.Compiled | RegexOptions.IgnoreCase);
-                if (regex.IsMatch(@event.RawContent["url"]!.GetValue<string>())) {
-                    logger.LogInformation("{url} matched rule {rule}", @event.RawContent["url"], rule.ToJson(ignoreNull: true));
-                    return state;
-                }
-            }
-
-            if (rule.Entity is not null && uriHash.SequenceEqual(rule.Entity)) {
-                logger.LogInformation("{url} matched rule {rule} by uri hash", @event.RawContent["url"], rule.ToJson(ignoreNull: true));
-                return state;
-            }
-
-            logger.LogInformation("uri hash {uriHash} did not match rule's {ruleUriHash}", Convert.ToBase64String(uriHash), Convert.ToBase64String(rule.Entity));
-
-            if (rule.FileHash is not null && fileHash is not null && rule.FileHash.SequenceEqual(fileHash)) {
-                logger.LogInformation("{url} matched rule {rule} by file hash", @event.RawContent["url"], rule.ToJson(ignoreNull: true));
-                return state;
-            }
-
-            logger.LogInformation("file hash {fileHash} did not match rule's {ruleFileHash}", Convert.ToBase64String(fileHash), Convert.ToBase64String(rule.FileHash));
-
-            //check pixels every 10% of the way through the image using ImageSharp
-            // var image = Image.Load(await _hs._httpClient.GetStreamAsync(resolvedUri));
-        }
-
-        logger.LogInformation("{url} did not match any rules", @event.RawContent["url"]);
-
-        return null;
-    }
-}
diff --git a/ExampleBots/MediaModeratorPoC/MediaModBotConfiguration.cs b/ExampleBots/MediaModeratorPoC/MediaModBotConfiguration.cs
deleted file mode 100644
index cb5b596..0000000
--- a/ExampleBots/MediaModeratorPoC/MediaModBotConfiguration.cs
+++ /dev/null
@@ -1,10 +0,0 @@
-using Microsoft.Extensions.Configuration;
-
-namespace MediaModeratorPoC;
-
-public class MediaModBotConfiguration {
-    public MediaModBotConfiguration(IConfiguration config) => config.GetRequiredSection("MediaMod").Bind(this);
-
-    public List<string> Admins { get; set; } = new();
-    public bool DemoMode { get; set; } = false;
-}
diff --git a/ExampleBots/MediaModeratorPoC/PolicyEngine.cs b/ExampleBots/MediaModeratorPoC/PolicyEngine.cs
deleted file mode 100644
index 0a0a565..0000000
--- a/ExampleBots/MediaModeratorPoC/PolicyEngine.cs
+++ /dev/null
@@ -1,86 +0,0 @@
-using LibMatrix.EventTypes.Spec;
-using LibMatrix.Helpers;
-using LibMatrix.Homeservers;
-using LibMatrix.RoomTypes;
-using LibMatrix.Services;
-using MediaModeratorPoC.AccountData;
-using MediaModeratorPoC.StateEventTypes;
-using Microsoft.Extensions.Logging;
-
-namespace MediaModeratorPoC;
-
-public class PolicyEngine(AuthenticatedHomeserverGeneric hs, ILogger<MediaModBot> logger, MediaModBotConfiguration configuration,
-    HomeserverResolverService hsResolver) {
-    public List<PolicyList> ActivePolicyLists { get; set; } = new();
-    private GenericRoom? _logRoom;
-    private GenericRoom? _controlRoom;
-
-    public async Task ReloadActivePolicyLists() {
-        // first time init
-        if (_logRoom is null || _controlRoom is null) {
-            var botData = await hs.GetAccountDataAsync<BotData>("gay.rory.modbot_data");
-            _logRoom ??= hs.GetRoom(botData.LogRoom ?? botData.ControlRoom);
-            _controlRoom ??= hs.GetRoom(botData.ControlRoom);
-        }
-
-        await _controlRoom?.SendMessageEventAsync(MessageFormatter.FormatSuccess("Reloading policy lists!"))!;
-        await _logRoom?.SendMessageEventAsync(
-            new RoomMessageEventContent(
-                body: "Reloading policy lists!",
-                messageType: "m.text"))!;
-
-        await _controlRoom?.SendMessageEventAsync(MessageFormatter.FormatSuccess("0/? policy lists loaded"))!;
-
-        var policyLists = new List<PolicyList>();
-        var policyListAccountData = await hs.GetAccountDataAsync<Dictionary<string, PolicyList>>("gay.rory.modbot.policy_lists");
-        foreach (var (roomId, policyList) in policyListAccountData) {
-            _logRoom?.SendMessageEventAsync(
-                new RoomMessageEventContent(
-                    body: $"Loading policy list {MessageFormatter.HtmlFormatMention(roomId)}!",
-                    messageType: "m.text"));
-            var room = hs.GetRoom(roomId);
-
-            policyList.Room = room;
-
-            var stateEvents = room.GetFullStateAsync();
-            await foreach (var stateEvent in stateEvents) {
-                if (stateEvent != null && stateEvent.GetType.IsAssignableTo(typeof(BasePolicy))) {
-                    policyList.Policies.Add(stateEvent);
-                }
-            }
-
-            //html table of policy count by type
-            var policyCount = policyList.Policies.GroupBy(x => x.Type).ToDictionary(x => x.Key, x => x.Count());
-            var policyCountTable = policyCount.Aggregate(
-                "<table><tr><th>Policy Type</th><th>Count</th></tr>",
-                (current, policy) => current + $"<tr><td>{policy.Key}</td><td>{policy.Value}</td></tr>");
-            policyCountTable += "</table>";
-
-            var policyCountTablePlainText = policyCount.Aggregate(
-                "Policy Type       | Count\n",
-                (current, policy) => current + $"{policy.Key,-16} | {policy.Value}\n");
-            await _logRoom?.SendMessageEventAsync(
-                new RoomMessageEventContent() {
-                    MessageType = "org.matrix.custom.html",
-                    Body = $"Policy count for {roomId}:\n{policyCountTablePlainText}",
-                    FormattedBody = $"Policy count for {MessageFormatter.HtmlFormatMention(roomId)}:\n{policyCountTable}",
-                })!;
-
-            await _logRoom?.SendMessageEventAsync(
-                new RoomMessageEventContent(
-                    body: $"Loaded {policyList.Policies.Count} policies for {MessageFormatter.HtmlFormatMention(roomId)}!",
-                    messageType: "m.text"))!;
-
-            policyLists.Add(policyList);
-
-            var progressMsgContent = MessageFormatter.FormatSuccess($"{policyLists.Count}/{policyListAccountData.Count} policy lists loaded");
-            //edit old message
-            progressMsgContent.RelatesTo = new() {
-
-            };
-            _controlRoom?.SendMessageEventAsync(progressMsgContent);
-        }
-
-        ActivePolicyLists = policyLists;
-    }
-}
diff --git a/ExampleBots/MediaModeratorPoC/AccountData/BotData.cs b/ExampleBots/ModerationBot/AccountData/BotData.cs
index 0fee4eb..df86589 100644
--- a/ExampleBots/MediaModeratorPoC/AccountData/BotData.cs
+++ b/ExampleBots/ModerationBot/AccountData/BotData.cs
@@ -1,6 +1,6 @@
 using System.Text.Json.Serialization;
 
-namespace MediaModeratorPoC.AccountData;
+namespace ModerationBot.AccountData;
 
 public class BotData {
     [JsonPropertyName("control_room")]
@@ -8,4 +8,7 @@ public class BotData {
 
     [JsonPropertyName("log_room")]
     public string? LogRoom { get; set; } = "";
-}
+
+    [JsonPropertyName("default_policy_room")]
+    public string? DefaultPolicyRoom { get; set; }
+}
\ No newline at end of file
diff --git a/ExampleBots/MediaModeratorPoC/Commands/BanMediaCommand.cs b/ExampleBots/ModerationBot/Commands/BanMediaCommand.cs
index 5dfa706..21e0a94 100644
--- a/ExampleBots/MediaModeratorPoC/Commands/BanMediaCommand.cs
+++ b/ExampleBots/ModerationBot/Commands/BanMediaCommand.cs
@@ -6,18 +6,19 @@ using LibMatrix.EventTypes.Spec;
 using LibMatrix.Helpers;
 using LibMatrix.Services;
 using LibMatrix.Utilities.Bot.Interfaces;
-using MediaModeratorPoC.AccountData;
-using MediaModeratorPoC.StateEventTypes;
+using ModerationBot.AccountData;
+using ModerationBot.StateEventTypes;
+using ModerationBot.StateEventTypes.Policies.Implementations;
 
-namespace MediaModeratorPoC.Commands;
+namespace ModerationBot.Commands;
 
-public class BanMediaCommand(IServiceProvider services, HomeserverProviderService hsProvider, HomeserverResolverService hsResolver) : ICommand {
+public class BanMediaCommand(IServiceProvider services, HomeserverProviderService hsProvider, HomeserverResolverService hsResolver, PolicyEngine engine) : ICommand {
     public string Name { get; } = "banmedia";
     public string Description { get; } = "Create a policy banning a piece of media, must be used in reply to a message";
 
     public async Task<bool> CanInvoke(CommandContext ctx) {
         //check if user is admin in control room
-        var botData = await ctx.Homeserver.GetAccountDataAsync<BotData>("gay.rory.modbot_data");
+        var botData = await ctx.Homeserver.GetAccountDataAsync<BotData>("gay.rory.moderation_bot_data");
         var controlRoom = ctx.Homeserver.GetRoom(botData.ControlRoom);
         var isAdmin = (await controlRoom.GetPowerLevelsAsync())!.UserHasPermission(ctx.MessageEvent.Sender, "m.room.ban");
         if (!isAdmin) {
@@ -30,8 +31,9 @@ public class BanMediaCommand(IServiceProvider services, HomeserverProviderServic
     }
 
     public async Task Invoke(CommandContext ctx) {
-        var botData = await ctx.Homeserver.GetAccountDataAsync<BotData>("gay.rory.modbot_data");
-        var policyRoom = ctx.Homeserver.GetRoom(botData.PolicyRoom ?? botData.ControlRoom);
+        
+        var botData = await ctx.Homeserver.GetAccountDataAsync<BotData>("gay.rory.moderation_bot_data");
+        var policyRoom = ctx.Homeserver.GetRoom(botData.DefaultPolicyRoom ?? botData.ControlRoom);
         var logRoom = ctx.Homeserver.GetRoom(botData.LogRoom ?? botData.ControlRoom);
 
         //check if reply
@@ -69,7 +71,7 @@ public class BanMediaCommand(IServiceProvider services, HomeserverProviderServic
                 byte[]? fileHash = null;
 
                 try {
-                    fileHash = await hashAlgo.ComputeHashAsync(await ctx.Homeserver._httpClient.GetStreamAsync(resolvedUri));
+                    fileHash = await hashAlgo.ComputeHashAsync(await ctx.Homeserver.ClientHttpClient.GetStreamAsync(resolvedUri));
                 }
                 catch (Exception ex) {
                     await logRoom.SendMessageEventAsync(
@@ -77,7 +79,7 @@ public class BanMediaCommand(IServiceProvider services, HomeserverProviderServic
                             ex));
                     try {
                         resolvedUri = await hsResolver.ResolveMediaUri(ctx.Homeserver.BaseUrl, mxcUri);
-                        fileHash = await hashAlgo.ComputeHashAsync(await ctx.Homeserver._httpClient.GetStreamAsync(resolvedUri));
+                        fileHash = await hashAlgo.ComputeHashAsync(await ctx.Homeserver.ClientHttpClient.GetStreamAsync(resolvedUri));
                     }
                     catch (Exception ex2) {
                         await ctx.Room.SendMessageEventAsync(MessageFormatter.FormatException("Error calculating file hash", ex2));
@@ -86,10 +88,10 @@ public class BanMediaCommand(IServiceProvider services, HomeserverProviderServic
                     }
                 }
 
-                MediaPolicyEventContent policy;
-                await policyRoom.SendStateEventAsync("gay.rory.media_moderator_poc.rule.media", Guid.NewGuid().ToString(), policy = new MediaPolicyEventContent {
-                    // Entity = uriHash,
-                    FileHash = fileHash,
+                MediaPolicyFile policy;
+                await policyRoom.SendStateEventAsync("gay.rory.moderation.rule.media", Guid.NewGuid().ToString(), policy = new MediaPolicyFile {
+                    Entity = Convert.ToBase64String(uriHash),
+                    FileHash = Convert.ToBase64String(fileHash),
                     Reason = string.Join(' ', ctx.Args[1..]),
                     Recommendation = recommendation,
                 });
diff --git a/ExampleBots/MediaModeratorPoC/MediaModeratorPoC.csproj b/ExampleBots/ModerationBot/ModerationBot.csproj
index c3a5d87..5c8f8ff 100644
--- a/ExampleBots/MediaModeratorPoC/MediaModeratorPoC.csproj
+++ b/ExampleBots/ModerationBot/ModerationBot.csproj
@@ -23,7 +23,7 @@
   </ItemGroup>

 

   <ItemGroup>

-    <PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0-preview.7.23375.6" />

+    <PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" />

   </ItemGroup>

   <ItemGroup>

     <Content Include="appsettings*.json">

diff --git a/ExampleBots/MediaModeratorPoC/PolicyList.cs b/ExampleBots/ModerationBot/PolicyList.cs
index 0f49c97..a3052bd 100644
--- a/ExampleBots/MediaModeratorPoC/PolicyList.cs
+++ b/ExampleBots/ModerationBot/PolicyList.cs
@@ -1,9 +1,9 @@
 using System.Text.Json.Serialization;
 using LibMatrix;
 using LibMatrix.RoomTypes;
-using MediaModeratorPoC.StateEventTypes;
+using ModerationBot.StateEventTypes;
 
-namespace MediaModeratorPoC;
+namespace ModerationBot;
 
 public class PolicyList {
     [JsonIgnore]
@@ -13,5 +13,5 @@ public class PolicyList {
     public bool Trusted { get; set; } = false;
 
     [JsonIgnore]
-    public List<StateEvent> Policies { get; set; } = new();
+    public List<StateEventResponse> Policies { get; set; } = new();
 }
diff --git a/ExampleBots/MediaModeratorPoC/Program.cs b/ExampleBots/ModerationBot/Program.cs
index 5b8e734..b41b0be 100644
--- a/ExampleBots/MediaModeratorPoC/Program.cs
+++ b/ExampleBots/ModerationBot/Program.cs
@@ -2,7 +2,7 @@
 

 using LibMatrix.Services;

 using LibMatrix.Utilities.Bot;

-using MediaModeratorPoC;

+using ModerationBot;

 using Microsoft.Extensions.DependencyInjection;

 using Microsoft.Extensions.Hosting;

 

@@ -15,12 +15,14 @@ var host = Host.CreateDefaultBuilder(args).ConfigureServices((_, services) => {
             dataStorageProvider: new FileStorageProvider("bot_data/data/")

         )

     );

-    services.AddSingleton<MediaModBotConfiguration>();

+    services.AddSingleton<ModerationBotConfiguration>();

 

     services.AddRoryLibMatrixServices();

     services.AddBot(withCommands: true);

 

-    services.AddHostedService<MediaModBot>();

+    services.AddSingleton<PolicyEngine>();

+    

+    services.AddHostedService<ModerationBot.ModerationBot>();

 }).UseConsoleLifetime().Build();

 

 await host.RunAsync();

diff --git a/ExampleBots/MediaModeratorPoC/Properties/launchSettings.json b/ExampleBots/ModerationBot/Properties/launchSettings.json
index 997e294..997e294 100644
--- a/ExampleBots/MediaModeratorPoC/Properties/launchSettings.json
+++ b/ExampleBots/ModerationBot/Properties/launchSettings.json
diff --git a/ExampleBots/MediaModeratorPoC/StateEventTypes/BasePolicy.cs b/ExampleBots/ModerationBot/StateEventTypes/Policies/BasePolicy.cs
index 7735314..94b2f63 100644
--- a/ExampleBots/MediaModeratorPoC/StateEventTypes/BasePolicy.cs
+++ b/ExampleBots/ModerationBot/StateEventTypes/Policies/BasePolicy.cs
@@ -3,14 +3,14 @@ using System.Text.Json.Serialization;
 using LibMatrix;
 using LibMatrix.Interfaces;
 
-namespace MediaModeratorPoC.StateEventTypes;
+namespace ModerationBot.StateEventTypes.Policies;
 
 public abstract class BasePolicy : EventContent {
     /// <summary>
-    ///     Entity this policy applies to
+    ///     Entity this policy applies to, null if event was redacted
     /// </summary>
     [JsonPropertyName("entity")]
-    public string Entity { get; set; }
+    public string? Entity { get; set; }
 
     /// <summary>
     ///     Reason this policy exists
@@ -40,4 +40,13 @@ public abstract class BasePolicy : EventContent {
         get => Expiry == null ? null : DateTimeOffset.FromUnixTimeMilliseconds(Expiry.Value).DateTime;
         set => Expiry = value is null ? null : ((DateTimeOffset)value).ToUnixTimeMilliseconds();
     }
+
+#region Internal metadata
+
+    [JsonIgnore]
+    public PolicyList PolicyList { get; set; }
+
+    public StateEventResponse OriginalEvent { get; set; }
+
+#endregion
 }
diff --git a/ExampleBots/MediaModeratorPoC/StateEventTypes/MediaPolicyStateEventData.cs b/ExampleBots/ModerationBot/StateEventTypes/Policies/Implementations/MediaPolicyFile.cs
index 603a858..c5b6ef2 100644
--- a/ExampleBots/MediaModeratorPoC/StateEventTypes/MediaPolicyStateEventData.cs
+++ b/ExampleBots/ModerationBot/StateEventTypes/Policies/Implementations/MediaPolicyFile.cs
@@ -1,17 +1,16 @@
 using System.Text.Json.Serialization;
 using LibMatrix.EventTypes;
 
-namespace MediaModeratorPoC.StateEventTypes;
+namespace ModerationBot.StateEventTypes.Policies.Implementations;
 
 /// <summary>
 ///     File policy event, entity is the MXC URI of the file, hashed with SHA3-256.
 /// </summary>
-[MatrixEvent(EventName = "gay.rory.media_moderator_poc.rule.homeserver")]
-[MatrixEvent(EventName = "gay.rory.media_moderator_poc.rule.media")]
-public class MediaPolicyEventContent : BasePolicy {
+[MatrixEvent(EventName = "gay.rory.moderation.rule.media")]
+public class MediaPolicyFile : BasePolicy {
     /// <summary>
     ///     Hash of the file
     /// </summary>
     [JsonPropertyName("file_hash")]
-    public byte[]? FileHash { get; set; }
+    public string? FileHash { get; set; }
 }
diff --git a/ExampleBots/MediaModeratorPoC/appsettings.Development.json b/ExampleBots/ModerationBot/appsettings.Development.json
index 600efc3..224d0da 100644
--- a/ExampleBots/MediaModeratorPoC/appsettings.Development.json
+++ b/ExampleBots/ModerationBot/appsettings.Development.json
@@ -14,7 +14,7 @@
     // The command prefix
     "Prefix": "?"
   },
-  "MediaMod": {
+  "ModerationBot": {
     // List of people who should be invited to the control room
     "Admins": [
       "@emma:conduit.rory.gay",
diff --git a/ExampleBots/MediaModeratorPoC/appsettings.json b/ExampleBots/ModerationBot/appsettings.json
index 6ba02f3..6ba02f3 100644
--- a/ExampleBots/MediaModeratorPoC/appsettings.json
+++ b/ExampleBots/ModerationBot/appsettings.json