Skip to content

Commit

Permalink
Fix naming and DI
Browse files Browse the repository at this point in the history
  • Loading branch information
Plerx2493 committed Jun 22, 2024
1 parent ba3893a commit a24333e
Show file tree
Hide file tree
Showing 13 changed files with 102 additions and 55 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,16 @@
using DSharpPlus.Commands.Processors.SlashCommands.ArgumentModifiers;
using MADS.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

namespace MADS.Commands.AutoCompletion;

public class ReminderAutoCompletion : IAutoCompleteProvider
{
private readonly IDbContextFactory<MadsContext> _factory;

public ReminderAutoCompletion(IServiceProvider services)
public ReminderAutoCompletion(IDbContextFactory<MadsContext> dbContextFactory)
{
_factory = services.GetRequiredService<IDbContextFactory<MadsContext>>();
_factory = dbContextFactory;
}

public async ValueTask<IReadOnlyDictionary<string, object>> AutoCompleteAsync(AutoCompleteContext context)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,25 +12,25 @@
// See the License for the specific language governing permissions and
// limitations under the License.

using DeepL;
using DeepL.Model;
using DSharpPlus.Commands.Processors.SlashCommands;
using DSharpPlus.Commands.Processors.SlashCommands.ArgumentModifiers;
using MADS.Services;

namespace MADS.Commands.AutoCompletion;

public class TargetLanguageAutoCompletion : IAutoCompleteProvider
{
private readonly Translator _translator;
private readonly TranslateInformationService _service;

public TargetLanguageAutoCompletion(Translator translator)
public TargetLanguageAutoCompletion(TranslateInformationService service)
{
_translator = translator;
_service = service;
}

public async ValueTask<IReadOnlyDictionary<string, object>> AutoCompleteAsync(AutoCompleteContext context)
{
TargetLanguage[] sourceLangs = await _translator.GetTargetLanguagesAsync();
TargetLanguage[] sourceLangs = await _service.GetTargetLanguagesAsync();
Dictionary<string, object> choices = sourceLangs
.Where(x => x.ToString().StartsWith(context.UserInput.ToString() ?? ""))
.Take(25)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,21 @@
using DSharpPlus.Entities;
using MADS.Entities;
using MADS.Services;
using Microsoft.Extensions.DependencyInjection;

namespace MADS.Commands.AutoCompletion;

public class VoiceAlertAutoCompletion : IAutoCompleteProvider
{
private readonly VoiceAlertService _voiceAlertService;

public VoiceAlertAutoCompletion(IServiceProvider services)
public VoiceAlertAutoCompletion(VoiceAlertService service)
{
_voiceAlertService = services.GetRequiredService<VoiceAlertService>();
_voiceAlertService = service;
}

public async ValueTask<IReadOnlyDictionary<string, object>> AutoCompleteAsync(AutoCompleteContext context)
{
IEnumerable<VoiceAlert> choices = await _voiceAlertService.GetVoiceAlerts(context.User.Id);
IEnumerable<VoiceAlert> choices = await _voiceAlertService.GetVoiceAlertsAsync(context.User.Id);

List<DiscordChannel> result = new();
foreach (VoiceAlert choice in choices)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@ public StealEmojiMessage(HttpClient httpClient)
_httpClient = httpClient;
}

[SlashCommandTypes(DiscordApplicationCommandType.MessageContextMenu),Command("Steal emoji(s)"),
[SlashCommandTypes(DiscordApplicationCommandType.MessageContextMenu), Command("Steal emoji(s)"),
RequirePermissions(DiscordPermissions.ManageEmojis)]
public async Task YoinkAsync(SlashCommandContext ctx, DiscordMessage targetMessage)
public async Task YoinkAsync(CommandContext ctx, DiscordMessage targetMessage)
{
await ctx.DeferAsync(true);

Expand Down Expand Up @@ -90,7 +90,7 @@ await ctx.EditResponseAsync(
await ctx.EditResponseAsync(discordWebhook);
}

private async Task<DiscordEmoji> CopyEmoji(SlashCommandContext ctx, string name, ulong id, bool animated)
private async Task<DiscordEmoji> CopyEmoji(CommandContext ctx, string name, ulong id, bool animated)
{
Stream downloadedEmoji =
await _httpClient.GetStreamAsync($"https://cdn.discordapp.com/emojis/{id}.{(animated ? "gif" : "png")}");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,20 +52,14 @@ public async Task TranslateAsync(SlashCommandContext ctx, DiscordMessage target
DiscordMessage message = await ctx.Channel.GetMessageAsync(messageId);
string? messageContent = message.Content;

if (messageContent.IsNullOrWhiteSpace() || messageContent is null)
if (messageContent.IsNullOrWhiteSpace())
{
await ctx.CreateResponse_Error("⚠️ Message is empty!");
return;
}

if (preferredLanguage is null)
{
await ctx.CreateResponse_Error("⚠️ No language set!");
return;
}

TextResult translatedMessage =
await _translator.TranslateTextAsync(messageContent, null, preferredLanguage);
await _translator.TranslateTextAsync(messageContent, null, preferredLanguage!);

DiscordEmbedBuilder embed = new DiscordEmbedBuilder()
.WithAuthor(message.Author?.Username,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,13 @@ public async Task GetUserInfo(SlashCommandContext ctx, DiscordUser targetUser)

try
{
if (!ctx.Channel.IsPrivate)
if (user is DiscordMember dMember)
{
member = await ctx.Guild.GetMemberAsync(user.Id);
member = dMember;
}
else if (!ctx.Channel.IsPrivate)
{
member = await ctx.Guild!.GetMemberAsync(user.Id);
}
}
catch (DiscordException e)
Expand Down
24 changes: 14 additions & 10 deletions ModularAssistentForDiscordServer/Commands/Slash/VoiceAlerts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
using System.Text;
using DSharpPlus.Commands;
using DSharpPlus.Commands.ArgumentModifiers;
using DSharpPlus.Commands.ContextChecks;
using DSharpPlus.Commands.Processors.SlashCommands.ArgumentModifiers;
using DSharpPlus.Entities;
using MADS.Commands.AutoCompletion;
Expand All @@ -35,15 +36,18 @@ public VoiceAlerts(VoiceAlertService voiceAlertService)
_voiceAlertService = voiceAlertService;
}

[Command("add"), Description("add a voicealert")]
[Command("add"), Description("add a voicealert"), RequireGuild]
public async Task AddAlert
(
CommandContext ctx,

[Description("channel which will be monitored"),
ChannelTypes(DiscordChannelType.Voice, DiscordChannelType.Stage)]
DiscordChannel channel,

[Description("time which has to pass between alerts")]
TimeSpan? minTimeBetween,

[Description("If the alert should be repeated or one shot. (Defaults to false (one shot))")]
bool repeat = false
)
Expand All @@ -61,15 +65,15 @@ await ctx.CreateResponse_Error(
true);
return;
}
IEnumerable<VoiceAlert> currentAlerts = await _voiceAlertService.GetVoiceAlerts(ctx.User.Id);

IEnumerable<VoiceAlert> currentAlerts = await _voiceAlertService.GetVoiceAlertsAsync(ctx.User.Id);
if (currentAlerts.Any(x => x.ChannelId == channel.Id))
{
await ctx.CreateResponse_Error($"<#{channel.Id}> is already in your VoiceAlerts", true);
return;
}

await _voiceAlertService.AddVoiceAlertAsync(ctx.User.Id, channel.Id, ctx.Guild.Id, repeat,
await _voiceAlertService.AddVoiceAlertAsync(ctx.User.Id, channel.Id, ctx.Guild!.Id, repeat,
minTimeBetween.Value);

await ctx.CreateResponse_Success($"Added <#{channel.Id}> to your VoiceAlerts", true);
Expand All @@ -90,23 +94,23 @@ string channel
await ctx.CreateResponse_Error($"**{channel}** is not a valid id", true);
return;
}
IEnumerable<VoiceAlert> currentAlerts = await _voiceAlertService.GetVoiceAlerts(ctx.User.Id);

IEnumerable<VoiceAlert> currentAlerts = await _voiceAlertService.GetVoiceAlertsAsync(ctx.User.Id);
if (!currentAlerts.Any(x => x.ChannelId == id))
{
await ctx.CreateResponse_Error($"<#{id}> is not in your VoiceAlerts", true);
return;
}
await _voiceAlertService.RemoveVoiceAlert(ctx.User.Id, id, ctx.Guild.Id);

await _voiceAlertService.RemoveVoiceAlertAsync(ctx.User.Id, id, ctx.Guild.Id);

Check warning on line 105 in ModularAssistentForDiscordServer/Commands/Slash/VoiceAlerts.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.

await ctx.CreateResponse_Success($"Removed <#{channel}> from your VoiceAlerts", true);
}

[Command("list"), Description("list all voicealerts")]
public async Task ListAlerts(CommandContext ctx)
{
IEnumerable<VoiceAlert> alerts = await _voiceAlertService.GetVoiceAlerts(ctx.User.Id);
IEnumerable<VoiceAlert> alerts = await _voiceAlertService.GetVoiceAlertsAsync(ctx.User.Id);
StringBuilder builder = new();
foreach (VoiceAlert alert in alerts)
{
Expand Down
30 changes: 20 additions & 10 deletions ModularAssistentForDiscordServer/Commands/Text/Base/Eval.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,16 @@
using DSharpPlus;
using DSharpPlus.Commands;
using DSharpPlus.Commands.ArgumentModifiers;
using DSharpPlus.Commands.ContextChecks;
using DSharpPlus.Commands.Processors.TextCommands;
using DSharpPlus.Entities;
using MADS.CommandsChecks;
using MADS.Services;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;

namespace MADS.Commands.Text.Base;

[RequireOwner]
[RequireApplicationOwner]
public class Eval
{
private DiscordCommandService _service;
Expand All @@ -52,22 +52,32 @@ await ctx.RespondAsync(new DiscordEmbedBuilder()
TestVariables globalVariables = new(ctx.Client, ctx, _service);

ScriptOptions? scriptOptions = ScriptOptions.Default;
scriptOptions = scriptOptions.WithImports("System", "System.Collections.Generic", "System.Linq",
"System.Text", "System.Threading.Tasks", "DSharpPlus", "DSharpPlus.Entities", "DSharpPlus.CommandsNext",
"DSharpPlus.Interactivity", "DSharpPlus.SlashCommands",
"MADS", "Humanizer");
scriptOptions = scriptOptions.WithImports(
"System",
"System.Collections.Generic",
"System.Linq",
"System.Text",
"System.Threading.Tasks",
"DSharpPlus",
"DSharpPlus.Entities",
"DSharpPlus.Commands",
"DSharpPlus.Interactivity",
"MADS",
"Humanizer"
);

scriptOptions = scriptOptions.WithReferences(AppDomain.CurrentDomain.GetAssemblies()
.Where(assembly =>
!assembly.IsDynamic
&& !string.IsNullOrWhiteSpace(
assembly.Location)));

Script<object>? script = CSharpScript.Create(csCode, scriptOptions, typeof(TestVariables));
script.Compile();

ScriptState<object>? result = await script.RunAsync(globalVariables);
if (result?.ReturnValue != null && !string.IsNullOrWhiteSpace(result.ReturnValue.ToString()))
{
await message.ModifyAsync(new DiscordEmbedBuilder
await message!.ModifyAsync(new DiscordEmbedBuilder
{
Title = "✅ Evaluation Result",
Description = result.ReturnValue.ToString()!,
Expand All @@ -76,7 +86,7 @@ await message.ModifyAsync(new DiscordEmbedBuilder
}
else
{
await message.ModifyAsync(new DiscordEmbedBuilder
await message!.ModifyAsync(new DiscordEmbedBuilder
{
Title = "✅ Evaluation Successful",
Description = "No result was returned.",
Expand All @@ -86,7 +96,7 @@ await message.ModifyAsync(new DiscordEmbedBuilder
}
catch (Exception ex)
{
await message.ModifyAsync(new DiscordEmbedBuilder
await message!.ModifyAsync(new DiscordEmbedBuilder
{
Title = "⚠️ Evaluation Failure",
Description = string.Concat("**", ex.GetType().ToString(), "**: ", ex.Message),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,9 +154,28 @@ params object[] args
actionCode = (int) ActionDiscordButtonEnum.AnswerDmChannel;
customId += actionCode + ":" + args[0];
break;


case 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 NotImplementedException("Action code not implemented");
throw new ArgumentOutOfRangeException(nameof(action), action, null);
}

string label = button.Label;
Expand Down
2 changes: 1 addition & 1 deletion ModularAssistentForDiscordServer/Entities/UserDbEntity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public class UserDbEntity
public string Username { get; set; }

[Column("prefered_language")]
public string PreferedLanguage { get; set; }
public string? PreferedLanguage { get; set; }

public List<IncidentDbEntity> Incidents { get; set; }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ public static async ValueTask DeferAsync(this CommandContext ctx, bool ephemeral
if (ctx is SlashCommandContext slashContext)
{
await slashContext.DeferResponseAsync(ephemeral);
return;
}

await ctx.DeferResponseAsync();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.

using DeepL;
using DeepL.Model;
using MADS.Entities;
using Microsoft.EntityFrameworkCore;

Expand All @@ -20,10 +22,14 @@ namespace MADS.Services;
public class TranslateInformationService
{
private readonly IDbContextFactory<MadsContext> _dbContextFactory;
private readonly Translator _translator;

private TargetLanguage[]? _targetLanguages;

public TranslateInformationService(IDbContextFactory<MadsContext> factory)
public TranslateInformationService(IDbContextFactory<MadsContext> factory, Translator translator)
{
_dbContextFactory = factory;
_translator = translator;
}

public async void SetPreferredLanguage(ulong userId, string language)
Expand Down Expand Up @@ -51,4 +57,15 @@ internal static string StandardizeLang(string code)
string[] strArray = code.Split(['-'], 2);
return strArray.Length != 1 ? strArray[0].ToLowerInvariant() + "-" + strArray[1].ToUpperInvariant() : strArray[0].ToLowerInvariant();
}

internal async ValueTask<TargetLanguage[]> GetTargetLanguagesAsync()
{
if (_targetLanguages is not null)
{
return _targetLanguages;
}

_targetLanguages = await _translator.GetTargetLanguagesAsync();
return _targetLanguages;
}
}
Loading

0 comments on commit a24333e

Please sign in to comment.