Skip to content

Commit

Permalink
apply editorconfig
Browse files Browse the repository at this point in the history
  • Loading branch information
Plerx2493 committed Feb 23, 2024
1 parent 7066f98 commit 9a4c75d
Show file tree
Hide file tree
Showing 42 changed files with 903 additions and 543 deletions.
32 changes: 32 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -687,3 +687,35 @@ ij_yaml_sequence_on_new_line = false
ij_yaml_space_before_colon = false
ij_yaml_spaces_within_braces = true
ij_yaml_spaces_within_brackets = true


###############################
# C# Coding Conventions #
###############################
[*.cs]

# File-scoped namespaces
csharp_style_namespace_declarations = file_scoped:error

# var preferences
csharp_style_var_for_built_in_types = false:error
csharp_style_var_when_type_is_apparent = false:error
csharp_style_var_elsewhere = false:error

# Pattern matching preferences
csharp_style_pattern_matching_over_is_with_cast_check = true:error
csharp_style_pattern_matching_over_as_with_null_check = true:error

# Null-checking preferences
csharp_style_throw_expression = true:error
csharp_style_conditional_delegate_call = true:error

# Modifier preferences
csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:error

# Expression-level preferences
csharp_prefer_braces = true:error
csharp_style_deconstructed_variable_declaration = true:error
csharp_prefer_simple_default_expression = true:error
csharp_style_pattern_local_over_anonymous_function = true:error
csharp_style_inlined_variable_declaration = true:error
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ public async Task<IEnumerable<DiscordAutoCompleteChoice>> Provider(AutocompleteC
}
*/

await using var db = await _factory.CreateDbContextAsync();
var choices = db.Reminders
await using MadsContext db = await _factory.CreateDbContextAsync();
IEnumerable<DiscordAutoCompleteChoice> choices = db.Reminders
.Where(x => x.UserId == ctx.User.Id)
.Select(x => x.Id.ToString())
.ToList()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
// limitations under the License.

using DeepL;
using DeepL.Model;
using DSharpPlus.Entities;
using DSharpPlus.SlashCommands;

Expand All @@ -29,8 +30,8 @@ public TargetLanguageAutoCompletion(Translator translator)

public async Task<IEnumerable<DiscordAutoCompleteChoice>> Provider(AutocompleteContext ctx)
{
var sourceLangs = await _translator.GetTargetLanguagesAsync();
var choices = sourceLangs
TargetLanguage[] sourceLangs = await _translator.GetTargetLanguagesAsync();
IEnumerable<DiscordAutoCompleteChoice> choices = sourceLangs
.Select(x => new DiscordAutoCompleteChoice(x.Name, x.Code))
.Take(25);
return choices;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

using DSharpPlus.Entities;
using DSharpPlus.SlashCommands;
using MADS.Entities;
using MADS.Services;
using Microsoft.Extensions.DependencyInjection;

Expand All @@ -30,13 +31,13 @@ public VoiceAlertAutoCompletion(IServiceProvider services)

public async Task<IEnumerable<DiscordAutoCompleteChoice>> Provider(AutocompleteContext ctx)
{
var choices = await _voiceAlertService.GetVoiceAlerts(ctx.User.Id);
IEnumerable<VoiceAlert> choices = await _voiceAlertService.GetVoiceAlerts(ctx.User.Id);

var result = new List<DiscordAutoCompleteChoice>();
List<DiscordAutoCompleteChoice> result = new();

foreach (var choice in choices)
foreach (VoiceAlert choice in choices)
{
var chn = ctx.Guild.GetChannel(choice.ChannelId);
DiscordChannel chn = ctx.Guild.GetChannel(choice.ChannelId);
result.Add(new DiscordAutoCompleteChoice(chn.Name, choice.ChannelId.ToString()));
}

Expand Down
29 changes: 0 additions & 29 deletions ModularAssistentForDiscordServer/Commands/CommandUtillity.cs

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ namespace MADS.Commands.ContextMenu;

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

public StealEmojiMessage(HttpClient httpClient)
{
Expand All @@ -42,30 +42,33 @@ public async Task YoinkAsync(ContextMenuContext ctx)
return;
}

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

if (matches.Count < 1)
{
await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("⚠️ Emoji not found!"));
return;
}

var distinctMatches = matches.DistinctBy(x => x.Value).ToList();
List<Match> distinctMatches = matches.DistinctBy(x => x.Value).ToList();

var newEmojis = new List<DiscordEmoji>();
List<DiscordEmoji> newEmojis = new();

foreach (var match in distinctMatches)
foreach (Match match in distinctMatches)
{
try
{
var split = match.Groups[2].Value;
var emojiName = match.Groups[1].Value;
var animated = match.Value.StartsWith("<a");
string split = match.Groups[2].Value;
string emojiName = match.Groups[1].Value;
bool animated = match.Value.StartsWith("<a");

if (!ulong.TryParse(split, out var emojiId))
if (!ulong.TryParse(split, out ulong emojiId))
{
await ctx.EditResponseAsync(
new DiscordWebhookBuilder().WithContent("⚠️ Failed to fetch your new emoji."));
var success = await CopyEmoji(ctx, emojiName, emojiId, animated);
}

DiscordEmoji success = await CopyEmoji(ctx, emojiName, emojiId, animated);

newEmojis.Add(success);
}
Expand All @@ -77,27 +80,27 @@ await ctx.EditResponseAsync(
await IntendedWait(500);
}

var message = newEmojis.Aggregate("✅ Yoink! These emoji(s) have been added to your server: ",
string message = newEmojis.Aggregate("✅ Yoink! These emoji(s) have been added to your server: ",
(current, emoji) => current + $" {emoji}");
message += $" {newEmojis.Count}/{distinctMatches.Count} emojis added";

var discordWebhook = new DiscordWebhookBuilder().AddEmbed(
DiscordWebhookBuilder discordWebhook = new DiscordWebhookBuilder().AddEmbed(
new DiscordEmbedBuilder().WithTitle(message));

await ctx.EditResponseAsync(discordWebhook);
}

private async Task<DiscordEmoji> CopyEmoji(ContextMenuContext ctx, string name, ulong id, bool animated)
{
var downloadedEmoji =
Stream downloadedEmoji =
await _httpClient.GetStreamAsync($"https://cdn.discordapp.com/emojis/{id}.{(animated ? "gif" : "png")}");

MemoryStream memory = new();

await downloadedEmoji.CopyToAsync(memory);

await downloadedEmoji.DisposeAsync();
var 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 @@ -13,6 +13,7 @@
// limitations under the License.

using DeepL;
using DeepL.Model;
using DSharpPlus;
using DSharpPlus.Entities;
using DSharpPlus.SlashCommands;
Expand All @@ -39,14 +40,17 @@ public async Task TranslateAsync(ContextMenuContext ctx)
{
await ctx.DeferAsync(true);

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

if(!isPreferredLanguageSet) preferredLanguage = "en-US";

var messageId = ctx.TargetMessage.Id;
var message = await ctx.Channel.GetMessageAsync(messageId);
var messageContent = message.Content;
if(!isPreferredLanguageSet)
{
preferredLanguage = "en-US";
}

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

if (messageContent.IsNullOrWhiteSpace() || messageContent is null)
{
Expand All @@ -60,22 +64,25 @@ public async Task TranslateAsync(ContextMenuContext ctx)
return;
}

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

var embed = new DiscordEmbedBuilder()
DiscordEmbedBuilder embed = new DiscordEmbedBuilder()
.WithAuthor(message.Author?.Username,
message.Author?.AvatarUrl)
.WithDescription(transaltedMessage.Text)
.WithDescription(translatedMessage.Text)
.WithColor(new DiscordColor(0, 255, 194))
.WithFooter($"Translated from {transaltedMessage.DetectedSourceLanguageCode} to {preferredLanguage}")
.WithFooter($"Translated from {translatedMessage.DetectedSourceLanguageCode} to {preferredLanguage}")
.WithTimestamp(DateTime.Now);

await ctx.CreateResponseAsync(embed);

if (isPreferredLanguageSet) return;
if (isPreferredLanguageSet)
{
return;
}

var followUpMessage = new DiscordFollowupMessageBuilder()
DiscordFollowupMessageBuilder followUpMessage = new DiscordFollowupMessageBuilder()
.WithContent("⚠️ You haven't set a preferred language yet. Default is english.")
.AddComponents(new DiscordButtonComponent(ButtonStyle.Primary, "setLanguage", "Set language").AsActionButton(ActionDiscordButtonEnum.SetTranslationLanguage))
.AddComponents(new DiscordButtonComponent(ButtonStyle.Primary, "setLanguage", "Set your language to en-US").AsActionButton(ActionDiscordButtonEnum.SetTranslationLanguage, "en-US"))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,22 +26,28 @@ public class UserInfoUser : MadsBaseApplicationCommand
[ContextMenu(ApplicationCommandType.UserContextMenu, "Info")]
public async Task GetUserInfo(ContextMenuContext ctx)
{
var user = ctx.TargetUser;
DiscordUser user = ctx.TargetUser;

DiscordMember? member = null;

try
{
if (!ctx.Channel.IsPrivate) member = await ctx.Guild.GetMemberAsync(user.Id);
if (!ctx.Channel.IsPrivate)
{
member = await ctx.Guild.GetMemberAsync(user.Id);
}
}
catch (DiscordException e)
{
if (e.GetType() != typeof(NotFoundException)) throw;
if (e.GetType() != typeof(NotFoundException))
{
throw;
}
}

DiscordEmbedBuilder embed = new();

var userUrl = "https://discordapp.com/users/" + user.Id;
string userUrl = "https://discordapp.com/users/" + user.Id;

embed
.WithAuthor($"{user.Username}#{user.Discriminator}", userUrl, user.AvatarUrl)
Expand All @@ -56,15 +62,21 @@ public async Task GetUserInfo(ContextMenuContext ctx)
embed.AddField("Joined at:",
$"{member.JoinedAt.Humanize()} {Formatter.Timestamp(member.JoinedAt, TimestampFormat.ShortDate)}",
true);
if (member.MfaEnabled.HasValue) embed.AddField("2FA:", member.MfaEnabled.ToString()!);
if (member.MfaEnabled.HasValue)
{
embed.AddField("2FA:", member.MfaEnabled.ToString()!);
}

embed.AddField("Permissions:", member.Permissions.Humanize());

embed.AddField("Hierarchy:",
member.Hierarchy != int.MaxValue ? member.Hierarchy.ToString() : "Server owner", true);


if (member.Roles.Any()) embed.AddField("Roles", member.Roles.Select(x => x.Name).Humanize());
if (member.Roles.Any())
{
embed.AddField("Roles", member.Roles.Select(x => x.Name).Humanize());
}
}

await ctx.CreateResponseAsync(embed.Build(), true);
Expand Down
12 changes: 6 additions & 6 deletions ModularAssistentForDiscordServer/Commands/Slash/About.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,14 @@ public sealed class About : MadsBaseApplicationCommand
[SlashCommand("about", "Infos about the bot")]
public async Task AboutCommand(InteractionContext ctx)
{
var discordEmbedBuilder = CommandUtility.GetDiscordEmbed();
var discordMessageBuilder = new DiscordInteractionResponseBuilder();
var inviteUri = ctx.Client.CurrentApplication.GenerateOAuthUri(null, Permissions.Administrator, DiscordOAuthScope.Bot,
DiscordEmbedBuilder discordEmbedBuilder = new();
DiscordInteractionResponseBuilder discordMessageBuilder = new();
string inviteUri = ctx.Client.CurrentApplication.GenerateOAuthUri(null, Permissions.Administrator, DiscordOAuthScope.Bot,
DiscordOAuthScope.ApplicationsCommands);
var addMe = $"[Click here!]({inviteUri.Replace(" ", "%20")})";
string addMe = $"[Click here!]({inviteUri.Replace(" ", "%20")})";

var diff = DateTime.Now - CommandService.StartTime;
var date = $"{diff.Days} days {diff.Hours} hours {diff.Minutes} minutes";
TimeSpan diff = DateTime.Now - CommandService.StartTime;
string date = $"{diff.Days} days {diff.Hours} hours {diff.Minutes} minutes";

discordEmbedBuilder
.WithTitle("About me")
Expand Down
26 changes: 13 additions & 13 deletions ModularAssistentForDiscordServer/Commands/Slash/BotStats.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,29 +38,29 @@ public BotStats(IDbContextFactory<MadsContext> contextFactory, DiscordRestClient
[SlashCommand("botstats", "Get statistics about the bot")]
public async Task GetBotStatsAsync(InteractionContext ctx)
{
await using var db = await _contextFactory.CreateDbContextAsync();
var swDb = new Stopwatch();
var swRest = new Stopwatch();
await using MadsContext db = await _contextFactory.CreateDbContextAsync();
Stopwatch swDb = new();
Stopwatch swRest = new();

var _ = await db.Users.FirstOrDefaultAsync();
_ = await db.Users.FirstOrDefaultAsync();
swDb.Start();
var __ = await db.Guilds.FirstOrDefaultAsync();
_ = await db.Guilds.FirstOrDefaultAsync();
swDb.Stop();

var ___ = await _discordRestClient.GetChannelAsync(ctx.Guild.Channels.Values.First().Id);
_ = await _discordRestClient.GetChannelAsync(ctx.Guild.Channels.Values.First().Id);
swRest.Start();
var ____ = await _discordRestClient.GetChannelAsync(ctx.Channel.Id);
_ = await _discordRestClient.GetChannelAsync(ctx.Channel.Id);
swRest.Stop();

using var process = Process.GetCurrentProcess();
using Process process = Process.GetCurrentProcess();

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

var embed = new DiscordEmbedBuilder();
DiscordEmbedBuilder embed = new();
embed
.WithTitle("Statistics")
.WithColor(new DiscordColor(0, 255, 194))
Expand Down
Loading

0 comments on commit 9a4c75d

Please sign in to comment.