-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCommandHandler.cs
694 lines (592 loc) · 27.3 KB
/
CommandHandler.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
using BattleBitAPI.Common;
using BBRAPIModules;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
namespace Commands;
[Module("Basic in-game chat command handler library", "1.1.1")]
public class CommandHandler : BattleBitModule
{
public static CommandConfiguration CommandConfiguration { get; set; } = null!;
public CommandSettings CommandSettings { get; set; } = null!;
private Dictionary<string, (BattleBitModule Module, MethodInfo Method)> commandCallbacks = new();
[ModuleReference]
public dynamic? PlayerFinder { get; set; }
[ModuleReference]
public dynamic? GranularPermissions { get; set; }
[ModuleReference]
public dynamic? PlayerPermissions { get; set; }
public override void OnModulesLoaded()
{
if (this.PlayerPermissions is null && this.GranularPermissions is null)
{
this.Logger.Warn($"Neither PlayerPermissions nor GranularPermissions is loaded. This module will not be able to check permissions for commands.");
}
this.Register(this);
}
public void Register(BattleBitModule module)
{
foreach (MethodInfo method in module.GetType().GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
{
CommandCallbackAttribute? attribute = method.GetCustomAttribute<CommandCallbackAttribute>();
if (attribute == null)
{
continue;
}
if (attribute.AllowedRoles != Roles.None)
{
this.Logger.Warn($"Command callback method {method.Name} in module {module.GetType().Name} has the deprecated AllowedRoles property set. Use Permissions instead. If you did not make this module, report the issue to the module author.");
}
else if (attribute.Permissions.Length == 1 && attribute.Permissions[0] == "*")
{
this.Logger.Warn($"Command callback method {method.Name} in module {module.GetType().Name} has no permissions set. This is not recommended as it allows everyone to use the command. Commands should have at least one granular permission or a PlayerPermissions role.");
}
// Store command permissions
if (!this.CommandSettings.Settings.ContainsKey(attribute.Name))
{
this.CommandSettings.Settings.Add(attribute.Name, new());
}
// Validate parameter
ParameterInfo[] parameters = method.GetParameters();
if (parameters.Length == 0)
{
this.Logger.Error($"Command callback method {method.Name} in module {module.GetType().Name} has no parameters. Must have at least one parameter of type Context.");
continue;
}
if (parameters[0].ParameterType != typeof(Context))
{
this.Logger.Error($"Command callback method {method.Name} in module {module.GetType().Name} has invalid first parameter. Must be of type Context.");
continue;
}
string command = attribute.Name.Trim().ToLower();
// Prevent duplicate command names in different methods or modules
if (this.commandCallbacks.ContainsKey(command))
{
if (this.commandCallbacks[command].Method == method)
{
continue;
}
if (this.commandCallbacks[command].Module.GetType().Name == module.GetType().Name)
{
this.Logger.Error($"Command callback method {method.Name} in module {module.GetType().Name} has the same command name {command} as another command callback method {this.commandCallbacks[command].Method.Name} in the same module.");
continue;
}
else
{
this.Logger.Error($"Command callback method {method.Name} in module {module.GetType().Name} has the same command name {command} as command callback method {this.commandCallbacks[command].Method.Name} in module {this.commandCallbacks[command].Module.GetType().Name}.");
continue;
}
}
// Prevent parent commands of subcommands (!perm command does not allow !perm add and !perm remove)
foreach (string subcommand in this.commandCallbacks.Keys.Where(c => c.Contains(' ')))
{
if (!subcommand.StartsWith(command))
{
continue;
}
this.Logger.Error($"Command callback {command} in module {module.GetType().Name} conflicts with subcommand {subcommand}.");
continue;
}
// Prevent subcommands of existing commands (!perm add and !perm remove do not allow !perm)
if (command.Contains(' '))
{
string[] subcommandChain = command.Split(' ');
string subcommand = "";
for (int i = 0; i < subcommandChain.Length; i++)
{
subcommand += $"{subcommandChain[i]} ";
if (this.commandCallbacks.ContainsKey(subcommand.Trim()))
{
this.Logger.Error($"Command callback {command} in module {module.GetType().Name} conflicts with parent command {subcommand.Trim()}.");
continue;
}
}
}
this.commandCallbacks.Add(command, (module, method));
}
this.CommandSettings.Save();
}
public override Task<bool> OnPlayerTypedMessage(RunnerPlayer player, ChatChannel channel, string message)
{
if (!IsCommand(message))
{
return Task.FromResult(true);
}
Task.Run(() => this.HandleCommand(new ChatSource(player), message));
return Task.FromResult(false);
}
public override void OnConsoleCommand(string command)
{
if (!IsCommand(command))
{
return;
}
Task.Run(() => this.HandleCommand(new ConsoleSource(), command));
}
public bool IsCommand(string message)
{
return message.StartsWith(CommandConfiguration.CommandPrefix) && message.Length > CommandConfiguration.CommandPrefix.Length;
}
public bool HasPermissionForCommand(RunnerPlayer player, CommandCallbackAttribute attribute)
{
if (attribute.AllowedRoles != Roles.None)
{
this.Logger.Warn($"Command {attribute.Name} has the deprecated AllowedRoles property set. Use Permissions instead. If you did not make this module, report the issue to the module author.");
if (attribute.Permissions.Length == 1 && attribute.Permissions[0] == "*")
{
List<Roles> roles = new();
foreach (Roles role in Enum.GetValues(typeof(Roles)))
{
if (role == Roles.None)
{
continue;
}
if ((attribute.AllowedRoles & role) == role)
{
roles.Add(role);
}
}
this.Logger.Info($"Overwriting Permissions property of command {attribute.Name} with roles {string.Join(", ", roles.Select(r => r.ToString()))} from AllowedRoles property.");
attribute.Permissions = roles.Select(r => r.ToString()).ToArray();
}
}
if (attribute.Permissions.Length == 0 || attribute.Permissions[0] == "*")
{
return true;
}
if (this.PlayerPermissions is null && this.GranularPermissions is null)
{
this.Logger.Warn($"Command {attribute.Name} requires permissions but neither PlayerPermissions nor GranularPermissions is loaded.");
return false;
}
// Permission overwrites from configuration file
string[] requiredPermissions = attribute.Permissions;
if (this.CommandSettings.Settings.ContainsKey(attribute.Name) && this.CommandSettings.Settings.ContainsKey(attribute.Name) && this.CommandSettings.Settings[attribute.Name]?.Permissions is not null)
{
requiredPermissions = this.CommandSettings.Settings[attribute.Name]!.Permissions!;
}
// PlayerPermissions module
if (this.PlayerPermissions is not null)
{
foreach (string requiredPermission in requiredPermissions)
{
if (!Enum.TryParse(requiredPermission, true, out Roles role))
{
this.Logger.Warn($"Command {attribute.Name} could not resolve {requiredPermission} to a Role for PlayerPermissions.");
this.Logger.Info($"This warning can be ignored if you are also using the GranularPermissions module as the permission may be defined there.");
continue;
}
if (this.PlayerPermissions?.HasPlayerRole(player.SteamID, role))
{
return true;
}
}
}
// GranularPermissions module
if (this.GranularPermissions is not null)
{
foreach (string requiredPermission in requiredPermissions)
{
if (this.GranularPermissions.HasPermission(player.SteamID, requiredPermission))
{
return true;
}
}
}
return false;
}
public void HandleCommand(Source source, string message)
{
string[] fullCommand = parseCommandString(message);
string command = fullCommand[0].Trim().ToLower()[CommandConfiguration.CommandPrefix.Length..];
ChatSource? chatSource = source as ChatSource;
Context errorContext = new Context(source, message, command, Array.Empty<string>(), Array.Empty<object?>(), null, this, null);
int subCommandSkip;
for (subCommandSkip = 1; subCommandSkip < fullCommand.Length && !this.commandCallbacks.ContainsKey(command); subCommandSkip++)
{
command += $" {fullCommand[subCommandSkip]}";
}
if (!this.commandCallbacks.ContainsKey(command))
{
if (chatSource is not null)
{
errorContext.Reply($"<color=\"red\">Command not found: {command}");
}
else
{
errorContext.Reply($"Command not found: {command}");
}
return;
}
fullCommand = new[] { command }.Concat(fullCommand.Skip(subCommandSkip)).ToArray();
(BattleBitModule module, MethodInfo method) = this.commandCallbacks[command];
CommandCallbackAttribute commandCallbackAttribute = method.GetCustomAttribute<CommandCallbackAttribute>()!;
if (source is ConsoleSource && !commandCallbackAttribute.ConsoleCommand)
{
this.Logger.Error($"Command {command} is not a console command.");
return;
}
// Permissions
if (chatSource is not null && !this.HasPermissionForCommand(chatSource.Invoker, commandCallbackAttribute))
{
bool hideInaccessible = CommandConfiguration.HideInaccessibleCommands;
if (this.CommandSettings.Settings[command]?.HideInaccessible is not null)
{
hideInaccessible = this.CommandSettings.Settings[command]!.HideInaccessible!.Value;
}
if (hideInaccessible)
{
errorContext.Reply($"<color=\"red\">Command not found: {command}");
return;
}
errorContext.Reply($"<color=\"red\">You don't have permission to use this command.{Environment.NewLine}<color=\"white\">Required permission: {string.Join(" or ", commandCallbackAttribute.Permissions)}");
return;
}
ParameterInfo[] parameters = method.GetParameters();
bool hasOptional = parameters.Any(p => p.IsOptional);
if (fullCommand.Length - 1 < parameters.Skip(1).Count(p => !p.IsOptional) || fullCommand.Length - 1 > parameters.Length - 1)
{
sendCommandUsageMessage(errorContext, method, $"Require {(hasOptional ? $"between {parameters.Skip(1).Count(p => !p.IsOptional)} and {parameters.Length - 1}" : $"{parameters.Length - 1}")} but got {fullCommand.Length - 1} argument{((fullCommand.Length - 1) == 1 ? "" : "s")}.");
return;
}
object?[] args = new object[parameters.Length];
for (int i = 1; i < parameters.Length; i++)
{
ParameterInfo parameter = parameters[i];
if (parameter.IsOptional && i >= fullCommand.Length)
{
args[i] = parameter.DefaultValue;
continue;
}
string argument = fullCommand[i].Trim();
if (parameter.ParameterType == typeof(string))
{
args[i] = argument;
}
else if (parameter.ParameterType == typeof(RunnerPlayer))
{
RunnerPlayer? targetPlayer = null;
if (ulong.TryParse(argument, out ulong steamId) && this.Server.AllPlayers.FirstOrDefault(p => p.SteamID == steamId) is RunnerPlayer playerBySteamId)
{
args[i] = targetPlayer;
continue;
}
if (this.PlayerFinder is not null)
{
try
{
targetPlayer = this.PlayerFinder.ByNamePart(argument);
}
catch (Exception ex)
{
if (chatSource is not null)
{
errorContext.Reply($"<color=\"red\">Error while searching for player name containing {argument}.{Environment.NewLine}<color=\"white\">{ex.Message}");
}
else
{
this.Logger.Error($"Error while searching for player name containing {argument}.{Environment.NewLine}{ex.Message}");
}
return;
}
if (targetPlayer == null)
{
errorContext.Reply($"Could not find player name containing {argument}.");
return;
}
}
else
{
targetPlayer = this.Server.AllPlayers.FirstOrDefault(p => p.Name.Equals(argument, StringComparison.OrdinalIgnoreCase));
}
if (targetPlayer == null)
{
errorContext.Reply($"Could not find player {argument}.");
return;
}
args[i] = targetPlayer;
}
else
{
if (!tryParseParameter(parameter, argument, out object? parsedValue))
{
sendCommandUsageMessage(errorContext, method, $"Couldn't parse value {argument} to type {parameter.ParameterType.Name}");
return;
}
args[i] = parsedValue;
}
}
args[0] = new Context(source, message, command, fullCommand.Skip(1).ToArray(), args.Skip(1).ToArray(), module, this, commandCallbackAttribute);
object? result = method.Invoke(module, args);
if (result is not null)
{
source.Reply((Context)args[0]!, result.ToString() ?? "No reply");
}
}
private void sendCommandUsageMessage(Context context, MethodInfo method, string? error = null)
{
CommandCallbackAttribute commandCallbackAttribute = method.GetCustomAttribute<CommandCallbackAttribute>()!;
bool hasOptional = method.GetParameters().Any(p => p.IsOptional);
if (context.Source is ChatSource chatSource)
{
context.Reply($"<color=\"red\">Invalid command usage{(error == null ? "" : $" ({error})")}.<color=\"white\"><br><b>Usage</b>: {CommandConfiguration.CommandPrefix}{commandCallbackAttribute.Name} {string.Join(' ', method.GetParameters().Skip(1).Select(s => $"{s.Name}{(s.IsOptional ? "*" : "")}"))}{(hasOptional ? "<br><size=80%>* Parameter is optional." : "")}");
}
else
{
context.Reply($"Invalid command usage{(error == null ? "" : $" ({error})")}.{Environment.NewLine}Usage: {CommandConfiguration.CommandPrefix}{commandCallbackAttribute.Name} {string.Join(' ', method.GetParameters().Skip(1).Select(s => $"{s.Name}{(s.IsOptional ? "*" : "")}"))}{(hasOptional ? $"{Environment.NewLine}* Parameter is optional." : "")}");
}
}
private static bool tryParseParameter(ParameterInfo parameterInfo, string input, out object? parsedValue)
{
parsedValue = null;
try
{
if (parameterInfo.ParameterType.IsEnum)
{
parsedValue = Enum.Parse(parameterInfo.ParameterType, input, true);
}
else
{
Type? targetType = targetType = Nullable.GetUnderlyingType(parameterInfo.ParameterType);
if (targetType is null)
{
targetType = parameterInfo.ParameterType;
}
parsedValue = Convert.ChangeType(input, targetType);
}
return true;
}
catch
{
return false;
}
}
private static string[] parseCommandString(string command)
{
List<string> parameterValues = new();
string[] tokens = command.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
bool insideQuotes = false;
StringBuilder currentValue = new();
foreach (var token in tokens)
{
if (!insideQuotes)
{
if (token.StartsWith("\"") && token.EndsWith("\""))
{
insideQuotes = false;
currentValue.Clear();
parameterValues.Add(token.Substring(1, token.Length - 2));
}
else if (token.StartsWith("\""))
{
insideQuotes = true;
currentValue.Append(token.Substring(1));
}
else
{
parameterValues.Add(token);
}
}
else
{
if (token.EndsWith("\""))
{
insideQuotes = false;
currentValue.Append(" ").Append(token.Substring(0, token.Length - 1));
parameterValues.Add(currentValue.ToString());
currentValue.Clear();
}
else
{
currentValue.Append(" ").Append(token);
}
}
}
return parameterValues.Select(unescapeQuotes).ToArray();
}
private static string unescapeQuotes(string input)
{
return input.Replace("\\\"", "\"");
}
[CommandCallback("help", Description = "Shows this help message", Permissions = new[] { "CommandHandler.Help" }, ConsoleCommand = true)]
public string HelpCommand(Context context, int page = 1)
{
List<string> helpLines = new();
foreach (var (commandKey, (module, method)) in this.commandCallbacks)
{
CommandCallbackAttribute commandCallbackAttribute = method.GetCustomAttribute<CommandCallbackAttribute>()!;
if (context.Source is ChatSource chatSource && !this.HasPermissionForCommand(chatSource.Invoker, commandCallbackAttribute))
{
continue;
}
if (context.Source is ChatSource)
{
helpLines.Add($"<b>{CommandConfiguration.CommandPrefix}{commandCallbackAttribute.Name}</b>{(string.IsNullOrEmpty(commandCallbackAttribute.Description) ? "" : $": {commandCallbackAttribute.Description}")}");
}
else
{
helpLines.Add($"{CommandConfiguration.CommandPrefix}{commandCallbackAttribute.Name}{(string.IsNullOrEmpty(commandCallbackAttribute.Description) ? "" : $": {commandCallbackAttribute.Description}")}");
}
}
int pages = (int)Math.Ceiling((double)helpLines.Count / CommandConfiguration.CommandsPerPage);
if (page < 1 || page > pages)
{
if (context.Source is ChatSource)
{
return $"<color=\"red\">Invalid page number. Must be between 1 and {pages}.";
}
else
{
return $"Invalid page number. Must be between 1 and {pages}.";
}
}
if (context.Source is ChatSource)
{
return $"<#FFA500>Available commands<br><color=\"white\">{Environment.NewLine}{string.Join(Environment.NewLine, helpLines.Skip((page - 1) * CommandConfiguration.CommandsPerPage).Take(CommandConfiguration.CommandsPerPage))}{(pages > 1 ? $"{Environment.NewLine}Page {page} of {pages}{(page < pages ? $" - type !help {page + 1} for next page" : "")}" : "")}";
}
else
{
return $"Available commands{Environment.NewLine}{string.Join(Environment.NewLine, helpLines.Skip((page - 1) * CommandConfiguration.CommandsPerPage).Take(CommandConfiguration.CommandsPerPage))}{(pages > 1 ? $"{Environment.NewLine}Page {page} of {pages}{(page < pages ? $" - type !help {page + 1} for next page" : "")}" : "")}";
}
}
[CommandCallback("cmdhelp", Description = "Shows help for a specific command", Permissions = new[] { "CommandHandler.CommandHelp" }, ConsoleCommand = true)]
public string CommandHelpCommand(Context context, string command)
{
if (!this.commandCallbacks.TryGetValue(command, out var commandCallback))
{
if (context.Source is ChatSource)
{
return $"<color=\"red\">Command {command} not found.<color=\"white\">";
}
else
{
return $"Command {command} not found.";
}
}
CommandCallbackAttribute commandCallbackAttribute = commandCallback.Method.GetCustomAttribute<CommandCallbackAttribute>()!;
if (context.Source is ChatSource chatSource && !this.HasPermissionForCommand(chatSource.Invoker, commandCallbackAttribute))
{
bool hideInaccessible = CommandConfiguration.HideInaccessibleCommands;
if (this.CommandSettings.Settings[command]?.HideInaccessible is not null)
{
hideInaccessible = this.CommandSettings.Settings[command]!.HideInaccessible!.Value;
}
if (hideInaccessible)
{
return $"<color=\"red\">Command {command} not found.";
}
return $"<color=\"red\">You don't have permission to see help about this command.";
}
bool hasOptional = commandCallback.Method.GetParameters().Any(p => p.IsOptional);
if (context.Source is ChatSource)
{
return $"<size=120%>{commandCallback.Module.GetType().Name} {commandCallbackAttribute.Name}<size=100%><br>{commandCallbackAttribute.Description}<br><#F5F5F5>{CommandConfiguration.CommandPrefix}{commandCallbackAttribute.Name} {string.Join(' ', commandCallback.Method.GetParameters().Skip(1).Select(s => $"{s.Name}{(s.IsOptional ? "*" : "")}"))}{(hasOptional ? "<br><color=\"white\"><size=80%>* Parameter is optional." : "")}";
}
else
{
return $"{commandCallback.Module.GetType().Name} {commandCallbackAttribute.Name}{Environment.NewLine}{commandCallbackAttribute.Description}{Environment.NewLine}{CommandConfiguration.CommandPrefix}{commandCallbackAttribute.Name} {string.Join(' ', commandCallback.Method.GetParameters().Skip(1).Select(s => $"{s.Name}{(s.IsOptional ? "*" : "")}"))}{(hasOptional ? $"{Environment.NewLine}* Parameter is optional." : "")}";
}
}
}
public class CommandCallbackAttribute : Attribute
{
public string Name { get; set; }
public string Description { get; set; } = string.Empty;
public Roles AllowedRoles { get; set; } = Roles.None;
public string[] Permissions { get; set; } = new[] { "*" };
public bool ConsoleCommand { get; set; } = false;
public CommandCallbackAttribute(string name)
{
this.Name = name;
}
}
public class CommandConfiguration : ModuleConfiguration
{
public string CommandPrefix { get; set; } = "!";
public int CommandsPerPage { get; set; } = 6;
public int MessageTimeout { get; set; } = 15;
public bool HideInaccessibleCommands { get; set; } = false;
public bool ReplyToChat { get; set; } = false;
}
public class CommandSettings : ModuleConfiguration
{
public Dictionary<string, CommandSetting?> Settings { get; set; } = new();
}
public class CommandSetting
{
public string[]? Permissions { get; set; }
public bool? ReplyToChat { get; set; }
public int? MessageTimeout { get; set; }
public bool? HideInaccessible { get; set; }
}
public class Context
{
public Source Source { get; set; }
public string Message { get; set; }
public string Command { get; set; }
public string[] RawParameters { get; set; }
public object?[] Parameters { get; set; }
public BattleBitModule? Module { get; set; }
public CommandHandler CommandHandler { get; set; }
public CommandCallbackAttribute? CommandCallbackAttribute { get; set; }
public Context(Source source, string message, string command, string[] rawParameters, object?[] parameters, BattleBitModule? module, CommandHandler commandHandler, CommandCallbackAttribute? commandCallbackAttribute)
{
this.Source = source;
this.Message = message;
this.Command = command;
this.RawParameters = rawParameters;
this.Parameters = parameters;
this.Module = module;
this.CommandHandler = commandHandler;
this.CommandCallbackAttribute = commandCallbackAttribute;
}
public virtual void Reply(string message)
{
this.Source.Reply(this, message);
}
}
public abstract class Source
{
public abstract void Reply(Context context, string message);
}
public class ChatSource : Source
{
public ChatSource(RunnerPlayer invoker)
{
this.Invoker = invoker;
}
public RunnerPlayer Invoker { get; }
public override void Reply(Context context, string message)
{
bool replyToChat = CommandHandler.CommandConfiguration.ReplyToChat;
if (context.CommandHandler.CommandSettings.Settings[context.Command]?.ReplyToChat is not null)
{
replyToChat = context.CommandHandler.CommandSettings.Settings[context.Command]!.ReplyToChat!.Value;
}
if (replyToChat)
{
this.Invoker.SayToChat(message);
}
else
{
int messageTimeout = CommandHandler.CommandConfiguration.MessageTimeout;
if (context.CommandHandler.CommandSettings.Settings[context.Command]?.MessageTimeout is not null)
{
messageTimeout = context.CommandHandler.CommandSettings.Settings[context.Command]!.MessageTimeout!.Value;
}
this.Invoker.Message(message, messageTimeout);
}
}
}
public class ConsoleSource : Source
{
public override void Reply(Context context, string message)
{
context.CommandHandler.Logger.Info(message);
}
}