Style updates

This commit is contained in:
Noi 2022-08-31 21:09:10 -07:00
parent a725ecca87
commit 12fe869b26
18 changed files with 16 additions and 36 deletions

View file

@ -3,7 +3,6 @@ using Discord.Interactions;
using System.Text; using System.Text;
namespace BirthdayBot.ApplicationCommands; namespace BirthdayBot.ApplicationCommands;
[RequireGuildContext] [RequireGuildContext]
[Group("birthday", HelpCmdBirthday)] [Group("birthday", HelpCmdBirthday)]
public class BirthdayModule : BotModuleBase { public class BirthdayModule : BotModuleBase {
@ -133,7 +132,7 @@ public class BirthdayModule : BotModuleBase {
var query = GetSortedUserList(Context.Guild); var query = GetSortedUserList(Context.Guild);
// TODO pagination instead of this workaround // TODO pagination instead of this workaround
bool hasOutputOneLine = false; var hasOutputOneLine = false;
// First output is shown as an interaction response, followed then as regular channel messages // First output is shown as an interaction response, followed then as regular channel messages
async Task doOutput(string msg) { async Task doOutput(string msg) {
if (!hasOutputOneLine) { if (!hasOutputOneLine) {
@ -147,8 +146,7 @@ public class BirthdayModule : BotModuleBase {
var output = new StringBuilder(); var output = new StringBuilder();
var resultCount = 0; var resultCount = 0;
output.AppendLine("Recent and upcoming birthdays:"); output.AppendLine("Recent and upcoming birthdays:");
for (int count = 0; count <= 21; count++) // cover 21 days total (7 prior, current day, 14 upcoming) for (var count = 0; count <= 21; count++) { // cover 21 days total (7 prior, current day, 14 upcoming)
{
var results = from item in query var results = from item in query
where item.DateIndex == search where item.DateIndex == search
select item; select item;

View file

@ -3,7 +3,6 @@ using Discord.Interactions;
using static BirthdayBot.Common; using static BirthdayBot.Common;
namespace BirthdayBot.ApplicationCommands; namespace BirthdayBot.ApplicationCommands;
[RequireBotModerator] [RequireBotModerator]
[Group("override", HelpCmdOverride)] [Group("override", HelpCmdOverride)]
public class BirthdayOverrideModule : BotModuleBase { public class BirthdayOverrideModule : BotModuleBase {

View file

@ -39,7 +39,7 @@ public abstract class BotModuleBase : InteractionModuleBase<SocketInteractionCon
/// throwing a FormatException if the input is not recognized. /// throwing a FormatException if the input is not recognized.
/// </summary> /// </summary>
protected static string ParseTimeZone(string tzinput) { protected static string ParseTimeZone(string tzinput) {
if (!TzNameMap.TryGetValue(tzinput, out string? tz)) if (!TzNameMap.TryGetValue(tzinput, out var tz))
throw new FormatException(":x: Unknown time zone name.\n" + throw new FormatException(":x: Unknown time zone name.\n" +
"To find your time zone, please refer to: https://kevinnovak.github.io/Time-Zone-Picker/"); "To find your time zone, please refer to: https://kevinnovak.github.io/Time-Zone-Picker/");
return tz!; return tz!;

View file

@ -3,7 +3,6 @@ using Discord.Interactions;
using System.Text; using System.Text;
namespace BirthdayBot.ApplicationCommands; namespace BirthdayBot.ApplicationCommands;
[RequireBotModerator] [RequireBotModerator]
[Group("config", HelpCmdConfig)] [Group("config", HelpCmdConfig)]
public class ConfigModule : BotModuleBase { public class ConfigModule : BotModuleBase {
@ -98,8 +97,8 @@ public class ConfigModule : BotModuleBase {
internal static async Task CmdSetMessageResponse(SocketModal modal, SocketGuildChannel channel, internal static async Task CmdSetMessageResponse(SocketModal modal, SocketGuildChannel channel,
Dictionary<string, SocketMessageComponentData> data) { Dictionary<string, SocketMessageComponentData> data) {
string? newSingle = data[ModalComCidSingle].Value; var newSingle = data[ModalComCidSingle].Value;
string? newMulti = data[ModalComCidMulti].Value; var newMulti = data[ModalComCidMulti].Value;
if (string.IsNullOrWhiteSpace(newSingle)) newSingle = null; if (string.IsNullOrWhiteSpace(newSingle)) newSingle = null;
if (string.IsNullOrWhiteSpace(newMulti)) newMulti = null; if (string.IsNullOrWhiteSpace(newMulti)) newMulti = null;
@ -157,7 +156,7 @@ public class ConfigModule : BotModuleBase {
var existing = db.BlocklistEntries var existing = db.BlocklistEntries
.Where(bl => bl.GuildId == (long)user.Guild.Id && bl.UserId == (long)user.Id).FirstOrDefault(); .Where(bl => bl.GuildId == (long)user.Guild.Id && bl.UserId == (long)user.Id).FirstOrDefault();
bool already = (existing != null) == setting; var already = (existing != null) == setting;
if (already) { if (already) {
await RespondAsync($":white_check_mark: User is already {(setting ? "" : "not ")}blocked.").ConfigureAwait(false); await RespondAsync($":white_check_mark: User is already {(setting ? "" : "not ")}blocked.").ConfigureAwait(false);
return; return;
@ -172,13 +171,13 @@ public class ConfigModule : BotModuleBase {
[SlashCommand("set-moderated", HelpPfxModOnly + "Set moderated mode on the server.")] [SlashCommand("set-moderated", HelpPfxModOnly + "Set moderated mode on the server.")]
public async Task CmdSetModerated([Summary(name: "enable", description: "The moderated mode setting.")] bool setting) { public async Task CmdSetModerated([Summary(name: "enable", description: "The moderated mode setting.")] bool setting) {
bool current = false; var current = false;
await DoDatabaseUpdate(Context, s => { await DoDatabaseUpdate(Context, s => {
current = s.Moderated; current = s.Moderated;
s.Moderated = setting; s.Moderated = setting;
}); });
bool already = setting == current; var already = setting == current;
if (already) { if (already) {
await RespondAsync($":white_check_mark: Moderated mode is already **{(setting ? "en" : "dis")}abled**."); await RespondAsync($":white_check_mark: Moderated mode is already **{(setting ? "en" : "dis")}abled**.");
} else { } else {
@ -205,7 +204,7 @@ public class ConfigModule : BotModuleBase {
result.AppendLine($"Server time zone: `{ (guildconf.TimeZone ?? "Not set - using UTC") }`"); result.AppendLine($"Server time zone: `{ (guildconf.TimeZone ?? "Not set - using UTC") }`");
result.AppendLine(); result.AppendLine();
bool hasMembers = Common.HasMostMembersDownloaded(guild); var hasMembers = Common.HasMostMembersDownloaded(guild);
result.Append(DoTestFor("Bot has obtained the user list", () => hasMembers)); result.Append(DoTestFor("Bot has obtained the user list", () => hasMembers));
result.AppendLine($" - Has `{guild.DownloadedMemberCount}` of `{guild.MemberCount}` members."); result.AppendLine($" - Has `{guild.DownloadedMemberCount}` of `{guild.MemberCount}` members.");
int bdayCount = default; int bdayCount = default;
@ -239,7 +238,7 @@ public class ConfigModule : BotModuleBase {
announcech = guild.GetTextChannel((ulong)(guildconf.ChannelAnnounceId ?? 0)); announcech = guild.GetTextChannel((ulong)(guildconf.ChannelAnnounceId ?? 0));
return announcech != null; return announcech != null;
})); }));
string disp = announcech == null ? "announcement channel" : $"<#{announcech.Id}>"; var disp = announcech == null ? "announcement channel" : $"<#{announcech.Id}>";
result.AppendLine(DoTestFor($"(Optional) Bot can send messages into { disp }", delegate { result.AppendLine(DoTestFor($"(Optional) Bot can send messages into { disp }", delegate {
if (announcech == null) return false; if (announcech == null) return false;
return guild.CurrentUser.GetPermissions(announcech).SendMessages; return guild.CurrentUser.GetPermissions(announcech).SendMessages;
@ -252,7 +251,7 @@ public class ConfigModule : BotModuleBase {
const int announceMsgPreviewLimit = 350; const int announceMsgPreviewLimit = 350;
static string prepareAnnouncePreview(string announce) { static string prepareAnnouncePreview(string announce) {
string trunc = announce.Length > announceMsgPreviewLimit ? announce[..announceMsgPreviewLimit] + "`(...)`" : announce; var trunc = announce.Length > announceMsgPreviewLimit ? announce[..announceMsgPreviewLimit] + "`(...)`" : announce;
var result = new StringBuilder(); var result = new StringBuilder();
foreach (var line in trunc.Split('\n')) foreach (var line in trunc.Split('\n'))
result.AppendLine($"> {line}"); result.AppendLine($"> {line}");

View file

@ -1,7 +1,6 @@
using Discord.Interactions; using Discord.Interactions;
namespace BirthdayBot.ApplicationCommands; namespace BirthdayBot.ApplicationCommands;
public class HelpModule : BotModuleBase { public class HelpModule : BotModuleBase {
private const string TopMessage = private const string TopMessage =
"Thank you for using Birthday Bot!\n" + "Thank you for using Birthday Bot!\n" +
@ -33,12 +32,10 @@ public class HelpModule : BotModuleBase {
public async Task CmdHelp() { public async Task CmdHelp() {
const string DMWarn = "Please note that this bot works in servers only. " + const string DMWarn = "Please note that this bot works in servers only. " +
"The bot will not respond to any other commands within a DM."; "The bot will not respond to any other commands within a DM.";
string ver =
#if DEBUG #if DEBUG
"DEBUG flag set"; var ver = "DEBUG flag set";
#else #else
"v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version!.ToString(3); var ver = "v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version!.ToString(3);
#endif #endif
var result = new EmbedBuilder() var result = new EmbedBuilder()
.WithAuthor("Help & About") .WithAuthor("Help & About")
@ -48,6 +45,6 @@ public class HelpModule : BotModuleBase {
.AddField("Commands", RegularCommandsField) .AddField("Commands", RegularCommandsField)
.AddField("Moderator commands", ModCommandsField) .AddField("Moderator commands", ModCommandsField)
.Build(); .Build();
await RespondAsync(text: (Context.Channel is IDMChannel ? DMWarn : null), embed: result).ConfigureAwait(false); await RespondAsync(text: Context.Channel is IDMChannel ? DMWarn : null, embed: result).ConfigureAwait(false);
} }
} }

View file

@ -1,5 +1,4 @@
namespace BirthdayBot.ApplicationCommands; namespace BirthdayBot.ApplicationCommands;
/// <summary> /// <summary>
/// An instance-less class meant to handle incoming submitted modals. /// An instance-less class meant to handle incoming submitted modals.
/// </summary> /// </summary>

View file

@ -2,7 +2,6 @@
using Discord.Interactions; using Discord.Interactions;
namespace BirthdayBot.ApplicationCommands; namespace BirthdayBot.ApplicationCommands;
/// <summary> /// <summary>
/// Only users not on the blocklist or affected by moderator mode may use the command.<br/> /// Only users not on the blocklist or affected by moderator mode may use the command.<br/>
/// This is used in the <see cref="BotModuleBase"/> base class. Manually using it anywhere else is unnecessary. /// This is used in the <see cref="BotModuleBase"/> base class. Manually using it anywhere else is unnecessary.

View file

@ -2,7 +2,6 @@
using Discord.Interactions; using Discord.Interactions;
namespace BirthdayBot.ApplicationCommands; namespace BirthdayBot.ApplicationCommands;
/// <summary> /// <summary>
/// Precondition requiring the executing user be recognized as a bot moderator.<br/> /// Precondition requiring the executing user be recognized as a bot moderator.<br/>
/// A bot moderator has either the Manage Server permission or is a member of the designated bot moderator role. /// A bot moderator has either the Manage Server permission or is a member of the designated bot moderator role.

View file

@ -1,7 +1,6 @@
using Discord.Interactions; using Discord.Interactions;
namespace BirthdayBot.ApplicationCommands; namespace BirthdayBot.ApplicationCommands;
/// <summary> /// <summary>
/// Implements the included precondition from Discord.Net, requiring a guild context while using our custom error message.<br/><br/> /// Implements the included precondition from Discord.Net, requiring a guild context while using our custom error message.<br/><br/>
/// Combining this with <see cref="RequireBotModeratorAttribute"/> is redundant. If possible, only use the latter instead. /// Combining this with <see cref="RequireBotModeratorAttribute"/> is redundant. If possible, only use the latter instead.

View file

@ -1,7 +1,6 @@
using BirthdayBot.Data; using BirthdayBot.Data;
namespace BirthdayBot.BackgroundServices; namespace BirthdayBot.BackgroundServices;
/// <summary> /// <summary>
/// Proactively fills the user cache for guilds in which any birthday data already exists. /// Proactively fills the user cache for guilds in which any birthday data already exists.
/// </summary> /// </summary>
@ -16,7 +15,7 @@ class AutoUserDownload : BackgroundService {
// ...and if the guild contains any user data // ...and if the guild contains any user data
var mustFetch = db.UserEntries.Where(e => incompleteCaches.Contains(e.GuildId)).Select(e => e.GuildId).Distinct(); var mustFetch = db.UserEntries.Where(e => incompleteCaches.Contains(e.GuildId)).Select(e => e.GuildId).Distinct();
int processed = 0; var processed = 0;
foreach (var item in mustFetch) { foreach (var item in mustFetch) {
// May cause a disconnect in certain situations. Cancel all further attempts until the next pass if it happens. // May cause a disconnect in certain situations. Cancel all further attempts until the next pass if it happens.
if (ShardInstance.DiscordClient.ConnectionState != ConnectionState.Connected) break; if (ShardInstance.DiscordClient.ConnectionState != ConnectionState.Connected) break;

View file

@ -1,5 +1,4 @@
namespace BirthdayBot.BackgroundServices; namespace BirthdayBot.BackgroundServices;
abstract class BackgroundService { abstract class BackgroundService {
protected static SemaphoreSlim DbConcurrentOperationsLock { get; } = new(ShardManager.MaxConcurrentOperations); protected static SemaphoreSlim DbConcurrentOperationsLock { get; } = new(ShardManager.MaxConcurrentOperations);
protected ShardInstance ShardInstance { get; } protected ShardInstance ShardInstance { get; }

View file

@ -1,7 +1,6 @@
using System.Text; using System.Text;
namespace BirthdayBot.BackgroundServices; namespace BirthdayBot.BackgroundServices;
/// <summary> /// <summary>
/// Reports user count statistics to external services on a shard by shard basis. /// Reports user count statistics to external services on a shard by shard basis.
/// </summary> /// </summary>

View file

@ -1,7 +1,6 @@
using System.Text; using System.Text;
namespace BirthdayBot; namespace BirthdayBot;
static class Common { static class Common {
/// <summary> /// <summary>
/// Formats a user's name to a consistent, readable format which makes use of their nickname. /// Formats a user's name to a consistent, readable format which makes use of their nickname.
@ -42,7 +41,7 @@ static class Common {
if (guild.MemberCount > 30) { if (guild.MemberCount > 30) {
// For guilds of size over 30, require 85% or more of the members to be known // For guilds of size over 30, require 85% or more of the members to be known
// (26/30, 42/50, 255/300, etc) // (26/30, 42/50, 255/300, etc)
int threshold = (int)(guild.MemberCount * 0.85); var threshold = (int)(guild.MemberCount * 0.85);
return guild.DownloadedMemberCount >= threshold; return guild.DownloadedMemberCount >= threshold;
} else { } else {
// For smaller guilds, fail if two or more members are missing // For smaller guilds, fail if two or more members are missing

View file

@ -6,7 +6,6 @@ using System.Reflection;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
namespace BirthdayBot; namespace BirthdayBot;
/// <summary> /// <summary>
/// Loads and holds configuration values. /// Loads and holds configuration values.
/// </summary> /// </summary>

View file

@ -2,7 +2,6 @@
using Npgsql; using Npgsql;
namespace BirthdayBot.Data; namespace BirthdayBot.Data;
public class BotDatabaseContext : DbContext { public class BotDatabaseContext : DbContext {
private static readonly string _connectionString; private static readonly string _connectionString;

View file

@ -1,5 +1,4 @@
namespace BirthdayBot.Data; namespace BirthdayBot.Data;
internal static class Extensions { internal static class Extensions {
/// <summary> /// <summary>
/// Gets the corresponding <see cref="GuildConfig"/> for this guild, or a new one if one does not exist. /// Gets the corresponding <see cref="GuildConfig"/> for this guild, or a new one if one does not exist.

View file

@ -2,7 +2,6 @@
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
namespace BirthdayBot.Data; namespace BirthdayBot.Data;
[Table("settings")] [Table("settings")]
public class GuildConfig { public class GuildConfig {
public GuildConfig() { public GuildConfig() {

View file

@ -2,7 +2,6 @@
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
namespace BirthdayBot.Data; namespace BirthdayBot.Data;
[Table("user_birthdays")] [Table("user_birthdays")]
public class UserEntry { public class UserEntry {
[Key] [Key]