Skip to content

Commit

Permalink
Update to newer DSP version (#36)
Browse files Browse the repository at this point in the history
  • Loading branch information
Plerx2493 authored Jul 27, 2024
1 parent c0c7766 commit 4cc6137
Show file tree
Hide file tree
Showing 27 changed files with 207 additions and 385 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -34,16 +34,16 @@ public TranslateMessage(TranslateInformationService translateInformationService,
_translateInformationService = translateInformationService;
_translator = translator;
}

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

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

if (!isPreferredLanguageSet)
{
preferredLanguage = "en-US";
}
Expand All @@ -54,15 +54,15 @@ public async Task TranslateAsync(SlashCommandContext ctx, DiscordMessage target

if (messageContent.IsNullOrWhiteSpace())
{
await ctx.CreateResponse_Error("⚠️ Message is empty!");
await ctx.RespondErrorAsync("⚠️ Message is empty!");
return;
}
TextResult translatedMessage =

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

DiscordEmbedBuilder embed = new DiscordEmbedBuilder()
.WithAuthor(message.Author?.Username,
.WithAuthor(message.Author?.Username,
message.Author?.AvatarUrl)
.WithDescription(translatedMessage.Text)
.WithColor(new DiscordColor(0, 255, 194))
Expand All @@ -83,8 +83,8 @@ public async Task TranslateAsync(SlashCommandContext ctx, DiscordMessage target
.AddComponents(new DiscordButtonComponent(DiscordButtonStyle.Primary, "setLanguage", "Set your language to en-US")
.AsActionButton(ActionDiscordButtonEnum.SetTranslationLanguage, "en-US"))
.AsEphemeral();


await ctx.FollowupAsync(followUpMessage);
}
}
2 changes: 1 addition & 1 deletion ModularAssistentForDiscordServer/Commands/Slash/About.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public async Task AboutCommand(CommandContext ctx)
.AddField("D#+ Version:", ctx.Client.VersionString)
.AddField("Guilds", ctx.Client.Guilds.Count.ToString(), true)
.AddField("Uptime", date.Humanize(), true)
.AddField("Ping", $"{ctx.Client.Ping} ms", true)
.AddField("Ping", $"{ctx.Client.GetConnectionLatency(ctx.Guild?.Id ?? 0).TotalMilliseconds} ms", true)
.AddField("Add me", addMe);

discordMessageBuilder.AddEmbed(discordEmbedBuilder.Build());
Expand Down
10 changes: 6 additions & 4 deletions ModularAssistentForDiscordServer/Commands/Slash/BotStats.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
using DSharpPlus.Entities;
using Humanizer;
using MADS.Entities;
using MADS.Extensions;
using Microsoft.EntityFrameworkCore;

namespace MADS.Commands.Slash;
Expand All @@ -37,6 +38,7 @@ public BotStats(IDbContextFactory<MadsContext> contextFactory, DiscordRestClient
[Command("botstats"), Description("Get statistics about the bot")]
public async Task GetBotStatsAsync(CommandContext ctx)
{
await ctx.DeferAsync(true);
await using MadsContext db = await _contextFactory.CreateDbContextAsync();
Stopwatch swDb = new();
Stopwatch swRest = new();
Expand All @@ -46,16 +48,16 @@ public async Task GetBotStatsAsync(CommandContext ctx)
_ = await db.Guilds.FirstOrDefaultAsync();
swDb.Stop();

_ = await _discordRestClient.GetChannelAsync(ctx.Guild.Channels.Values.First().Id);
swRest.Start();
_ = await _discordRestClient.GetChannelAsync(ctx.Channel.Id);
swRest.Start();
_ = await _discordRestClient.GetUserAsync(ctx.User.Id);
swRest.Stop();

using Process process = Process.GetCurrentProcess();

int members = db.Users.Count();
int guilds = db.Guilds.Count();
int ping = ctx.Client.Ping;
TimeSpan ping = ctx.Client.GetConnectionLatency(0);
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true, true);
string heapMemory = $"{process.PrivateMemorySize64 / 1024 / 1024} MB";

Expand All @@ -66,7 +68,7 @@ public async Task GetBotStatsAsync(CommandContext ctx)
.AddField("Membercount:", members.ToString("N0"), true)
.AddField("Guildcount:", guilds.ToString("N0"), true)
.AddField("Threads:", $"{ThreadPool.ThreadCount}", true)
.AddField("Websocket Latency:", ping.ToString("N0") + " ms", true)
.AddField("Websocket Latency (Shard 0):", ping.TotalMilliseconds.ToString("N0") + " ms", true)
.AddField("DB Latency:", swDb.ElapsedMilliseconds.ToString("N0") + " ms", true)
.AddField("Rest Latency:", swRest.ElapsedMilliseconds.ToString("N0") + " ms", true)
.AddField("Memory:", heapMemory, true)
Expand Down
13 changes: 7 additions & 6 deletions ModularAssistentForDiscordServer/Commands/Slash/MessageSnipe.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
using System.ComponentModel;
using DSharpPlus;
using DSharpPlus.Commands;
using DSharpPlus.Commands.ContextChecks;
using DSharpPlus.Entities;
using MADS.CustomComponents;
using MADS.Extensions;
Expand All @@ -31,13 +32,13 @@ public MessageSnipe(MessageSnipeService messageSnipeService)
_messageSnipeService = messageSnipeService;
}

[Command("snipe"), Description("Snipes the last deleted message.")]
[Command("snipe"), Description("Snipes the last deleted message."), RequireGuild]
public async Task SnipeAsync(CommandContext ctx)
{
await DoSnipeAsync(ctx, false);
}

[Command("snipeedit"), Description("Snipes the last edited message.")]
[Command("snipeedit"), Description("Snipes the last edited message."), RequireGuild]
public async Task SnipeEditAsync(CommandContext ctx)
{
await DoSnipeAsync(ctx, true);
Expand All @@ -53,7 +54,7 @@ private async Task DoSnipeAsync(CommandContext ctx, bool edit)

if (!result || message is null)
{
await ctx.EditResponse_Error(
await ctx.RespondAsync(
"⚠️ No message to snipe! Either nothing was deleted, or the message has expired (12 hours)!");
return;
}
Expand All @@ -64,14 +65,14 @@ await ctx.EditResponse_Error(
content = string.Concat(content.AsSpan(0, 497), "...");
}

DiscordMember? member = message.Author is not null ? await ctx.Guild.GetMemberAsync(message.Author.Id) : null;
DiscordMember? member = message.Author is not null ? await ctx.Guild!.GetMemberAsync(message.Author.Id) : null;

DiscordEmbedBuilder embed = new DiscordEmbedBuilder()
.WithAuthor(
$"{member?.DisplayName ?? message.Author?.GlobalName}" + (edit ? " (Edited)" : ""),
iconUrl: message.Author?.GetAvatarUrl(ImageFormat.Png))
.WithFooter(
$"{(edit ? "Edit" : "Deletion")} sniped by {ctx.Member.DisplayName}",
$"{(edit ? "Edit" : "Deletion")} sniped by {ctx.Member!.DisplayName}",
ctx.User.AvatarUrl);

if (!string.IsNullOrEmpty(content))
Expand Down Expand Up @@ -124,6 +125,6 @@ public async Task DeleteSnipeAsync(CommandContext ctx)
_messageSnipeService.DeleteMessage(ctx.Channel.Id);
_messageSnipeService.DeleteEditedMessage(ctx.Channel.Id);

await ctx.EditResponse_Success("✅ Snipe cache cleared!");
await ctx.RespondSuccessAsync("✅ Snipe cache cleared!");
}
}
5 changes: 3 additions & 2 deletions ModularAssistentForDiscordServer/Commands/Slash/Ping.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,9 @@ public async Task PingCommand(CommandContext ctx)
.WithTitle("Status")
.WithTimestamp(DateTime.Now)
.WithColor(new DiscordColor(0, 255, 194))
.AddField("Uptime", $"{DateTimeOffset.UtcNow.Subtract(process.StartTime).Humanize(3, minUnit: TimeUnit.Millisecond, maxUnit: TimeUnit.Day)}")
.AddField("Websocket ping", $"{ctx.Client.Ping} ms");
.AddField("Uptime",
$"{DateTimeOffset.UtcNow.Subtract(process.StartTime).Humanize(3, minUnit: TimeUnit.Millisecond, maxUnit: TimeUnit.Day)}");
//.AddField("Websocket ping", $"{ctx.Client.Ping} ms");

DiscordInteractionResponseBuilder responseBuilder = new();
responseBuilder.AddEmbed(discordEmbedBuilder).AsEphemeral();
Expand Down
6 changes: 3 additions & 3 deletions ModularAssistentForDiscordServer/Commands/Slash/Purge.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,15 @@ public async Task PurgeMessages
{
if (amount > 100)
{
await ctx.CreateResponse_Error("You cannot purge more than 100 messages at once", true);
await ctx.RespondErrorAsync("You cannot purge more than 100 messages at once", true);
return;
}

await ctx.DeferAsync();
DiscordMessage? response = await ctx.GetResponseAsync()!;

List<DiscordMessage> messages = [];
await foreach (DiscordMessage msg in ctx.Channel.GetMessagesAsync((int) amount))
await foreach (DiscordMessage msg in ctx.Channel.GetMessagesAsync((int)amount))
{
messages.Add(msg);
}
Expand Down
8 changes: 4 additions & 4 deletions ModularAssistentForDiscordServer/Commands/Slash/Reminder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public async Task AddReminder

if (timeSpan is null)
{
await ctx.EditResponse_Error("Invalid timespan (5s, 3m, 7h, 2d)");
await ctx.RespondErrorAsync("Invalid timespan (5s, 3m, 7h, 2d)");
return;
}

Expand All @@ -71,7 +71,7 @@ public async Task AddReminder

ReminderDbEntity reminder = await _reminderService.AddReminder(newReminder);

await ctx.EditResponse_Success($"Reminder created with id `{reminder.Id}`. I will remind you in {Formatter.Timestamp(timeSpan.Value)}");
await ctx.RespondSuccessAsync($"Reminder created with id `{reminder.Id}`. I will remind you in {Formatter.Timestamp(timeSpan.Value)}");
}

[Command("list"), Description("list your Reminder")]
Expand Down Expand Up @@ -110,15 +110,15 @@ long id

if (reminder is null)
{
await ctx.EditResponse_Error("Reminder does not exists");
await ctx.RespondErrorAsync("Reminder does not exists");
return;
}

bool success = await _reminderService.TryDeleteById((ulong) id, ctx.User.Id);

if (!success)
{
await ctx.EditResponse_Error("Something went wrong. Are you sure you own this reminder?");
await ctx.RespondErrorAsync("Something went wrong. Are you sure you own this reminder?");
return;
}

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.GuildId == ctx.Guild.Id);
GuildConfigDbEntity guildConfig = db.Configs.First(x => x.GuildId == ctx.Guild!.Id);

if (!DiscordEmoji.TryFromUnicode(emojiString, out DiscordEmoji emoji))
{
Expand Down
26 changes: 13 additions & 13 deletions ModularAssistentForDiscordServer/Commands/Slash/Translation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,21 +29,21 @@ public class Translation
{
private readonly TranslateInformationService _translationUserInfo;
private readonly Translator _translator;

public Translation(TranslateInformationService translationUserInfo, Translator translator)
{
_translationUserInfo = translationUserInfo;
_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"}`");

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

[Command("setLanguage"), Description("Set your preferred language")]
public async Task SetLanguageAsync
(
Expand All @@ -54,15 +54,15 @@ public async Task SetLanguageAsync
{
if (string.IsNullOrWhiteSpace(language))
{
await ctx.CreateResponse_Error("⚠️ Language can't be empty!");
await ctx.RespondErrorAsync("⚠️ Language can't be empty!");
return;
}

string code = TranslateInformationService.StandardizeLang(language);

_translationUserInfo.SetPreferredLanguage(ctx.User.Id, code);
await ctx.CreateResponse_Success($"✅ Language set to {code}");

await ctx.RespondSuccessAsync($"✅ Language set to {code}");
}

[Command("translate"), Description("Translate a text")]
Expand All @@ -78,22 +78,22 @@ public async Task TranslateText
)
{
await ctx.DeferAsync();

if (string.IsNullOrWhiteSpace(text))
{
await ctx.EditResponseAsync(new DiscordWebhookBuilder()
.WithContent("⚠️ Text can't be empty!"));
return;
}

TextResult translatedText = await _translator.TranslateTextAsync(text, null, language);

DiscordEmbedBuilder embed = new DiscordEmbedBuilder()
.WithDescription(translatedText.Text)
.WithColor(new DiscordColor(0, 255, 194))
.WithFooter($"Translated from {translatedText.DetectedSourceLanguageCode} to {language}")
.WithTimestamp(DateTime.Now);

DiscordInteractionResponseBuilder responseBuilder = new();
responseBuilder.AddEmbed(embed).AsEphemeral(!publicResult);

Expand Down
Loading

0 comments on commit 4cc6137

Please sign in to comment.