-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommandHandler.cs
More file actions
355 lines (298 loc) · 13.4 KB
/
CommandHandler.cs
File metadata and controls
355 lines (298 loc) · 13.4 KB
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
using BattleBitAPI.Common;
using BBRAPIModules;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
namespace Commands;
public class CommandConfiguration : ModuleConfiguration
{
public string CommandPrefix { get; set; } = "!";
}
public class CommandHandler : BattleBitModule
{
public static CommandConfiguration CommandConfiguration { get; set; }
private Dictionary<string, (BattleBitModule Module, MethodInfo Method)> commandCallbacks = new();
[ModuleReference]
public BattleBitModule? PlayerFinder { get; set; }
[ModuleReference]
public BattleBitModule? PlayerPermissions { get; set; }
public override void OnModulesLoaded()
{
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)
{
// Validate parameter
ParameterInfo[] parameters = method.GetParameters();
if (parameters.Length > 0 && parameters[0].ParameterType != typeof(RunnerPlayer))
{
throw new Exception($"Command callback method {method.Name} in module {module.GetType().Name} has invalid first parameter. Must be of type RunnerPlayer.");
}
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;
}
throw new Exception($"Command callback method {method.Name} in module {module.GetType().Name} has the same name as another command callback method in the same module.");
}
// 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;
}
throw new Exception($"Command callback {command} in module {module.GetType().Name} conflicts with subcommand {subcommand}.");
}
// 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()))
{
throw new Exception($"Command callback {command} in module {module.GetType().Name} conflicts with parent command {subcommand.Trim()}.");
}
}
}
this.commandCallbacks.Add(command, (module, method));
}
}
}
public override Task<bool> OnPlayerTypedMessage(RunnerPlayer player, ChatChannel channel, string message)
{
if (!message.StartsWith(CommandConfiguration.CommandPrefix) || (message.StartsWith(CommandConfiguration.CommandPrefix) && message.Length <= CommandConfiguration.CommandPrefix.Length))
{
return Task.FromResult(true);
}
Task.Run(() => this.handleCommand(player, message));
return Task.FromResult(false);
}
private void handleCommand(RunnerPlayer player, string message)
{
string[] fullCommand = parseCommandString(message);
string command = fullCommand[0].Trim().ToLower()[CommandConfiguration.CommandPrefix.Length..];
int subCommandSkip;
for (subCommandSkip = 1; subCommandSkip < fullCommand.Length && !this.commandCallbacks.ContainsKey(command); subCommandSkip++)
{
command += $" {fullCommand[subCommandSkip]}";
}
if (!this.commandCallbacks.ContainsKey(command))
{
player.Message("Command not found");
return;
}
fullCommand = new[] { command }.Concat(fullCommand.Skip(subCommandSkip)).ToArray();
(BattleBitModule module, MethodInfo method) = this.commandCallbacks[command];
CommandCallbackAttribute commandCallbackAttribute = method.GetCustomAttribute<CommandCallbackAttribute>()!;
// Permissions
if (this.PlayerPermissions is not null)
{
if (commandCallbackAttribute.AllowedRoles != Roles.None && (this.PlayerPermissions.Call<Roles>("GetPlayerRoles", player.SteamID) & commandCallbackAttribute.AllowedRoles) == 0)
{
player.Message($"You don't have permission to use this command.");
return;
}
}
ParameterInfo[] parameters = method.GetParameters();
if (parameters.Length == 0)
{
method.Invoke(module, null);
return;
}
bool hasOptional = parameters.Any(p => p.IsOptional);
if (fullCommand.Length - 1 < parameters.Skip(1).Count(p => !p.IsOptional) || fullCommand.Length - 1 > parameters.Length - 1)
{
messagePlayerCommandUsage(player, 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];
args[0] = player;
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 (this.PlayerFinder is not null)
{
try
{
targetPlayer = this.PlayerFinder.Call<RunnerPlayer?>("ByNamePart", argument);
}
catch (Exception ex)
{
player.Message(ex.ToString());
return;
}
if (targetPlayer == null)
{
player.Message($"Could not find player name containing {argument}.");
return;
}
}
else
{
targetPlayer = this.Server.AllPlayers.FirstOrDefault(p => p.Name.Equals(argument, StringComparison.OrdinalIgnoreCase));
}
if (targetPlayer == null)
{
player.Message($"Could not find player {argument}.");
return;
}
args[i] = targetPlayer;
}
else
{
if (!tryParseParameter(parameter, argument, out object? parsedValue))
{
messagePlayerCommandUsage(player, method, $"Couldn't parse value {argument} to type {parameter.ParameterType.Name}");
return;
}
args[i] = parsedValue;
}
}
method.Invoke(module, args);
}
private static void messagePlayerCommandUsage(RunnerPlayer player, MethodInfo method, string? error = null)
{
CommandCallbackAttribute commandCallbackAttribute = method.GetCustomAttribute<CommandCallbackAttribute>()!;
bool hasOptional = method.GetParameters().Any(p => p.IsOptional);
player.Message($"<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." : "")}");
}
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("\""))
{
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")]
public void HelpCommand(RunnerPlayer player, string? command = null)
{
StringBuilder helpOutput = new();
if (command is null)
{
helpOutput.AppendLine("<#FFA500>Available commands<br><color=\"white\">");
helpOutput.AppendLine($"<b>{CommandConfiguration.CommandPrefix}help command</b>: Shows the command syntax");
foreach (var (commandKey, (module, method)) in this.commandCallbacks)
{
CommandCallbackAttribute commandCallbackAttribute = method.GetCustomAttribute<CommandCallbackAttribute>()!;
if (this.PlayerPermissions is not null)
{
if (commandCallbackAttribute.AllowedRoles != Roles.None && (this.PlayerPermissions.Call<Roles>("GetPlayerRoles", player.SteamID) & commandCallbackAttribute.AllowedRoles) == 0)
{
continue;
}
}
helpOutput.AppendLine($"<b>{CommandConfiguration.CommandPrefix}{commandCallbackAttribute.Name}</b>{(string.IsNullOrEmpty(commandCallbackAttribute.Description) ? "" : $": {commandCallbackAttribute.Description}")}");
}
}
else
{
if (!this.commandCallbacks.TryGetValue(command, out var commandCallback))
{
player.Message($"<color=\"red\">Command {command} not found.<color=\"white\">");
return;
}
CommandCallbackAttribute commandCallbackAttribute = commandCallback.Method.GetCustomAttribute<CommandCallbackAttribute>()!;
bool hasOptional = commandCallback.Method.GetParameters().Any(p => p.IsOptional);
player.Message($"<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." : "")}");
}
player.Message(helpOutput.ToString());
}
}
public class CommandCallbackAttribute : Attribute
{
public string Name { get; set; }
public string Description { get; set; } = string.Empty;
public Roles AllowedRoles { get; set; }
public CommandCallbackAttribute(string name)
{
this.Name = name;
}
}