From 5e13af7480fb40ff26a3e266217c0db702ee4b2f Mon Sep 17 00:00:00 2001 From: Rory& Date: Thu, 15 May 2025 23:09:41 +0200 Subject: Some various improvements, redo configuration, clean up example config --- .../.idea/inspectionProfiles/Project_Default.xml | 8 ++++ LibMatrix | 2 +- MatrixAntiDmSpam.Core/AntiDmSpamConfiguration.cs | 2 +- MatrixAntiDmSpam.Core/PolicyExecutor.cs | 11 +++-- MatrixAntiDmSpam.Core/PolicyListFetcher.cs | 15 ++---- MatrixAntiDmSpam.sln.DotSettings | 2 + MatrixAntiDmSpam.sln.DotSettings.user | 1 + MatrixAntiDmSpam/Program.cs | 4 +- MatrixAntiDmSpam/appsettings.Development.json | 53 +++++++++++++--------- 9 files changed, 59 insertions(+), 39 deletions(-) create mode 100644 .idea/.idea.MatrixAntiDmSpam/.idea/inspectionProfiles/Project_Default.xml create mode 100644 MatrixAntiDmSpam.sln.DotSettings diff --git a/.idea/.idea.MatrixAntiDmSpam/.idea/inspectionProfiles/Project_Default.xml b/.idea/.idea.MatrixAntiDmSpam/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000..030f244 --- /dev/null +++ b/.idea/.idea.MatrixAntiDmSpam/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,8 @@ + + + + \ No newline at end of file diff --git a/LibMatrix b/LibMatrix index 8ae6fac..e16e9f3 160000 --- a/LibMatrix +++ b/LibMatrix @@ -1 +1 @@ -Subproject commit 8ae6fac9c2dcfdf792df0f208047eea0d524edc2 +Subproject commit e16e9f3093fab575f5f9323248e7b19fa6d54566 diff --git a/MatrixAntiDmSpam.Core/AntiDmSpamConfiguration.cs b/MatrixAntiDmSpam.Core/AntiDmSpamConfiguration.cs index 1ce901e..ff6814f 100644 --- a/MatrixAntiDmSpam.Core/AntiDmSpamConfiguration.cs +++ b/MatrixAntiDmSpam.Core/AntiDmSpamConfiguration.cs @@ -8,7 +8,7 @@ public class AntiDmSpamConfiguration { public bool LogInviteDataAsFile { get; set; } = true; public bool IgnoreBannedUsers { get; set; } = false; public bool ReportBlockedInvites { get; set; } = false; - public TimeSpan MinimumSyncTime { get; set; } = TimeSpan.Zero; + public TimeSpan? MinimumSyncTime { get; set; } public required List PolicyLists { get; set; } diff --git a/MatrixAntiDmSpam.Core/PolicyExecutor.cs b/MatrixAntiDmSpam.Core/PolicyExecutor.cs index 96ec344..9d6a843 100644 --- a/MatrixAntiDmSpam.Core/PolicyExecutor.cs +++ b/MatrixAntiDmSpam.Core/PolicyExecutor.cs @@ -161,6 +161,8 @@ public class PolicyExecutor( #endregion #region Feature: Report blocked invites + + #endregion @@ -213,17 +215,18 @@ public class PolicyExecutor( } if (!policyMatches) return null; - logger.LogWarning("[{}] Rejecting invite to {}, matching {} {}", homeserver.WhoAmI.UserId, invite.RoomId, policy.GetType().GetFriendlyName(), - policy.ToJson(ignoreNull: true)); + var policyRoom = config.PolicyLists.First(x=>x.RoomId == policyEvent.RoomId); + logger.LogWarning("[{}] Rejecting invite to {}, matching {} in {}: {}", homeserver.WhoAmI.UserId, invite.RoomId, policy.GetType().GetFriendlyName(), + policyRoom.Name, policy.ToJson(ignoreNull: true)); return Task.Run(async () => { if (_logRoom is not null) { - string roomName = await invite.TryGetRoomNameAsync(); + var roomName = await invite.TryGetRoomNameAsync(); await roomInviteHandler.RejectInvite(invite, new MessageBuilder() .WithColoredBody("#FF0000", cb => cb.WithBody("Rejecting invite to ").WithMention(invite.RoomId, roomName) - .WithBody($", matching {policy.GetType().GetFriendlyName().ToLowerInvariant()}.") + .WithBody($", matching {policy.GetType().GetFriendlyName().ToLowerInvariant()} in {policyRoom.Name}.") .WithNewline()) .WithCollapsibleSection("Policy JSON", cb => cb.WithCodeBlock(policy.ToJson(ignoreNull: true), "json")) ); diff --git a/MatrixAntiDmSpam.Core/PolicyListFetcher.cs b/MatrixAntiDmSpam.Core/PolicyListFetcher.cs index 31b8835..51db44f 100644 --- a/MatrixAntiDmSpam.Core/PolicyListFetcher.cs +++ b/MatrixAntiDmSpam.Core/PolicyListFetcher.cs @@ -2,25 +2,17 @@ using LibMatrix.Filters; using LibMatrix.Helpers; using LibMatrix.Homeservers; using LibMatrix.RoomTypes; +using LibMatrix.Utilities.Bot; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace MatrixAntiDmSpam.Core; -public class PolicyListFetcher(ILogger logger, AntiDmSpamConfiguration config, AuthenticatedHomeserverGeneric homeserver, PolicyStore policyStore) +public class PolicyListFetcher(ILogger logger, AntiDmSpamConfiguration config, AuthenticatedHomeserverGeneric homeserver, PolicyStore policyStore, LibMatrixBotConfiguration botConfig) : IHostedService { private CancellationTokenSource _cts = new(); public async Task StartAsync(CancellationToken cancellationToken) { - // _ = Enumerable.Range(0, 10_000_000).Select(x => { - // policyStore.AllPolicies.Add(Guid.NewGuid().ToString(), new UserPolicyRuleEventContent() { - // Entity = Guid.NewGuid().ToString() + x, - // Reason = "meow " + x, - // Recommendation = "m.ban" - // }); - // return 0; - // }).ToList(); - logger.LogInformation("Starting policy list fetcher"); await EnsurePolicyListsJoined(); _ = SyncPolicyLists().ContinueWith(x => { @@ -49,7 +41,8 @@ public class PolicyListFetcher(ILogger logger, AntiDmSpamConf private async Task SyncPolicyLists() { var syncHelper = new SyncHelper(homeserver, logger) { Timeout = 30_000, - MinimumDelay = config.MinimumSyncTime, + SetPresence = botConfig.Presence, + MinimumDelay = config.MinimumSyncTime ?? TimeSpan.Zero, FilterId = (await homeserver.UploadFilterAsync(new SyncFilter { AccountData = SyncFilter.EventFilter.Empty, Presence = SyncFilter.EventFilter.Empty, diff --git a/MatrixAntiDmSpam.sln.DotSettings b/MatrixAntiDmSpam.sln.DotSettings new file mode 100644 index 0000000..b57955d --- /dev/null +++ b/MatrixAntiDmSpam.sln.DotSettings @@ -0,0 +1,2 @@ + + True \ No newline at end of file diff --git a/MatrixAntiDmSpam.sln.DotSettings.user b/MatrixAntiDmSpam.sln.DotSettings.user index 159add8..4cc1d7d 100644 --- a/MatrixAntiDmSpam.sln.DotSettings.user +++ b/MatrixAntiDmSpam.sln.DotSettings.user @@ -1,5 +1,6 @@  ForceIncluded + ForceIncluded ForceIncluded ForceIncluded ForceIncluded diff --git a/MatrixAntiDmSpam/Program.cs b/MatrixAntiDmSpam/Program.cs index 935e23f..5da7184 100644 --- a/MatrixAntiDmSpam/Program.cs +++ b/MatrixAntiDmSpam/Program.cs @@ -1,4 +1,3 @@ -using LibMatrix.Extensions; using LibMatrix.Services; using LibMatrix.Utilities.Bot; using MatrixAntiDmSpam.Core; @@ -15,6 +14,9 @@ builder.Services.AddHostedService(); builder.Services.AddSingleton(); +builder.Configuration["LibMatrixBot:InviteListener:SyncConfiguration:MinimumSyncTime"] ??= builder.Configuration["AntiDmSpam:MinimumSyncTime"]; + + // MatrixHttpClient.LogRequests = false; var host = builder.Build(); diff --git a/MatrixAntiDmSpam/appsettings.Development.json b/MatrixAntiDmSpam/appsettings.Development.json index 00d6dd4..8c69222 100644 --- a/MatrixAntiDmSpam/appsettings.Development.json +++ b/MatrixAntiDmSpam/appsettings.Development.json @@ -7,43 +7,54 @@ } }, "LibMatrixBot": { - // Homeserver to connect to. + // Homeserver to connect to, or rather, where your account is hosted. // Note: Homeserver resolution is applied here, but a direct base URL can be used. "Homeserver": "rory.gay", // Absolute path to the file containing the access token + // Hint: log into https://riot.im/app/, go to Settings > Help & About > Advanced > Access Token, + // write this into a file, and then clear site data for riot.im so you don't accidentally log it out. + // Also, it's recommended to rename the session in your devices list "AccessTokenPath": "/home/Rory/matrix_access_token", - "InviteHandler": { - "SyncConfiguration": { - // How long to wait until the sync request times out - // "Timeout": 300000, - // Minimum sync interval, useful if you want to have less traffic than a normal client. - "MinimumSyncTime": "00:00:10.000", - - // What presence value to set - // Defaults to "online" if null or not set - "Presence": "offline", - - // Filter to apply to the sync request. Useful if you want custom data to be sent. - // "Filter": { }, - - // Whether to initial sync on startup - very useful in development, or just to be sure. + "InviteListener": { + "SyncConfiguration": { + // Whether to initial sync on startup + // Leaving this enabled is the same as doing a "Clear Cache & Reload" every time you restart the bot. + // This causes a slower startup, but increases reliability by a fairly large margin. "InitialSyncOnStartup": true } } }, "AntiDmSpam": { - // Whether invites should be logged to a room. - "LogRoom": "!GrLSwdAkdrvfMrRYKR:rory.gay", - "LogInviteDataAsFile": true, - // Whether to report users and rooms when an invite is blocked. + // Whether to log received/blocked invites into a room. + // This MUST be `null`, or a valid room ID (`!abcdefgh:yourserver.org`), not an alias (`#alias:yourserver.org`). + // WARNING: These messages, nor the optional files, are encrypted, even if the room has encryption enabled! + "LogRoom": null, + "LogInviteDataAsFile": true, // Also send the raw data as a file for manual reporting + + // Whether to report users and rooms when an invitation is blocked. + // Some homeserver admins may not like this, and consider it spam, hence the option to opt out :) "ReportBlockedInvites": true, + + // Automatically add banned users to your ignore list, also automatically removed automatic ignores when the policy is revoked. + // This is useful if you want to hide invites and messages from them. // WARNING: If you're a room moderator, this will cause your client to not receive events from ignored users! "IgnoreBannedUsers": true, - // Policy lists to follow + + // Minimum sync interval, useful if you want to have less traffic than a normal client. + // WARNING: this will also cause the bot to be slower to respond to invites/policies. + // This is considered to be a worthy tradeoff for both reduced energy usage, and reduced server load. + // ***ABSOLUTE*** minimum recommended value: 00:00:01.000 - but please don't use this unless you have a good reason, + // don't contribute to homeservers slowing down for everyone else. + "MinimumSyncTime": "00:00:05.000", + + // Policy lists to follow - must contain at least one list! + // What is a policy list? See https://matrix-community-help.codestorm.net/automated-tools.html#3 + // Hint: you might also see them referred to as banlists "PolicyLists": [ { + // Community Moderation Effort is a widely used policy list, and recommended as a base set for usage with MADS. "Name": "Community Moderation Effort", "RoomId": "!fTjMjIzNKEsFlUIiru:neko.dev", "Vias": [ "rory.gay" ] -- cgit 1.5.1