Skip to content

Commit 2e25e54

Browse files
committed
#335: Private threads hotfix.
#!components: grid-bot ExecuteScript.cs: ~ Take reference to current DiscordShardedClient. ~ Move correspondence calls when errors are called to use LuaError instead of regular follow ups. ~ Add detection of scripts containing code blocks within zero content (causes exception) ~ Rewrite error for scripts that contain unicode to reduce ambiguity. ~ Rename GridJob to ClientJob. ~ Clean up call to PollDeletion ~ Integrate use of GetChannelAsString and GetGuild. OnSlashCommand, OnSlashCommandExecuted, LoggerFactory, ScriptLogger: ~ Clean up usings. ~ Rewrite GetGuildId to use extension methods. ~ Change around references to channel to use extension methods.
1 parent 6258bf0 commit 2e25e54

File tree

5 files changed

+71
-44
lines changed

5 files changed

+71
-44
lines changed

services/grid-bot/lib/commands/Modules/ExecuteScript.cs

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ namespace Grid.Bot.Interactions.Public;
1313
using System.Text.RegularExpressions;
1414

1515
using Discord;
16+
using Discord.WebSocket;
1617
using Discord.Interactions;
1718

1819
using Loretta.CodeAnalysis;
@@ -25,7 +26,7 @@ namespace Grid.Bot.Interactions.Public;
2526
using Commands;
2627
using Extensions;
2728

28-
using GridJob = Client.Job;
29+
using ClientJob = Client.Job;
2930

3031
/// <summary>
3132
/// Interaction handler for executing Luau code.
@@ -36,6 +37,7 @@ namespace Grid.Bot.Interactions.Public;
3637
/// <param name="logger">The <see cref="ILogger"/>.</param>
3738
/// <param name="gridSettings">The <see cref="GridSettings"/>.</param>
3839
/// <param name="scriptsSettings">The <see cref="ScriptsSettings"/>.</param>
40+
/// <param name="discordClient">The <see cref="DiscordShardedClient"/>.</param>
3941
/// <param name="luaUtility">The <see cref="ILuaUtility"/>.</param>
4042
/// <param name="floodCheckerRegistry">The <see cref="IFloodCheckerRegistry"/>.</param>
4143
/// <param name="backtraceUtility">The <see cref="IBacktraceUtility"/>.</param>
@@ -48,6 +50,7 @@ namespace Grid.Bot.Interactions.Public;
4850
/// - <paramref name="logger"/> cannot be null.
4951
/// - <paramref name="gridSettings"/> cannot be null.
5052
/// - <paramref name="scriptsSettings"/> cannot be null.
53+
/// - <paramref name="discordClient"/> cannot be null.
5154
/// - <paramref name="luaUtility"/> cannot be null.
5255
/// - <paramref name="floodCheckerRegistry"/> cannot be null.
5356
/// - <paramref name="backtraceUtility"/> cannot be null.
@@ -64,6 +67,7 @@ public partial class ExecuteScript(
6467
ILogger logger,
6568
GridSettings gridSettings,
6669
ScriptsSettings scriptsSettings,
70+
DiscordShardedClient discordClient,
6771
ILuaUtility luaUtility,
6872
IFloodCheckerRegistry floodCheckerRegistry,
6973
IBacktraceUtility backtraceUtility,
@@ -83,6 +87,7 @@ IGridServerFileHelper gridServerFileHelper
8387
private readonly GridSettings _gridSettings = gridSettings ?? throw new ArgumentNullException(nameof(gridSettings));
8488
private readonly ScriptsSettings _scriptsSettings = scriptsSettings ?? throw new ArgumentNullException(nameof(scriptsSettings));
8589

90+
private readonly DiscordShardedClient _discordClient = discordClient ?? throw new ArgumentNullException(nameof(discordClient));
8691
private readonly ILuaUtility _luaUtility = luaUtility ?? throw new ArgumentNullException(nameof(luaUtility));
8792
private readonly IFloodCheckerRegistry _floodCheckerRegistry = floodCheckerRegistry ?? throw new ArgumentNullException(nameof(floodCheckerRegistry));
8893
private readonly IBacktraceUtility _backtraceUtility = backtraceUtility ?? throw new ArgumentNullException(nameof(backtraceUtility));
@@ -304,12 +309,20 @@ string script
304309
{
305310
if (string.IsNullOrWhiteSpace(script))
306311
{
307-
await FollowupAsync("The script cannot be empty.");
312+
await LuaErrorAsync("The script cannot be empty!");
308313

309314
return;
310315
}
311316

312317
script = GetCodeBlockContents(script);
318+
319+
if (string.IsNullOrEmpty(script))
320+
{
321+
await LuaErrorAsync("There must be content within a code block!");
322+
323+
return;
324+
}
325+
313326
script = EscapeQuotes(script);
314327

315328
var originalScript = script;
@@ -318,7 +331,7 @@ string script
318331

319332
if (ContainsUnicode(script))
320333
{
321-
await FollowupAsync("The script cannot contain unicode characters as grid-servers cannot support unicode in transit.");
334+
await LuaErrorAsync("Scripts can only contain ASCII characters!");
322335

323336
return;
324337
}
@@ -352,7 +365,7 @@ string script
352365
#endif
353366

354367

355-
var gridJob = new GridJob() { id = scriptId, expirationInSeconds = _gridSettings.ScriptExecutionJobMaxTimeout.TotalSeconds };
368+
var gridJob = new ClientJob() { id = scriptId, expirationInSeconds = _gridSettings.ScriptExecutionJobMaxTimeout.TotalSeconds };
356369
var job = new Job(Guid.NewGuid().ToString());
357370

358371
var sw = Stopwatch.StartNew();
@@ -461,9 +474,8 @@ string script
461474
scriptName
462475
);
463476
scriptName.PollDeletion(
464-
10,
465-
ex => _logger.Warning("Failed to delete '{0}' because: {1}", scriptName, ex.Message),
466-
() => _logger.Debug(
477+
onFailure: ex => _logger.Warning("Failed to delete '{0}' because: {1}", scriptName, ex.Message),
478+
onSuccess: () => _logger.Debug(
467479
"Successfully deleted the script '{0}' at path '{1}'!",
468480
scriptId,
469481
scriptName
@@ -493,10 +505,8 @@ private async Task AlertForSystem(string script, string originalScript, string s
493505
_backtraceUtility.UploadException(ex);
494506

495507
var userInfo = Context.User.ToString();
496-
var guildInfo = Context.Guild?.ToString() ?? "DMs";
497-
498-
/* Temporary until mfdlabs/grid-bot#335 is resolved */
499-
var channelInfo = Context.Channel?.ToString() ?? Context.Interaction.ChannelId?.ToString() ?? "Thread";
508+
var guildInfo = Context.Interaction.GetGuild(_discordClient)?.ToString() ?? "DMs";
509+
var channelInfo = Context.Interaction.GetChannelAsString();
500510

501511
// Script & original script in attachments
502512
var scriptAttachment = new FileAttachment(new MemoryStream(Encoding.ASCII.GetBytes(script)), "script.lua");

services/grid-bot/lib/events/Events/OnSlashCommand.cs

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,14 @@
44
using System.Threading.Tasks;
55
using System.Collections.Generic;
66

7+
using Discord;
78
using Discord.WebSocket;
89
using Discord.Interactions;
910

1011
using Prometheus;
1112

1213
using Utility;
13-
using Discord;
14+
using Extensions;
1415

1516
/// <summary>
1617
/// Event handler for interactions.
@@ -87,14 +88,8 @@ ILoggerFactory loggerFactory
8788
}
8889
);
8990

90-
private static string GetGuildId(SocketInteraction interaction)
91-
{
92-
/* Always false in private thread channels, please look into discord-net/Discord.Net#2997 and mfdlabs/grid-bot#335 */
93-
if (interaction.Channel is SocketGuildChannel guildChannel)
94-
return guildChannel.Guild.Id.ToString();
95-
96-
return "DM";
97-
}
91+
private string GetGuildId(SocketInteraction interaction)
92+
=> interaction.GetGuild(_client).ToString() ?? "DM";
9893

9994
/// <summary>
10095
/// Invoke the event handler.
@@ -149,8 +144,7 @@ public async Task Invoke(SocketInteraction interaction)
149144

150145
_totalUsersBypassedMaintenance.WithLabels(
151146
interaction.User.Id.ToString(),
152-
/* Temporary until mfdlabs/grid-bot#335 is resolved */
153-
interaction.Channel?.Id.ToString() ?? interaction.ChannelId?.ToString() ?? "Thread",
147+
interaction.GetChannelAsString(),
154148
GetGuildId(interaction)
155149
).Inc();
156150
}
@@ -159,8 +153,7 @@ public async Task Invoke(SocketInteraction interaction)
159153
{
160154
_totalBlacklistedUserAttemptedInteractions.WithLabels(
161155
interaction.User.Id.ToString(),
162-
/* Temporary until mfdlabs/grid-bot#335 is resolved */
163-
interaction.Channel?.Id.ToString() ?? interaction.ChannelId?.ToString() ?? "Thread",
156+
interaction.GetChannelAsString(),
164157
GetGuildId(interaction)
165158
).Inc();
166159

services/grid-bot/lib/events/Events/OnSlashCommandExecuted.cs

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,16 @@ namespace Grid.Bot.Events;
66
using System.Threading.Tasks;
77

88
using Discord;
9+
using Discord.WebSocket;
910
using Discord.Interactions;
1011

1112
using Prometheus;
1213

1314
using Logging;
1415

1516
using Utility;
17+
using Extensions;
18+
1619

1720
/// <summary>
1821
/// Invoked when slash commands are executed.
@@ -23,15 +26,18 @@ namespace Grid.Bot.Events;
2326
/// <param name="logger">The <see cref="ILogger"/>.</param>
2427
/// <param name="backtraceUtility">The <see cref="BacktraceUtility"/>.</param>
2528
/// <param name="discordRolesSettings">The <see cref="DiscordRolesSettings"/>.</param>
29+
/// <param name="discordClient">The <see cref="DiscordShardedClient"/>.</param>
2630
/// <exception cref="ArgumentNullException">
2731
/// - <paramref name="logger"/> cannot be null.
2832
/// - <paramref name="backtraceUtility"/> cannot be null.
2933
/// - <paramref name="discordRolesSettings"/> cannot be null.
34+
/// - <paramref name="discordClient"/> cannot be null.
3035
/// </exception>
3136
public class OnInteractionExecuted(
3237
ILogger logger,
3338
IBacktraceUtility backtraceUtility,
34-
DiscordRolesSettings discordRolesSettings
39+
DiscordRolesSettings discordRolesSettings,
40+
DiscordShardedClient discordClient
3541
)
3642
{
3743
private const string UnhandledExceptionOccurredFromCommand = "An error occured with the command:";
@@ -40,6 +46,7 @@ DiscordRolesSettings discordRolesSettings
4046

4147
private readonly ILogger _logger = logger ?? throw new ArgumentNullException(nameof(logger));
4248
private readonly IBacktraceUtility _backtraceUtility = backtraceUtility ?? throw new ArgumentNullException(nameof(backtraceUtility));
49+
private readonly DiscordShardedClient _discordClient = discordClient ?? throw new ArgumentNullException(nameof(discordClient));
4350

4451
private readonly Counter _totalInteractionsFailed = Metrics.CreateCounter(
4552
"grid_interactions_failed_total",
@@ -51,9 +58,9 @@ DiscordRolesSettings discordRolesSettings
5158
"interaction_guild_id"
5259
);
5360

54-
private string GetGuildId(IInteractionContext context)
61+
private string GetGuildId(SocketInteraction interaction)
5562
{
56-
return context.Guild?.Id.ToString() ?? "DM";
63+
return interaction.GetGuild(_discordClient)?.Id.ToString() ?? "DM";
5764
}
5865

5966
/// <summary>
@@ -64,7 +71,8 @@ private string GetGuildId(IInteractionContext context)
6471
/// <param name="result">The <see cref="IResult"/>.</param>
6572
public async Task Invoke(ICommandInfo command, IInteractionContext context, IResult result)
6673
{
67-
var interaction = context.Interaction;
74+
if (context.Interaction is not SocketInteraction interaction)
75+
return;
6876

6977
if (!result.IsSuccess)
7078
{
@@ -75,8 +83,8 @@ public async Task Invoke(ICommandInfo command, IInteractionContext context, IRes
7583
interaction.Id.ToString(),
7684
interaction.User.Id.ToString(),
7785
/* Temporary until mfdlabs/grid-bot#335 is resolved */
78-
interaction.ChannelId?.ToString() ?? "Thread",
79-
GetGuildId(context)
86+
interaction.GetChannelAsString(),
87+
GetGuildId(interaction)
8088
).Inc();
8189

8290
if (result is not ExecuteResult executeResult)

services/grid-bot/lib/utility/Implementation/LoggerFactory.cs

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,24 @@
11
namespace Grid.Bot.Utility;
22

3+
using System;
4+
35
using Discord.WebSocket;
46

57
using Logging;
68

9+
using Extensions;
10+
711
/// <summary>
812
/// Implementation of <see cref="ILoggerFactory"/>.
913
/// </summary>
14+
/// <param name="discordClient">The <see cref="DiscordShardedClient"/>.</param>
15+
/// <exception cref="ArgumentNullException"><paramref name="discordClient"/> cannot be null.</exception>
1016
/// <seealso cref="ILoggerFactory"/>
1117
/// <seealso cref="ILogger"/>
12-
public class LoggerFactory : ILoggerFactory
18+
public class LoggerFactory(DiscordShardedClient discordClient) : ILoggerFactory
1319
{
20+
private readonly DiscordShardedClient _discordClient = discordClient ?? throw new ArgumentNullException(nameof(discordClient));
21+
1422
/// <inheritdoc cref="ILoggerFactory.CreateLogger(SocketInteraction)"/>
1523
public ILogger CreateLogger(SocketInteraction interaction)
1624
{
@@ -21,12 +29,14 @@ public ILogger CreateLogger(SocketInteraction interaction)
2129
logToFileSystem: false
2230
);
2331

24-
logger.CustomLogPrefixes.Add(() => interaction.ChannelId?.ToString() ?? "Thread");
25-
logger.CustomLogPrefixes.Add(() => interaction.User.Id.ToString());
32+
logger.CustomLogPrefixes.Add(() => interaction.GetChannelAsString());
33+
logger.CustomLogPrefixes.Add(() => interaction.User.ToString());
34+
35+
var guild = interaction.GetGuild(_discordClient);
2636

2737
// Add guild id if the interaction is from a guild.
28-
if (interaction.Channel is SocketGuildChannel guildChannel)
29-
logger.CustomLogPrefixes.Add(() => guildChannel.Guild.Id.ToString());
38+
if (guild is not null)
39+
logger.CustomLogPrefixes.Add(() => guild.ToString());
3040

3141
return logger;
3242
}
@@ -41,13 +51,12 @@ public ILogger CreateLogger(SocketMessage message)
4151
logToFileSystem: false
4252
);
4353

44-
logger.CustomLogPrefixes.Add(() => message.Channel.Id.ToString());
45-
logger.CustomLogPrefixes.Add(() => message.Author.Id.ToString());
54+
logger.CustomLogPrefixes.Add(() => message.Channel.ToString());
55+
logger.CustomLogPrefixes.Add(() => message.Author.ToString());
4656

4757
// Add guild id if the message is from a guild.
48-
/* Always false in private thread channels, please look into discord-net/Discord.Net#2997 and mfdlabs/grid-bot#335 */
4958
if (message.Channel is SocketGuildChannel guildChannel)
50-
logger.CustomLogPrefixes.Add(() => guildChannel.Guild.Id.ToString());
59+
logger.CustomLogPrefixes.Add(() => guildChannel.Guild.ToString());
5160

5261
return logger;
5362
}

services/grid-bot/lib/utility/Implementation/ScriptLogger.cs

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,17 @@ namespace Grid.Bot.Utility;
99
using System.Collections.Concurrent;
1010

1111
using Discord;
12+
using Discord.WebSocket;
1213
using Discord.Interactions;
1314

1415
using Newtonsoft.Json;
1516

1617
using Random;
1718
using Networking;
1819

20+
using Extensions;
21+
22+
1923
/// <summary>
2024
/// Handles sending alerts to a Discord webhook.
2125
/// </summary>
@@ -26,6 +30,7 @@ public class ScriptLogger : IScriptLogger
2630
private readonly IPercentageInvoker _percentageInvoker;
2731
private readonly IHttpClientFactory _httpClientFactory;
2832
private readonly ScriptsSettings _scriptsSettings;
33+
private readonly DiscordShardedClient _discordClient;
2934

3035
private readonly ConcurrentBag<string> _scriptHashes = new();
3136

@@ -36,23 +41,27 @@ public class ScriptLogger : IScriptLogger
3641
/// <param name="percentageInvoker">The <see cref="IPercentageInvoker"/> to use.</param>
3742
/// <param name="httpClientFactory">The <see cref="IHttpClientFactory"/> to use.</param>
3843
/// <param name="scriptsSettings">The <see cref="ScriptsSettings"/> to use.</param>
44+
/// <param name="discordClient">The <see cref="DiscordShardedClient"/> to use.</param>
3945
/// <exception cref="ArgumentNullException">
4046
/// - <paramref name="localIpAddressProvider"/> cannot be null.
4147
/// - <paramref name="percentageInvoker"/> cannot be null.
4248
/// - <paramref name="httpClientFactory"/> cannot be null.
4349
/// - <paramref name="scriptsSettings"/> cannot be null.
50+
/// - <paramref name="discordClient"/> cannot be null.
4451
/// </exception>
4552
public ScriptLogger(
4653
ILocalIpAddressProvider localIpAddressProvider,
4754
IPercentageInvoker percentageInvoker,
4855
IHttpClientFactory httpClientFactory,
49-
ScriptsSettings scriptsSettings
56+
ScriptsSettings scriptsSettings,
57+
DiscordShardedClient discordClient
5058
)
5159
{
5260
_localIpAddressProvider = localIpAddressProvider ?? throw new ArgumentNullException(nameof(localIpAddressProvider));
5361
_percentageInvoker = percentageInvoker ?? throw new ArgumentNullException(nameof(percentageInvoker));
5462
_httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory));
5563
_scriptsSettings = scriptsSettings ?? throw new ArgumentNullException(nameof(scriptsSettings));
64+
_discordClient = discordClient ?? throw new ArgumentNullException(nameof(discordClient));
5665

5766
foreach (var hash in _scriptsSettings.LoggedScriptHashes)
5867
_scriptHashes.Add(hash);
@@ -83,10 +92,8 @@ public async Task LogScriptAsync(string script, ShardedInteractionContext contex
8392
// username based off machine info
8493
var username = $"{Environment.MachineName} ({_localIpAddressProvider.AddressV4} / {_localIpAddressProvider.AddressV6})";
8594
var userInfo = context.User.ToString();
86-
var guildInfo = context.Guild?.ToString() ?? "DMs";
87-
88-
/* Temporary until mfdlabs/grid-bot#335 is resolved */
89-
var channelInfo = context.Channel?.ToString() ?? context.Interaction.ChannelId?.ToString() ?? "Thread";
95+
var guildInfo = context.Interaction.GetGuild(_discordClient)?.ToString() ?? "DMs";
96+
var channelInfo = context.Interaction.GetChannelAsString();
9097

9198
// Get a SHA256 hash of the script (hex)
9299
var scriptHash = string.Join("", SHA256.HashData(Encoding.UTF8.GetBytes(script)).Select(b => b.ToString("x2")));

0 commit comments

Comments
 (0)