Skip to content

Commit

Permalink
Migrate other commands and add checks
Browse files Browse the repository at this point in the history
  • Loading branch information
Plerx2493 committed May 8, 2024
1 parent 74f7a64 commit 7e8989c
Show file tree
Hide file tree
Showing 11 changed files with 179 additions and 80 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,15 @@
// limitations under the License.

using System.Text.RegularExpressions;
using DSharpPlus.Commands;
using DSharpPlus.Commands.ContextChecks;
using DSharpPlus.Commands.Processors.SlashCommands;
using DSharpPlus.Entities;
using MADS.Extensions;

namespace MADS.Commands.ContextMenu;

public partial class StealEmojiMessage : MadsBaseApplicationCommand
public partial class StealEmojiMessage
{
private readonly HttpClient _httpClient;

Expand All @@ -26,19 +30,19 @@ public StealEmojiMessage(HttpClient httpClient)
_httpClient = httpClient;
}

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

if (ctx.TargetMessage.Content is null)
if (string.IsNullOrWhiteSpace(targetMessage.Content))
{
await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("⚠️ Message has not content!"));
return;
}

MatchCollection matches = EmojiRegex().Matches(ctx.TargetMessage.Content.Replace("><", "> <"));
MatchCollection matches = EmojiRegex().Matches(targetMessage.Content.Replace("><", "> <"));

if (matches.Count < 1)
{
Expand Down Expand Up @@ -73,7 +77,7 @@ await ctx.EditResponseAsync(
// ignored
}

await IntendedWait(500);
await Task.Delay(500);
}

string message = newEmojis.Aggregate("✅ Yoink! These emoji(s) have been added to your server: ",
Expand All @@ -86,7 +90,7 @@ await ctx.EditResponseAsync(
await ctx.EditResponseAsync(discordWebhook);
}

private async Task<DiscordEmoji> CopyEmoji(ContextMenuContext ctx, string name, ulong id, bool animated)
private async Task<DiscordEmoji> CopyEmoji(SlashCommandContext ctx, string name, ulong id, bool animated)
{
Stream downloadedEmoji =
await _httpClient.GetStreamAsync($"https://cdn.discordapp.com/emojis/{id}.{(animated ? "gif" : "png")}");
Expand All @@ -96,7 +100,7 @@ private async Task<DiscordEmoji> CopyEmoji(ContextMenuContext ctx, string name,
await downloadedEmoji.CopyToAsync(memory);

await downloadedEmoji.DisposeAsync();
DiscordGuildEmoji newEmoji = await ctx.Guild.CreateEmojiAsync(name, memory);
DiscordGuildEmoji newEmoji = await ctx.Guild!.CreateEmojiAsync(name, memory);

return newEmoji;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,17 @@

using DeepL;
using DeepL.Model;
using DSharpPlus.Commands;
using DSharpPlus.Commands.Processors.SlashCommands;
using DSharpPlus.Entities;
using MADS.CustomComponents;
using MADS.Extensions;
using MADS.Services;
using Quartz.Util;

namespace MADS.Commands.ContextMenu;

public class TranslateMessage : MadsBaseApplicationCommand
public class TranslateMessage
{
private readonly TranslateInformationService _translateInformationService;
private readonly Translator _translator;
Expand All @@ -32,8 +35,8 @@ public TranslateMessage(TranslateInformationService translateInformationService,
_translator = translator;
}

[ContextMenu(DiscordApplicationCommandType.MessageContextMenu, "Translate message")]
public async Task TranslateAsync(ContextMenuContext ctx)
[SlashCommandTypes(DiscordApplicationCommandType.MessageContextMenu), Command("Translate message")]
public async Task TranslateAsync(SlashCommandContext ctx, DiscordMessage targetMessage)
{
await ctx.DeferAsync(true);

Expand All @@ -45,19 +48,19 @@ public async Task TranslateAsync(ContextMenuContext ctx)
preferredLanguage = "en-US";
}

ulong messageId = ctx.TargetMessage.Id;
ulong messageId = targetMessage.Id;
DiscordMessage message = await ctx.Channel.GetMessageAsync(messageId);
string? messageContent = message.Content;

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

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

Expand All @@ -72,7 +75,7 @@ public async Task TranslateAsync(ContextMenuContext ctx)
.WithFooter($"Translated from {translatedMessage.DetectedSourceLanguageCode} to {preferredLanguage}")
.WithTimestamp(DateTime.Now);

await ctx.CreateResponseAsync(embed);
await ctx.RespondAsync(embed);

if (isPreferredLanguageSet)
{
Expand All @@ -86,6 +89,6 @@ public async Task TranslateAsync(ContextMenuContext ctx)
.AsEphemeral();


await ctx.FollowUpAsync(followUpMessage);
await ctx.FollowupAsync(followUpMessage);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,20 @@
// limitations under the License.

using DSharpPlus;
using DSharpPlus.Commands;
using DSharpPlus.Commands.Processors.SlashCommands;
using DSharpPlus.Entities;
using DSharpPlus.Exceptions;
using Humanizer;

namespace MADS.Commands.ContextMenu;

public class UserInfoUser : MadsBaseApplicationCommand
public class UserInfoUser
{
[ContextMenu(DiscordApplicationCommandType.UserContextMenu, "Info")]
public async Task GetUserInfo(ContextMenuContext ctx)
[SlashCommandTypes(DiscordApplicationCommandType.UserContextMenu), Command("Info")]
public async Task GetUserInfo(SlashCommandContext ctx, DiscordUser targetUser)
{
DiscordUser user = ctx.TargetUser;
DiscordUser user = targetUser;

DiscordMember? member = null;

Expand Down Expand Up @@ -77,6 +79,6 @@ public async Task GetUserInfo(ContextMenuContext ctx)
}
}

await ctx.CreateResponseAsync(embed.Build(), true);
await ctx.RespondAsync(embed.Build(), true);
}
}
14 changes: 3 additions & 11 deletions ModularAssistentForDiscordServer/Commands/Text/Base/Eval.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
using DSharpPlus.Commands.ArgumentModifiers;
using DSharpPlus.Commands.Processors.TextCommands;
using DSharpPlus.Entities;
using MADS.CommandsChecks;
using MADS.Services;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
Expand All @@ -35,18 +36,9 @@ public Eval(DiscordClientService service)
}

[Command("eval"), Description("Evaluate the result of c# code")]
public async Task EvalCommand(CommandContext ctx, [RemainingText] string code)
public async Task EvalCommand(TextCommandContext ctx, [FromCode] string code)
{
int codeStart = code.IndexOf("```", StringComparison.Ordinal) + 3;
codeStart = code.IndexOf('\n', codeStart) + 1;
int codeEnd = code.LastIndexOf("```", StringComparison.Ordinal);

if (codeStart == -1 || codeEnd == -1)
{
throw new ArgumentException("⚠️ You need to wrap the code into a code block.");
}

string csCode = code[codeStart..codeEnd];
string csCode = code;

await ctx.RespondAsync(new DiscordEmbedBuilder()
.WithColor(new DiscordColor("#FF007F"))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,23 @@
using System.ComponentModel;
using DSharpPlus.Commands;
using DSharpPlus.Commands.ContextChecks;
using DSharpPlus.Commands.Processors.TextCommands;
using DSharpPlus.Entities;
using MADS.CommandsChecks;

namespace MADS.Commands.Text.Base;

public class ExitGuild
{
[Command("exit"), Description("Exit the bot"), RequirePermissions(DiscordPermissions.ManageGuild), RequireGuild]
public async Task ExitGuildCommand(CommandContext ctx)
public async Task ExitGuildCommand(TextCommandContext ctx)
{
await ctx.RespondAsync("Leaving server...");
await ctx.Guild.LeaveAsync();
}

[Command("leave"), Description("Leave given server"), RequireGuild, Hidden, RequireOwner]
public async Task LeaveGuildOwner(CommandContext ctx)
[Command("leave"), Description("Leave given server"), RequireGuild, RequireOwner]
public async Task LeaveGuildOwner(TextCommandContext ctx)
{
await ctx.Message.DeleteAsync();
await ctx.Guild.LeaveAsync();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// Copyright 2023 Plerx2493
//
// Licensed under the Apache License, Version 2.0 (the "License")
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using DSharpPlus.Commands;
using DSharpPlus.Commands.ContextChecks;
using DSharpPlus.Entities;
using MADS.Entities;
using Microsoft.EntityFrameworkCore;

namespace MADS.CommandsChecks;

public class EnsureDBEntitiesCheck : IContextCheck<UnconditionalCheckAttribute>
{
private IDbContextFactory<MadsContext> _contextFactory;

public EnsureDBEntitiesCheck(IDbContextFactory<MadsContext> dbContextFactory)
{
_contextFactory = dbContextFactory;
}

public async ValueTask<string?> ExecuteCheckAsync(UnconditionalCheckAttribute _, CommandContext context)
{
DiscordUser user = context.User;

await using MadsContext dbContext = await _contextFactory.CreateDbContextAsync();

UserDbEntity userdbEntity = new()
{
Id = user.Id,
Username = user.Username,
PreferedLanguage = "en-US"
};

await dbContext.Users.Upsert(userdbEntity)
.On(x => x.Id)
.NoUpdate()
.RunAsync();

if (context.Guild is null)
{
return null;
}

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

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

return null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Copyright 2023 Plerx2493
//
// Licensed under the Apache License, Version 2.0 (the "License")
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using DSharpPlus.Commands.ContextChecks;

namespace MADS.CommandsChecks;

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class), ]
public class RequireOwnerAttribute : ContextCheckAttribute
{

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Copyright 2023 Plerx2493
//
// Licensed under the Apache License, Version 2.0 (the "License")
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using DSharpPlus.Commands;
using DSharpPlus.Commands.ContextChecks;
using DSharpPlus.Entities;

namespace MADS.CommandsChecks;

public class RequireOwnerCheck : IContextCheck<RequireOwnerAttribute>
{
public ValueTask<string?> ExecuteCheckAsync(RequireOwnerAttribute attribute, CommandContext context)
{
DiscordApplication app = context.Client.CurrentApplication;
DiscordUser me = context.Client.CurrentUser;

bool isOwner = app is not null ? app!.Owners!.Any(x => x.Id == context.User.Id) : context.User.Id == me.Id;

if (!isOwner)
{
return ValueTask.FromResult<string?>("User must be on of the application owner");
}

return ValueTask.FromResult<string?>(null);
}
}
Loading

0 comments on commit 7e8989c

Please sign in to comment.