Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

♻️ Lot of analyser fixes #399

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 5 additions & 8 deletions src/HonzaBotner.Discord.Services/Commands/EmoteCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,20 +59,17 @@ public async Task EmoteStatsCommandAsync(
continue;
}

if (emoji.IsAnimated && type == DisplayTypes.Still)
switch (emoji.IsAnimated)
{
continue;
}

if (!emoji.IsAnimated && type == DisplayTypes.Animated)
{
continue;
case true when type == DisplayTypes.Still:
case false when type == DisplayTypes.Animated:
continue;
}

string label = total ? "×" : "×/day";

builder.Append(emoji)
.Append("`")
.Append('`')
.Append(
(total
? result.Used.ToString()
Expand Down
9 changes: 4 additions & 5 deletions src/HonzaBotner.Discord.Services/Commands/FunCommands.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
Expand All @@ -21,7 +20,7 @@ public async Task ChooseCommandAsync(
string delimiter = ","
)
{
var answers = options.Split(delimiter, StringSplitOptions.TrimEntries & StringSplitOptions.RemoveEmptyEntries)
string[] answers = options.Split(delimiter)
.Select(option => option.Trim().RemoveDiscordMentions(ctx.Guild))
.Where(option => option != "").ToArray();
if (answers.Length == 0)
Expand All @@ -31,13 +30,13 @@ public async Task ChooseCommandAsync(
}
Random random = new();
var text = new StringBuilder("I picked: ");
var winNumber = random.Next(answers.Length);
var winner = answers[winNumber];
int winNumber = random.Next(answers.Length);
string winner = answers[winNumber];
Comment on lines 32 to +34
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You marked this change as inconsistent in PR #317 (here)

text.Append("`" + winner + "`");
if (answers.Length > 1)
{
text.Append("\nOptions were:\n");
foreach (var option in answers)
foreach (string option in answers)
{
text.Append("`" + option+ "`, ");
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DSharpPlus;
using DSharpPlus.Entities;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,15 @@ public ModerationCommands(IWarningService warningService, ILogger<ModerationComm
public async Task WarnMenuAsync(ContextMenuContext ctx)
{
string modalId = $"warn-{ctx.User.Id}-{ctx.TargetUser.Id}";
string reasonId = "id-reason";
const string reasonId = "id-reason";

var response = new DiscordInteractionResponseBuilder()
.WithTitle($"New Warning for {ctx.TargetMember.DisplayName}")
.WithCustomId(modalId)
.AddComponents(new TextInputComponent("Reason:", reasonId, required: true));
await ctx.CreateResponseAsync(InteractionResponseType.Modal, response);

var numberOfWarnings = await _warningService.GetNumberOfWarnings(ctx.TargetUser.Id);
int numberOfWarnings = await _warningService.GetNumberOfWarnings(ctx.TargetUser.Id);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same goes here link


var interactivity = ctx.Client.GetInteractivity();
var modalReason = await interactivity.WaitForModalAsync(modalId, TimeSpan.FromMinutes(10));
Expand Down Expand Up @@ -104,9 +104,9 @@ await buttonResponse.Result.Interaction.CreateResponseAsync(InteractionResponseT
[SlashCommand("show", "Show moderation entry with provided Id.")]
public async Task ShowCommandAsync(
InteractionContext ctx,
[Option("Id", "Id of the entry to show")] long entryid)
[Option("Id", "Id of the entry to show")] long entryId)
{
Warning? warning = await _warningService.GetWarningAsync((int) entryid);
Warning? warning = await _warningService.GetWarningAsync((int) entryId);

if (warning is null)
{
Expand Down
6 changes: 3 additions & 3 deletions src/HonzaBotner.Discord.Services/Commands/Polls/Poll.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,13 @@ protected Poll(DiscordMessage originalMessage)
{
ExistingPollMessage = originalMessage;
DiscordEmbed originalPoll = ExistingPollMessage.Embeds[0];
int startIndex = originalPoll.Description.LastIndexOf("<", StringComparison.Ordinal);

// Extract original author Mention via discord's mention format <@!123456789>.
AuthorMention = originalPoll.Description.Substring(
originalPoll.Description.LastIndexOf("<", StringComparison.Ordinal)
);
AuthorMention = originalPoll.Description[startIndex..];

Question = originalPoll.Title;
NewChoices = new List<string>();
}

public async Task PostAsync(DiscordClient client, DiscordChannel channel)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public async Task<EventHandlerResult> Handle(ComponentInteractionCreateEventArgs

DiscordUser user = eventArgs.User;
DiscordMember member = await eventArgs.Guild.GetMemberAsync(user.Id);
var builder = new DiscordInteractionResponseBuilder().AsEphemeral(true);
var builder = new DiscordInteractionResponseBuilder().AsEphemeral();

// Check if the button to remove staff roles was pressed.
if (eventArgs.Id == _buttonOptions.StaffRemoveRoleId)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public async Task<EventHandlerResult> Handle(ComponentInteractionCreateEventArgs
_translation.SetLanguage(ITranslation.Language.Czech);
}

DiscordInteractionResponseBuilder builder = new DiscordInteractionResponseBuilder().AsEphemeral(true);
DiscordInteractionResponseBuilder builder = new DiscordInteractionResponseBuilder().AsEphemeral();
DiscordUser user = eventArgs.User;
DiscordMember member = await eventArgs.Guild.GetMemberAsync(user.Id);
string link = _urlProvider.GetAuthLink(user.Id, RolesPool.Auth);
Expand Down
22 changes: 12 additions & 10 deletions src/HonzaBotner.Discord.Services/Extensions/DiscordExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,23 +62,25 @@ public static IEnumerable<Page> GeneratePages(this InteractivityExtension _,
string descriptionValue = description;
if (description.Length > 250)
{
descriptionValue = description.Substring(0, 250) + "...";
descriptionValue = description[..250] + "...";
}

embed.AddField(name, descriptionValue);
item++;

if (item == pageRows || page * pageRows + item == items.Count)
if (item != pageRows && page * pageRows + item != items.Count)
{
item = 0;
page++;
result.Add(
new Page("",
new DiscordEmbedBuilder(embed).WithFooter($"Page {page}/{pagesCount}")
)
);
embed.ClearFields();
continue;
}

item = 0;
page++;
result.Add(
new Page("",
new DiscordEmbedBuilder(embed).WithFooter($"Page {page}/{pagesCount}")
)
);
embed.ClearFields();
}

return result;
Expand Down
38 changes: 20 additions & 18 deletions src/HonzaBotner.Discord.Services/Extensions/StringExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using System.Text.RegularExpressions;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using DSharpPlus.Entities;
using DSharpPlus.Exceptions;
Expand Down Expand Up @@ -36,26 +35,29 @@ public static string RemoveDiscordMentions(
private static async Task<string> MentionEvaluateAsync(Match match, DiscordGuild? guild)
{
// Invalidate ID pings, replacing them with their name (only in guilds)
if (guild is not null && match.Groups.TryGetValue("2", out Group? idMention) && idMention.Value != "")
if (guild is null || !match.Groups.TryGetValue("2", out Group? idMention) || idMention.Value == "")
{
ulong snowflakeId = ulong.Parse(idMention.Value);
return match.Value.Replace("@",
"@" + char.ConvertFromUtf32(int.Parse("200b", System.Globalization.NumberStyles.HexNumber)));
}

if (match.Groups.TryGetValue("1", out Group? idType) && idType.Value == "&")
{
DiscordRole mentionedRole = guild.GetRole(snowflakeId);
if (mentionedRole is not null)
return mentionedRole.Name.RemoveDiscordMentions();
}
else
ulong snowflakeId = ulong.Parse(idMention.Value);

if (match.Groups.TryGetValue("1", out Group? idType) && idType.Value == "&")
{
DiscordRole mentionedRole = guild.GetRole(snowflakeId);
if (mentionedRole is not null)
return mentionedRole.Name.RemoveDiscordMentions();
}
else
{
try
{
try
{
DiscordMember mentionedMember = await guild.GetMemberAsync(snowflakeId);
return mentionedMember.DisplayName.RemoveDiscordMentions();
}
catch (NotFoundException)
{}
DiscordMember mentionedMember = await guild.GetMemberAsync(snowflakeId);
return mentionedMember.DisplayName.RemoveDiscordMentions();
}
catch (NotFoundException)
{}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure if this change increases readability. There is also duplicite code now.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Github changed it... This review was for the changes in the whole file StringExtensions.cs


// Invalidate @everyone, @here, or pings which have correct ID format, but no name was found for them
Expand Down
2 changes: 1 addition & 1 deletion src/HonzaBotner.Discord.Services/Helpers/StandUpStats.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public void Increment(string priority)
}
}

public int Sum => _normal + _must;
private int Sum => _normal + _must;

public override string ToString()
{
Expand Down
2 changes: 1 addition & 1 deletion src/HonzaBotner.Discord.Services/Jobs/NewsJobProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public class NewsJobProvider : IJob
{
private const int RunOffset = -3;

public string Name { get; } = "news-publisher";
public string Name => "news-publisher";

private readonly ILogger<NewsJobProvider> _logger;
private readonly INewsConfigService _configService;
Expand Down
5 changes: 1 addition & 4 deletions src/HonzaBotner.Discord.Services/Managers/ReminderManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,16 @@
using HonzaBotner.Discord.Services.Extensions;
using HonzaBotner.Discord.Managers;
using HonzaBotner.Services.Contract.Dto;
using Microsoft.Extensions.Logging;

namespace HonzaBotner.Discord.Services.Managers;

public class ReminderManager : IReminderManager
{
private readonly IGuildProvider _guildProvider;
private readonly ILogger<ReminderManager> _logger;

public ReminderManager(IGuildProvider guildProvider, ILogger<ReminderManager> logger)
public ReminderManager(IGuildProvider guildProvider)
{
_guildProvider = guildProvider;
_logger = logger;
}

public async Task<DiscordEmbed> CreateDmReminderEmbedAsync(Reminder reminder)
Expand Down
2 changes: 1 addition & 1 deletion src/HonzaBotner.Discord.Services/Managers/VoiceManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ public async Task DeleteAllUnusedVoiceChannelsAsync()
private string? ConvertStringToValidState(string? input, string? defaultValue = null)
{
input = Regex.Replace(input ?? "", @"\p{C}+", string.Empty);
return input.Trim().Length == 0 ? defaultValue : input.Substring(0, Math.Min(input.Length, 30));
return input.Trim().Length == 0 ? defaultValue : input[..Math.Min(input.Length, 30)];
Comment on lines 129 to +130
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is really cool. Feels like python :D

}

private async Task EditChannelAsync(bool isEdit, DiscordChannel? channel, string? name, long? limit,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ private static string Limit(string str, int limit)
return str;
}

StringBuilder sb = new(str.Substring(0, limit - 1 - andMore.Length));
StringBuilder sb = new(str [ ..(limit - 1 - andMore.Length)]);
sb.Append(andMore);

return sb.ToString();
Expand All @@ -42,7 +42,7 @@ public async Task Publish(News news, params ulong[] channels)
{
// Embed titles are limited to 256 characters
Title = Limit(news.Title, 256),
Author = new DiscordEmbedBuilder.EmbedAuthor()
Author = new DiscordEmbedBuilder.EmbedAuthor
{
// The author name is limited to 256 characters
Name = Limit(news.Author, 256)
Expand Down
10 changes: 7 additions & 3 deletions src/HonzaBotner.Discord.Services/Utils/Translation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,19 +69,23 @@ public class Translation : ITranslation
},
{
"RemoveRolesButton",
new() { { ITranslation.Language.Czech, "Odebrat role" }, { ITranslation.Language.English, "Remove roles" } }
new Dictionary<ITranslation.Language, string>
{
{ ITranslation.Language.Czech, "Odebrat role" },
{ ITranslation.Language.English, "Remove roles" }
}
},
{
"VerifyStaff",
new()
new Dictionary<ITranslation.Language, string>
{
{ ITranslation.Language.Czech, "Ahoj, pro ověření rolí zaměstnance klikni na tlačítko." },
{ ITranslation.Language.English, "Hi, click the button to verify the staff roles." }
}
},
{
"AlreadyVerified",
new()
new Dictionary<ITranslation.Language, string>
{
{ ITranslation.Language.Czech, "Ahoj, už jsi ověřený.\nPro aktualizaci rolí klikni na tlačítko." },
{
Expand Down
9 changes: 0 additions & 9 deletions src/HonzaBotner.Discord/Attributes/ICustomAttribute.cs

This file was deleted.

17 changes: 1 addition & 16 deletions src/HonzaBotner.Discord/DiscordHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,6 @@ namespace HonzaBotner.Discord;

public static class DiscordHelper
{
public static string GetMention(ulong authorId)
{
return $"<@{authorId}>";
}

public static string GetChannel(ulong channelId)
{
return $"<#{channelId}>";
}

public static string GetMessageLink(ulong guild, ulong channel, ulong message)
{
return $"https://discordapp.com/channels/{guild}/{channel}/{message}";
}

/// <summary>
/// Finds DiscordMessage from Discord link to message.
/// </summary>
Expand All @@ -32,7 +17,7 @@ public static string GetMessageLink(ulong guild, ulong channel, ulong message)
{
// Match the channel and message IDs.
const string pattern = @"https://discord(?:app)?\.com/channels/(?:\d+)/(\d+)/(\d+)/?";
Regex regex = new Regex(pattern);
Regex regex = new(pattern);
Match match = regex.Match(link);

// Malformed message link.
Expand Down
2 changes: 1 addition & 1 deletion src/HonzaBotner.Discord/Extensions/DiscordExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public static async Task ReportException(this DiscordChannel channel, string sou
static string Truncate(string value, int maxLength)
{
if (string.IsNullOrEmpty(value)) return value;
return value.Length <= maxLength ? value : value.Substring(0, maxLength) + "...";
return value.Length <= maxLength ? value : value[..maxLength] + "...";
}

await channel.SendMessageAsync(
Expand Down
4 changes: 2 additions & 2 deletions src/HonzaBotner.Scheduler/CronJobWrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ public CronJobWrapper(ICronJob job, string cronExpression, DateTime nextRunTime)
public ICronJob Job { get; }
private CronExpression Expression { get; }

public DateTime NextRunTime { get; private set; }
public DateTime LastRunTime { get; private set; }
private DateTime NextRunTime { get; set; }
private DateTime LastRunTime { get; set; }

public void Next()
{
Expand Down
7 changes: 3 additions & 4 deletions src/HonzaBotner.Services.Test/NewsConfigEnumsTest.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using System.Collections;
using System.Collections.Generic;
using HonzaBotner.Services.Contract;
using HonzaBotner.Services.Contract.Dto;
Expand Down Expand Up @@ -27,7 +26,7 @@ public void NewsProviderToTypeTest(NewsProviderType newsProviderType)
Type? t = Type.GetType(type);

Assert.NotNull(t);
Assert.True(t!.IsAssignableTo(interfaceType));
Assert.True(t.IsAssignableTo(interfaceType));
}

public static IEnumerable<object[]> GetPublisherEnums()
Expand All @@ -48,6 +47,6 @@ public void PublisherToTypeTest(PublisherType publisherType)
Type? t = Type.GetType(type);

Assert.NotNull(t);
Assert.True(t!.IsAssignableTo(interfaceType));
Assert.True(t.IsAssignableTo(interfaceType));
}
}
}
Loading