diff options
Diffstat (limited to 'MatrixRoomUtils.Bot')
-rw-r--r-- | MatrixRoomUtils.Bot/MRUBot.cs | 87 | ||||
-rw-r--r-- | MatrixRoomUtils.Bot/MRUBotConfiguration.cs | 11 | ||||
-rw-r--r-- | MatrixRoomUtils.Bot/MatrixRoomUtils.Bot.csproj | 6 | ||||
-rw-r--r-- | MatrixRoomUtils.Bot/Program.cs | 26 | ||||
-rw-r--r-- | MatrixRoomUtils.Bot/Properties/launchSettings.json | 26 | ||||
-rw-r--r-- | MatrixRoomUtils.Bot/appsettings.Development.json | 9 | ||||
-rw-r--r-- | MatrixRoomUtils.Bot/appsettings.json | 13 |
7 files changed, 132 insertions, 46 deletions
diff --git a/MatrixRoomUtils.Bot/MRUBot.cs b/MatrixRoomUtils.Bot/MRUBot.cs index 9b2a395..157673d 100644 --- a/MatrixRoomUtils.Bot/MRUBot.cs +++ b/MatrixRoomUtils.Bot/MRUBot.cs @@ -1,55 +1,82 @@ -using System.CodeDom.Compiler; +using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using MatrixRoomUtils.Bot; using MatrixRoomUtils.Core; using MatrixRoomUtils.Core.Extensions; using MatrixRoomUtils.Core.Helpers; -using MatrixRoomUtils.Core.Responses; using MatrixRoomUtils.Core.Services; +using MatrixRoomUtils.Core.StateEventTypes; 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; - public MRUBot(HomeserverProviderService homeserverProviderService, ILogger<MRUBot> logger) { + public MRUBot(HomeserverProviderService homeserverProviderService, ILogger<MRUBot> logger, + MRUBotConfiguration configuration) { Console.WriteLine("MRUBot hosted service instantiated!"); _homeserverProviderService = homeserverProviderService; _logger = logger; + _configuration = configuration; } /// <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) { - var hs = await _homeserverProviderService.GetAuthenticatedWithToken("rory.gay", "syt_bXJ1Y29yZXRlc3Q_XKUmPswDGZBiLAmFfAut_1iO0KD"); + 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(); - // #pragma warning disable CS4014 - // Task.Run(async Task? () => { - // #pragma warning restore CS4014 - // while (true) { - // var rooms = await hs.GetJoinedRooms(); - // foreach (var room in rooms) { - // var states = await room.GetStateAsync<List<StateEventResponse>>(""); - // foreach (var state in states) { - // // Console.WriteLine( - // // $"{state.RoomId}: {state.Type}::{state.StateKey} = {ObjectExtensions.ToJson(state.Content, indent: false)}"); - // } - // } - // - // await Task.Delay(1000, cancellationToken); - // } - // }, cancellationToken); - #pragma warning disable CS4014 - Task.Run(async Task? () => { - #pragma warning restore CS4014 - SyncResult? sync = null; - while (true) { - sync = await hs.SyncHelper.Sync(sync?.NextBatch); - _logger.LogInformation($"Got sync, next batch: {sync?.NextBatch}!"); - } - }, cancellationToken); - + + hs.SyncHelper.InviteReceived += async (_, args) => { + // Console.WriteLine($"Got invite to {args.Key}:"); + // foreach (var stateEvent in args.Value.InviteState.Events) { + // Console.WriteLine($"[{stateEvent.Sender}: {stateEvent.StateKey}::{stateEvent.Type}] " + + // ObjectExtensions.ToJson(stateEvent.Content, indent: false, ignoreNull: true)); + // } + + 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 MemberEventData).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)}"); + + // Console.WriteLine(eventResponse.ToJson(indent: false)); + if (@event is { Type: "m.room.message", TypedContent: MessageEventData message }) { + if (message is { MessageType: "m.text", Body: "!ping" }) { + Console.WriteLine( + $"Got ping from {@event.Sender} in {@event.RoomId} with message id {@event.EventId}!"); + await (await hs.GetRoom(@event.RoomId)).SendMessageEventAsync("m.room.message", + new MessageEventData() { MessageType = "m.text", Body = "pong!" }); + } + } + }; + + await hs.SyncHelper.RunSyncLoop(cancellationToken); } /// <summary>Triggered when the application host is performing a graceful shutdown.</summary> diff --git a/MatrixRoomUtils.Bot/MRUBotConfiguration.cs b/MatrixRoomUtils.Bot/MRUBotConfiguration.cs new file mode 100644 index 0000000..14d9b60 --- /dev/null +++ b/MatrixRoomUtils.Bot/MRUBotConfiguration.cs @@ -0,0 +1,11 @@ +using Microsoft.Extensions.Configuration; + +namespace MatrixRoomUtils.Bot; + +public class MRUBotConfiguration { + public MRUBotConfiguration(IConfiguration config) { + config.GetRequiredSection("Bot").Bind(this); + } + public string Homeserver { get; set; } = ""; + public string AccessToken { get; set; } = ""; +} \ No newline at end of file diff --git a/MatrixRoomUtils.Bot/MatrixRoomUtils.Bot.csproj b/MatrixRoomUtils.Bot/MatrixRoomUtils.Bot.csproj index 095d0f6..a82b6aa 100644 --- a/MatrixRoomUtils.Bot/MatrixRoomUtils.Bot.csproj +++ b/MatrixRoomUtils.Bot/MatrixRoomUtils.Bot.csproj @@ -23,5 +23,9 @@ <ItemGroup> <PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0-preview.5.23280.8" /> </ItemGroup> - + <ItemGroup> + <Content Include="appsettings*.json"> + <CopyToOutputDirectory>Always</CopyToOutputDirectory> + </Content> + </ItemGroup> </Project> diff --git a/MatrixRoomUtils.Bot/Program.cs b/MatrixRoomUtils.Bot/Program.cs index 441003e..e8a5b96 100644 --- a/MatrixRoomUtils.Bot/Program.cs +++ b/MatrixRoomUtils.Bot/Program.cs @@ -7,20 +7,16 @@ using Microsoft.Extensions.Hosting; Console.WriteLine("Hello, World!"); -using IHost host = Host.CreateDefaultBuilder(args) - .ConfigureServices((_, services) => { - services.AddScoped<TieredStorageService>(x => - new( - cacheStorageProvider: new FileStorageProvider("data/cache/"), - dataStorageProvider: new FileStorageProvider("data/data/") - ) - ); - - services.AddRoryLibMatrixServices(); - - services.AddHostedService<MRUBot>(); - }) - .Build(); - +var host = Host.CreateDefaultBuilder(args).ConfigureServices((_, services) => { + services.AddScoped<TieredStorageService>(x => + new( + cacheStorageProvider: new FileStorageProvider("bot_data/cache/"), + dataStorageProvider: new FileStorageProvider("bot_data/data/") + ) + ); + services.AddScoped<MRUBotConfiguration>(); + services.AddRoryLibMatrixServices(); + services.AddHostedService<MRUBot>(); +}).UseConsoleLifetime().Build(); await host.RunAsync(); \ No newline at end of file diff --git a/MatrixRoomUtils.Bot/Properties/launchSettings.json b/MatrixRoomUtils.Bot/Properties/launchSettings.json new file mode 100644 index 0000000..997e294 --- /dev/null +++ b/MatrixRoomUtils.Bot/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/MatrixRoomUtils.Bot/appsettings.Development.json b/MatrixRoomUtils.Bot/appsettings.Development.json new file mode 100644 index 0000000..27bbd50 --- /dev/null +++ b/MatrixRoomUtils.Bot/appsettings.Development.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Debug", + "System": "Information", + "Microsoft": "Information" + } + } +} \ No newline at end of file diff --git a/MatrixRoomUtils.Bot/appsettings.json b/MatrixRoomUtils.Bot/appsettings.json new file mode 100644 index 0000000..5668b53 --- /dev/null +++ b/MatrixRoomUtils.Bot/appsettings.json @@ -0,0 +1,13 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Debug", + "System": "Information", + "Microsoft": "Information" + } + }, + "Bot": { + "Homeserver": "rory.gay", + "AccessToken": "syt_xxxxxxxxxxxxxxxxx" + } +} \ No newline at end of file |