Add more information to check command

Additionally, fix up null checks in affected files
This commit is contained in:
Noi 2021-10-24 18:15:46 -07:00
parent 16ac294fe3
commit 800bba2193
4 changed files with 38 additions and 44 deletions

View file

@ -72,7 +72,7 @@ class BirthdayRoleUpdate : BackgroundService {
// Birthday announcement // Birthday announcement
var announce = gc.AnnounceMessages; var announce = gc.AnnounceMessages;
var announceping = gc.AnnouncePing; var announceping = gc.AnnouncePing;
SocketTextChannel channel = null; SocketTextChannel? channel = null;
if (gc.AnnounceChannelId.HasValue) channel = guild.GetTextChannel(gc.AnnounceChannelId.Value); if (gc.AnnounceChannelId.HasValue) channel = guild.GetTextChannel(gc.AnnounceChannelId.Value);
if (announcementList.Any()) { if (announcementList.Any()) {
await AnnounceBirthdaysAsync(announce, announceping, channel, announcementList).ConfigureAwait(false); await AnnounceBirthdaysAsync(announce, announceping, channel, announcementList).ConfigureAwait(false);
@ -83,21 +83,14 @@ class BirthdayRoleUpdate : BackgroundService {
/// Gets all known users from the given guild and returns a list including only those who are /// Gets all known users from the given guild and returns a list including only those who are
/// currently experiencing a birthday in the respective time zone. /// currently experiencing a birthday in the respective time zone.
/// </summary> /// </summary>
private static HashSet<ulong> GetGuildCurrentBirthdays(IEnumerable<GuildUserConfiguration> guildUsers, string defaultTzStr) { public static HashSet<ulong> GetGuildCurrentBirthdays(IEnumerable<GuildUserConfiguration> guildUsers, string? defaultTzStr) {
var tzdb = DateTimeZoneProviders.Tzdb;
DateTimeZone defaultTz = (defaultTzStr != null ? DateTimeZoneProviders.Tzdb.GetZoneOrNull(defaultTzStr) : null) ?? tzdb.GetZoneOrNull("UTC")!;
var birthdayUsers = new HashSet<ulong>(); var birthdayUsers = new HashSet<ulong>();
DateTimeZone defaultTz = null;
if (defaultTzStr != null) defaultTz = DateTimeZoneProviders.Tzdb.GetZoneOrNull(defaultTzStr);
defaultTz ??= DateTimeZoneProviders.Tzdb.GetZoneOrNull("UTC");
foreach (var item in guildUsers) { foreach (var item in guildUsers) {
// Determine final time zone to use for calculation // Determine final time zone to use for calculation
DateTimeZone tz = null; DateTimeZone tz = (item.TimeZone != null ? tzdb.GetZoneOrNull(item.TimeZone) : null) ?? defaultTz;
if (item.TimeZone != null) {
// Try user-provided time zone
tz = DateTimeZoneProviders.Tzdb.GetZoneOrNull(item.TimeZone);
}
tz ??= defaultTz;
var targetMonth = item.BirthMonth; var targetMonth = item.BirthMonth;
var targetDay = item.BirthDay; var targetDay = item.BirthDay;
@ -112,7 +105,6 @@ class BirthdayRoleUpdate : BackgroundService {
birthdayUsers.Add(item.UserId); birthdayUsers.Add(item.UserId);
} }
} }
return birthdayUsers; return birthdayUsers;
} }
@ -155,13 +147,12 @@ class BirthdayRoleUpdate : BackgroundService {
public const string DefaultAnnouncePl = "Please wish a happy birthday to our esteemed members: %n"; public const string DefaultAnnouncePl = "Please wish a happy birthday to our esteemed members: %n";
/// <summary> /// <summary>
/// Makes (or attempts to make) an announcement in the specified channel that includes all users /// Attempts to send an announcement message.
/// who have just had their birthday role added.
/// </summary> /// </summary>
/// <returns>The message to place into operation status log.</returns> private static async Task AnnounceBirthdaysAsync(
private static async Task<string> AnnounceBirthdaysAsync( (string?, string?) announce, bool announcePing, SocketTextChannel? c, IEnumerable<SocketGuildUser> names) {
(string, string) announce, bool announcePing, SocketTextChannel c, IEnumerable<SocketGuildUser> names) { if (c == null) return;
if (c == null) return "Announcement channel is not configured, or has gone missing."; if (!c.Guild.CurrentUser.GetPermissions(c).SendMessages) return;
string announceMsg; string announceMsg;
if (names.Count() == 1) announceMsg = announce.Item1 ?? announce.Item2 ?? DefaultAnnounce; if (names.Count() == 1) announceMsg = announce.Item1 ?? announce.Item2 ?? DefaultAnnounce;
@ -182,12 +173,6 @@ class BirthdayRoleUpdate : BackgroundService {
} }
namedisplay.Remove(0, 2); // Remove initial comma and space namedisplay.Remove(0, 2); // Remove initial comma and space
try { await c.SendMessageAsync(announceMsg.Replace("%n", namedisplay.ToString())).ConfigureAwait(false);
await c.SendMessageAsync(announceMsg.Replace("%n", namedisplay.ToString())).ConfigureAwait(false);
return null;
} catch (Discord.Net.HttpException ex) {
// Directly use the resulting exception message in the operation status log
return ex.Message;
}
} }
} }

View file

@ -3,7 +3,7 @@
<PropertyGroup> <PropertyGroup>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework> <TargetFramework>net6.0</TargetFramework>
<Version>3.2.0</Version> <Version>3.2.1</Version>
<PackageId>BirthdayBot</PackageId> <PackageId>BirthdayBot</PackageId>
<Authors>NoiTheCat</Authors> <Authors>NoiTheCat</Authors>
<Description>Discord bot for birthday recognition and reminders.</Description> <Description>Discord bot for birthday recognition and reminders.</Description>

View file

@ -34,7 +34,7 @@ class GuildConfiguration {
/// Gets or sets the guild's default time zone ztring. /// Gets or sets the guild's default time zone ztring.
/// Updating this value requires a call to <see cref="UpdateAsync"/>. /// Updating this value requires a call to <see cref="UpdateAsync"/>.
/// </summary> /// </summary>
public string TimeZone { get; set; } public string? TimeZone { get; set; }
/// <summary> /// <summary>
/// Gets or sets the guild's moderated mode setting. /// Gets or sets the guild's moderated mode setting.
@ -52,7 +52,7 @@ class GuildConfiguration {
/// Gets or sets the guild-specific birthday announcement message. /// Gets or sets the guild-specific birthday announcement message.
/// Updating this value requires a call to <see cref="UpdateAsync"/>. /// Updating this value requires a call to <see cref="UpdateAsync"/>.
/// </summary> /// </summary>
public (string, string) AnnounceMessages { get; set; } public (string?, string?) AnnounceMessages { get; set; }
/// <summary> /// <summary>
/// Gets or sets the announcement ping setting. /// Gets or sets the announcement ping setting.
@ -68,8 +68,8 @@ class GuildConfiguration {
TimeZone = reader.IsDBNull(3) ? null : reader.GetString(3); TimeZone = reader.IsDBNull(3) ? null : reader.GetString(3);
IsModerated = reader.GetBoolean(4); IsModerated = reader.GetBoolean(4);
if (!reader.IsDBNull(5)) ModeratorRole = (ulong)reader.GetInt64(5); if (!reader.IsDBNull(5)) ModeratorRole = (ulong)reader.GetInt64(5);
string announceMsg = reader.IsDBNull(6) ? null : reader.GetString(6); string? announceMsg = reader.IsDBNull(6) ? null : reader.GetString(6);
string announceMsgPl = reader.IsDBNull(7) ? null : reader.GetString(7); string? announceMsgPl = reader.IsDBNull(7) ? null : reader.GetString(7);
AnnounceMessages = (announceMsg, announceMsgPl); AnnounceMessages = (announceMsg, announceMsgPl);
AnnouncePing = reader.GetBoolean(8); AnnouncePing = reader.GetBoolean(8);
} }
@ -169,7 +169,7 @@ class GuildConfiguration {
/// If true, this method shall not create a new entry and will return null if the guild does /// If true, this method shall not create a new entry and will return null if the guild does
/// not exist in the database. /// not exist in the database.
/// </param> /// </param>
public static async Task<GuildConfiguration> LoadAsync(ulong guildId, bool nullIfUnknown) { public static async Task<GuildConfiguration?> LoadAsync(ulong guildId, bool nullIfUnknown) {
using (var db = await Database.OpenConnectionAsync().ConfigureAwait(false)) { using (var db = await Database.OpenConnectionAsync().ConfigureAwait(false)) {
using (var c = db.CreateCommand()) { using (var c = db.CreateCommand()) {
// Take note of ordinals for the constructor // Take note of ordinals for the constructor
@ -242,8 +242,8 @@ class GuildConfiguration {
c.Parameters.Add("@AnnouncePing", NpgsqlDbType.Boolean).Value = AnnouncePing; c.Parameters.Add("@AnnouncePing", NpgsqlDbType.Boolean).Value = AnnouncePing;
c.Prepare(); await c.PrepareAsync().ConfigureAwait(false);
c.ExecuteNonQuery(); await c.ExecuteNonQueryAsync().ConfigureAwait(false);
} }
#endregion #endregion
} }

View file

@ -391,15 +391,23 @@ internal class ManagerCommands : CommandsCommon {
var result = new StringBuilder(); var result = new StringBuilder();
var guild = reqChannel.Guild; var guild = reqChannel.Guild;
var conf = await GuildConfiguration.LoadAsync(guild.Id, true).ConfigureAwait(false); var conf = await GuildConfiguration.LoadAsync(guild.Id, true).ConfigureAwait(false);
result.AppendLine($"Server ID: {guild.Id} | Bot shard ID: {instance.ShardId:00}");
result.AppendLine();
result.AppendLine(DoTestFor("Bot has obtained the user list", () => Common.HasMostMembersDownloaded(guild))); result.AppendLine($"Server ID: {guild.Id} | Bot shard ID: {instance.ShardId:00}");
result.AppendLine(DoTestFor("Server configuration exists", delegate { bool hasMembers = Common.HasMostMembersDownloaded(guild);
if (conf == null) return false; result.Append(DoTestFor("Bot has obtained the user list", () => hasMembers));
result.AppendLine($" - Has {guild.DownloadedMemberCount} of {guild.MemberCount} members.");
int bdayCount = -1;
result.Append(DoTestFor("Check if users have a birthday today", delegate {
if (!hasMembers) return false;
var gc = GuildConfiguration.LoadAsync(guild.Id, true).ConfigureAwait(false).GetAwaiter().GetResult();
var users = GuildUserConfiguration.LoadAllAsync(guild.Id).ConfigureAwait(false).GetAwaiter().GetResult();
bdayCount = BackgroundServices.BirthdayRoleUpdate.GetGuildCurrentBirthdays(users, gc?.TimeZone).Count;
return true; return true;
})); }));
if (hasMembers) result.AppendLine($" - {bdayCount} user(s) currently having a birthday.");
else result.AppendLine(" - Cannot check without user list.");
result.AppendLine(); result.AppendLine();
result.AppendLine(DoTestFor("Birthday role set with `bb.config role`", delegate { result.AppendLine(DoTestFor("Birthday role set with `bb.config role`", delegate {
if (conf == null) return false; if (conf == null) return false;
SocketRole? role = guild.GetRole(conf.RoleId ?? 0); SocketRole? role = guild.GetRole(conf.RoleId ?? 0);
@ -412,14 +420,15 @@ internal class ManagerCommands : CommandsCommon {
return guild.CurrentUser.GuildPermissions.ManageRoles && role.Position < guild.CurrentUser.Hierarchy; return guild.CurrentUser.GuildPermissions.ManageRoles && role.Position < guild.CurrentUser.Hierarchy;
})); }));
result.AppendLine(); result.AppendLine();
SocketTextChannel? channel = null;
result.AppendLine(DoTestFor("(Optional) Announcement channel set with `bb.config channel`", delegate { result.AppendLine(DoTestFor("(Optional) Announcement channel set with `bb.config channel`", delegate {
if (conf == null) return false; if (conf == null) return false;
SocketTextChannel? channel = guild.GetTextChannel(conf.AnnounceChannelId ?? 0); channel = guild.GetTextChannel(conf.AnnounceChannelId ?? 0);
return channel != null; return channel != null;
})); }));
result.AppendLine(DoTestFor("(Optional) Bot can send messages into announcement channel", delegate { string disp = channel == null ? "announcement channel" : $"<#{channel.Id}>";
if (conf == null) return false; result.AppendLine(DoTestFor($"(Optional) Bot can send messages into { disp }", delegate {
SocketTextChannel? channel = guild.GetTextChannel(conf.AnnounceChannelId ?? 0);
if (channel == null) return false; if (channel == null) return false;
return guild.CurrentUser.GetPermissions(channel).SendMessages; return guild.CurrentUser.GetPermissions(channel).SendMessages;
})); }));