diff options
author | TheArcaneBrony <myrainbowdash949@gmail.com> | 2023-06-26 02:43:54 +0200 |
---|---|---|
committer | TheArcaneBrony <myrainbowdash949@gmail.com> | 2023-06-27 17:43:00 +0200 |
commit | 3ed00f732a284b5a3e96e52d4e3a71869135869b (patch) | |
tree | 308cdd5c9891a676dc55cbf0e0e998ab5a74b2d2 /MatrixRoomUtils.Bot/Bot/MRUBot.cs | |
parent | Working state, refactored Rory&::LibMatrix (diff) | |
download | MatrixUtils-3ed00f732a284b5a3e96e52d4e3a71869135869b.tar.xz |
Dependency injection stuff
Diffstat (limited to 'MatrixRoomUtils.Bot/Bot/MRUBot.cs')
-rw-r--r-- | MatrixRoomUtils.Bot/Bot/MRUBot.cs | 115 |
1 files changed, 115 insertions, 0 deletions
diff --git a/MatrixRoomUtils.Bot/Bot/MRUBot.cs b/MatrixRoomUtils.Bot/Bot/MRUBot.cs new file mode 100644 index 0000000..81123e0 --- /dev/null +++ b/MatrixRoomUtils.Bot/Bot/MRUBot.cs @@ -0,0 +1,115 @@ +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using MatrixRoomUtils.Bot; +using MatrixRoomUtils.Bot.Interfaces; +using MatrixRoomUtils.Core; +using MatrixRoomUtils.Core.Extensions; +using MatrixRoomUtils.Core.Helpers; +using MatrixRoomUtils.Core.Services; +using MatrixRoomUtils.Core.StateEventTypes; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +public class MRUBot : IHostedService { + private readonly HomeserverProviderService _homeserverProviderService; + private readonly ILogger<MRUBot> _logger; + private readonly MRUBotConfiguration _configuration; + private readonly IEnumerable<ICommand> _commands; + + public MRUBot(HomeserverProviderService homeserverProviderService, ILogger<MRUBot> logger, + MRUBotConfiguration configuration, IServiceProvider services) { + Console.WriteLine("MRUBot hosted service instantiated!"); + _homeserverProviderService = homeserverProviderService; + _logger = logger; + _configuration = configuration; + Console.WriteLine("Getting commands..."); + _commands = services.GetServices<ICommand>(); + Console.WriteLine($"Got {_commands.Count()} commands!"); + } + + /// <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); + AuthenticatedHomeServer hs; + try { + hs = await _homeserverProviderService.GetAuthenticatedWithToken(_configuration.Homeserver, + _configuration.AccessToken); + } + catch (Exception e) { + _logger.LogError(e.Message); + throw; + } + + await (await hs.GetRoom("!DoHEdFablOLjddKWIp:rory.gay")).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; + // } + // Console.WriteLine($"Got room state for {room.RoomId}!"); + // } + + hs.SyncHelper.InviteReceived += async (_, args) => { + var inviteEvent = + args.Value.InviteState.Events.FirstOrDefault(x => + x.Type == "m.room.member" && x.StateKey == hs.WhoAmI.UserId); + Console.WriteLine( + $"Got invite to {args.Key} by {inviteEvent.Sender} with reason: {(inviteEvent.TypedContent as RoomMemberEventData).Reason}"); + if (inviteEvent.Sender == "@emma:rory.gay") { + try { + await (await hs.GetRoom(args.Key)).JoinAsync(reason: "I was invited by Emma (Rory&)!"); + } + catch (Exception e) { + Console.WriteLine(e); + await (await hs.GetRoom(args.Key)).LeaveAsync(reason: "I was unable to join the room: " + e); + } + } + }; + hs.SyncHelper.TimelineEventReceived += async (_, @event) => { + Console.WriteLine( + $"Got timeline event in {@event.RoomId}: {@event.ToJson(indent: false, ignoreNull: true)}"); + + var room = await hs.GetRoom(@event.RoomId); + // Console.WriteLine(eventResponse.ToJson(indent: false)); + if (@event is { Type: "m.room.message", TypedContent: MessageEventData 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("m.room.message", + new MessageEventData() { + MessageType = "m.text", + Body = "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("m.room.message", + new MessageEventData() { + MessageType = "m.text", + Body = "You do not have permission to run this command!" + }); + } + } + } + }; + await hs.SyncHelper.RunSyncLoop(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 async Task StopAsync(CancellationToken cancellationToken) { + Console.WriteLine("Shutting down bot!"); + } +} \ No newline at end of file |