diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md index 7285119..68710eb 100644 --- a/.github/CODE_OF_CONDUCT.md +++ b/.github/CODE_OF_CONDUCT.md @@ -105,7 +105,7 @@ Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community -standards, including sustained inappropriate behavior, harassment of an +standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index dd84ea7..3205926 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -12,6 +12,7 @@ A clear and concise description of what the bug is. **To Reproduce** Steps to reproduce the behavior: + 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' @@ -24,15 +25,17 @@ A clear and concise description of what you expected to happen. If applicable, add screenshots to help explain your problem. **Desktop (please complete the following information):** - - OS: [e.g. iOS] - - Browser [e.g. chrome, safari] - - Version [e.g. 22] + +- OS: [e.g. iOS] +- Browser [e.g. chrome, safari] +- Version [e.g. 22] **Smartphone (please complete the following information):** - - Device: [e.g. iPhone6] - - OS: [e.g. iOS8.1] - - Browser [e.g. stock browser, safari] - - Version [e.g. 22] + +- Device: [e.g. iPhone6] +- OS: [e.g. iOS8.1] +- Browser [e.g. stock browser, safari] +- Version [e.g. 22] **Additional context** Add any other context about the problem here. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index fb8a9e5..af36d4f 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,13 +1,16 @@ ## Description + ## Motivation and Context + ## How has this been tested? + @@ -15,14 +18,18 @@ ## Screenshots (if appropriate): ## Types of changes + + - [ ] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) ## Checklist: + + - [ ] My code follows the code style of this project. - [ ] My change requires a change to the documentation. - [ ] I have updated the documentation accordingly. diff --git a/.github/README.md b/.github/README.md index 2c7ea8c..8b0eab8 100644 --- a/.github/README.md +++ b/.github/README.md @@ -61,8 +61,10 @@ ## About The Project -A simple Discord Bot Template build with the [Color-Chan.Discord library](https://github.com/Color-Chan/Color-Chan.Discord). -This template includes basic commands including a help command with multiple pages using buttons. Plus a simple [MongoDB](https://www.mongodb.com/) connection. +A simple Discord Bot Template build with +the [Color-Chan.Discord library](https://github.com/Color-Chan/Color-Chan.Discord). +This template includes basic commands including a help command with multiple pages using buttons. Plus a +simple [MongoDB](https://www.mongodb.com/) connection. - Basic commands - Persistent command request logging @@ -94,10 +96,13 @@ To get a local copy up and running follow these simple steps. #### Using the template -See the [Create reposotiry from a template](https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-repository-from-a-template) guide for a more detailed explanation. +See +the [Create reposotiry from a template](https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-repository-from-a-template) +guide for a more detailed explanation. + 1. Navigate to the main page of the repository. 2. Above the file list, click `Use this template`. -![Use template button](https://cdn.brammys.com/file/brammys/screenshots/2022/02/use-this-template-button.png) + ![Use template button](https://cdn.brammys.com/file/brammys/screenshots/2022/02/use-this-template-button.png) 3. Enter the name for your new repository and choose a visibility option. 4. Click the `Create repositoiry from template` button. @@ -116,22 +121,28 @@ See the [Create reposotiry from a template](https://docs.github.com/en/repositor dotnet build ``` - ### Usage -#### Environment variables -To run the Bot you will need to set 2 environment variables first. +#### Secrets + +To run the Bot you will need to set a couple of secrets first. +You can set these secret either as environment variables or using the [dotnet secret manager](https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets#set-a-secret). + - `BOT_TOKEN` : Add your bot token as the value. The bot token van be found [here](https://discord.com/developers/applications/). - `MONGO_CON_STRING` : Add your MongoDB connection string as the value. You can get a free MongoDB host on [MongoDB Atlas](https://www.mongodb.com/atlas/database). #### Constants -After this you need to set the `PublicKey` and the `BotId` for your bot. These can be set in the [Constants.cs](https://github.com/BrammyS/Discord-Bot-Template/blob/dev/src/Bot.Discord/Constants.cs) class in Bot.Discord. +After this you need to set the `PublicKey` and the `BotId` for your bot. These can be set in +the [Constants.cs](https://github.com/BrammyS/Discord-Bot-Template/blob/dev/src/Bot.Discord/Constants.cs) class in +Bot.Discord. ### URL -Set the interaction end point for your bot. You will need to add this URL to you [application](https://discord.com/developers/applications/). -The interaction endpoint is located at `https://YOUR_DOMAIN.COM:5001/api/v1/discord/interaction`. Please do keep in mind that you will need to be able to access this endpoint from outside of your network. +Set the interaction end point for your bot. You will need to add this URL to +you [application](https://discord.com/developers/applications/). +The interaction endpoint is located at `https://YOUR_DOMAIN.COM:5001/api/v1/discord/interaction`. Please do keep in mind +that you will need to be able to access this endpoint from outside of your network. [![interactionUrlSetup](https://cdn.colorchan.com/examples/interactionUrlExample.png)](https://discord.com/developers/applications/) @@ -166,8 +177,13 @@ Distributed under the MIT License. See `LICENSE` for more information. [stars-shield]: https://img.shields.io/github/stars/BrammyS/Discord-Bot-Template?style=for-the-badge + [stars-url]: https://github.com/BrammyS/Discord-Bot-Template/stargazers + [issues-shield]: https://img.shields.io/github/issues/BrammyS/Discord-Bot-Template?style=for-the-badge + [issues-url]: https://github.com/BrammyS/Discord-Bot-Template/issues + [license-shield]: https://img.shields.io/github/license/BrammyS/Discord-Bot-Template?style=for-the-badge + [license-url]: https://github.com/BrammyS/Discord-Bot-Template/blob/main/LICENSE diff --git a/.github/workflows/dotnetBuild.yml b/.github/workflows/dotnetBuild.yml index f8b9610..8d07d10 100644 --- a/.github/workflows/dotnetBuild.yml +++ b/.github/workflows/dotnetBuild.yml @@ -7,7 +7,7 @@ jobs: timeout-minutes: 15 strategy: matrix: - os: [ubuntu-latest] + os: [ ubuntu-latest ] steps: - name: Checkout uses: actions/checkout@v3 @@ -17,7 +17,7 @@ jobs: - name: Setup .NET SDK uses: actions/setup-dotnet@v3 with: - dotnet-version: 7.0.x + dotnet-version: 7.0.x - name: Install dependencies run: dotnet restore diff --git a/src/Bot.Discord/Bot.Discord.csproj b/src/Bot.Discord/Bot.Discord.csproj index 34fc1bd..b10adf2 100644 --- a/src/Bot.Discord/Bot.Discord.csproj +++ b/src/Bot.Discord/Bot.Discord.csproj @@ -7,7 +7,7 @@ - + diff --git a/src/Bot.Discord/Commands/InviteCommands.cs b/src/Bot.Discord/Commands/InviteCommands.cs index 3171582..76789c4 100644 --- a/src/Bot.Discord/Commands/InviteCommands.cs +++ b/src/Bot.Discord/Commands/InviteCommands.cs @@ -18,6 +18,11 @@ public class InviteCommands : SlashCommandModule public const string InviteCommandName = "invite"; public const string InviteCommandDesc = "Invite the bot somewhere else!"; + public static readonly IDiscordComponent InviteMe = + new ActionRowComponentBuilder() + .WithButton("Invite me!", DiscordButtonStyle.Link, null, $"https://discord.com/api/oauth2/authorize?client_id={Constants.BotId}&permissions=0&scope=bot%20applications.commands") + .Build(); + /// /// An invitation command where the bot will reply back with a link to be added to other servers. /// @@ -28,24 +33,19 @@ public class InviteCommands : SlashCommandModule public Task> InviteAsync() { var inviteMeEmbed = new DiscordEmbedBuilder() - .WithTitle("Invite me") - .WithDescription("I need more friends, add me to other Discord servers!") - .WithColor(Constants.Colors.Successful) - .WithTimeStamp() - .Build(); + .WithTitle("Invite me") + .WithDescription("I need more friends, add me to other Discord servers!") + .WithColor(Constants.Colors.Successful) + .WithTimeStamp() + .Build(); // Build the embedded response. var inviteResponse = new InteractionResponseBuilder() - .WithEmbed(inviteMeEmbed) - .WithComponent(InviteMe) - .Build(); + .WithEmbed(inviteMeEmbed) + .WithComponent(InviteMe) + .Build(); // Return the response to Discord. return Task.FromResult(FromSuccess(inviteResponse)); } - - public static readonly IDiscordComponent InviteMe = - new ActionRowComponentBuilder() - .WithButton("Invite me!", DiscordButtonStyle.Link, null, $"https://discord.com/api/oauth2/authorize?client_id={Constants.BotId}&permissions=0&scope=bot%20applications.commands") - .Build(); } \ No newline at end of file diff --git a/src/Bot.Discord/Extensions/ServiceCollectionExtensions.cs b/src/Bot.Discord/Extensions/ServiceCollectionExtensions.cs index 96b98d6..9d88ae1 100644 --- a/src/Bot.Discord/Extensions/ServiceCollectionExtensions.cs +++ b/src/Bot.Discord/Extensions/ServiceCollectionExtensions.cs @@ -3,18 +3,19 @@ using Color_Chan.Discord.Commands.Extensions; using Color_Chan.Discord.Configurations; using Color_Chan.Discord.Extensions; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace Bot.Discord.Extensions; public static class ServiceCollectionExtensions { - public static IServiceCollection AddDiscord(this IServiceCollection services) + public static IServiceCollection AddDiscord(this IServiceCollection services, IConfiguration configuration) { - var token = Environment.GetEnvironmentVariable("BOT_TOKEN"); + var token = configuration["BOT_TOKEN"]; if (token is null) { - throw new NullReferenceException("Please set the BOT_TOKEN env variable!"); + throw new NullReferenceException("Please set the BOT_TOKEN configuration!"); } // Configure Color-Chan.Discord @@ -23,10 +24,8 @@ public static IServiceCollection AddDiscord(this IServiceCollection services) SlashCommandConfigs = slashOptions => { slashOptions.SendDefaultErrorMessage = true; } }; - services.AddSlashCommandPipeline(); - services.AddSlashCommandPipeline(); - services.AddComponentInteractionPipeline(); - + services.AddInteractionPipeline(); + services.AddInteractionPipeline(); services.AddColorChanDiscord(token, Constants.PublicKey, Constants.BotId, config); services.AddMongoDb(); diff --git a/src/Bot.Discord/Helpers/CommandHelper.cs b/src/Bot.Discord/Helpers/CommandHelper.cs new file mode 100644 index 0000000..844edd8 --- /dev/null +++ b/src/Bot.Discord/Helpers/CommandHelper.cs @@ -0,0 +1,12 @@ +namespace Bot.Discord.Helpers; + +public static class CommandHelper +{ + public static string SanitizeCommandName(string commandName) + { + var paramIndex = commandName.IndexOf(';'); + return paramIndex >= 0 + ? commandName.Remove(paramIndex) + : commandName; + } +} \ No newline at end of file diff --git a/src/Bot.Discord/Pipelines/ComponentLoggingPipeline.cs b/src/Bot.Discord/Pipelines/ComponentLoggingPipeline.cs deleted file mode 100644 index 74963fe..0000000 --- a/src/Bot.Discord/Pipelines/ComponentLoggingPipeline.cs +++ /dev/null @@ -1,74 +0,0 @@ -using System.Diagnostics; -using Bot.persistence.Domain.Models; -using Bot.persistence.UnitOfWorks; -using Color_Chan.Discord.Commands; -using Color_Chan.Discord.Commands.Models.Contexts; -using Color_Chan.Discord.Core.Common.Models.Interaction; -using Color_Chan.Discord.Core.Results; -using Microsoft.Extensions.Logging; -using MongoDB.Bson; - -namespace Bot.Discord.Pipelines; - -/// -/// A pipeline that will measure the performance of the component commands -/// and log the component command requests. -/// -public class ComponentLoggingPipeline : IComponentInteractionPipeline -{ - private readonly ILogger _logger; - private readonly IUnitOfWork _unitOfWork; - - /// - /// Initializes a new instance of . - /// - /// The logger that will log the performance of the component commands to the console. - /// The that will executed queries on the DB. - public ComponentLoggingPipeline(ILogger logger, IUnitOfWork unitOfWork) - { - _logger = logger; - _unitOfWork = unitOfWork; - } - - /// - public async Task> HandleAsync(IInteractionContext context, ComponentInteractionHandlerDelegate next) - { - var sw = new Stopwatch(); - - sw.Start(); - - // Run the command - var result = await next().ConfigureAwait(false); - - sw.Stop(); - - await LogComponentRequestAsync(context, result, sw); - - return result; - } - - private async Task LogComponentRequestAsync(IInteractionContext context, Result result, Stopwatch sw) - { - var request = new Request - { - Command = context.Data.CustomId ?? context.MethodName, - IsSuccessful = result.IsSuccessful, - ErrorMessage = result.ErrorResult?.ErrorMessage, - MessageId = context.InteractionId, - ServerId = context.GuildId ?? context.ChannelId, - TimeStamp = DateTime.UtcNow, - UserId = context.User.Id, - AddedAtUtc = DateTime.UtcNow, - ElapsedMilliseconds = sw.ElapsedMilliseconds, - BsonObjectId = ObjectId.GenerateNewId().ToString() - }; - - await _unitOfWork.Requests.AddAsync(request).ConfigureAwait(false); - await _unitOfWork.DailyStats.IncrementCommandsUsedAsync().ConfigureAwait(false); - - _logger.Log(sw.ElapsedMilliseconds > 1500 ? LogLevel.Warning : LogLevel.Debug, "Executed component command {ComponentCommandName} in {ElapsedMilliseconds}ms - {IsSuccessful}", - request.Command, - sw.ElapsedMilliseconds.ToString(), - request.IsSuccessful ? "Successfully" : "Unsuccessfully"); - } -} \ No newline at end of file diff --git a/src/Bot.Discord/Pipelines/GuildDbPipeline.cs b/src/Bot.Discord/Pipelines/GuildDbPipeline.cs index 92a9c94..2fb3d6d 100644 --- a/src/Bot.Discord/Pipelines/GuildDbPipeline.cs +++ b/src/Bot.Discord/Pipelines/GuildDbPipeline.cs @@ -8,7 +8,7 @@ namespace Bot.Discord.Pipelines; -public class GuildDbPipeline : ISlashCommandPipeline +public class GuildDbPipeline : IInteractionPipeline { private readonly ILogger _logger; private readonly IUnitOfWork _unitOfWork; @@ -25,7 +25,7 @@ public GuildDbPipeline(ILogger logger, IUnitOfWork unitOfWork) } /// - public async Task> HandleAsync(ISlashCommandContext context, SlashCommandHandlerDelegate next) + public async Task> HandleAsync(IInteractionContext context, InteractionHandlerDelegate next) { // Skip commands that were used outside of a guild. if (context.GuildId is null) diff --git a/src/Bot.Discord/Pipelines/CommandLoggingPipeline.cs b/src/Bot.Discord/Pipelines/InteractionLoggingPipeline.cs similarity index 65% rename from src/Bot.Discord/Pipelines/CommandLoggingPipeline.cs rename to src/Bot.Discord/Pipelines/InteractionLoggingPipeline.cs index 10e77b6..2002358 100644 --- a/src/Bot.Discord/Pipelines/CommandLoggingPipeline.cs +++ b/src/Bot.Discord/Pipelines/InteractionLoggingPipeline.cs @@ -1,5 +1,6 @@ using System.Diagnostics; using Bot.Discord.Extensions; +using Bot.Discord.Helpers; using Bot.persistence.Domain.Models; using Bot.persistence.UnitOfWorks; using Color_Chan.Discord.Commands; @@ -12,27 +13,27 @@ namespace Bot.Discord.Pipelines; /// -/// A pipeline that will measure the performance of the slash commands +/// A pipeline that will measure the performance of the interaction /// and log the slash command requests. /// -public class CommandLoggingPipeline : ISlashCommandPipeline +public class InteractionLoggingPipeline : IInteractionPipeline { - private readonly ILogger _logger; + private readonly ILogger _logger; private readonly IUnitOfWork _unitOfWork; /// - /// Initializes a new instance of . + /// Initializes a new instance of . /// - /// The logger that will log the performance of the slash commands to the console. + /// The logger that will log the performance of the interaction to the console. /// The that will executed queries on the DB. - public CommandLoggingPipeline(ILogger logger, IUnitOfWork unitOfWork) + public InteractionLoggingPipeline(ILogger logger, IUnitOfWork unitOfWork) { _logger = logger; _unitOfWork = unitOfWork; } /// - public async Task> HandleAsync(ISlashCommandContext context, SlashCommandHandlerDelegate next) + public async Task> HandleAsync(IInteractionContext context, InteractionHandlerDelegate next) { var sw = new Stopwatch(); @@ -48,11 +49,13 @@ public async Task> HandleAsync(ISlashCommand return result; } - private async Task LogCommandRequestAsync(ISlashCommandContext context, Result result, Stopwatch sw) + private async Task LogCommandRequestAsync(IInteractionContext context, Result result, Stopwatch sw) { var request = new Request { - Command = context.SlashCommandName.GetFullCommandName(), + Command = context is SlashCommandContext slashCommandContext + ? slashCommandContext.SlashCommandName.GetFullCommandName() + : (context.Data.CustomId ?? context.MethodName) ?? "unknown", IsSuccessful = result.IsSuccessful, ErrorMessage = result.ErrorResult?.ErrorMessage, MessageId = context.InteractionId, @@ -64,10 +67,12 @@ private async Task LogCommandRequestAsync(ISlashCommandContext context, Result 1500 ? LogLevel.Warning : LogLevel.Debug, "Executed slash command {SlashCommandName} in {ElapsedMilliseconds}ms - {IsSuccessful}", + _logger.Log(sw.ElapsedMilliseconds > 1500 ? LogLevel.Warning : LogLevel.Debug, "Executed interaction {InteractionName} in {ElapsedMilliseconds}ms - {IsSuccessful}", request.Command, sw.ElapsedMilliseconds.ToString(), request.IsSuccessful ? "Successfully" : "Unsuccessfully"); diff --git a/src/Bot/Bot.csproj b/src/Bot/Bot.csproj index 7d13192..eedc7d4 100644 --- a/src/Bot/Bot.csproj +++ b/src/Bot/Bot.csproj @@ -1,10 +1,11 @@ - + net7.0 enable enable Linux + dc598d14-7d94-401a-bfed-13264b7426b5 @@ -12,7 +13,7 @@ - + diff --git a/src/Bot/Configurations/SerilogConfig.cs b/src/Bot/Configurations/SerilogConfig.cs index 83effbf..caeb46d 100644 --- a/src/Bot/Configurations/SerilogConfig.cs +++ b/src/Bot/Configurations/SerilogConfig.cs @@ -8,7 +8,8 @@ public static class SerilogConfig /// /// Configures misc settings for serilog. /// - public static void Configure() + /// The containing the application secrets and configurations. + public static void Configure(IConfiguration configuration) { Log.Logger = new LoggerConfiguration() #if DEBUG @@ -26,7 +27,7 @@ public static void Configure() .WriteTo.Async(writeTo => { writeTo.Console(); - writeTo.MongoDb(); + writeTo.MongoDb(configuration); }).CreateLogger(); } diff --git a/src/Bot/Program.cs b/src/Bot/Program.cs index 93f7dfb..c74e03a 100644 --- a/src/Bot/Program.cs +++ b/src/Bot/Program.cs @@ -9,13 +9,15 @@ public class Program { public static async Task Main(string[] args) { - SerilogConfig.Configure(); - try { + var host = CreateHostBuilder(args).Build(); + + var configuration = host.Services.GetRequiredService(); + SerilogConfig.Configure(configuration); + Log.Information("Starting Bot web host"); - var host = CreateHostBuilder(args).Build(); await host.RegisterSlashCommandsAsync(Assembly.Load("Bot.Discord")).ConfigureAwait(false); await host.RunAsync().ConfigureAwait(false); @@ -28,7 +30,7 @@ public static async Task Main(string[] args) } finally { - Log.CloseAndFlush(); + await Log.CloseAndFlushAsync(); } } diff --git a/src/Bot/Startup.cs b/src/Bot/Startup.cs index 1f83d08..82f5665 100644 --- a/src/Bot/Startup.cs +++ b/src/Bot/Startup.cs @@ -11,12 +11,12 @@ public Startup(IConfiguration configuration) Configuration = configuration; } - public IConfiguration Configuration { get; } + private IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { - services.AddDiscord(); + services.AddDiscord(Configuration); services.AddControllers(); services.ConfigureCors(); diff --git a/src/persistence/Bot.persistence.MongoDb/Bot.persistence.MongoDb.csproj b/src/persistence/Bot.persistence.MongoDb/Bot.persistence.MongoDb.csproj index b9b2c41..1bfb8e0 100644 --- a/src/persistence/Bot.persistence.MongoDb/Bot.persistence.MongoDb.csproj +++ b/src/persistence/Bot.persistence.MongoDb/Bot.persistence.MongoDb.csproj @@ -7,10 +7,11 @@ + - + diff --git a/src/persistence/Bot.persistence.MongoDb/ConnectionStringHelper.cs b/src/persistence/Bot.persistence.MongoDb/ConnectionStringHelper.cs index e29ad72..362475a 100644 --- a/src/persistence/Bot.persistence.MongoDb/ConnectionStringHelper.cs +++ b/src/persistence/Bot.persistence.MongoDb/ConnectionStringHelper.cs @@ -1,11 +1,13 @@ -namespace Bot.persistence.MongoDb; +using Microsoft.Extensions.Configuration; + +namespace Bot.persistence.MongoDb; public class ConnectionStringHelper { - public static string GetMongoDbConnectionString() + public static string GetMongoDbConnectionString(IConfiguration configuration) { // https://docs.mongodb.com/manual/reference/connection-string/ - var connectionString = Environment.GetEnvironmentVariable("MONGO_CON_STRING"); + var connectionString = configuration["MONGO_CON_STRING"]; if (string.IsNullOrWhiteSpace(connectionString)) { diff --git a/src/persistence/Bot.persistence.MongoDb/LoggingSink/MongoDbLogSink.cs b/src/persistence/Bot.persistence.MongoDb/LoggingSink/MongoDbLogSink.cs index c23acd6..9edabe7 100644 --- a/src/persistence/Bot.persistence.MongoDb/LoggingSink/MongoDbLogSink.cs +++ b/src/persistence/Bot.persistence.MongoDb/LoggingSink/MongoDbLogSink.cs @@ -1,4 +1,5 @@ -using MongoDB.Driver; +using Microsoft.Extensions.Configuration; +using MongoDB.Driver; using Serilog; using Serilog.Configuration; using Serilog.Sinks.Mongodb.TimeSeries.Configurations; @@ -12,13 +13,14 @@ public static class MongoDbLogSink /// Add a MongoDB log sink to serilog. /// This will save all the logs to the database. /// - /// Controls sink configuration. + /// Controls sink configuration. + /// The containing the application secrets and configurations. /// /// The sink configurations. /// - public static LoggerConfiguration MongoDb(this LoggerSinkConfiguration configuration) + public static LoggerConfiguration MongoDb(this LoggerSinkConfiguration sinkConfiguration, IConfiguration configuration) { - var client = new MongoClient(ConnectionStringHelper.GetMongoDbConnectionString()); + var client = new MongoClient(ConnectionStringHelper.GetMongoDbConnectionString(configuration)); var mongoDatabase = client.GetDatabase(Constants.DatabaseName); var configs = new MongoDbTimeSeriesSinkConfig(mongoDatabase) @@ -29,6 +31,6 @@ public static LoggerConfiguration MongoDb(this LoggerSinkConfiguration configura LogsExpireAfter = TimeSpan.FromDays(7) }; - return configuration.MongoDbTimeSeriesSink(configs); + return sinkConfiguration.MongoDbTimeSeriesSink(configs); } } \ No newline at end of file diff --git a/src/persistence/Bot.persistence.MongoDb/MongoContext.cs b/src/persistence/Bot.persistence.MongoDb/MongoContext.cs index 943cf30..06160f7 100644 --- a/src/persistence/Bot.persistence.MongoDb/MongoContext.cs +++ b/src/persistence/Bot.persistence.MongoDb/MongoContext.cs @@ -1,4 +1,5 @@ -using MongoDB.Driver; +using Microsoft.Extensions.Configuration; +using MongoDB.Driver; namespace Bot.persistence.MongoDb; @@ -12,9 +13,9 @@ public class MongoContext : BaseMongoContext /// /// Creates a new . /// - public MongoContext() + public MongoContext(IConfiguration configuration) { - var client = new MongoClient(ConnectionStringHelper.GetMongoDbConnectionString()); + var client = new MongoClient(ConnectionStringHelper.GetMongoDbConnectionString(configuration)); _database = client.GetDatabase("Bot"); } diff --git a/tests/Bot.Discord.Tests/Bot.Discord.Tests.csproj b/tests/Bot.Discord.Tests/Bot.Discord.Tests.csproj index 3001a77..fdc7a89 100644 --- a/tests/Bot.Discord.Tests/Bot.Discord.Tests.csproj +++ b/tests/Bot.Discord.Tests/Bot.Discord.Tests.csproj @@ -12,10 +12,10 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - + - - + + diff --git a/tests/persistence/Bot.persistence.MongoDb.Tests/Bot.persistence.MongoDb.Tests.csproj b/tests/persistence/Bot.persistence.MongoDb.Tests/Bot.persistence.MongoDb.Tests.csproj index 32045a1..fc32e34 100644 --- a/tests/persistence/Bot.persistence.MongoDb.Tests/Bot.persistence.MongoDb.Tests.csproj +++ b/tests/persistence/Bot.persistence.MongoDb.Tests/Bot.persistence.MongoDb.Tests.csproj @@ -12,10 +12,10 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - + - - + +