Skip to content

Commit

Permalink
Fix db issues and fix bugs in translate commands
Browse files Browse the repository at this point in the history
  • Loading branch information
Plerx2493 committed Jun 22, 2024
1 parent a24333e commit 97b60f8
Show file tree
Hide file tree
Showing 25 changed files with 1,210 additions and 108 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,9 @@ public async ValueTask<IReadOnlyDictionary<string, object>> AutoCompleteAsync(Au
{
TargetLanguage[] sourceLangs = await _service.GetTargetLanguagesAsync();
Dictionary<string, object> choices = sourceLangs
.Where(x => x.ToString().StartsWith(context.UserInput.ToString() ?? ""))
.Where(x => x.ToString().ToLowerInvariant().StartsWith(context.UserInput.ToLowerInvariant()))
.Take(25)
.Select(x => x.ToString())
.ToDictionary(x => x, x => (object)x);
.ToDictionary(x => x.ToString(), x => (object)x.Code);

return choices;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public async Task TranslateAsync(SlashCommandContext ctx, DiscordMessage target
{
await ctx.DeferAsync(true);

string? preferredLanguage = await _translateInformationService.GetPreferredLanguage(ctx.User.Id);
string? preferredLanguage = await _translateInformationService.GetPreferredLanguageAsync(ctx.User.Id);
bool isPreferredLanguageSet = !preferredLanguage.IsNullOrWhiteSpace();

if(!isPreferredLanguageSet)
Expand Down Expand Up @@ -78,8 +78,10 @@ public async Task TranslateAsync(SlashCommandContext ctx, DiscordMessage target

DiscordFollowupMessageBuilder followUpMessage = new DiscordFollowupMessageBuilder()
.WithContent("⚠️ You haven't set a preferred language yet. Default is english.")
.AddComponents(new DiscordButtonComponent(DiscordButtonStyle.Primary, "setLanguage", "Set language").AsActionButton(ActionDiscordButtonEnum.SetTranslationLanguage))
.AddComponents(new DiscordButtonComponent(DiscordButtonStyle.Primary, "setLanguage", "Set your language to en-US").AsActionButton(ActionDiscordButtonEnum.SetTranslationLanguage, "en-US"))
.AddComponents(new DiscordButtonComponent(DiscordButtonStyle.Primary, "setLanguage", "Set language")
.AsActionButton(ActionDiscordButtonEnum.SetTranslationLanguage))
.AddComponents(new DiscordButtonComponent(DiscordButtonStyle.Primary, "setLanguage", "Set your language to en-US")
.AsActionButton(ActionDiscordButtonEnum.SetTranslationLanguage, "en-US"))
.AsEphemeral();


Expand Down
7 changes: 6 additions & 1 deletion ModularAssistentForDiscordServer/Commands/Slash/Jumpad.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public sealed class Jumppad
{
[Command("jumppad"), Description("Create a jumppad button"), RequireGuild,
RequirePermissions(DiscordPermissions.MoveMembers)]
public async Task Test
public async Task CreateJumppad
(
CommandContext ctx,
[Description("Channel where the users will be moved out"),
Expand All @@ -38,6 +38,11 @@ public async Task Test
[Description("Message to be sent")] string? content = null
)
{
if (originChannel == targetChannel)
{
await ctx.RespondAsync(new DiscordInteractionResponseBuilder().WithContent("Can't create a jumppad from a channel to itself").AsEphemeral());
}

DiscordInteractionResponseBuilder message = new();
DiscordButtonComponent newButton = new(DiscordButtonStyle.Success, "Placeholder", "Jump");
newButton = newButton.AsActionButton(
Expand Down
3 changes: 1 addition & 2 deletions ModularAssistentForDiscordServer/Commands/Slash/Quotes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,11 @@ public async Task AddQuoteUser
{
await ctx.DeferAsync(true);


QuoteDbEntity newQuote = new()
{
Content = content,
CreatedAt = DateTime.Now,
DiscordGuildId = ctx.Guild!.Id,
GuildId = ctx.Guild!.Id,
QuotedUserId = user.Id,
UserId = ctx.User.Id
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public async Task StarboardConfigCommand

MadsContext db = await _contextFactory.CreateDbContextAsync();

GuildConfigDbEntity guildConfig = db.Configs.First(x => x.DiscordGuildId == ctx.Guild.Id);
GuildConfigDbEntity guildConfig = db.Configs.First(x => x.GuildId == ctx.Guild.Id);

Check warning on line 56 in ModularAssistentForDiscordServer/Commands/Slash/StarboardConfig.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.

if (!DiscordEmoji.TryFromUnicode(emojiString, out DiscordEmoji emoji))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,14 @@ public Translation(TranslateInformationService translationUserInfo, Translator t
_translator = translator;
}

[Command("info"), Description("Get your preferred language")]
public async Task InfoAsync(CommandContext ctx)
{
string? lang = await _translationUserInfo.GetPreferredLanguageAsync(ctx.User.Id);

await ctx.CreateResponse_Success($"Language set to `{lang ?? "null"}`");
}

[Command("setLanguage"), Description("Set your preferred language")]
public async Task SetLanguageAsync
(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,16 +52,14 @@ await dbContext.Users.Upsert(userdbEntity)
return null;
}

GuildDbEntity guildDbEntity = new()
{
DiscordId = context.Guild.Id
};
GuildDbEntity guildDbEntity = new(context.Guild.Id);

await dbContext.Guilds.Upsert(guildDbEntity)
.On(x => x.DiscordId)
.On(x => x.Id)
.NoUpdate()
.RunAsync();

await dbContext.SaveChangesAsync();
return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -156,24 +156,22 @@ params object[] args
break;

case ActionDiscordButtonEnum.SetTranslationLanguage:
actionCode = (int) ActionDiscordButtonEnum.SetTranslationLanguage;
if (args.Length == 0)
{
actionCode = (int) ActionDiscordButtonEnum.AnswerDmChannel;
customId += actionCode;
break;
}

if (args is [string lang])
{
actionCode = (int) ActionDiscordButtonEnum.AnswerDmChannel;
customId += actionCode + ":" + lang ;
break;
}

throw new ArgumentException("Please provide 1 lang identifier (string)");
break;


default:
throw new ArgumentOutOfRangeException(nameof(action), action, null);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ public class GuildConfigDbEntity
/// Snowflake id of the guild the config is related to
/// </summary>
[Required, Column("discordId")]
public ulong DiscordGuildId { get; set; }
public ulong GuildId { get; set; }

[Column("prefix")]
[Column("prefix"), MaxLength(5)]
public string Prefix { get; set; }

[Column("starboardEnabled")]
Expand All @@ -43,7 +43,7 @@ public class GuildConfigDbEntity
[Column("starboardEmojiId")]
public ulong? StarboardEmojiId { get; set; }

[Column("starboardEmojiName")]
[Column("starboardEmojiName"), MaxLength(50)]
public string? StarboardEmojiName { get; set; }

public GuildDbEntity Guild;
Expand Down
21 changes: 5 additions & 16 deletions ModularAssistentForDiscordServer/Entities/GuildDbEntity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,28 +22,17 @@ namespace MADS.Entities;

public class GuildDbEntity
{
public GuildDbEntity()
public GuildDbEntity(ulong id)
{
Id = 0;
Id = id;
Incidents = new List<IncidentDbEntity>();
Settings = new GuildConfigDbEntity();
Quotes = new List<QuoteDbEntity>();
}

public GuildDbEntity(GuildDbEntity old)
{
Id = old.Id;
Incidents = old.Incidents;
Settings = old.Settings;
Quotes = old.Quotes;
}

[Key, Column("id"), DefaultValue(0), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key, Column("id"), DatabaseGenerated(DatabaseGeneratedOption.None)]
public ulong Id { get; init; }

[Required, Column("discordId")]
public ulong DiscordId { get; set; }

public GuildConfigDbEntity Settings { get; set; }

public List<IncidentDbEntity> Incidents { get; set; }
Expand All @@ -61,7 +50,7 @@ public void Configure(EntityTypeBuilder<GuildDbEntity> builder)

builder.HasOne<GuildConfigDbEntity>(x => x.Settings)
.WithOne(x => x.Guild)
.HasForeignKey<GuildConfigDbEntity>(x => x.DiscordGuildId)
.HasForeignKey<GuildConfigDbEntity>(x => x.GuildId)
.OnDelete(DeleteBehavior.Cascade);

builder.HasMany<IncidentDbEntity>(x => x.Incidents)
Expand All @@ -71,7 +60,7 @@ public void Configure(EntityTypeBuilder<GuildDbEntity> builder)

builder.HasMany<QuoteDbEntity>(x => x.Quotes)
.WithOne(x => x.Guild)
.HasForeignKey(x => x.DiscordGuildId)
.HasForeignKey(x => x.GuildId)
.OnDelete(DeleteBehavior.Cascade);
}
}
2 changes: 1 addition & 1 deletion ModularAssistentForDiscordServer/Entities/QuoteDbEntity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public class QuoteDbEntity
public ulong Id { get; set; }

[Column("discordGuildId")]
public ulong DiscordGuildId { get; set; }
public ulong GuildId { get; set; }

/// <summary>
/// User which was quoted
Expand Down
2 changes: 1 addition & 1 deletion ModularAssistentForDiscordServer/Entities/UserDbEntity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ namespace MADS.Entities;

public class UserDbEntity
{
[Key, Column("id")]
[Key, Column("id"), DatabaseGenerated(DatabaseGeneratedOption.None)]
public ulong Id { get; set; }

[Column("username")]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ private static async Task SetTranslationLanguage(ComponentInteractionCreatedEven

InteractivityExtension interactive = sender.GetInteractivity();
InteractivityResult<ModalSubmittedEventArgs> result =
await interactive.WaitForModalAsync($"setLanguage-{args.User.Id}");
await interactive.WaitForModalAsync($"setLanguage-{args.User.Id}", TimeSpan.FromMinutes(5));

if (result.TimedOut)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,8 @@ internal static partial class EventListener
public static async Task UpdateDb(DiscordClient client, GuildDownloadCompletedEventArgs args)
{
IDbContextFactory<MadsContext> dbFactory = ModularDiscordBot.Services.GetRequiredService<IDbContextFactory<MadsContext>>();
Task updateGuilds = UpdateGuilds(args, dbFactory);
Task updateUsers = UpdateUsersDb(args, dbFactory);

await Task.WhenAll(updateGuilds, updateUsers);
await UpdateGuilds(args, dbFactory);
await UpdateUsersDb(args, dbFactory);
client.Logger.LogInformation("Database updated!");
}

Expand Down Expand Up @@ -88,16 +86,15 @@ IDbContextFactory<MadsContext> dbFactory
{
await using MadsContext db = await dbFactory.CreateDbContextAsync();

List<ulong> dbGuildIds = db.Guilds.Select(x => x.DiscordId).ToList();
List<ulong> dbGuildIds = db.Guilds.Select(x => x.Id).ToList();

GuildDbEntity[] newGuildEntities = args.Guilds
.Where(x => !dbGuildIds.Contains(x.Key))
.Select(x => new GuildDbEntity
.Select(x => new GuildDbEntity(x.Value.Id)
{
DiscordId = x.Value.Id,
Settings = new GuildConfigDbEntity
{
DiscordGuildId = x.Value.Id,
GuildId = x.Value.Id,
Prefix = "",
StarboardActive = false
}
Expand Down
Loading

0 comments on commit 97b60f8

Please sign in to comment.