diff options
author | TheArcaneBrony <myrainbowdash949@gmail.com> | 2023-09-15 09:50:45 +0200 |
---|---|---|
committer | TheArcaneBrony <myrainbowdash949@gmail.com> | 2023-09-15 09:50:45 +0200 |
commit | 6bd02248ccfbcb46960a6f39eaad23888d190eb5 (patch) | |
tree | 110578f31b6f9f70a7a1edab32fb3a34d6ad4f1a /ExampleBots/PluralContactBotPoC | |
parent | Media moderator PoC works, abstract command handling to library (diff) | |
download | LibMatrix-6bd02248ccfbcb46960a6f39eaad23888d190eb5.tar.xz |
Some refactoring
Diffstat (limited to '')
10 files changed, 359 insertions, 0 deletions
diff --git a/ExampleBots/PluralContactBotPoC/Bot/AccountData/BotData.cs b/ExampleBots/PluralContactBotPoC/Bot/AccountData/BotData.cs new file mode 100644 index 0000000..9477488 --- /dev/null +++ b/ExampleBots/PluralContactBotPoC/Bot/AccountData/BotData.cs @@ -0,0 +1,16 @@ +using System.Text.Json.Serialization; +using LibMatrix.Helpers; +using LibMatrix.Interfaces; + +namespace PluralContactBotPoC.Bot.AccountData; +[MatrixEvent(EventName = "gay.rory.plural_contact_bot.bot_config")] +public class BotData : EventContent { + [JsonPropertyName("control_room")] + public string ControlRoom { get; set; } = ""; + + [JsonPropertyName("log_room")] + public string? LogRoom { get; set; } = ""; + + [JsonPropertyName("policy_room")] + public string? PolicyRoom { get; set; } = ""; +} diff --git a/ExampleBots/PluralContactBotPoC/Bot/AccountData/SystemData.cs b/ExampleBots/PluralContactBotPoC/Bot/AccountData/SystemData.cs new file mode 100644 index 0000000..5edfc0e --- /dev/null +++ b/ExampleBots/PluralContactBotPoC/Bot/AccountData/SystemData.cs @@ -0,0 +1,15 @@ +using System.Text.Json.Serialization; +using LibMatrix.Helpers; +using LibMatrix.Interfaces; + +namespace PluralContactBotPoC.Bot.StateEventTypes; + +[MatrixEvent(EventName = "gay.rory.plural_contact_bot.system_data")] +public class SystemData : EventContent { + [JsonPropertyName("control_room")] + public string ControlRoom { get; set; } = null!; + [JsonPropertyName("system_members")] + public List<string> Members { get; set; } = new(); + [JsonPropertyName("dm_space")] + public string? DmSpace { get; set; } +} diff --git a/ExampleBots/PluralContactBotPoC/Bot/Commands/CreateSystemCommand.cs b/ExampleBots/PluralContactBotPoC/Bot/Commands/CreateSystemCommand.cs new file mode 100644 index 0000000..5da4f5e --- /dev/null +++ b/ExampleBots/PluralContactBotPoC/Bot/Commands/CreateSystemCommand.cs @@ -0,0 +1,57 @@ +using LibMatrix; +using LibMatrix.Helpers; +using LibMatrix.Services; +using LibMatrix.StateEventTypes.Spec; +using MediaModeratorPoC.Bot.Interfaces; +using PluralContactBotPoC.Bot.AccountData; +using PluralContactBotPoC.Bot.StateEventTypes; + +namespace PluralContactBotPoC.Bot.Commands; + +public class CreateSystemCommand(IServiceProvider services, HomeserverProviderService hsProvider, HomeserverResolverService hsResolver) : ICommand { + public string Name { get; } = "createsystem"; + public string Description { get; } = "Create a new system"; + + public async Task<bool> CanInvoke(CommandContext ctx) { + return true; + } + + public async Task Invoke(CommandContext ctx) { + if (ctx.Args.Length != 1) { + await ctx.Reply("m.notice", MessageFormatter.FormatError("Only one argument is allowed: system name!")); + return; + } + + var sysName = ctx.Args[0]; + try { + try { + await ctx.Homeserver.GetAccountData<BotData>("gay.rory.plural_contact_bot.system_data"); + await ctx.Reply("m.notice", MessageFormatter.FormatError($"System {sysName} already exists!")); + } + catch (MatrixException e) { + if (e is { ErrorCode: "M_NOT_FOUND" }) { + var sysData = new SystemData() { + ControlRoom = ctx.Room.RoomId, + Members = new(), + }; + + var state = ctx.Room.GetMembersAsync(); + await foreach (var member in state) { + sysData.Members.Add(member.UserId); + } + + await ctx.Room.SendStateEventAsync("m.room.name", new RoomNameEventContent() { + Name = sysName + " control room" + }); + + return; + } + + throw; + } + } + catch (Exception e) { + await ctx.Reply("m.notice", MessageFormatter.FormatException("Something went wrong!", e)); + } + } +} 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<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!"); + } +} diff --git a/ExampleBots/PluralContactBotPoC/Bot/PluralContactBotConfiguration.cs b/ExampleBots/PluralContactBotPoC/Bot/PluralContactBotConfiguration.cs new file mode 100644 index 0000000..f5c21af --- /dev/null +++ b/ExampleBots/PluralContactBotPoC/Bot/PluralContactBotConfiguration.cs @@ -0,0 +1,9 @@ +using Microsoft.Extensions.Configuration; + +namespace PluralContactBotPoC.Bot; + +public class PluralContactBotConfiguration { + public PluralContactBotConfiguration(IConfiguration config) => config.GetRequiredSection("PluralContactBot").Bind(this); + + // public string +} diff --git a/ExampleBots/PluralContactBotPoC/PluralContactBotPoC.csproj b/ExampleBots/PluralContactBotPoC/PluralContactBotPoC.csproj new file mode 100644 index 0000000..cd549f9 --- /dev/null +++ b/ExampleBots/PluralContactBotPoC/PluralContactBotPoC.csproj @@ -0,0 +1,36 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net8.0</TargetFramework> + <LangVersion>preview</LangVersion> + <ImplicitUsings>enable</ImplicitUsings> + <Nullable>enable</Nullable> + <PublishAot>false</PublishAot> + <InvariantGlobalization>true</InvariantGlobalization> + <!-- <PublishTrimmed>true</PublishTrimmed>--> + <!-- <PublishReadyToRun>true</PublishReadyToRun>--> + <!-- <PublishSingleFile>true</PublishSingleFile>--> + <!-- <PublishReadyToRunShowWarnings>true</PublishReadyToRunShowWarnings>--> + <!-- <PublishTrimmedShowLinkerSizeComparison>true</PublishTrimmedShowLinkerSizeComparison>--> + <!-- <PublishTrimmedShowLinkerSizeComparisonWarnings>true</PublishTrimmedShowLinkerSizeComparisonWarnings>--> + </PropertyGroup> + + <ItemGroup> + <!-- <ProjectReference Include="..\..\..\ArcaneLibs\ArcaneLibs\ArcaneLibs.csproj" />--> + <ProjectReference Include="..\..\LibMatrix\LibMatrix.csproj" /> + <ProjectReference Include="..\..\Utilities\LibMatrix.Utilities.Bot\LibMatrix.Utilities.Bot.csproj" /> + </ItemGroup> + + <ItemGroup> + <PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0-preview.7.23375.6" /> + </ItemGroup> + <ItemGroup> + <Content Include="appsettings*.json"> + <CopyToOutputDirectory>Always</CopyToOutputDirectory> + </Content> + </ItemGroup> + <ItemGroup> + <Folder Include="Bot\StateEventTypes\" /> + </ItemGroup> +</Project> diff --git a/ExampleBots/PluralContactBotPoC/Program.cs b/ExampleBots/PluralContactBotPoC/Program.cs new file mode 100644 index 0000000..b2e041e --- /dev/null +++ b/ExampleBots/PluralContactBotPoC/Program.cs @@ -0,0 +1,75 @@ +// See https://aka.ms/new-console-template for more information + +using System.Text.Json; +using System.Text.Json.Serialization; +using ArcaneLibs.Extensions; +using LibMatrix.Services; +using LibMatrix.Utilities.Bot; +using MediaModeratorPoC.Bot; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using PluralContactBotPoC; +using PluralContactBotPoC.Bot; + +Console.WriteLine("Hello, World!"); + +var randomBytes = new byte[32]; +Random.Shared.NextBytes(randomBytes); +var ASToken = Convert.ToBase64String(randomBytes); +Random.Shared.NextBytes(randomBytes); +var HSToken = Convert.ToBase64String(randomBytes); + +var asConfig = new AppServiceConfiguration() { + Id = "plural_contact_bot", + Url = null, + SenderLocalpart = "plural_contact_bot", + AppserviceToken = ASToken, + HomeserverToken = HSToken, + Namespaces = new() { + Users = new() { + new() { + Exclusive = false, + Regex = "@.*" + } + }, + Aliases = new() { + new() { + Exclusive = false, + Regex = "#.*" + } + }, + Rooms = new() { + new() { + Exclusive = false, + Regex = "!.*" + } + } + }, + RateLimited = false, + Protocols = new List<string>() { "matrix" } +}; + +if(File.Exists("appservice.json")) + asConfig = JsonSerializer.Deserialize<AppServiceConfiguration>(File.ReadAllText("appservice.json"))!; + +File.WriteAllText("appservice.yaml", asConfig.ToYaml()); +File.WriteAllText("appservice.json", asConfig.ToJson()); +Environment.Exit(0); + +var host = Host.CreateDefaultBuilder(args).ConfigureServices((_, services) => { + services.AddScoped<TieredStorageService>(x => + new TieredStorageService( + cacheStorageProvider: new FileStorageProvider("bot_data/cache/"), + dataStorageProvider: new FileStorageProvider("bot_data/data/") + ) + ); + services.AddSingleton<PluralContactBotConfiguration>(); + services.AddSingleton<AppServiceConfiguration>(); + + services.AddRoryLibMatrixServices(); + services.AddBot(withCommands: true); + + services.AddHostedService<PluralContactBot>(); +}).UseConsoleLifetime().Build(); + +await host.RunAsync(); diff --git a/ExampleBots/PluralContactBotPoC/Properties/launchSettings.json b/ExampleBots/PluralContactBotPoC/Properties/launchSettings.json new file mode 100644 index 0000000..997e294 --- /dev/null +++ b/ExampleBots/PluralContactBotPoC/Properties/launchSettings.json @@ -0,0 +1,26 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "profiles": { + "Default": { + "commandName": "Project", + "dotnetRunMessages": true, + "environmentVariables": { + + } + }, + "Development": { + "commandName": "Project", + "dotnetRunMessages": true, + "environmentVariables": { + "DOTNET_ENVIRONMENT": "Development" + } + }, + "Local config": { + "commandName": "Project", + "dotnetRunMessages": true, + "environmentVariables": { + "DOTNET_ENVIRONMENT": "Local" + } + } + } +} diff --git a/ExampleBots/PluralContactBotPoC/appsettings.Development.json b/ExampleBots/PluralContactBotPoC/appsettings.Development.json new file mode 100644 index 0000000..93dc0e6 --- /dev/null +++ b/ExampleBots/PluralContactBotPoC/appsettings.Development.json @@ -0,0 +1,17 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Debug", + "System": "Information", + "Microsoft": "Information" + } + }, + "LibMatrixBot": { + // The homeserver to connect to + "Homeserver": "rory.gay", + // The access token to use + "AccessToken": "syt_xxxxxxxxxxxxxxxxx", + // The command prefix + "Prefix": "?" + } +} diff --git a/ExampleBots/PluralContactBotPoC/appsettings.json b/ExampleBots/PluralContactBotPoC/appsettings.json new file mode 100644 index 0000000..6ba02f3 --- /dev/null +++ b/ExampleBots/PluralContactBotPoC/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Debug", + "System": "Information", + "Microsoft": "Information" + } + } +} |