Skip to content

Commit

Permalink
use Humanizer fix, use Channels and other improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
Plerx2493 committed Mar 11, 2024
1 parent 26c5973 commit b2a411f
Show file tree
Hide file tree
Showing 18 changed files with 172 additions and 253 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ public TestVariables(DiscordMessage msg, DiscordClient client, CommandContext ct
public DiscordChannel? Channel { get; private set; }
public DiscordGuild? Guild { get; private set; }
public DiscordUser? User { get; private set; }
public DiscordMember Member { get; private set; }
public DiscordMember? Member { get; private set; }
public CommandContext Context { get; private set; }
public DiscordClient Client { get; private set; }
public DiscordClientService ClientService { get; private set; }
Expand Down
1 change: 1 addition & 0 deletions ModularAssistentForDiscordServer/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ RUN dotnet publish -c Release -o out

# RUNNER IMAGE
FROM mcr.microsoft.com/dotnet/aspnet:8.0-alpine
RUN apk add --no-cache icu-libs
WORKDIR /app
COPY --from=build /src/out .
WORKDIR /config
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,19 @@ public void Configure(EntityTypeBuilder<GuildDbEntity> builder)
builder.HasMany(u => u.Incidents)
.WithOne(i => i.Guild)
.HasForeignKey(i => i.GuildId)
.HasPrincipalKey(x => x.DiscordId);
.HasPrincipalKey(x => x.DiscordId)
.OnDelete(DeleteBehavior.Cascade);

builder.HasOne(a => a.Settings)
.WithOne(b => b.Guild)
.HasForeignKey<GuildDbEntity>(b => b.DiscordId)
.HasPrincipalKey<GuildConfigDbEntity>(x => x.DiscordGuildId);
.HasPrincipalKey<GuildConfigDbEntity>(x => x.DiscordGuildId)
.OnDelete(DeleteBehavior.Cascade);

builder.HasMany(x => x.Quotes)
.WithOne(x => x.Guild)
.HasForeignKey(x => x.DiscordGuildId)
.HasPrincipalKey(x => x.DiscordId);
.HasPrincipalKey(x => x.DiscordId)
.OnDelete(DeleteBehavior.Cascade);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,14 @@ public void Configure(EntityTypeBuilder<UserDbEntity> builder)
builder.HasMany(u => u.Reminders)
.WithOne(x => x.User)
.HasPrincipalKey(x => x.Id)
.HasForeignKey(x => x.UserId);
.HasForeignKey(x => x.UserId)
.OnDelete(DeleteBehavior.Cascade);

builder.HasMany(u => u.VoiceAlerts)
.WithOne(x => x.User)
.HasPrincipalKey(x => x.Id)
.HasForeignKey(x => x.UserId);
.HasForeignKey(x => x.UserId)
.OnDelete(DeleteBehavior.Cascade);

builder.HasMany(u => u.Incidents)
.WithOne(x => x.TargetUser)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,6 @@ public enum DiscordReactionUpdateType
{
ReactionAdded,
ReactionRemoved,
ReactionsCleard,
ReactionsCleared,
ReactionEmojiRemoved
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public GuildConfigDbEntity(ulong guildId)
public ulong Id { get; init; }

/// <summary>
/// Snowflake id of the guild the config is related to
/// Snowflake id of the guild the config is related to
/// </summary>
[Required, Column("discordId")]
public ulong DiscordGuildId { get; set; }
Expand Down
20 changes: 0 additions & 20 deletions ModularAssistentForDiscordServer/Extensions/ExtensionMethods.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
using DSharpPlus;
using DSharpPlus.Entities;
using MADS.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
Expand All @@ -24,25 +23,6 @@ namespace MADS.Extensions;

public static class ExtensionMethods
{
public static IServiceCollection AddDbFactoryDebugOrRelease(this IServiceCollection serviceCollection,
MadsConfig config)
{
ILoggerFactory logger = new LoggerFactory().AddSerilog(new LoggerConfiguration()
.WriteTo.Console()
.MinimumLevel.Warning()
.CreateLogger());

serviceCollection.AddDbContextFactory<MadsContext>(
options =>
{
options.UseMySql(config.ConnectionString, ServerVersion.AutoDetect(config.ConnectionString));
options.UseLoggerFactory(logger);
options.EnableDetailedErrors();
}
);

return serviceCollection;
}

public static IServiceCollection AddDiscordRestClient(this IServiceCollection serviceCollection,
MadsConfig config)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public class MadsBaseApplicationCommand : ApplicationCommandModule
{
private InteractionContext? _ctx;
private readonly Stopwatch _executionTimer = new();
public DiscordClientService CommandService => ModularDiscordBot.Services.GetRequiredService<DiscordClientService>();
protected DiscordClientService CommandService => ModularDiscordBot.Services.GetRequiredService<DiscordClientService>();

public override Task<bool> BeforeSlashExecutionAsync(InteractionContext ctx)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
<StartupObject>MADS.MainProgram</StartupObject>
<RootNamespace>MADS</RootNamespace>
<LangVersion>latest</LangVersion>
<InvariantGlobalization>false</InvariantGlobalization>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
Expand All @@ -31,6 +32,7 @@
<PackageReference Include="DSharpPlus.VoiceNext" Version="5.0.0-nightly-02115" />
<PackageReference Include="EntityFramework" Version="6.4.4" />
<PackageReference Include="FlexLabs.EntityFrameworkCore.Upsert" Version="8.0.0" />
<PackageReference Include="Humanizer" Version="2.14.1" />
<PackageReference Include="Humanizer.Core" Version="2.14.1" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.9.0-3.final" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Scripting" Version="4.9.0-3.final" />
Expand Down
13 changes: 8 additions & 5 deletions ModularAssistentForDiscordServer/ModularDiscordBot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@
// limitations under the License.

using DeepL;
using DSharpPlus;
using MADS.Entities;
using MADS.Extensions;
using MADS.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
Expand Down Expand Up @@ -46,7 +46,13 @@ await Host.CreateDefaultBuilder()
.AddSingleton<DiscordClientService>()
.AddHostedService(s => s.GetRequiredService<DiscordClientService>())
.AddSingleton(s => s.GetRequiredService<DiscordClientService>().DiscordClient)
.AddDbFactoryDebugOrRelease(_config)
.AddDbContextFactory<MadsContext>(
options =>
{
options.UseMySql(_config.ConnectionString, ServerVersion.AutoDetect(_config.ConnectionString));
options.EnableDetailedErrors();
}
)
.AddDiscordRestClient(_config)
.AddMemoryCache(options =>
{
Expand Down Expand Up @@ -77,9 +83,6 @@ await Host.CreateDefaultBuilder()
.AddSingleton<QuotesService>()
.AddSingleton<StarboardService>()
.AddHostedService(s => s.GetRequiredService<StarboardService>())
.AddSingleton(s =>
new TokenListener("51151", "/api/v1/mads/token/"))
.AddHostedService(s => s.GetRequiredService<TokenListener>())
.AddSingleton<ReminderService>()
.AddHostedService(s => s.GetRequiredService<ReminderService>())
.AddSingleton<VoiceAlertService>()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,15 +47,16 @@ public class DiscordClientService : IHostedService
public DiscordClientService
(
MadsConfig pConfig,
IDbContextFactory<MadsContext> dbDbContextFactory
IDbContextFactory<MadsContext> dbDbContextFactory,
LoggingService loggingService
)
{
_logger.Warning("DiscordClientService");

StartTime = DateTime.Now;
MadsConfig config = pConfig;
_dbContextFactory = dbDbContextFactory;
Logging = new LoggingService(this);
Logging = loggingService;

DiscordConfiguration discordConfig = new()
{
Expand Down Expand Up @@ -152,7 +153,7 @@ public Task StopAsync(CancellationToken cancellationToken)

private Task OnGuildDownloadCompleted(DiscordClient sender, GuildDownloadCompletedEventArgs e)
{
Logging.Setup();
Logging.Setup(this);
return Task.CompletedTask;
}
}
54 changes: 20 additions & 34 deletions ModularAssistentForDiscordServer/Services/LoggingService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,28 +30,26 @@ namespace MADS.Services;
public class LoggingService
{
private static readonly Regex PrettyNameRegex = new("PRETTY_NAME=(.*)", RegexOptions.Compiled);

//Utilities
private readonly string _dirPath = DataProvider.GetPath("Logs");
private readonly string _logPath;
private readonly DiscordClientService _modularDiscordBot;
private DiscordRestClient? _discordRestClient;
private readonly DiscordRestClient _discordRestClient;
private DiscordClientService? _modularDiscordBot;
private DiscordWebhookClient _discordWebhookClient = new();
private bool _isSetup;
private List<DiscordDmChannel> _ownerChannel = [];

private static readonly Serilog.ILogger _logger = Log.ForContext<LoggingService>();

internal LoggingService(DiscordClientService dBot)
internal LoggingService(DiscordRestClient discordRestClient)
{
Log.Warning("LoggingService");
DateTime startDate = DateTime.Now;
_modularDiscordBot = dBot;
_discordRestClient = discordRestClient;
Directory.CreateDirectory(_dirPath);
string osVersion = Environment.OSVersion.VersionString;

DateTime startDate = DateTime.Now;
_logPath = DataProvider.GetPath("Logs",
$"{startDate.Day}-{startDate.Month}-{startDate.Year}_{startDate.Hour}-{startDate.Minute}-{startDate.Second}.log");

string osVersion = Environment.OSVersion.VersionString;
string os = osVersion.StartsWith("Unix") ? FetchLinuxName() : Environment.OSVersion.VersionString;

File.AppendAllText(_logPath, $".Net: {RuntimeInformation.FrameworkDescription}\n", Encoding.UTF8);
Expand All @@ -74,43 +72,26 @@ private static string FetchLinuxName()
}
}

public void Setup()
public void Setup(DiscordClientService modularDiscordBot)
{
_modularDiscordBot = modularDiscordBot;
if (_isSetup)
{
return;
}

AddRestClient();

AddOwnerChannels();
SetupFeedback();
SetupWebhookLogging();

_isSetup = true;
}

private void AddRestClient()
{
if (_discordRestClient != null)
{
return;
}

MadsConfig config = DataProvider.GetConfig();

DiscordConfiguration discordConfig = new()
{
Token = config.Token
};

_discordRestClient = new DiscordRestClient(discordConfig);
}


private async void AddOwnerChannels()
{
DiscordApplication application = _modularDiscordBot.DiscordClient.CurrentApplication;
DiscordUser[]? owners = application.Owners?.ToArray();
if (owners is null || _ownerChannel.Count == owners.Length)
DiscordApplication? application = _modularDiscordBot?.DiscordClient.CurrentApplication;
DiscordUser[]? owners = application?.Owners?.ToArray();
if (owners is null || owners.Length == 0)
{
return;
}
Expand All @@ -123,7 +104,7 @@ private async void AddOwnerChannels()

try
{
ownerChannel = await _discordRestClient!.CreateDmAsync(owner.Id);
ownerChannel = await _discordRestClient.CreateDmAsync(owner.Id);
}
catch (DiscordException)
{
Expand All @@ -140,6 +121,11 @@ private async void AddOwnerChannels()

private void SetupFeedback()
{
if (_modularDiscordBot is null)
{
throw new Exception("LoggingService is not set up.");
}

//Button response with modal
_modularDiscordBot.DiscordClient.ComponentInteractionCreated += async (_, e) =>
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,13 +114,13 @@ private static void PostEvictionCallback(object key, object? value, EvictionReas
_logger.Verbose("MessageSniper: Message eviction - {Reason}", reason.Humanize());
}

public void AddMessage(DiscordMessage message)
private void AddMessage(DiscordMessage message)
{
string id = CacheHelper.GetMessageSnipeKey(message.ChannelId);
_memoryCache.Set(id, message, _options);
}

public void AddEditedMessage(DiscordMessage message)
private void AddEditedMessage(DiscordMessage message)
{
string id = CacheHelper.GetMessageEditSnipeKey(message.ChannelId);
_memoryCache.Set(id, message, _options);
Expand Down
Loading

0 comments on commit b2a411f

Please sign in to comment.