diff --git a/Utilities/LibMatrix.DevTestBot/Bot/Commands/CmdCommand.cs b/Utilities/LibMatrix.DevTestBot/Bot/Commands/CmdCommand.cs
index 89a9033..874d195 100644
--- a/Utilities/LibMatrix.DevTestBot/Bot/Commands/CmdCommand.cs
+++ b/Utilities/LibMatrix.DevTestBot/Bot/Commands/CmdCommand.cs
@@ -1,11 +1,13 @@
using ArcaneLibs.StringNormalisation;
using LibMatrix.EventTypes.Spec;
-using LibMatrix.ExampleBot.Bot.Interfaces;
+using LibMatrix.Utilities.Bot.Interfaces;
namespace LibMatrix.ExampleBot.Bot.Commands;
public class CmdCommand : ICommand {
public string Name => "cmd";
+ public string[]? Aliases => [];
+ public bool Unlisted => false;
public string Description => "Runs a command on the host system";
public Task<bool> CanInvoke(CommandContext ctx) => Task.FromResult(ctx.MessageEvent.Sender.EndsWith(":rory.gay") || ctx.MessageEvent.Sender.EndsWith(":conduit.rory.gay"));
diff --git a/Utilities/LibMatrix.DevTestBot/Bot/Commands/DbgAniRainbowTest.cs b/Utilities/LibMatrix.DevTestBot/Bot/Commands/DbgAniRainbowTest.cs
index f75c863..0dde297 100644
--- a/Utilities/LibMatrix.DevTestBot/Bot/Commands/DbgAniRainbowTest.cs
+++ b/Utilities/LibMatrix.DevTestBot/Bot/Commands/DbgAniRainbowTest.cs
@@ -1,16 +1,20 @@
using System.Diagnostics;
using LibMatrix.EventTypes.Spec;
-using LibMatrix.ExampleBot.Bot.Interfaces;
using LibMatrix.Helpers;
-using LibMatrix.RoomTypes;
using LibMatrix.Services;
+using LibMatrix.Utilities.Bot.Interfaces;
namespace ModerationBot.Commands;
public class DbgAniRainbowTest(IServiceProvider services, HomeserverProviderService hsProvider, HomeserverResolverService hsResolver) : ICommand {
public string Name { get; } = "ani-rainbow";
+
+ public string[]? Aliases => [];
+ public bool Unlisted => false;
+
public string Description { get; } = "[Debug] animated rainbow :)";
+
public async Task<bool> CanInvoke(CommandContext ctx) => ctx.Room.RoomId == "!hLEefBaYvNfJwcTjmt:rory.gay";
public async Task Invoke(CommandContext ctx) {
diff --git a/Utilities/LibMatrix.DevTestBot/Bot/Commands/HelpCommand.cs b/Utilities/LibMatrix.DevTestBot/Bot/Commands/HelpCommand.cs
index 7ecbeb3..33bbc5a 100644
--- a/Utilities/LibMatrix.DevTestBot/Bot/Commands/HelpCommand.cs
+++ b/Utilities/LibMatrix.DevTestBot/Bot/Commands/HelpCommand.cs
@@ -1,12 +1,14 @@
using System.Text;
using LibMatrix.EventTypes.Spec;
-using LibMatrix.ExampleBot.Bot.Interfaces;
+using LibMatrix.Utilities.Bot.Interfaces;
using Microsoft.Extensions.DependencyInjection;
namespace LibMatrix.ExampleBot.Bot.Commands;
public class HelpCommand(IServiceProvider services) : ICommand {
public string Name { get; } = "help";
+ public string[]? Aliases => [];
+ public bool Unlisted => false;
public string Description { get; } = "Displays this help message";
public async Task Invoke(CommandContext ctx) {
diff --git a/Utilities/LibMatrix.DevTestBot/Bot/Commands/PingCommand.cs b/Utilities/LibMatrix.DevTestBot/Bot/Commands/PingCommand.cs
index 85c86a3..350d89e 100644
--- a/Utilities/LibMatrix.DevTestBot/Bot/Commands/PingCommand.cs
+++ b/Utilities/LibMatrix.DevTestBot/Bot/Commands/PingCommand.cs
@@ -1,11 +1,24 @@
using LibMatrix.EventTypes.Spec;
-using LibMatrix.ExampleBot.Bot.Interfaces;
+using LibMatrix.Utilities.Bot.Interfaces;
namespace LibMatrix.ExampleBot.Bot.Commands;
public class PingCommand : ICommand {
- public string Name { get; } = "ping";
+ public string Name { get; } = "do-ping";
+ public string[]? Aliases => [];
+ public bool Unlisted => false;
public string Description { get; } = "Pong!";
- public async Task Invoke(CommandContext ctx) => await ctx.Room.SendMessageEventAsync(new RoomMessageEventContent(body: "pong!"));
+ // public async Task Invoke(CommandContext ctx) => await ctx.Room.SendMessageEventAsync(new RoomMessageEventContent(body: "pong!"));
+ public async Task Invoke(CommandContext ctx) {
+ // await ctx.Room.SendMessageEventAsync(new RoomMessageEventContent(body: "pong!"));
+ var count = ctx.Args.Length > 0 ? int.Parse(ctx.Args[0]) : 1;
+ var tasks = Enumerable.Range(0, count).Select(async i => {
+ await ctx.Room.SendMessageEventAsync(new RoomMessageEventContent(body: $"!ping {i}", messageType: "m.text"));
+ await Task.Delay(1000);
+ }).ToList();
+ await Task.WhenAll(tasks);
+
+ await ctx.Room.SendMessageEventAsync(new RoomMessageEventContent(body: "Pong!"));
+ }
}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.DevTestBot/Bot/DevTestBot.cs b/Utilities/LibMatrix.DevTestBot/Bot/DevTestBot.cs
index fa80bfd..3bb0c25 100644
--- a/Utilities/LibMatrix.DevTestBot/Bot/DevTestBot.cs
+++ b/Utilities/LibMatrix.DevTestBot/Bot/DevTestBot.cs
@@ -1,8 +1,7 @@
using System.Diagnostics.CodeAnalysis;
using ArcaneLibs.Extensions;
using LibMatrix.EventTypes.Spec;
-using LibMatrix.EventTypes.Spec.State;
-using LibMatrix.ExampleBot.Bot.Interfaces;
+using LibMatrix.EventTypes.Spec.State.RoomInfo;
using LibMatrix.Helpers;
using LibMatrix.Homeservers;
using LibMatrix.Services;
@@ -16,17 +15,13 @@ public class DevTestBot : IHostedService {
private readonly HomeserverProviderService _homeserverProviderService;
private readonly ILogger<DevTestBot> _logger;
private readonly DevTestBotConfiguration _configuration;
- private readonly IEnumerable<ICommand> _commands;
public DevTestBot(HomeserverProviderService homeserverProviderService, ILogger<DevTestBot> logger,
- DevTestBotConfiguration configuration, IServiceProvider services) {
+ DevTestBotConfiguration configuration) {
logger.LogInformation("{} instantiated!", GetType().Name);
_homeserverProviderService = homeserverProviderService;
_logger = logger;
_configuration = configuration;
- _logger.LogInformation("Getting commands...");
- _commands = services.GetServices<ICommand>();
- _logger.LogInformation("Got {} commands!", _commands.Count());
}
/// <summary>Triggered when the application host is ready to start the service.</summary>
@@ -59,48 +54,6 @@ public class DevTestBot : IHostedService {
// _logger.LogInformation($"Got room state for {room.RoomId}!");
// }
- 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 {args.Key} by {inviteEvent.Sender} with reason: {(inviteEvent.TypedContent as RoomMemberEventContent).Reason}");
- if (inviteEvent.Sender.EndsWith(":rory.gay") || inviteEvent.Sender == "@mxidupwitch:the-apothecary.club")
- 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("I was unable to join the room: " + e);
- }
- });
- syncHelper.TimelineEventHandlers.Add(async @event => {
- _logger.LogInformation(
- "Got timeline event in {}: {}", @event.RoomId, @event.ToJson(false, true));
-
- var room = hs.GetRoom(@event.RoomId);
- // _logger.LogInformation(eventResponse.ToJson(indent: false));
- if (@event is { Type: "m.room.message", TypedContent: RoomMessageEventContent message })
- if (message is { MessageType: "m.text" } && message.Body.StartsWith(_configuration.Prefix)) {
- var command = _commands.FirstOrDefault(x => x.Name == message.Body.Split(' ')[0][_configuration.Prefix.Length..]);
- if (command == null) {
- await room.SendMessageEventAsync(
- new RoomMessageEventContent("m.text", "Command not found!"));
- return;
- }
-
- var ctx = new CommandContext {
- Room = room,
- MessageEvent = @event
- };
- if (await command.CanInvoke(ctx))
- await command.Invoke(ctx);
- else
- await room.SendMessageEventAsync(
- new RoomMessageEventContent("m.text", "You do not have permission to run this command!"));
- }
- });
await syncHelper.RunSyncLoopAsync(cancellationToken: cancellationToken);
}
diff --git a/Utilities/LibMatrix.DevTestBot/Bot/Interfaces/CommandContext.cs b/Utilities/LibMatrix.DevTestBot/Bot/Interfaces/CommandContext.cs
deleted file mode 100644
index 90a95e4..0000000
--- a/Utilities/LibMatrix.DevTestBot/Bot/Interfaces/CommandContext.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-using LibMatrix.EventTypes.Spec;
-using LibMatrix.RoomTypes;
-
-namespace LibMatrix.ExampleBot.Bot.Interfaces;
-
-public class CommandContext {
- public GenericRoom Room { get; set; }
- public StateEventResponse MessageEvent { get; set; }
- public string CommandName => (MessageEvent.TypedContent as RoomMessageEventContent).Body.Split(' ')[0][1..];
- public string[] Args => (MessageEvent.TypedContent as RoomMessageEventContent).Body.Split(' ')[1..];
-}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.DevTestBot/Bot/Interfaces/ICommand.cs b/Utilities/LibMatrix.DevTestBot/Bot/Interfaces/ICommand.cs
deleted file mode 100644
index a6dc8da..0000000
--- a/Utilities/LibMatrix.DevTestBot/Bot/Interfaces/ICommand.cs
+++ /dev/null
@@ -1,10 +0,0 @@
-namespace LibMatrix.ExampleBot.Bot.Interfaces;
-
-public interface ICommand {
- public string Name { get; }
- public string Description { get; }
-
- public Task<bool> CanInvoke(CommandContext ctx) => Task.FromResult(true);
-
- public Task Invoke(CommandContext ctx);
-}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.DevTestBot/Bot/PingTestBot.cs b/Utilities/LibMatrix.DevTestBot/Bot/PingTestBot.cs
new file mode 100644
index 0000000..e992e3c
--- /dev/null
+++ b/Utilities/LibMatrix.DevTestBot/Bot/PingTestBot.cs
@@ -0,0 +1,125 @@
+using System.Diagnostics.CodeAnalysis;
+using System.Windows.Input;
+using ArcaneLibs.Extensions;
+using LibMatrix.EventTypes.Spec;
+using LibMatrix.Filters;
+using LibMatrix.Helpers;
+using LibMatrix.Homeservers;
+using LibMatrix.Services;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
+
+namespace LibMatrix.ExampleBot.Bot;
+
+public class PingTestBot : IHostedService {
+ private readonly HomeserverProviderService _homeserverProviderService;
+ private readonly ILogger<DevTestBot> _logger;
+ private readonly DevTestBotConfiguration _configuration;
+ private readonly IEnumerable<ICommand> _commands;
+
+ public PingTestBot(HomeserverProviderService homeserverProviderService, ILogger<DevTestBot> logger,
+ DevTestBotConfiguration configuration, IServiceProvider services) {
+ logger.LogInformation("{} instantiated!", GetType().Name);
+ _homeserverProviderService = homeserverProviderService;
+ _logger = logger;
+ _configuration = configuration;
+ _logger.LogInformation("Getting commands...");
+ _commands = services.GetServices<ICommand>();
+ _logger.LogInformation("Got {} commands!", _commands.Count());
+ }
+
+ /// <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>
+ [SuppressMessage("ReSharper", "FunctionNeverReturns")]
+ public async Task StartAsync(CancellationToken cancellationToken) {
+ // Directory.GetFiles("bot_data/cache").ToList().ForEach(File.Delete);
+ AuthenticatedHomeserverGeneric hs;
+ try {
+ hs = await _homeserverProviderService.GetAuthenticatedWithToken(_configuration.Homeserver,
+ _configuration.AccessToken);
+ }
+ catch (Exception e) {
+ _logger.LogError("{}", e.Message);
+ throw;
+ }
+
+ var msg = new MessageBuilder().WithRainbowString("Meanwhile, I'm sitting here, still struggling with trying to rainbow. ^^'").Build();
+
+ var syncHelper = new SyncHelper(hs);
+ syncHelper.Filter = new SyncFilter {
+ Room = new SyncFilter.RoomFilter {
+ Timeline = new SyncFilter.RoomFilter.StateFilter() {
+ Limit = 1,
+ Senders = ["@me"]
+ },
+ Rooms = ["!ping-v11:maunium.net"],
+ AccountData = new(types: []),
+ IncludeLeave = false
+ }
+ };
+
+ // await hs.GetRoom("!VJwxdebqoQlhGSEncc:codestorm.net").JoinAsync();
+
+ // foreach (var room in await hs.GetJoinedRooms()) {
+ // if(room.RoomId is "!OGEhHVWSdvArJzumhm:matrix.org") continue;
+ // foreach (var stateEvent in await room.GetStateAsync<List<StateEvent>>("")) {
+ // var _ = stateEvent.GetType;
+ // }
+ // _logger.LogInformation($"Got room state for {room.RoomId}!");
+ // }
+
+ // 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 {args.Key} by {inviteEvent.Sender} with reason: {(inviteEvent.TypedContent as RoomMemberEventContent).Reason}");
+ // if (inviteEvent.Sender.EndsWith(":rory.gay") || inviteEvent.Sender == "@mxidupwitch:the-apothecary.club")
+ // 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("I was unable to join the room: " + e);
+ // }
+ // });
+ // Deprecated, using Bot Utils instead:
+ // syncHelper.TimelineEventHandlers.Add(async @event => {
+ // _logger.LogInformation(
+ // "Got timeline event in {}: {}", @event.RoomId, @event.ToJson(false, true));
+ //
+ // var room = hs.GetRoom(@event.RoomId);
+ // // _logger.LogInformation(eventResponse.ToJson(indent: false));
+ // if (@event is not { Sender: "@emma:rory.gay" }) return;
+ // if (@event is { Type: "m.room.message", TypedContent: RoomMessageEventContent message })
+ // if (message is { MessageType: "m.text" } && message.Body.StartsWith(_configuration.Prefix)) {
+ // var command = _commands.FirstOrDefault(x => x.Name == message.Body.Split(' ')[0][_configuration.Prefix.Length..]);
+ // if (command == null) {
+ // await room.SendMessageEventAsync(
+ // new RoomMessageEventContent("m.text", "Command not found!"));
+ // return;
+ // }
+ //
+ // var ctx = new CommandContext {
+ // Room = room,
+ // MessageEvent = @event
+ // };
+ // if (await command.CanInvoke(ctx))
+ // await command.Invoke(ctx);
+ // else
+ // await room.SendMessageEventAsync(
+ // new RoomMessageEventContent("m.text", "You do not have permission to run this command!"));
+ // }
+ // });
+ await syncHelper.RunSyncLoopAsync(cancellationToken: cancellationToken);
+ }
+
+ /// <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 Task StopAsync(CancellationToken cancellationToken) {
+ _logger.LogInformation("Shutting down bot!");
+ return Task.CompletedTask;
+ }
+}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.DevTestBot/Bot/StartupTasks/ServerRoomSizeCalulator.cs b/Utilities/LibMatrix.DevTestBot/Bot/StartupTasks/ServerRoomSizeCalulator.cs
index 253eb37..fdc7717 100644
--- a/Utilities/LibMatrix.DevTestBot/Bot/StartupTasks/ServerRoomSizeCalulator.cs
+++ b/Utilities/LibMatrix.DevTestBot/Bot/StartupTasks/ServerRoomSizeCalulator.cs
@@ -1,5 +1,4 @@
using System.Diagnostics.CodeAnalysis;
-using LibMatrix.ExampleBot.Bot.Interfaces;
using LibMatrix.Homeservers;
using LibMatrix.Services;
using Microsoft.Extensions.Hosting;
@@ -11,10 +10,9 @@ public class ServerRoomSizeCalulator : IHostedService {
private readonly HomeserverProviderService _homeserverProviderService;
private readonly ILogger<ServerRoomSizeCalulator> _logger;
private readonly DevTestBotConfiguration _configuration;
- private readonly IEnumerable<ICommand> _commands;
public ServerRoomSizeCalulator(HomeserverProviderService homeserverProviderService, ILogger<ServerRoomSizeCalulator> logger,
- DevTestBotConfiguration configuration, IServiceProvider services) {
+ DevTestBotConfiguration configuration) {
logger.LogInformation("Server room size calculator hosted service instantiated!");
_homeserverProviderService = homeserverProviderService;
_logger = logger;
diff --git a/Utilities/LibMatrix.DevTestBot/LibMatrix.DevTestBot.csproj b/Utilities/LibMatrix.DevTestBot/LibMatrix.DevTestBot.csproj
index 6518c67..acff3e2 100644
--- a/Utilities/LibMatrix.DevTestBot/LibMatrix.DevTestBot.csproj
+++ b/Utilities/LibMatrix.DevTestBot/LibMatrix.DevTestBot.csproj
@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
- <TargetFramework>net8.0</TargetFramework>
+ <TargetFramework>net9.0</TargetFramework>
<LangVersion>preview</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
@@ -18,13 +18,16 @@
</PropertyGroup>
<ItemGroup>
+ <PackageReference Include="ArcaneLibs.StringNormalisation" Version="1.0.0-preview.20250419-174711" Condition="'$(Configuration)' == 'Release'" />
+ <ProjectReference Include="..\..\ArcaneLibs\ArcaneLibs.StringNormalisation\ArcaneLibs.StringNormalisation.csproj" Condition="'$(Configuration)' == 'Debug'"/>
<ProjectReference Include="..\..\LibMatrix\LibMatrix.csproj"/>
+ <ProjectReference Include="..\LibMatrix.Utilities.Bot\LibMatrix.Utilities.Bot.csproj" />
</ItemGroup>
<ItemGroup>
- <PackageReference Include="ArcaneLibs.StringNormalisation" Version="1.0.0-preview7205256004.28c0e5a"/>
- <PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0"/>
+ <PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.1"/>
</ItemGroup>
+
<ItemGroup>
<Content Include="appsettings*.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
diff --git a/Utilities/LibMatrix.DevTestBot/Program.cs b/Utilities/LibMatrix.DevTestBot/Program.cs
index eb5ad76..7eb74d4 100644
--- a/Utilities/LibMatrix.DevTestBot/Program.cs
+++ b/Utilities/LibMatrix.DevTestBot/Program.cs
@@ -1,30 +1,24 @@
// See https://aka.ms/new-console-template for more information
-using ArcaneLibs;
using LibMatrix.ExampleBot.Bot;
-using LibMatrix.ExampleBot.Bot.Interfaces;
using LibMatrix.Services;
+using LibMatrix.Utilities.Bot;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
Console.WriteLine("Hello, World!");
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.AddScoped<DevTestBotConfiguration>();
services.AddRoryLibMatrixServices();
- foreach (var commandClass in new ClassCollector<ICommand>().ResolveFromAllAccessibleAssemblies()) {
- Console.WriteLine($"Adding command {commandClass.Name}");
- services.AddScoped(typeof(ICommand), commandClass);
- }
+
+ services.AddMatrixBot()
+ .AddCommandHandler()
+ .DiscoverAllCommands()
+ .WithInviteHandler(ctx => Task.FromResult(ctx.MemberEvent.Sender!.EndsWith(":rory.gay")));
// services.AddHostedService<ServerRoomSizeCalulator>();
- services.AddHostedService<DevTestBot>();
+ services.AddHostedService<PingTestBot>();
}).UseConsoleLifetime().Build();
await host.RunAsync();
\ No newline at end of file
diff --git a/Utilities/LibMatrix.DevTestBot/appsettings.json b/Utilities/LibMatrix.DevTestBot/appsettings.json
index db64c22..815d2a5 100644
--- a/Utilities/LibMatrix.DevTestBot/appsettings.json
+++ b/Utilities/LibMatrix.DevTestBot/appsettings.json
@@ -8,7 +8,7 @@
},
"Bot": {
"Homeserver": "rory.gay",
- "AccessToken": "syt_xxxxxxxxxxxxxxxxx",
- "Prefix": "!"
+ "AccessToken": "syt_xxxxxx_xxxxxxxxxxxxxxxxxxxx_xxxxxx",
+ "Prefix": "$"
}
}
\ No newline at end of file
|