Configure all the awaits

This commit is contained in:
Noi 2020-10-10 00:28:11 -07:00
parent 9ef164bac1
commit 651de4e78a
11 changed files with 161 additions and 133 deletions

View file

@ -31,7 +31,7 @@ namespace BirthdayBot.BackgroundServices
if (token.IsCancellationRequested) throw new TaskCanceledException();
try
{
await ProcessGuildAsync(guild);
await ProcessGuildAsync(guild).ConfigureAwait(false);
}
catch (Exception ex)
{
@ -48,7 +48,7 @@ namespace BirthdayBot.BackgroundServices
/// Access to <see cref="ProcessGuildAsync(SocketGuild)"/> for the testing command.
/// </summary>
/// <returns>Diagnostic data in string form.</returns>
public async Task<string> SingleProcessGuildAsync(SocketGuild guild) => (await ProcessGuildAsync(guild)).Export();
public async Task<string> SingleProcessGuildAsync(SocketGuild guild) => (await ProcessGuildAsync(guild).ConfigureAwait(false)).Export();
/// <summary>
/// Main method where actual guild processing occurs.
@ -58,7 +58,7 @@ namespace BirthdayBot.BackgroundServices
var diag = new PGDiagnostic();
// Load guild information - stop if there is none (bot never previously used in guild)
var gc = await GuildConfiguration.LoadAsync(guild.Id, true);
var gc = await GuildConfiguration.LoadAsync(guild.Id, true).ConfigureAwait(false);
if (gc == null) return diag;
// Check if role settings are correct before continuing with further processing
@ -71,7 +71,7 @@ namespace BirthdayBot.BackgroundServices
// Note: This is where we'd call DownloadUsersAsync, but this method is capable of blocking indefinitely
// and making the task completely unresponsive. Must investigate further before calling it here and disabling
// AlwaysDownloadUsers in client settings.
var users = await GuildUserConfiguration.LoadAllAsync(guild.Id);
var users = await GuildUserConfiguration.LoadAllAsync(guild.Id).ConfigureAwait(false);
var tz = gc.TimeZone;
var birthdays = GetGuildCurrentBirthdays(users, tz);
// Note: Don't quit here if zero people are having birthdays. Roles may still need to be removed by BirthdayApply.
@ -81,7 +81,7 @@ namespace BirthdayBot.BackgroundServices
// Update roles as appropriate
try
{
var updateResult = await UpdateGuildBirthdayRoles(guild, role, birthdays);
var updateResult = await UpdateGuildBirthdayRoles(guild, role, birthdays).ConfigureAwait(false);
announcementList = updateResult.Item1;
diag.RoleApplyResult = updateResult.Item2; // statistics
}
@ -99,7 +99,8 @@ namespace BirthdayBot.BackgroundServices
if (gc.AnnounceChannelId.HasValue) channel = guild.GetTextChannel(gc.AnnounceChannelId.Value);
if (announcementList.Count() != 0)
{
var announceResult = await AnnounceBirthdaysAsync(announce, announceping, channel, announcementList);
var announceResult =
await AnnounceBirthdaysAsync(announce, announceping, channel, announcementList).ConfigureAwait(false);
diag.Announcement = announceResult;
}
else
@ -195,7 +196,7 @@ namespace BirthdayBot.BackgroundServices
// TODO Can we remove during the iteration instead of after? investigate later...
foreach (var user in roleRemoves)
{
await user.RemoveRoleAsync(r);
await user.RemoveRoleAsync(r).ConfigureAwait(false);
}
// Apply role to members not already having it. Prepare announcement list.
@ -205,7 +206,7 @@ namespace BirthdayBot.BackgroundServices
var member = g.GetUser(target);
if (member == null) continue;
if (roleKeeps.Contains(member.Id)) continue; // already has role - do nothing
await member.AddRoleAsync(r);
await member.AddRoleAsync(r).ConfigureAwait(false);
newBirthdays.Add(member);
}
@ -247,7 +248,7 @@ namespace BirthdayBot.BackgroundServices
try
{
await c.SendMessageAsync(announceMsg.Replace("%n", namedisplay.ToString()));
await c.SendMessageAsync(announceMsg.Replace("%n", namedisplay.ToString())).ConfigureAwait(false);
return null;
}
catch (Discord.Net.HttpException ex)

View file

@ -63,16 +63,16 @@ namespace BirthdayBot.BackgroundServices
{
while (!_workerCanceller.IsCancellationRequested)
{
await Task.Delay(Interval * 1000, _workerCanceller.Token);
await Task.Delay(Interval * 1000, _workerCanceller.Token).ConfigureAwait(false);
// ConnectionStatus will always run. Its result determines if remaining tasks also this time.
await ConnStatus.OnTick(_workerCanceller.Token);
await ConnStatus.OnTick(_workerCanceller.Token).ConfigureAwait(false);
if (!ConnStatus.Stable) continue;
// Execute tasks sequentially
foreach (var service in _workers)
{
try { await service.OnTick(_workerCanceller.Token); }
try { await service.OnTick(_workerCanceller.Token).ConfigureAwait(false); }
catch (Exception ex)
{
var svcname = service.GetType().Name;

View file

@ -15,17 +15,18 @@ namespace BirthdayBot.Data
{
if (DBConnectionString == null) throw new Exception("Database connection string not set");
var db = new NpgsqlConnection(DBConnectionString);
await db.OpenAsync();
await db.OpenAsync().ConfigureAwait(false);
return db;
}
public static async Task DoInitialDatabaseSetupAsync()
{
using var db = await OpenConnectionAsync();
using var db = await OpenConnectionAsync().ConfigureAwait(false);
// Refer to the methods being called for information on how the database is set up.
await GuildConfiguration.DatabaseSetupAsync(db); // Note: Call this first. (Foreign reference constraints.)
await GuildUserConfiguration.DatabaseSetupAsync(db);
// Note: The order these are called is important. (Foreign reference constraints.)
await GuildConfiguration.DatabaseSetupAsync(db).ConfigureAwait(false);
await GuildUserConfiguration.DatabaseSetupAsync(db).ConfigureAwait(false);
}
}
}

View file

@ -84,16 +84,16 @@ namespace BirthdayBot.Data
{
if (IsModerated) return true;
using var db = await Database.OpenConnectionAsync();
using var db = await Database.OpenConnectionAsync().ConfigureAwait(false);
using var c = db.CreateCommand();
c.CommandText = $"select * from {BackingTableBans} "
+ "where guild_id = @Gid and user_id = @Uid";
c.Parameters.Add("@Gid", NpgsqlDbType.Bigint).Value = (long)GuildId;
c.Parameters.Add("@Uid", NpgsqlDbType.Bigint).Value = (long)userId;
c.Prepare();
using var r = await c.ExecuteReaderAsync();
if (await r.ReadAsync()) return true;
return false;
using var r = await c.ExecuteReaderAsync().ConfigureAwait(false);
if (!await r.ReadAsync().ConfigureAwait(false)) return false;
return true;
}
/// <summary>
@ -101,7 +101,7 @@ namespace BirthdayBot.Data
/// </summary>
public async Task BlockUserAsync(ulong userId)
{
using var db = await Database.OpenConnectionAsync();
using var db = await Database.OpenConnectionAsync().ConfigureAwait(false);
using var c = db.CreateCommand();
c.CommandText = $"insert into {BackingTableBans} (guild_id, user_id) "
+ "values (@Gid, @Uid) "
@ -110,7 +110,7 @@ namespace BirthdayBot.Data
c.Parameters.Add("@Gid", NpgsqlDbType.Bigint).Value = (long)GuildId;
c.Parameters.Add("@Uid", NpgsqlDbType.Bigint).Value = (long)userId;
c.Prepare();
await c.ExecuteNonQueryAsync();
await c.ExecuteNonQueryAsync().ConfigureAwait(false);
}
/// <summary>
@ -119,14 +119,14 @@ namespace BirthdayBot.Data
/// <returns>True if a user has been removed, false if the requested user was not in this list.</returns>
public async Task<bool> UnblockUserAsync(ulong userId)
{
using var db = await Database.OpenConnectionAsync();
using var db = await Database.OpenConnectionAsync().ConfigureAwait(false);
using var c = db.CreateCommand();
c.CommandText = $"delete from {BackingTableBans} where "
+ "guild_id = @Gid and user_id = @Uid";
c.Parameters.Add("@Gid", NpgsqlDbType.Bigint).Value = (long)GuildId;
c.Parameters.Add("@Uid", NpgsqlDbType.Bigint).Value = (long)userId;
c.Prepare();
var result = await c.ExecuteNonQueryAsync();
var result = await c.ExecuteNonQueryAsync().ConfigureAwait(false);
return result != 0;
}
@ -157,7 +157,7 @@ namespace BirthdayBot.Data
+ "announce_ping boolean not null default FALSE, "
+ "last_seen timestamptz not null default NOW()"
+ ")";
await c.ExecuteNonQueryAsync();
await c.ExecuteNonQueryAsync().ConfigureAwait(false);
}
using (var c = db.CreateCommand())
{
@ -166,7 +166,7 @@ namespace BirthdayBot.Data
+ "user_id bigint not null, "
+ "PRIMARY KEY (guild_id, user_id)"
+ ")";
await c.ExecuteNonQueryAsync();
await c.ExecuteNonQueryAsync().ConfigureAwait(false);
}
}
@ -179,7 +179,7 @@ namespace BirthdayBot.Data
/// </param>
public static async Task<GuildConfiguration> LoadAsync(ulong guildId, bool nullIfUnknown)
{
using (var db = await Database.OpenConnectionAsync())
using (var db = await Database.OpenConnectionAsync().ConfigureAwait(false))
{
using (var c = db.CreateCommand())
{
@ -189,8 +189,8 @@ namespace BirthdayBot.Data
+ $"from {BackingTable} where guild_id = @Gid";
c.Parameters.Add("@Gid", NpgsqlDbType.Bigint).Value = (long)guildId;
c.Prepare();
using var r = await c.ExecuteReaderAsync();
if (await r.ReadAsync()) return new GuildConfiguration(r);
using var r = await c.ExecuteReaderAsync().ConfigureAwait(false);
if (await r.ReadAsync().ConfigureAwait(false)) return new GuildConfiguration(r);
}
if (nullIfUnknown) return null;
@ -200,11 +200,11 @@ namespace BirthdayBot.Data
c.CommandText = $"insert into {BackingTable} (guild_id) values (@Gid)";
c.Parameters.Add("@Gid", NpgsqlDbType.Bigint).Value = (long)guildId;
c.Prepare();
await c.ExecuteNonQueryAsync();
await c.ExecuteNonQueryAsync().ConfigureAwait(false);
}
}
// With a new row created, try this again
return await LoadAsync(guildId, nullIfUnknown);
return await LoadAsync(guildId, nullIfUnknown).ConfigureAwait(false);
}
/// <summary>
@ -212,7 +212,7 @@ namespace BirthdayBot.Data
/// </summary>
public async Task UpdateAsync()
{
using var db = await Database.OpenConnectionAsync();
using var db = await Database.OpenConnectionAsync().ConfigureAwait(false);
using var c = db.CreateCommand();
c.CommandText = $"update {BackingTable} set "
+ "role_id = @RoleId, "

View file

@ -52,7 +52,7 @@ namespace BirthdayBot.Data
/// </summary>
public async Task UpdateAsync(int month, int day, string newtz)
{
using (var db = await Database.OpenConnectionAsync())
using (var db = await Database.OpenConnectionAsync().ConfigureAwait(false))
{
using var c = db.CreateCommand();
c.CommandText = $"insert into {BackingTable} "
@ -68,7 +68,7 @@ namespace BirthdayBot.Data
if (newtz != null) tzp.Value = newtz;
else tzp.Value = DBNull.Value;
c.Prepare();
await c.ExecuteNonQueryAsync();
await c.ExecuteNonQueryAsync().ConfigureAwait(false);
}
// Database update succeeded; update instance values
@ -83,14 +83,14 @@ namespace BirthdayBot.Data
/// </summary>
public async Task DeleteAsync()
{
using var db = await Database.OpenConnectionAsync();
using var db = await Database.OpenConnectionAsync().ConfigureAwait(false);
using var c = db.CreateCommand();
c.CommandText = $"delete from {BackingTable} "
+ "where guild_id = @Gid and user_id = @Uid";
c.Parameters.Add("@Gid", NpgsqlDbType.Bigint).Value = (long)GuildId;
c.Parameters.Add("@Uid", NpgsqlDbType.Bigint).Value = (long)UserId;
c.Prepare();
await c.ExecuteNonQueryAsync();
await c.ExecuteNonQueryAsync().ConfigureAwait(false);
}
#region Database
@ -110,7 +110,7 @@ namespace BirthdayBot.Data
+ "last_seen timestamptz not null default NOW(), "
+ "PRIMARY KEY (guild_id, user_id)" // index automatically created with this
+ ")";
await c.ExecuteNonQueryAsync();
await c.ExecuteNonQueryAsync().ConfigureAwait(false);
}
/// <summary>
@ -118,7 +118,7 @@ namespace BirthdayBot.Data
/// </summary>
public static async Task<GuildUserConfiguration> LoadAsync(ulong guildId, ulong userId)
{
using var db = await Database.OpenConnectionAsync();
using var db = await Database.OpenConnectionAsync().ConfigureAwait(false);
using var c = db.CreateCommand();
c.CommandText = $"select {SelectFields} from {BackingTable} where guild_id = @Gid and user_id = @Uid";
c.Parameters.Add("@Gid", NpgsqlDbType.Bigint).Value = (long)guildId;
@ -126,7 +126,7 @@ namespace BirthdayBot.Data
c.Prepare();
using var r = c.ExecuteReader();
if (await r.ReadAsync()) return new GuildUserConfiguration(r);
if (await r.ReadAsync().ConfigureAwait(false)) return new GuildUserConfiguration(r);
else return new GuildUserConfiguration(guildId, userId);
}
@ -135,15 +135,15 @@ namespace BirthdayBot.Data
/// </summary>
public static async Task<IEnumerable<GuildUserConfiguration>> LoadAllAsync(ulong guildId)
{
using var db = await Database.OpenConnectionAsync();
using var db = await Database.OpenConnectionAsync().ConfigureAwait(false);
using var c = db.CreateCommand();
c.CommandText = $"select {SelectFields} from {BackingTable} where guild_id = @Gid";
c.Parameters.Add("@Gid", NpgsqlDbType.Bigint).Value = (long)guildId;
c.Prepare();
using var r = await c.ExecuteReaderAsync();
using var r = await c.ExecuteReaderAsync().ConfigureAwait(false);
var result = new List<GuildUserConfiguration>();
while (await r.ReadAsync()) result.Add(new GuildUserConfiguration(r));
while (await r.ReadAsync().ConfigureAwait(false)) result.Add(new GuildUserConfiguration(r));
return result;
}
#endregion

View file

@ -53,7 +53,7 @@ namespace BirthdayBot
/// <summary>
/// Starts up this shard's connection to Discord and background task handling associated with it.
/// </summary>
public async Task Start()
public async Task StartAsync()
{
await Database.DoInitialDatabaseSetupAsync();

View file

@ -123,7 +123,7 @@ namespace BirthdayBot
disposeOldShard.Wait();
_shards[shardId] = newInstance;
}
await newInstance.Start();
await newInstance.StartAsync().ConfigureAwait(false);
}
private async Task WatchdogLoop()
@ -170,7 +170,7 @@ namespace BirthdayBot
}
// 120 second delay
await Task.Delay(120 * 1000, _watchdogCancel.Token);
await Task.Delay(120 * 1000, _watchdogCancel.Token).ConfigureAwait(false);
}
}
catch (TaskCanceledException) { }
@ -197,7 +197,6 @@ namespace BirthdayBot
post.Headers.Add("Authorization", dbotsToken);
post.Content = new StringContent(string.Format(Body, count), Encoding.UTF8, "application/json");
await Task.Delay(80); // Discord Bots rate limit for this endpoint is 20 per second
await _httpClient.SendAsync(post, token);
Log("Discord Bots: Update successful.");
}

View file

@ -92,11 +92,11 @@ namespace BirthdayBot.UserInterface
private async Task CmdHelp(ShardInstance instance, GuildConfiguration gconf,
string[] param, SocketTextChannel reqChannel, SocketGuildUser reqUser)
=> await reqChannel.SendMessageAsync(embed: _helpEmbed);
=> await reqChannel.SendMessageAsync(embed: _helpEmbed).ConfigureAwait(false);
private async Task CmdHelpConfig(ShardInstance instance, GuildConfiguration gconf,
string[] param, SocketTextChannel reqChannel, SocketGuildUser reqUser)
=> await reqChannel.SendMessageAsync(embed: _helpConfigEmbed);
=> await reqChannel.SendMessageAsync(embed: _helpConfigEmbed).ConfigureAwait(false);
private async Task CmdHelpTzdata(ShardInstance instance, GuildConfiguration gconf,
string[] param, SocketTextChannel reqChannel, SocketGuildUser reqUser)
@ -112,7 +112,7 @@ namespace BirthdayBot.UserInterface
Name = "Time Zone Support",
Value = tzhelp
});
await reqChannel.SendMessageAsync(embed: embed.Build());
await reqChannel.SendMessageAsync(embed: embed.Build()).ConfigureAwait(false);
}
private async Task CmdHelpMessage(ShardInstance instance, GuildConfiguration gconf,
@ -139,7 +139,7 @@ namespace BirthdayBot.UserInterface
Value = string.Format(msghelp2,
BackgroundServices.BirthdayRoleUpdate.DefaultAnnounce, BackgroundServices.BirthdayRoleUpdate.DefaultAnnouncePl)
});
await reqChannel.SendMessageAsync(embed: embed.Build());
await reqChannel.SendMessageAsync(embed: embed.Build()).ConfigureAwait(false);
}
private async Task CmdInfo(ShardInstance instance, GuildConfiguration gconf,
@ -174,7 +174,7 @@ namespace BirthdayBot.UserInterface
Name = "Statistics",
Value = strStats.ToString()
});
await reqChannel.SendMessageAsync(embed: embed.Build());
await reqChannel.SendMessageAsync(embed: embed.Build()).ConfigureAwait(false);
}
}
}

View file

@ -41,7 +41,7 @@ namespace BirthdayBot.UserInterface
// Requires a parameter
if (param.Length == 1)
{
await reqChannel.SendMessageAsync(ParameterError, embed: DocWhen.UsageEmbed);
await reqChannel.SendMessageAsync(ParameterError, embed: DocWhen.UsageEmbed).ConfigureAwait(false);
return;
}
@ -72,14 +72,14 @@ namespace BirthdayBot.UserInterface
}
if (searchTarget == null)
{
await reqChannel.SendMessageAsync(BadUserError, embed: DocWhen.UsageEmbed);
await reqChannel.SendMessageAsync(BadUserError, embed: DocWhen.UsageEmbed).ConfigureAwait(false);
return;
}
var searchTargetData = await GuildUserConfiguration.LoadAsync(reqChannel.Guild.Id, searchId);
var searchTargetData = await GuildUserConfiguration.LoadAsync(reqChannel.Guild.Id, searchId).ConfigureAwait(false);
if (!searchTargetData.IsKnown)
{
await reqChannel.SendMessageAsync("I do not have birthday information for that user.");
await reqChannel.SendMessageAsync("I do not have birthday information for that user.").ConfigureAwait(false);
return;
}
@ -88,7 +88,7 @@ namespace BirthdayBot.UserInterface
result += $"`{searchTargetData.BirthDay:00}-{Common.MonthNames[searchTargetData.BirthMonth]}`";
result += searchTargetData.TimeZone == null ? "" : $" - `{searchTargetData.TimeZone}`";
await reqChannel.SendMessageAsync(result);
await reqChannel.SendMessageAsync(result).ConfigureAwait(false);
}
// Creates a file with all birthdays.
@ -99,7 +99,7 @@ namespace BirthdayBot.UserInterface
if (!gconf.IsBotModerator(reqUser))
{
// Do not add detailed usage information to this error message.
await reqChannel.SendMessageAsync(":x: Only bot moderators may use this command.");
await reqChannel.SendMessageAsync(":x: Only bot moderators may use this command.").ConfigureAwait(false);
return;
}
@ -110,17 +110,18 @@ namespace BirthdayBot.UserInterface
if (param[1].ToLower() == "csv") useCsv = true;
else
{
await reqChannel.SendMessageAsync(":x: That is not available as an export format.", embed: DocList.UsageEmbed);
await reqChannel.SendMessageAsync(":x: That is not available as an export format.", embed: DocList.UsageEmbed)
.ConfigureAwait(false);
return;
}
}
else if (param.Length > 2)
{
await reqChannel.SendMessageAsync(ParameterError, embed: DocList.UsageEmbed);
await reqChannel.SendMessageAsync(ParameterError, embed: DocList.UsageEmbed).ConfigureAwait(false);
return;
}
var bdlist = await GetSortedUsersAsync(reqChannel.Guild);
var bdlist = await GetSortedUsersAsync(reqChannel.Guild).ConfigureAwait(false);
var filepath = Path.GetTempPath() + "birthdaybot-" + reqChannel.Guild.Id;
string fileoutput;
@ -134,11 +135,11 @@ namespace BirthdayBot.UserInterface
fileoutput = ListExportNormal(reqChannel, bdlist);
filepath += ".txt.";
}
await File.WriteAllTextAsync(filepath, fileoutput, Encoding.UTF8);
await File.WriteAllTextAsync(filepath, fileoutput, Encoding.UTF8).ConfigureAwait(false);
try
{
await reqChannel.SendFileAsync(filepath, $"Exported {bdlist.Count} birthdays to file.");
await reqChannel.SendFileAsync(filepath, $"Exported {bdlist.Count} birthdays to file.").ConfigureAwait(false);
}
catch (Discord.Net.HttpException)
{
@ -165,7 +166,7 @@ namespace BirthdayBot.UserInterface
var search = DateIndex(now.Month, now.Day) - 8; // begin search 8 days prior to current date UTC
if (search <= 0) search = 366 - Math.Abs(search);
var query = await GetSortedUsersAsync(reqChannel.Guild);
var query = await GetSortedUsersAsync(reqChannel.Guild).ConfigureAwait(false);
var output = new StringBuilder();
var resultCount = 0;
@ -201,7 +202,7 @@ namespace BirthdayBot.UserInterface
output.Append(item);
// If the output is starting to fill up, back out early and prepare to show the result as-is
if (output.Length > 970) goto listfull;
if (output.Length > 930) goto listfull;
}
continue;
@ -211,9 +212,11 @@ namespace BirthdayBot.UserInterface
}
if (resultCount == 0)
await reqChannel.SendMessageAsync("There are no recent or upcoming birthdays (within the last 3 days and/or next 7 days).");
await reqChannel.SendMessageAsync(
"There are no recent or upcoming birthdays (within the last 3 days and/or next 7 days).")
.ConfigureAwait(false);
else
await reqChannel.SendMessageAsync(output.ToString());
await reqChannel.SendMessageAsync(output.ToString()).ConfigureAwait(false);
}
/// <summary>

View file

@ -58,20 +58,22 @@ namespace BirthdayBot.UserInterface
// Ignore those without the proper permissions.
if (!gconf.IsBotModerator(reqUser))
{
await reqChannel.SendMessageAsync(":x: This command may only be used by bot moderators.");
await reqChannel.SendMessageAsync(":x: This command may only be used by bot moderators.").ConfigureAwait(false);
return;
}
if (param.Length < 2)
{
await reqChannel.SendMessageAsync($":x: See `{CommandPrefix}help-config` for information on how to use this command.");
await reqChannel.SendMessageAsync($":x: See `{CommandPrefix}help-config` for information on how to use this command.")
.ConfigureAwait(false);
return;
}
// Special case: Restrict 'modrole' to only guild managers, not mods
if (string.Equals(param[1], "modrole", StringComparison.OrdinalIgnoreCase) && !reqUser.GuildPermissions.ManageGuild)
{
await reqChannel.SendMessageAsync(":x: This command may only be used by those with the `Manage Server` permission.");
await reqChannel.SendMessageAsync(":x: This command may only be used by those with the `Manage Server` permission.")
.ConfigureAwait(false);
return;
}
@ -81,7 +83,7 @@ namespace BirthdayBot.UserInterface
if (_subcommands.TryGetValue(confparam[0], out ConfigSubcommand h))
{
await h(confparam, gconf, reqChannel);
await h(confparam, gconf, reqChannel).ConfigureAwait(false);
}
}
@ -91,7 +93,8 @@ namespace BirthdayBot.UserInterface
{
if (param.Length != 2)
{
await reqChannel.SendMessageAsync(":x: A role name, role mention, or ID value must be specified.");
await reqChannel.SendMessageAsync(":x: A role name, role mention, or ID value must be specified.")
.ConfigureAwait(false);
return;
}
var guild = reqChannel.Guild;
@ -99,17 +102,18 @@ namespace BirthdayBot.UserInterface
if (role == null)
{
await reqChannel.SendMessageAsync(RoleInputError);
await reqChannel.SendMessageAsync(RoleInputError).ConfigureAwait(false);
}
else if (role.Id == reqChannel.Guild.EveryoneRole.Id)
{
await reqChannel.SendMessageAsync(":x: You cannot set that as the birthday role.");
await reqChannel.SendMessageAsync(":x: You cannot set that as the birthday role.").ConfigureAwait(false);
}
else
{
gconf.RoleId = role.Id;
await gconf.UpdateAsync();
await reqChannel.SendMessageAsync($":white_check_mark: The birthday role has been set as **{role.Name}**.");
await gconf.UpdateAsync().ConfigureAwait(false);
await reqChannel.SendMessageAsync($":white_check_mark: The birthday role has been set as **{role.Name}**.")
.ConfigureAwait(false);
}
}
@ -119,7 +123,7 @@ namespace BirthdayBot.UserInterface
const string InputErr = ":x: You must specify either `off` or `on` in this setting.";
if (param.Length != 2)
{
await reqChannel.SendMessageAsync(InputErr);
await reqChannel.SendMessageAsync(InputErr).ConfigureAwait(false);
return;
}
@ -138,13 +142,13 @@ namespace BirthdayBot.UserInterface
}
else
{
await reqChannel.SendMessageAsync(InputErr);
await reqChannel.SendMessageAsync(InputErr).ConfigureAwait(false);
return;
}
gconf.AnnouncePing = setting;
await gconf.UpdateAsync();
await reqChannel.SendMessageAsync(result);
await gconf.UpdateAsync().ConfigureAwait(false);
await reqChannel.SendMessageAsync(result).ConfigureAwait(false);
}
// Announcement channel set
@ -155,13 +159,15 @@ namespace BirthdayBot.UserInterface
// Extra detail: Show a unique message if a channel hadn't been set prior.
if (!gconf.AnnounceChannelId.HasValue)
{
await reqChannel.SendMessageAsync(":x: There is no announcement channel set. Nothing to unset.");
await reqChannel.SendMessageAsync(":x: There is no announcement channel set. Nothing to unset.")
.ConfigureAwait(false);
return;
}
gconf.AnnounceChannelId = null;
await gconf.UpdateAsync();
await reqChannel.SendMessageAsync(":white_check_mark: The announcement channel has been unset.");
await reqChannel.SendMessageAsync(":white_check_mark: The announcement channel has been unset.")
.ConfigureAwait(false);
}
else
{
@ -194,16 +200,17 @@ namespace BirthdayBot.UserInterface
if (chId != 0) chTt = reqChannel.Guild.GetTextChannel(chId);
if (chTt == null)
{
await reqChannel.SendMessageAsync(":x: Unable to find the specified channel.");
await reqChannel.SendMessageAsync(":x: Unable to find the specified channel.").ConfigureAwait(false);
return;
}
// Update the value
gconf.AnnounceChannelId = chId;
await gconf.UpdateAsync();
await gconf.UpdateAsync().ConfigureAwait(false);
// Report the success
await reqChannel.SendMessageAsync($":white_check_mark: The announcement channel is now set to <#{chId}>.");
await reqChannel.SendMessageAsync($":white_check_mark: The announcement channel is now set to <#{chId}>.")
.ConfigureAwait(false);
}
}
@ -212,7 +219,8 @@ namespace BirthdayBot.UserInterface
{
if (param.Length != 2)
{
await reqChannel.SendMessageAsync(":x: A role name, role mention, or ID value must be specified.");
await reqChannel.SendMessageAsync(":x: A role name, role mention, or ID value must be specified.")
.ConfigureAwait(false);
return;
}
var guild = reqChannel.Guild;
@ -220,13 +228,14 @@ namespace BirthdayBot.UserInterface
if (role == null)
{
await reqChannel.SendMessageAsync(RoleInputError);
await reqChannel.SendMessageAsync(RoleInputError).ConfigureAwait(false);
}
else
{
gconf.ModeratorRole = role.Id;
await gconf.UpdateAsync();
await reqChannel.SendMessageAsync($":white_check_mark: The moderator role is now **{role.Name}**.");
await gconf.UpdateAsync().ConfigureAwait(false);
await reqChannel.SendMessageAsync($":white_check_mark: The moderator role is now **{role.Name}**.")
.ConfigureAwait(false);
}
}
@ -238,13 +247,14 @@ namespace BirthdayBot.UserInterface
// Extra detail: Show a unique message if there is no set zone.
if (!gconf.AnnounceChannelId.HasValue)
{
await reqChannel.SendMessageAsync(":x: A default zone is not set. Nothing to unset.");
await reqChannel.SendMessageAsync(":x: A default zone is not set. Nothing to unset.").ConfigureAwait(false);
return;
}
gconf.TimeZone = null;
await gconf.UpdateAsync();
await reqChannel.SendMessageAsync(":white_check_mark: The default time zone preference has been removed.");
await gconf.UpdateAsync().ConfigureAwait(false);
await reqChannel.SendMessageAsync(":white_check_mark: The default time zone preference has been removed.")
.ConfigureAwait(false);
}
else
{
@ -262,10 +272,11 @@ namespace BirthdayBot.UserInterface
// Update value
gconf.TimeZone = zone;
await gconf.UpdateAsync();
await gconf.UpdateAsync().ConfigureAwait(false);
// Report the success
await reqChannel.SendMessageAsync($":white_check_mark: The server's time zone has been set to **{zone}**.");
await reqChannel.SendMessageAsync($":white_check_mark: The server's time zone has been set to **{zone}**.")
.ConfigureAwait(false);
}
}
@ -274,7 +285,7 @@ namespace BirthdayBot.UserInterface
{
if (param.Length != 2)
{
await reqChannel.SendMessageAsync(ParameterError + ConfErrorPostfix);
await reqChannel.SendMessageAsync(ParameterError + ConfErrorPostfix).ConfigureAwait(false);
return;
}
@ -282,33 +293,33 @@ namespace BirthdayBot.UserInterface
if (!TryGetUserId(param[1], out ulong inputId))
{
await reqChannel.SendMessageAsync(BadUserError);
await reqChannel.SendMessageAsync(BadUserError).ConfigureAwait(false);
return;
}
var isBanned = await gconf.IsUserBlockedAsync(inputId);
var isBanned = await gconf.IsUserBlockedAsync(inputId).ConfigureAwait(false);
if (doBan)
{
if (!isBanned)
{
await gconf.BlockUserAsync(inputId);
await reqChannel.SendMessageAsync(":white_check_mark: User has been blocked.");
await gconf.BlockUserAsync(inputId).ConfigureAwait(false);
await reqChannel.SendMessageAsync(":white_check_mark: User has been blocked.").ConfigureAwait(false);
}
else
{
// TODO bug: this is incorrectly always displayed when in moderated mode
await reqChannel.SendMessageAsync(":white_check_mark: User is already blocked.");
await reqChannel.SendMessageAsync(":white_check_mark: User is already blocked.").ConfigureAwait(false);
}
}
else
{
if (await gconf.UnblockUserAsync(inputId))
if (await gconf.UnblockUserAsync(inputId).ConfigureAwait(false))
{
await reqChannel.SendMessageAsync(":white_check_mark: User is now unblocked.");
await reqChannel.SendMessageAsync(":white_check_mark: User is now unblocked.").ConfigureAwait(false);
}
else
{
await reqChannel.SendMessageAsync(":white_check_mark: The specified user is not blocked.");
await reqChannel.SendMessageAsync(":white_check_mark: The specified user is not blocked.").ConfigureAwait(false);
}
}
}
@ -318,7 +329,7 @@ namespace BirthdayBot.UserInterface
{
if (param.Length != 2)
{
await reqChannel.SendMessageAsync(ParameterError + ConfErrorPostfix);
await reqChannel.SendMessageAsync(ParameterError + ConfErrorPostfix).ConfigureAwait(false);
return;
}
@ -328,19 +339,22 @@ namespace BirthdayBot.UserInterface
else if (parameter == "off") modSet = false;
else
{
await reqChannel.SendMessageAsync(":x: Expecting `on` or `off` as a parameter." + ConfErrorPostfix);
await reqChannel.SendMessageAsync(":x: Expecting `on` or `off` as a parameter." + ConfErrorPostfix)
.ConfigureAwait(false);
return;
}
if (gconf.IsModerated == modSet)
{
await reqChannel.SendMessageAsync($":white_check_mark: Moderated mode is already {parameter}.");
await reqChannel.SendMessageAsync($":white_check_mark: Moderated mode is already {parameter}.")
.ConfigureAwait(false);
}
else
{
gconf.IsModerated = modSet;
await gconf.UpdateAsync();
await reqChannel.SendMessageAsync($":white_check_mark: Moderated mode has been turned {parameter}.");
await gconf.UpdateAsync().ConfigureAwait(false);
await reqChannel.SendMessageAsync($":white_check_mark: Moderated mode has been turned {parameter}.")
.ConfigureAwait(false);
}
}
@ -366,9 +380,9 @@ namespace BirthdayBot.UserInterface
if (!plural) update = (newmsg, gconf.AnnounceMessages.Item2);
else update = (gconf.AnnounceMessages.Item1, newmsg);
gconf.AnnounceMessages = update;
await gconf.UpdateAsync();
await gconf.UpdateAsync().ConfigureAwait(false);
await reqChannel.SendMessageAsync(string.Format(":white_check_mark: The {0} birthday announcement message has been {1}.",
plural ? "plural" : "singular", clear ? "reset" : "updated"));
plural ? "plural" : "singular", clear ? "reset" : "updated")).ConfigureAwait(false);
}
#endregion
@ -381,20 +395,20 @@ namespace BirthdayBot.UserInterface
if (param.Length != 3)
{
await reqChannel.SendMessageAsync(ParameterError, embed: DocOverride.UsageEmbed);
await reqChannel.SendMessageAsync(ParameterError, embed: DocOverride.UsageEmbed).ConfigureAwait(false);
return;
}
// Second parameter: determine the user to act as
if (!TryGetUserId(param[1], out ulong user))
{
await reqChannel.SendMessageAsync(BadUserError, embed: DocOverride.UsageEmbed);
await reqChannel.SendMessageAsync(BadUserError, embed: DocOverride.UsageEmbed).ConfigureAwait(false);
return;
}
var overuser = reqChannel.Guild.GetUser(user);
if (overuser == null)
{
await reqChannel.SendMessageAsync(BadUserError, embed: DocOverride.UsageEmbed);
await reqChannel.SendMessageAsync(BadUserError, embed: DocOverride.UsageEmbed).ConfigureAwait(false);
return;
}
@ -414,13 +428,17 @@ namespace BirthdayBot.UserInterface
}
if (!_usercommands.TryGetValue(cmdsearch, out CommandHandler action))
{
await reqChannel.SendMessageAsync($":x: `{cmdsearch}` is not an overridable command.", embed: DocOverride.UsageEmbed);
await reqChannel.SendMessageAsync(
$":x: `{cmdsearch}` is not an overridable command.", embed: DocOverride.UsageEmbed)
.ConfigureAwait(false);
return;
}
// Preparations complete. Run the command.
await reqChannel.SendMessageAsync($"Executing `{cmdsearch.ToLower()}` on behalf of {overuser.Nickname ?? overuser.Username}:");
await action.Invoke(instance, gconf, overparam, reqChannel, overuser);
await reqChannel.SendMessageAsync(
$"Executing `{cmdsearch.ToLower()}` on behalf of {overuser.Nickname ?? overuser.Username}:")
.ConfigureAwait(false);
await action.Invoke(instance, gconf, overparam, reqChannel, overuser).ConfigureAwait(false);
}
// Publicly available command that immediately processes the current guild,
@ -434,7 +452,7 @@ namespace BirthdayBot.UserInterface
{
// Too many parameters
// Note: Non-standard error display
await reqChannel.SendMessageAsync(NoParameterError);
await reqChannel.SendMessageAsync(NoParameterError).ConfigureAwait(false);
return;
}
@ -444,8 +462,8 @@ namespace BirthdayBot.UserInterface
try
{
var result = await instance.ForceBirthdayUpdateAsync(reqChannel.Guild);
await reqChannel.SendMessageAsync(result);
var result = await instance.ForceBirthdayUpdateAsync(reqChannel.Guild).ConfigureAwait(false);
await reqChannel.SendMessageAsync(result).ConfigureAwait(false);
}
catch (Exception ex)
{

View file

@ -117,7 +117,7 @@ namespace BirthdayBot.UserInterface
// Requires one parameter. Optionally two.
if (param.Length < 2 || param.Length > 3)
{
await reqChannel.SendMessageAsync(ParameterError, embed: DocSet.UsageEmbed);
await reqChannel.SendMessageAsync(ParameterError, embed: DocSet.UsageEmbed).ConfigureAwait(false);
return;
}
@ -141,9 +141,9 @@ namespace BirthdayBot.UserInterface
bool known; // Extra detail: Bot's response changes if the user was previously unknown.
try
{
var user = await GuildUserConfiguration.LoadAsync(gconf.GuildId, reqUser.Id);
var user = await GuildUserConfiguration.LoadAsync(gconf.GuildId, reqUser.Id).ConfigureAwait(false);
known = user.IsKnown;
await user.UpdateAsync(bmonth, bday, btz);
await user.UpdateAsync(bmonth, bday, btz).ConfigureAwait(false);
}
catch (Exception ex)
{
@ -154,11 +154,13 @@ namespace BirthdayBot.UserInterface
}
if (known)
{
await reqChannel.SendMessageAsync(":white_check_mark: Your information has been updated.");
await reqChannel.SendMessageAsync(":white_check_mark: Your information has been updated.")
.ConfigureAwait(false);
}
else
{
await reqChannel.SendMessageAsync(":white_check_mark: Your birthday has been recorded.");
await reqChannel.SendMessageAsync(":white_check_mark: Your birthday has been recorded.")
.ConfigureAwait(false);
}
}
@ -167,15 +169,16 @@ namespace BirthdayBot.UserInterface
{
if (param.Length != 2)
{
await reqChannel.SendMessageAsync(ParameterError, embed: DocZone.UsageEmbed);
await reqChannel.SendMessageAsync(ParameterError, embed: DocZone.UsageEmbed).ConfigureAwait(false);
return;
}
var user = await GuildUserConfiguration.LoadAsync(gconf.GuildId, reqUser.Id);
var user = await GuildUserConfiguration.LoadAsync(gconf.GuildId, reqUser.Id).ConfigureAwait(false);
if (!user.IsKnown)
{
await reqChannel.SendMessageAsync(":x: You may only update your time zone when you have a birthday registered."
+ $" Refer to the `{CommandPrefix}set` command.", embed: DocZone.UsageEmbed);
+ $" Refer to the `{CommandPrefix}set` command.", embed: DocZone.UsageEmbed)
.ConfigureAwait(false);
return;
}
@ -189,9 +192,10 @@ namespace BirthdayBot.UserInterface
reqChannel.SendMessageAsync(ex.Message, embed: DocZone.UsageEmbed).Wait();
return;
}
await user.UpdateAsync(user.BirthMonth, user.BirthDay, btz);
await user.UpdateAsync(user.BirthMonth, user.BirthDay, btz).ConfigureAwait(false);
await reqChannel.SendMessageAsync($":white_check_mark: Your time zone has been updated to **{btz}**.");
await reqChannel.SendMessageAsync($":white_check_mark: Your time zone has been updated to **{btz}**.")
.ConfigureAwait(false);
}
private async Task CmdRemove(ShardInstance instance, GuildConfiguration gconf,
@ -200,22 +204,24 @@ namespace BirthdayBot.UserInterface
// Parameter count check
if (param.Length != 1)
{
await reqChannel.SendMessageAsync(NoParameterError, embed: DocRemove.UsageEmbed);
await reqChannel.SendMessageAsync(NoParameterError, embed: DocRemove.UsageEmbed).ConfigureAwait(false);
return;
}
// Extra detail: Send a notification if the user isn't actually known by the bot.
bool known;
var u = await GuildUserConfiguration.LoadAsync(gconf.GuildId, reqUser.Id);
var u = await GuildUserConfiguration.LoadAsync(gconf.GuildId, reqUser.Id).ConfigureAwait(false);
known = u.IsKnown;
await u.DeleteAsync();
await u.DeleteAsync().ConfigureAwait(false);
if (!known)
{
await reqChannel.SendMessageAsync(":white_check_mark: This bot already does not contain your information.");
await reqChannel.SendMessageAsync(":white_check_mark: This bot already does not contain your information.")
.ConfigureAwait(false);
}
else
{
await reqChannel.SendMessageAsync(":white_check_mark: Your information has been removed.");
await reqChannel.SendMessageAsync(":white_check_mark: Your information has been removed.")
.ConfigureAwait(false);
}
}
}