private void Execute(IGameContext gameContext, ParsedCommand parsedCommand, Action<string> logInternal) { foreach (var command in _commands) { if (command.Names.Contains(parsedCommand.Name)) { var output = command.Execute(gameContext, parsedCommand.Name, parsedCommand.Parameters.ToArray()); var lines = output.Split('\n'); int start = -1, end = lines.Length; for (var i = 0; i < lines.Length; i++) { if (!string.IsNullOrEmpty(lines[i])) { start = i; break; } } if (start == -1) { return; } for (var i = lines.Length - 1; i >= start; i--) { if (string.IsNullOrEmpty(lines[i])) { end = i; break; } } for (var i = start; i < end; i++) { logInternal(lines[i]); } return; } } logInternal("No such command found."); }
private bool HandleBindingOperation(out string result, EntityComponent entityComponent, ParsedCommand parsedCommand) { if (!ValidateBindingOperation(out result, parsedCommand)) { return(false); } ArgumentIsEntityComponent(parsedCommand.arguments[2], Player.I, out EntityComponent recieverEntityComponent); Player.I.ConnectComponentIO(entityComponent, recieverEntityComponent); result = $"Connected input socket of {recieverEntityComponent.GetCurrentIdentifier()} to listen to output socket of {entityComponent.GetCurrentIdentifier()}"; return(true); }
/// <summary> /// Handles a player executing a game command. A game command can only be executed by a player either on the blue team or red team. /// </summary> /// <param name="ctfBot">The <see cref="CaptureTheFlagBot"/> instance.</param> /// <param name="player">The player executing the command.</param> /// <param name="parsedCommand">The command being executed.</param> /// <returns> /// True if the command was successfully handled, if not, false. A successful handle is when the parsed command is not equal to null and also the ValidCommands string /// array contains the parsed command. /// </returns> public override bool Handle(CaptureTheFlagBot ctfBot, Player player, ParsedCommand parsedCommand) { bool canHandle = base.Handle(ctfBot, player, parsedCommand); if (canHandle) { if (player.IsPlayingGame) { switch (parsedCommand.Command) { case "blueflag": case "redflag": { Team targetTeam = parsedCommand.Command == "blueflag" ? Team.Blue : Team.Red; string flagHolderUsername = ctfBot.FlagSystem.Flags[targetTeam].Holder?.Username ?? ""; string teamName = targetTeam.GetStringName(); string msgToSend = !string.IsNullOrEmpty(flagHolderUsername) ? $"Player {flagHolderUsername} has the {teamName} flag." : $"No one has {teamName} flag."; ctfBot.SayChatMessage(msgToSend); } break; case "dropflag": { Team enemyTeam = player.Team.GetOppositeTeam(); Flag enemyTeamFlag = ctfBot.FlagSystem.Flags[enemyTeam]; if (enemyTeamFlag.Holder == player) { if (ctfBot.JoinedWorld.Blocks != null) { if (ctfBot.JoinedWorld.Blocks[(uint)BlockLayer.Foreground, player.Location.X, player.Location.Y].Id == 0) { enemyTeamFlag.Drop(ctfBot); } else { ctfBot.SendPrivateMessage(player, "You can't drop the flag here!"); } } } else { ctfBot.SendPrivateMessage(player, "You are not holding the enemy flag."); } } break; case "gamefund": { ctfBot.SendPrivateMessage(player, $"The game fund is currently: {ctfBot.CurrentGameRound.GameFund} coins."); } break; case "heal": { string resultMsg = "You cannot heal yourself because you are not inside your base!"; // Default message if the player is not inside their base if ((player.Team == Team.Blue && player.IsInBlueBase) || (player.Team == Team.Red && player.IsInRedBase)) { player.RestoreHealth(); resultMsg = "Success! Your health was restored fully."; } ctfBot.SendPrivateMessage(player, resultMsg); } break; case "health": case "hp": { ctfBot.SendPrivateMessage(player, $"Your current health is: {player.Health} HP."); } break; case "lobby": case "quit": { player.GoToLobby(ctfBot); } break; case "maxflags": { ctfBot.SendPrivateMessage(player, $"The maximum number of flags to win is {FlagSystem.MaxScoreToWin} flag{(FlagSystem.MaxScoreToWin == 1 ? "" : "s")}."); } break; case "scores": { ctfBot.SendPrivateMessage(player, ctfBot.CurrentGameRound.GetScoresString()); } break; case "suicide": { if (!player.IsRespawning) { player.Die(ctfBot); } } break; } } else { ctfBot.SendPrivateMessage(player, "You must be on either team blue or team red to use this command."); } } return(canHandle); }
// Parse the command and try to execute it public static void ExecuteCommand(string command) { if (command == null) { return; } command = command.Trim(); if (command.Length == 0) { return; } ParsedCommand parsedCommand = ParseCommand(command); if (parsedCommand.error != null) { Debug.LogWarning(parsedCommand.error); return; } // Check if number of parameter match if (parsedCommand.methodInfo.parameterTypes.Length != parsedCommand.arguments.Count) { Debug.LogWarning("Parameter count mismatch: " + parsedCommand.methodInfo.parameterTypes.Length + " parameters are needed"); return; } Debug.Log("Executing command: " + parsedCommand.name); // Parse the parameters into objects object[] parameters = new object[parsedCommand.methodInfo.parameterTypes.Length]; for (int i = 0; i < parsedCommand.methodInfo.parameterTypes.Length; i++) { string argument = parsedCommand.arguments[i]; Type parameterType = parsedCommand.methodInfo.parameterTypes[i]; if (typeof(Component).IsAssignableFrom(parameterType)) { UnityEngine.Object val = argument == "null" ? null : GameObject.Find(argument); if (val) { val = ((GameObject)val).GetComponent(parameterType); } parameters[i] = val; } else { ParseFunction parseFunction; if (!parseFunctions.TryGetValue(parameterType, out parseFunction)) { Debug.LogError("Unsupported parameter type: " + parameterType.Name); return; } object val; if (!parseFunction(argument, out val)) { Debug.LogError("Couldn't parse " + argument + " to " + parameterType.Name); return; } parameters[i] = val; } } // Execute the method associated with the command object result = parsedCommand.methodInfo.method.Invoke(parsedCommand.methodInfo.instance, parameters); if (parsedCommand.methodInfo.method.ReturnType != typeof(void)) { // Print the returned value to the console if (result == null || result.Equals(null)) { Debug.Log("Value returned: null"); } else { Debug.Log("Value returned: " + result.ToString()); } } }
public ParsedSpec Run() { var vkXml = this.xmlCache.GetVkXml(); var knownExtensions = new List <string>(); foreach (var vkExtension in vkXml.Element("registry").Element("extensions").Elements("extension")) { string name = vkExtension.Attribute("name").Value; var nameParts = name.Split('_'); string extensionSuffix = nameParts[1].ToLower(); if (!knownExtensions.Contains(extensionSuffix)) { knownExtensions.Add(extensionSuffix); } } var typeXml = new Dictionary <string, ParsedType>(); foreach (var vkType in vkXml.Element("registry").Element("types").Elements("type")) { string name = vkType.Attribute("name")?.Value ?? vkType.Element("name").Value; var categoryAttribute = vkType.Attribute("category"); TypeCategory category = categoryAttribute == null ? TypeCategory.None : (TypeCategory)Enum.Parse(typeof(TypeCategory), categoryAttribute.Value); string requires = vkType.Attribute("requires")?.Value; string parent = vkType.Attribute("parent")?.Value; string returnedOnly = vkType.Attribute("returnedonly")?.Value; bool isReturnedOnly = returnedOnly != null ? bool.Parse(returnedOnly) : false; bool isTypePointer = false; string type = vkType.Element("type")?.Value; if (type == "VK_MAKE_VERSION") { type += vkType.Element("type").NextNode.ToString(); } if (category == TypeCategory.funcpointer) { type = ((XText)vkType.Nodes().First()).Value.Split(' ')[1]; if (type.EndsWith("*")) { type = type.TrimEnd('*'); isTypePointer = true; } } string extension; string[] nameParts = GetNameParts(category == TypeCategory.funcpointer ? name.Substring(4) : name, out extension, knownExtensions); // VkDisplayModeKHR has two parents defined, but associated // handle should cover the requirements for the second // so just take the first if (parent != null) { parent = parent.Split(',').First(); } var newType = new ParsedType { VkName = name, Category = category, Requires = requires, Parent = parent, IsReturnedOnly = isReturnedOnly, NameParts = nameParts, Extension = extension, Type = type, IsTypePointer = isTypePointer }; foreach (var vkMember in vkType.Elements("member")) { var nameElement = vkMember.Element("name"); string memberName = nameElement.Value; string memberType = vkMember.Element("type").Value; string optional = vkMember.Attribute("optional")?.Value; bool isOptional = optional != null ? bool.Parse(optional) : false; ParsedFixedLength fixedLength = new ParsedFixedLength(); var typeNodes = nameElement.NodesBeforeSelf(); PointerType pointerType = GetPointerType(typeNodes); if (nameElement.NodesAfterSelf().Any()) { string enumName = vkMember.Element("enum")?.Value; if (enumName != null) { fixedLength.Value = enumName; fixedLength.Type = FixedLengthType.EnumReference; } else { fixedLength.Value = fixedLengthParser.Parse(nameElement.NextNode.ToString()); fixedLength.Type = FixedLengthType.IntegerLiteral; } } else { int fixedLengthIndex = memberName.IndexOf('['); if (fixedLengthIndex >= 0) { string fixedLengthString = memberName.Substring(fixedLengthIndex); memberName = memberName.Substring(0, fixedLengthIndex); fixedLength.Value = fixedLengthParser.Parse(fixedLengthString); fixedLength.Type = FixedLengthType.IntegerLiteral; } } string vkName = memberName; int pointerCount = pointerType.GetPointerCount(); while (pointerCount > 0 && memberName.StartsWith("p")) { memberName = memberName.Substring(1); pointerCount--; } ParsedLen[] dimensions = GetDimensions(name, vkMember, memberName); // Capture member name without array suffix string memberExtension; string[] memberNameParts = GetNameParts(memberName, out memberExtension, knownExtensions, false); string typeExtension; string[] typeNameParts = GetNameParts(memberType, out typeExtension, knownExtensions, true); string typeWithoutExtension = typeNameParts != null ? "Vk" + string.Join("", typeNameParts.Select(CapitaliseFirst)) : null; string values = vkMember.Attribute("values")?.Value; if (vkName == "sType" && values == null) { //HACK VkDebugReportLayerFlagsEXT doesn't specify a // fixed value for the sType field, so it must be // scraped from the following comment. if (vkMember.NextNode != null) { // Split on spaces and skip "Must" & "be" values = ((XComment)vkMember.NextNode).Value.Trim().Split(' ')[2]; } } newType.Members.Add(new ParsedMember { VkName = vkName, Type = memberType, TypeWithoutExtension = typeWithoutExtension, TypeExtension = typeExtension, IsOptional = isOptional, FixedLength = fixedLength, PointerType = pointerType, NameParts = memberNameParts, Extension = extension, Dimensions = dimensions, Values = values }); } // Special parsing is required for funcpointer parameters if (category == TypeCategory.funcpointer) { var functionTail = vkType.Element("name").NodesAfterSelf(); foreach (var typeElement in functionTail.Where(x => x.NodeType == XmlNodeType.Element).Cast <XElement>()) { string pre = ((XText)typeElement.PreviousNode).Value.Split(',').Last().Trim('(', ')', ';').TrimStart(); string post = ((XText)typeElement.NextNode).Value.Split(',').First().Trim('(', ')', ';').TrimEnd(); string paramName = new string(post.Reverse().TakeWhile(char.IsLetterOrDigit).Reverse().ToArray()); string typeString = pre + "@" + (post.Substring(0, post.Length - paramName.Length).Trim()); string paramType = typeElement.Value; PointerType pointerType = MapTypeString(typeString); string paramExtension; string[] paramNameParts = GetNameParts(paramName, out paramExtension, knownExtensions, false); newType.Members.Add(new ParsedMember { VkName = paramName, Type = paramType, PointerType = pointerType, NameParts = paramNameParts, Extension = paramExtension }); } } typeXml.Add(name, newType); } var enumXml = new Dictionary <string, ParsedEnum>(); foreach (var vkEnum in vkXml.Element("registry").Elements("enums")) { string name = vkEnum.Attribute("name").Value; string type = vkEnum.Attribute("type")?.Value; string extension; string[] nameParts = GetNameParts(name, out extension, knownExtensions); var newEnum = new ParsedEnum { VkName = name, Type = type, NameParts = nameParts, Extension = extension }; foreach (var vkField in vkEnum.Elements("enum")) { string fieldName = vkField.Attribute("name").Value; bool isBitmask = true; string value = vkField.Attribute("bitpos")?.Value; string comment = NormaliseComment(vkField.Attribute("comment")?.Value); if (value == null) { isBitmask = false; value = vkField.Attribute("value").Value; // Special case for mapping C "unsigned long long" // (64-bit unsigned integer) to C# UInt64 if (value == "(~0ULL)") { value = "(~0UL)"; } value = value.Trim('(', ')'); } IEnumerable <string> fieldNameParts = GetEnumFieldNameParts(nameParts, fieldName, knownExtensions); newEnum.Fields.Add(fieldName, new ParsedEnumField { VkName = fieldName, NameParts = fieldNameParts.ToArray(), IsBitmask = isBitmask, Value = value, Comment = comment != null ? new List <string> { comment } : null }); } enumXml.Add(name, newEnum); } var commandXml = new Dictionary <string, ParsedCommand>(); foreach (var vkCommand in vkXml.Element("registry").Element("commands").Elements("command")) { string name = vkCommand.Element("proto").Element("name").Value; string type = vkCommand.Element("proto").Element("type").Value; string extension; string[] nameParts = GetNameParts(name, out extension, knownExtensions); string[] verbExceptions = new[] { "cmd", "queue", "device" }; string verb = verbExceptions.Contains(nameParts[0]) ? nameParts[1] : nameParts[0]; string[] successCodes = vkCommand.Attribute("successcodes")?.Value?.Split(','); var newCommand = new ParsedCommand { VkName = name, Type = type, NameParts = nameParts, Extension = extension, Verb = verb, SuccessCodes = successCodes }; commandXml.Add(name, newCommand); foreach (var vkParam in vkCommand.Elements("param")) { var nameElement = vkParam.Element("name"); string paramName = nameElement.Value; string paramType = vkParam.Element("type").Value; string optional = vkParam.Attribute("optional")?.Value; bool isOptional; bool.TryParse(optional, out isOptional); var typeNodes = nameElement.NodesBeforeSelf(); PointerType pointerType = GetPointerType(typeNodes); ParsedLen[] dimensions = GetDimensions(name, vkParam, paramName); string paramExtension; string[] paramNameParts = GetNameParts(paramName, out paramExtension, knownExtensions, false); string typeExtension; string[] typeNameParts = GetNameParts(paramType, out typeExtension, knownExtensions, true); string typeWithoutExtension = typeNameParts != null ? "Vk" + string.Join("", typeNameParts.Select(CapitaliseFirst)) : null; newCommand.Params.Add(new ParsedParam { VkName = paramName, Type = paramType, TypeWithoutExtension = typeWithoutExtension, TypeExtension = typeExtension, PointerType = pointerType, NameParts = paramNameParts, Extension = paramExtension, IsOptional = isOptional, Dimensions = dimensions }); } } var vkFeature = vkXml.Element("registry").Elements("feature").Single(x => x.Attribute("api").Value == "vulkan"); var vkExtensions = vkXml.Element("registry").Element("extensions").Elements("extension").Where(x => x.Attribute("supported").Value == "vulkan"); var filteredSpec = FilterRequiredElement(typeXml, enumXml, commandXml, vkFeature, vkExtensions, knownExtensions); foreach (var defineType in typeXml.Values.Where(x => x.Category == TypeCategory.define && x.VkName.StartsWith("VK_API_VERSION_"))) { IEnumerable <string> fieldNameParts = GetEnumFieldNameParts(null, defineType.VkName, knownExtensions); filteredSpec.Constants.Add(defineType.VkName, new ParsedEnumField { VkName = defineType.VkName, NameParts = fieldNameParts.ToArray(), IsBitmask = false, Value = defineType.Type, Comment = null }); } var vkDocsXmlCache = new DownloadedFileCache(this.tempFilePath, "https://raw.githubusercontent.com/FacticiusVir/SharpVk-Docs/master/Docs/vkDocs.xml"); var vkDocsXml = XDocument.Load(vkDocsXmlCache.GetFileLocation().Result); foreach (var vkDocType in vkDocsXml.Element("docs").Element("types").Elements("type")) { string typeName = vkDocType.Attribute("name").Value; ParsedElement parsedElement = null; if (filteredSpec.Enumerations.ContainsKey(typeName)) { parsedElement = filteredSpec.Enumerations[typeName]; } else if (filteredSpec.Types.ContainsKey(typeName)) { parsedElement = filteredSpec.Types[typeName]; } if (parsedElement != null) { var comment = new List <string> { vkDocType.Attribute("summary").Value }; var specification = vkDocType.Element("specification"); comment.AddRange(specification.Elements("para").Select(x => x.Value)); var description = vkDocType.Element("description"); parsedElement.Comment = new List <string>(); comment.AddRange(description.Elements("para").Select(x => x.Value)); comment.RemoveAll(x => x.StartsWith(".Valid Usage")); int totalLength = 0; foreach (var para in comment) { totalLength += para.Length; if (totalLength > 2000) { break; } else { parsedElement.Comment.Add(NormaliseComment(para)); } } IEnumerable <ParsedElement> members = null; var parsedType = parsedElement as ParsedType; var parsedEnum = parsedElement as ParsedEnum; if (parsedType != null) { members = parsedType.Members; } else if (parsedEnum != null) { members = parsedEnum.Fields.Values; } if (members != null) { foreach (var vkDocMember in vkDocType.Element("members").Elements("member")) { string memberName = vkDocMember.Attribute("name").Value; string memberSummary = NormaliseComment(vkDocMember.Value); var member = members.FirstOrDefault(x => x.VkName == memberName); if (member != null) { member.Comment = new List <string> { memberSummary }; } } } } } foreach (var vkDocCommand in vkDocsXml.Element("docs").Element("commands").Elements("command")) { string commandName = vkDocCommand.Attribute("name").Value; if (filteredSpec.Commands.ContainsKey(commandName)) { var parsedCommand = filteredSpec.Commands[commandName]; parsedCommand.Comment = new List <string> { vkDocCommand.Attribute("summary").Value }; } } return(filteredSpec); }
private (ParsedArgument newStart, Module <TContext> matchSubmodule) TryMatchSubModule(Module <TContext> module, ParsedCommand command) { var arg = command.FullArgsStart.Next; while (true) { if (arg == null) { return(null, module); } if (arg.ArgType != typeof(string)) { return(arg, module); } var matchModule = module.Children?.FirstOrDefault(x => ModuleIsMatchToString(x, (string)arg.ArgObj)); if (matchModule is null) { return(arg, module); } module = matchModule; arg = arg.Next; } }
public DuplicateCommandException(Type target, ParsedCommand command) : base(String.Format(errorMsg, target, command.Name)) { }
public List <Command> Load() { List <Command> commands = new List <Command>(); Command config = new Command("config"); config.RequiredPermission = Command.PermissionLevels.Admin; config.Description = "Configure the bot or see current config"; config.Usage = "config <option> <value>"; config.ToExecute += async(context) => { var _guildConfig = Core.GetGuildConfig(context.Guild.Id); if (context.Parameters.IsEmpty()) { string currentConfig = $"Prefix: `{Core.GetPrefix(context)}`\n" + $"Admin Roles: `{JsonConvert.SerializeObject(_guildConfig.AdminRoleIds)}`\n" + $"Mod Roles: `{JsonConvert.SerializeObject(_guildConfig.ModRoleIds)}`\n" + $"User Roles: `{JsonConvert.SerializeObject(_guildConfig.UserRoles)}`\n" + $"Logging\n" + $" Channel Id: `{_guildConfig.LoggingChannelId}`\n" + $" Ignored Channels: `{JsonConvert.SerializeObject(_guildConfig.MessageLoggingIgnoreChannels)}`\n" + $"Muted Role Id: `{_guildConfig.MutedRoleId}`\n" + $"Verification:\n" + $" Role Id: `{_guildConfig.VerifiedRole}`\n" + $" Message: Do `{Core.GetPrefix(context)}config verification message` to see the message\n" + $"Points: {_guildConfig.PointsEnabled}\n" + $"Auto Roles: `{JsonConvert.SerializeObject(_guildConfig.AutoRoleIds)}`"; await context.Message.ReplyAsync(currentConfig); } #region AdminRoles else if (context.Parameters[0].ToLower().Equals("adminroles")) { if (context.Parameters.Count == 1) { await context.Message.ReplyAsync($"Please enter a config option"); return; } if (context.Parameters.Count == 2) { await context.Message.ReplyAsync($"Please enter a roleId"); return; } ulong id; if (ulong.TryParse(context.Parameters[2], out id) && context.Guild.Roles.Select(r => r.Id).Any(u => u.Equals(id))) { if (context.Parameters[1].ToLower().Equals("add")) { if (!Core.GetGuildConfig(context.Guild.Id).AdminRoleIds.Contains(id)) { Core.GetGuildConfig(context.Guild.Id).AdminRoleIds.Add(id); await context.Message.ReplyAsync($"Added {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name} to Admin Roles"); } else { await context.Message.ReplyAsync($"Admin Roles already contains {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name}"); } } else if (context.Parameters[1].ToLower().Equals("remove")) { if (Core.GetGuildConfig(context.Guild.Id).AdminRoleIds.Contains(id)) { Core.GetGuildConfig(context.Guild.Id).AdminRoleIds.Remove(id); await context.Message.ReplyAsync($"Removed {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name} from Admin Roles"); } else { await context.Message.ReplyAsync( $"Admin Roles doesn't contain {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name}"); } } else { await context.Message.ReplyAsync($"Unknown property `{context.Parameters[1]}`."); } } else { await context.Message.ReplyAsync($"That is not a valid roleId"); } } #endregion AdminRoles #region ModRoles else if (context.Parameters[0].ToLower().Equals("moderatorroles") || context.Parameters[0].ToLower().Equals("modroles")) { if (context.Parameters.Count == 1) { await context.Message.ReplyAsync($"Please enter a config option"); return; } if (context.Parameters.Count == 2) { await context.Message.ReplyAsync($"Please enter a roleId"); return; } ulong id; if (ulong.TryParse(context.Parameters[2], out id) && context.Guild.Roles.Select(r => r.Id).Any(u => u.Equals(id))) { if (context.Parameters[1].ToLower().Equals("add")) { if (!_guildConfig.ModRoleIds.Contains(id)) { _guildConfig.ModRoleIds.Add(id); await context.Message.ReplyAsync($"Added {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name} to Moderator Roles"); } else { await context.Message.ReplyAsync($"Moderator Roles already contains {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name}"); } } else if (context.Parameters[1].ToLower().Equals("remove")) { if (_guildConfig.ModRoleIds.Contains(id)) { { _guildConfig.ModRoleIds.Remove(id); await context.Message.ReplyAsync( $"Removed {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name} from Moderator Roles"); } } else { await context.Message.ReplyAsync( $"Moderator Roles doesn't contain {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name}"); } } else { await context.Message.ReplyAsync($"Unknown property `{context.Parameters[1]}`."); } } else { await context.Message.ReplyAsync($"That is not a valid roleId"); } } #endregion ModRoles #region UserRoles else if (context.Parameters[0].ToLower().Equals("userroles")) { if (config.GetPermissions(context) >= Command.PermissionLevels.Admin) { if (context.Parameters.Count == 1) { await context.Message.ReplyAsync($"Please enter a config option"); return; } if (context.Parameters.Count == 2) { await context.Message.ReplyAsync($"Please enter a roleId"); return; } ulong id; if (ulong.TryParse(context.Parameters[2], out id) && context.Guild.Roles.Select(r => r.Id).Any(u => u.Equals(id))) { if (context.Parameters[1].ToLower().Equals("add")) { if (!_guildConfig.UserRoles.Any(rg => rg.Value.Contains(id))) { context.Parameters.RemoveRange(0, 3); if (context.Parameters.Count != 0) { if (_guildConfig.UserRoles.Any(rg => rg.Key.ToLower() == context.Parameters.Rejoin().ToLower())) { string groupName = _guildConfig.UserRoles.First(rg => rg.Key.ToLower() == context.Parameters.Rejoin().ToLower()).Key; _guildConfig.UserRoles[groupName].Add(id); await context.Message.ReplyAsync($"Added {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name} to User Roles in group {_guildConfig.UserRoles.First(rg => rg.Key.ToLower() == context.Parameters.Rejoin().ToLower()).Key}"); } else { _guildConfig.UserRoles.Add(context.Parameters.Rejoin(), new List <ulong>()); _guildConfig.UserRoles[context.Parameters.Rejoin()].Add(id); await context.Message.ReplyAsync($"Added {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name} to User Roles in new group {_guildConfig.UserRoles.First(rg => rg.Key.ToLower() == context.Parameters.Rejoin().ToLower()).Key}"); } } else { try { _guildConfig.UserRoles.Add("", new List <ulong>()); } catch (ArgumentException ex) { await Core.Logger.LogErrorMessage(ex, context); } _guildConfig.UserRoles[""].Add(id); await context.Message.ReplyAsync($"Added {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name} to User Roles"); } } else { await context.Message.ReplyAsync($"User Roles already contains {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name}"); } } else if (context.Parameters[1].ToLower().Equals("remove")) { if (_guildConfig.UserRoles.Any(rg => rg.Value.Contains(id))) { { _guildConfig.UserRoles.First(rg => rg.Value.Contains(id)).Value.Remove(id); await context.Message.ReplyAsync( $"Removed {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name} from User Roles"); } } else { await context.Message.ReplyAsync($"User Roles doesn't contain {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name}"); } } else { await context.Message.ReplyAsync($"Unknown property `{context.Parameters[1]}`."); } } else { await context.Message.ReplyAsync($"That is not a valid roleId"); } } else { await context.Message.ReplyAsync($"You don't have the permissions to do that"); } } #endregion UserRoles #region RequiresRoles else if (context.Parameters[0].ToLower().Equals("requiresroles")) { if (context.Parameters.Count == 1) { await context.Message.ReplyAsync($"Please enter a config option"); return; } var checkRegex = new Regex(@"requiresroles (add|remove) \d{17,19} requires \d{17,19}", RegexOptions.IgnoreCase); if (!checkRegex.IsMatch(context.ParameterString.ToLower().Replace(" ", " "))) { await context.Message.ReplyAsync($"Syntax incorrect. Please use the syntax {_guildConfig.Prefix}config requiresRoles <add|remove> [roleid] requires [requiredRoleId]"); return; } if (ulong.TryParse(context.Parameters[2], out ulong roleId) && context.Guild.Roles.Select(r => r.Id).Any(u => u.Equals(roleId)) && ulong.TryParse(context.Parameters[4], out ulong requiredRoleId) && context.Guild.Roles.Select(r => r.Id).Any(u => u.Equals(requiredRoleId))) { if (_guildConfig.RequiresRoles == null) { _guildConfig.RequiresRoles = new Dictionary <ulong, List <ulong> >(); } if (context.Parameters[1].ToLower().Equals("add")) { if (_guildConfig.RequiresRoles.ContainsKey(roleId)) { if (_guildConfig.RequiresRoles[roleId] == null || !_guildConfig.RequiresRoles[roleId].Contains(requiredRoleId)) { if (_guildConfig.RequiresRoles[roleId] == null) { _guildConfig.RequiresRoles[roleId] = new List <ulong>(); } _guildConfig.RequiresRoles[roleId].Add(requiredRoleId); await context.Message.ReplyAsync($"{context.Guild.Roles.First(r => r.Id == roleId).Name} now requires {context.Guild.Roles.First(r => r.Id == requiredRoleId).Name}"); } else { await context.Message.ReplyAsync($"{context.Guild.Roles.First(r => r.Id == roleId).Name} already requires {context.Guild.Roles.First(r => r.Id == requiredRoleId).Name}"); } } else { _guildConfig.RequiresRoles[roleId] = new List <ulong> { requiredRoleId }; await context.Message.ReplyAsync($"{context.Guild.Roles.First(r => r.Id == roleId).Name} now requires {context.Guild.Roles.First(r => r.Id == requiredRoleId).Name}"); } } else if (context.Parameters[1].ToLower().Equals("remove")) { if (_guildConfig.RequiresRoles.ContainsKey(roleId)) { if (_guildConfig.RequiresRoles[roleId] == null || !_guildConfig.RequiresRoles[roleId].Contains(requiredRoleId)) { await context.Message.ReplyAsync($"That requirement does not exist"); } else { _guildConfig.RequiresRoles[roleId].RemoveAll(r => r == requiredRoleId); if (!_guildConfig.RequiresRoles[roleId].Any()) { _guildConfig.RequiresRoles.Remove(roleId); } await context.Message.ReplyAsync($"{context.Guild.Roles.First(r => r.Id == roleId).Name} no longer requires {context.Guild.Roles.First(r => r.Id == requiredRoleId).Name}"); } } else { await context.Message.ReplyAsync($"That requirement does not exist"); } } } else { await context.Message.ReplyAsync($"One of those is not a valid roleId"); } } #endregion RequiresRoles #region Prefix else if (context.Parameters[0].ToLower().Equals("prefix")) { try { context.Parameters.RemoveAt(0); _guildConfig.Prefix = context.Parameters.Rejoin(); if (context.Message.Content.EndsWith('"') && context.Parameters[0].ToCharArray()[0].Equals('"')) { _guildConfig.Prefix = new Regex("\"(.*?)\"").Match(context.Message.Content).Value.Trim('"'); } await context.Message.ReplyAsync($"The prefix has been set to `{_guildConfig.Prefix}`"); } catch (Exception ex) { await Core.Logger.LogErrorMessage(ex, context); _guildConfig.Prefix = ""; await context.Message.ReplyAsync($"The prefix has been reset to the default of `{Core.GetGlobalPrefix()}`"); } } #endregion Prefix #region Logging else if (context.Parameters[0].ToLower().Equals("logging")) { if (context.Parameters[1].ToLower().Equals("channelid")) { if (context.Parameters.Count() == 2) { await context.Message.ReplyAsync( $"Current user event channel: <#{_guildConfig.LoggingChannelId}>"); } else { ulong cId; if (ulong.TryParse(context.Parameters[2], out cId) && (context.Guild.Channels.Any(c => c.Id == cId) || cId == 0)) { _guildConfig.LoggingChannelId = cId; await context.Message.ReplyAsync( $"User event channel set to <#{_guildConfig.LoggingChannelId}>"); } else { await context.Message.ReplyAsync("Invalid Channel Id"); } } } else if (context.Parameters[1].ToLower().Equals("ignorechannel")) { if (context.Parameters.Count == 2) { string m = "Ignored channels:"; foreach (var id in _guildConfig.MessageLoggingIgnoreChannels) { m += $"\n<#{id}>"; } await context.Message.ReplyAsync(m); } else { if (ulong.TryParse(context.Parameters[2], out ulong cId) && context.Guild.TextChannels.Any(c => c.Id == cId)) { if (!_guildConfig.MessageLoggingIgnoreChannels.Contains(cId)) { _guildConfig.MessageLoggingIgnoreChannels.Add(cId); await context.Message.ReplyAsync($"No longer logging <#{cId}>"); } else { _guildConfig.MessageLoggingIgnoreChannels.Remove(cId); await context.Message.ReplyAsync($"Resuming logging <#{cId}>"); } } else { await context.Message.ReplyAsync("Invalid Channel Id"); } } } } #endregion Logging #region MutedRoleId else if (context.Parameters[0].ToLower().Equals("mutedroleid")) { context.Parameters.RemoveAt(0); if (context.Parameters.Count != 1) { await context.Message.ReplyAsync( "Incorrect number of arguments. Make sure the command is `voicerole [VoiceChannelId] [RoleId]`"); return; } else { ulong roleId; if (ulong.TryParse(context.Parameters[0], out roleId) && (context.Guild.Roles.Any(r => r.Id == roleId) || roleId == 0)) { _guildConfig.MutedRoleId = roleId; Core.SaveGuildConfig(_guildConfig); await context.Message.ReplyAsync($"MutedRoleId is now `{roleId}`"); } else { await context.Message.ReplyAsync("Invalid Role Id"); } } } #endregion MutedRoleId #region Verification else if (context.Parameters[0].ToLower().Equals("verification")) { if (context.Parameters[1].ToLower().Equals("roleid")) { if (context.Parameters.Count == 2) { var roleId = _guildConfig.VerifiedRole; if (roleId == 0) { await context.Message.ReplyAsync("Verification is disabled on this server"); } else { await context.Message.ReplyAsync( $"Verification role is `{context.Guild.Roles.First(g => g.Id == roleId).Name}`"); } } else if (ulong.TryParse(context.Parameters[2], out ulong roleId) && (context.Guild.Roles.Any(g => g.Id == roleId) || roleId == 0)) { _guildConfig.VerifiedRole = roleId; if (roleId != 0) { await context.Message.ReplyAsync( $"Verification role set to `{context.Guild.Roles.First(g => g.Id == roleId).Name}`"); } else { await context.Message.ReplyAsync("Verification role cleared. Verification is off for this server."); } } else { await context.Message.ReplyAsync("Invalid RoleId"); } } else if (context.Parameters[1].ToLower().Equals("message")) { string pref = Core.GetPrefix(context); string message = context.ParameterString.Replace(" ", " ").Remove(0, "verification message".Length); if (string.IsNullOrEmpty(message) && string.IsNullOrEmpty(_guildConfig.VerifiedMessage)) { await context.Message.ReplyAsync("Verification is disabled on this server. Please make sure you have a roleid and message set."); return; } else if (!string.IsNullOrEmpty(message)) { _guildConfig.VerifiedMessage = message; } await context.Message.ReplyAsync("Example verification message:"); string vm = $"Hey {context.Author.Username}! To get verified on **{context.Guild.Name}** reply to this message with the hidden code in the message below\n\n" + _guildConfig.VerifiedMessage; string verificationMessage = VerificationEngine.InsertCodeInMessage(vm, VerificationEngine.GetVerificationCode(context.Author.Id, context.Guild.Id)); await context.Message.ReplyAsync(verificationMessage); } else { await context.Message.ReplyAsync("Invalid Option"); } } #endregion Verification #region JoinMessage else if (context.Parameters[0].ToLower().Equals("joinmessage")) { if (context.Parameters.Count >= 2 && context.Parameters[1].ToLower().Equals("channelid")) { if (context.Parameters.Count == 2) { var channelId = _guildConfig.JoinMessageChannelId; if (channelId == 0) { await context.Message.ReplyAsync("Join messages are disabled on this server"); } else { await context.Message.ReplyAsync($"Join message channel is <#{channelId}>"); } } else if (ulong.TryParse(context.Parameters[2], out ulong channelId) && (context.Guild.Channels.Any(g => g.Id == channelId) || channelId == 0)) { _guildConfig.JoinMessageChannelId = channelId; if (channelId != 0) { await context.Message.ReplyAsync( $"Join message channel set to <#{channelId}>"); } else { await context.Message.ReplyAsync("Join message channel cleared. Join messages are off for this server."); } } else { await context.Message.ReplyAsync("Invalid Channel Id"); } } else if (context.Parameters.Count >= 2 && context.Parameters[1].ToLower().Equals("message")) { string message = context.ParameterString.Replace(" ", " ").Remove(0, "joinmessage message".Length); if (string.IsNullOrEmpty(message) && string.IsNullOrEmpty(_guildConfig.VerifiedMessage)) { await context.Message.ReplyAsync("Join messages are disabled on this server. Please make sure you have a channelid and message set."); return; } else if (!string.IsNullOrEmpty(message)) { _guildConfig.JoinMessage = message; } await context.Message.ReplyAsync("Example join message:"); await context.Message.ReplyAsync(VerificationEngine.ConstructWelcomeMessage(_guildConfig.JoinMessage, context.Author)); } else { await context.Message.ReplyAsync("Invalid Option"); } } #endregion JoinMessage #region AutoRole else if (context.Parameters[0].ToLower().Equals("autoroles") || context.Parameters[0].ToLower().Equals("autorole")) { if (context.Parameters.Count == 2) { await context.Message.ReplyAsync($"Please enter a roleId"); return; } if (ulong.TryParse(context.Parameters[2], out ulong id)) { if (context.Parameters[1].ToLower().Equals("add")) { if (context.Guild.Roles.Select(r => r.Id).Any(u => u.Equals(id))) { if (!_guildConfig.AutoRoleIds.Contains(id)) { _guildConfig.AutoRoleIds.Add(id); await context.Message.ReplyAsync($"Added {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name} to autoroles"); } else { await context.Message.ReplyAsync($"Autoroles already contains {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name}"); } } else { await context.Message.ReplyAsync("Invalid RoleId (Not a role)"); } } else if (context.Parameters[1].ToLower().Equals("remove")) { if (_guildConfig.AutoRoleIds.Contains(id)) { { _guildConfig.AutoRoleIds.Remove(id); await context.Message.ReplyAsync( $"Removed `{id}` from autoroles"); } } else { await context.Message.ReplyAsync( $"The autoroles don't contain `{id}`"); } } else { await context.Message.ReplyAsync($"Unknown property `{context.Parameters[1]}`."); } } else { await context.Message.ReplyAsync($"That is not a valid roleId"); } } #endregion AutoRole #region Antispam else if (context.Parameters[0].ToLower().Equals("antispam")) { if (context.Parameters.Count != 2) { await context.Message.ReplyAsync("Please a single-word option"); } else { switch (context.Parameters[1].ToLower()) { case "none": _guildConfig.AntispamLevel = GuildConfig.AntiSpamLevel.None; await context.Message.ReplyAsync("Antispam Level **None** has been selected! The following options are enabled: None"); break; case "basic": _guildConfig.AntispamLevel = GuildConfig.AntiSpamLevel.Basic; await context.Message.ReplyAsync("Antispam Level **Basic** has been selected! The following options are enabled: None (yet)"); break; case "advanced": _guildConfig.AntispamLevel = GuildConfig.AntiSpamLevel.Advanced; await context.Message.ReplyAsync("Antispam Level **Advanced** has been selected! The following options are enabled: Username Link Kicking"); break; case "aggressive": _guildConfig.AntispamLevel = GuildConfig.AntiSpamLevel.Aggressive; await context.Message.ReplyAsync("Antispam Level **Aggressive** has been selected! The following options are enabled: Username Link Banning"); break; case "activeraid": _guildConfig.AntispamLevel = GuildConfig.AntiSpamLevel.ActiveRaid; await context.Message.ReplyAsync("Antispam Level **ActiveRaid** has been selected! The following options are enabled: Username Link Banning"); break; default: await context.Message.ReplyAsync("That is not an available option. You can select: `None`, `Basic`, `Advanced`, `Aggressive`, and `ActiveRaid`"); break; } } } #endregion Antispam #region Points else if (context.Parameters[0].ToLower().Equals("points")) { if (context.Parameters[1].ToLower().Equals("true") || context.Parameters[1].ToLower().Contains("enable")) { _guildConfig.PointsEnabled = true; } else if (context.Parameters[1].ToLower().Equals("false") || context.Parameters[1].ToLower().Contains("disable")) { _guildConfig.PointsEnabled = false; } else { await context.Message.ReplyAsync($"Unknown property `{context.Parameters[1]}`."); } await context.Message.ReplyAsync($"Points Enabled: {_guildConfig.PointsEnabled}"); } #endregion Points else { await context.Message.ReplyAsync($"Unknown property `{context.Parameters[0]}`."); } Core.SaveGuildConfig(_guildConfig); }; commands.Add(config); Command audit = new Command("audit"); audit.Description = "Get the audit log of mod commands for the server"; audit.RequiredPermission = Command.PermissionLevels.Admin; audit.ToExecute += async(context) => { var log = Core.GetAuditLog(context.Guild.Id); ulong uIdToSearch = 0; if (!context.Parameters.IsEmpty()) { if (ulong.TryParse(context.Parameters[0], out uIdToSearch)) { log = log.Where(l => l.UserId == uIdToSearch).ToList(); } } log = log.OrderByDescending(l => l.MessageId).ToList(); string message = string.Empty; int i = 0; while (i < log.Count) { var cmd = log.ElementAt(i++); if (message.Length + $"{cmd.Message} - <@{cmd.UserId}>\n".Length > 2000) { break; } message = $"{cmd.Message} - <@{cmd.UserId}>\n" + message; } var builder = new EmbedBuilder() .WithDescription(message) .WithColor(new Color(0xFFFF00)); await context.Channel.SendMessageAsync("", embed : builder.Build()); }; commands.Add(audit); Command runas = new Command("runas"); runas.RequiredPermission = Command.PermissionLevels.BotOwner; runas.ToExecute += async(context) => { if (context.Parameters.Count < 2 || context.Message.GetMentionedUsers().Count != 1) { await context.Message.ReplyAsync("Please make sure to provide a userid and a command to run"); return; } try { // >runas [UserId] [Command] [Params] ParsedCommand runContext = new ParsedCommand(); runContext = context; string message = context.ParameterString.Trim(); var runAsUser = context.Guild.GetUser(ulong.Parse(context.Parameters[0].Trim("<@! >".ToCharArray()))); if (Core.Commands.HasElement(c => context.Parameters[1].Equals(c.Name) || c.Aliases.Any(a => context.Parameters[1].Equals(a)), out Command cmd)) { runContext.RawCommand = cmd; // remove first two params (uid and command) message = new Regex(Regex.Escape(context.Parameters[0])).Replace(message, "", 1).TrimStart(); message = new Regex(Regex.Escape(context.Parameters[1])).Replace(message, "", 1).Trim(); // set new parameters runContext.ParameterString = message; runContext.Parameters = message.Split().Where(p => !string.IsNullOrEmpty(p.Trim())).ToList(); runContext.Author = runAsUser; await runContext.Execute(); } else { await context.Message.ReplyAsync("Invalid command"); } } catch (Exception ex) { await context.Message.ReplyAsync($"```{ex.Message}```"); await context.Message.ReplyAsync($"```{ex.StackTrace}```"); throw ex; } }; commands.Add(runas); return(commands); }
internal (Task, CommandExecutedEventArgs) ExecuteCommand(Command <TContext> commandMatch, ParsedCommand parsedCommand) { var commandMethod = commandMatch?.Method; if (commandMethod is null) { return(Task.CompletedTask, new CommandExecutedEventArgs(EventExecutionStatus.CommandNotFound, parsedCommand.Context)); } var argArray = ConstructArgumentArray(commandMatch, parsedCommand); if (!CheckUserHasSufficientPriviliges(commandMatch, parsedCommand)) { return (Task.CompletedTask, new CommandExecutedEventArgs(EventExecutionStatus.InsufficientPermissions, parsedCommand.Context)); } return((Task)commandMethod.Invoke(commandMatch.DeclaringModuleInstance, argArray), new CommandExecutedEventArgs(EventExecutionStatus.Executed, parsedCommand.Context)); }
/// <summary> /// Handles a player executing a bot command. Implementation will vary on class inheritance. /// </summary> /// <param name="ctfBot">The Capture The Flag bot instance.</param> /// <param name="player">The player to be handled.</param> /// <param name="parsedCommand">The command to be handled.</param> /// <returns> /// Default implementation returns true if the command was successfully handled, if not, false. A successful handle is when the parsed command is not equal to null /// and also the ValidCommands string array contains the parsed command. /// </returns> public virtual bool Handle(CaptureTheFlagBot ctfBot, Player player, ParsedCommand parsedCommand) { return(parsedCommand != null && ValidCommands.Contains(parsedCommand.Command)); }
/// <summary> /// Handles a player executing an administrator command. Administrators are defined in the MySql database. /// </summary> /// <param name="ctfBot">The <see cref="CaptureTheFlagBot"/> instance.</param> /// <param name="player">The player executing the command.</param> /// <param name="parsedCommand">The command being executed.</param> /// <returns> /// True if the command was successfully handled, if not, false. A successful handle is when the parsed command is not equal to null and also the ValidCommands string /// array contains the parsed command. /// </returns> public override bool Handle(CaptureTheFlagBot ctfBot, Player player, ParsedCommand parsedCommand) { bool canHandle = base.Handle(ctfBot, player, parsedCommand); if (canHandle) { if (MySqlDatabase.Loaded) { if (MySqlDatabase.GetRow(player.Username).IsAdministrator) { switch (parsedCommand.Command) { case "ban": case "unban": { if (parsedCommand.Parameters.Length >= 1) { string username = parsedCommand.Parameters[0]; PlayerData playerData = MySqlDatabase.GetRow(username); if (parsedCommand.Command.Equals("ban", System.StringComparison.OrdinalIgnoreCase)) { if (playerData != null) // Player exists in the database { if (!playerData.IsBanned) { playerData.IsBanned = true; ctfBot?.KickPlayer(username, "You've been banned from this world."); } else { ctfBot?.SendPrivateMessage(player, $"Player {username.ToUpper()} is already banned!"); } } else // Player does not exist in the database { MySqlDatabase.AddNewPlayer(username, true); } ctfBot?.SendPrivateMessage(player, $"Player {username.ToUpper()} has been banned from the world."); } else // The command is "unban" { if (playerData != null) { if (playerData.IsBanned) { playerData.IsBanned = false; ctfBot?.ForgivePlayer(username); ctfBot?.SendPrivateMessage(player, $"Player {username.ToUpper()} has been unbanned."); } else { ctfBot?.SendPrivateMessage(player, $"Player {username.ToUpper()} is not banned!"); } } else { ctfBot?.SendPrivateMessage(player, $"Cannot ban player {username.ToUpper()} because they don't exist."); } } } else { ctfBot?.SendPrivateMessage(player, "Insufficient amount of parameters!"); } } break; case "disconnect": { ctfBot.Disconnect(); } break; case "kick": { if (parsedCommand.Parameters.Length >= 1) { string playerToKick = parsedCommand.Parameters[0]; string reason = ""; if (parsedCommand.Parameters.Length >= 2) { for (int i = 2; i < parsedCommand.Parameters.Length; i++) { reason += parsedCommand.Parameters[i] + " "; } } ctfBot.KickPlayer(playerToKick, reason); } else { ctfBot.SendPrivateMessage(player, "Insufficient amount of parameters for command."); } } break; case "retf": // Return flag { if (parsedCommand.Parameters.Length >= 1) { bool isValidParameter = string.Equals(parsedCommand.Parameters[0], "blue", StringComparison.OrdinalIgnoreCase) || string.Equals(parsedCommand.Parameters[0], "red", StringComparison.OrdinalIgnoreCase); if (isValidParameter) { if (string.Equals(parsedCommand.Parameters[0], "blue", StringComparison.OrdinalIgnoreCase) && ctfBot.FlagSystem.Flags[Team.Blue].IsTaken) { ctfBot?.FlagSystem.Flags[Team.Blue].Return(ctfBot, null, false); } else if (string.Equals(parsedCommand.Parameters[0], "red", StringComparison.OrdinalIgnoreCase) && ctfBot.FlagSystem.Flags[Team.Red].IsTaken) { ctfBot?.FlagSystem.Flags[Team.Red].Return(ctfBot, null, false); } else { ctfBot?.SendPrivateMessage(player, $"Cannot return the {parsedCommand.Parameters[0].ToLower()} flag as it is already at its base!"); } } else // Parameter is not "blue" or "red" { ctfBot?.SendPrivateMessage(player, "Unknown flag type."); } } else { ctfBot?.SendPrivateMessage(player, "Insufficient amount of parameters for command."); } } break; } } else // User is not an administrator { ctfBot?.SendPrivateMessage(player, "You don't have permission to execute this command."); } } else { ctfBot?.SendPrivateMessage(player, "Administrator commands are disabled due to the database not being loaded!"); } } return(canHandle); }
protected virtual void OnCommand(Command command, ParsedCommand parsedCommand) { }
protected void OnCommand(Command command, ParsedCommand parsedCommand) { ModifyCharacters(parsedCommand.GetCommandString()); onCommand.Invoke(command, parsedCommand); }
//在CheckCommandCombinationLegal结果基础上 //检查重复关键字 //生成ParsedCommands和DistinctCommand public void FormatInitialList() { void HandleMissingCharException(string CurrentWord) { if (CurrentWord == "-h") { try { throw new StartCharMissing(); } catch (StartCharMissing e) { Console.WriteLine(e.Message); CommandLegal = false; StartCharMissing = true; } } else { try { throw new EndCharMissing(); } catch (EndCharMissing e) { Console.WriteLine(e.Message); CommandLegal = false; EndCharMissing = true; } } } for (int i = 0; i < LegalKeyWordCommands.Count; i++) { string CurrentWord = LegalKeyWordCommands[i]; // is command if (Command.LegalCommands.Contains(CurrentWord)) { //-t -h find next char if (CurrentWord == "-t" || CurrentWord == "-h") { //"-t" or "-h" at the end of the list(no char after the command) if (i == LegalKeyWordCommands.Count - 1) { HandleMissingCharException(CurrentWord); } //try to get the char from next item else { //next item after t h is also command if (Command.LegalCommands.Contains(LegalKeyWordCommands[i + 1])) { HandleMissingCharException(CurrentWord); continue; } //find legal char on next item(char has been filtered in GetLegalKeyWords func) else { ParsedCommands.Add(new Command(CurrentWord, Char.Parse(LegalKeyWordCommands[i + 1]))); i += 1; } } } //-w -c -r else { ParsedCommands.Add(new Command(CurrentWord)); } } //single char exception else { try { throw new UnExpectedChar(); } catch (UnExpectedChar e) { Console.WriteLine(e.Message + "-->" + CurrentWord); CommandLegal = false; UnExpectedChar = true; } } } //check duplicate commands and build distinct list foreach (Command ParsedCommand in ParsedCommands) { int Count = 0; if (ParsedCommand.CommandString != "-t" && ParsedCommand.CommandString != "-h") { foreach (Command parsedCommand in ParsedCommands) { if (ParsedCommand.Equals(parsedCommand)) { Count += 1; } } if (!DistinctParsedCommands.Contains(ParsedCommand)) { DistinctParsedCommands.Add(ParsedCommand); } } else { foreach (Command parsedCommand in ParsedCommands) { if (parsedCommand.CommandString == ParsedCommand.CommandString) { Count += 1; } if (Count == 1) { if (parsedCommand.Equals(ParsedCommand) && !DistinctParsedCommands.Contains(ParsedCommand)) { DistinctParsedCommands.Add(ParsedCommand); } } } } if (Count > 1) { try { throw new DuplicateKeyCommand(); } catch (DuplicateKeyCommand e) { Console.WriteLine(e.Message + "-->" + ParsedCommand.CommandString + " " + ParsedCommand.StartOrEndChar); CommandDuplicated = true; } } } }
private bool HandleClearOperation(out string result, EntityComponent entityComponent, ParsedCommand parsedCommand) { result = $"Removed all listeners to the output of {entityComponent.GetCurrentIdentifier()}"; entityComponent.onOutput.RemoveAllListeners(); return(true); }
public ArgumentNumberException(ParsedCommand command) : base(String.Format(_errorMsg, command.Name)) { this.Command = command; }
protected CommandHandlerBase(ParsedCommand parsedCommand) { ParsedCommand = parsedCommand; }
private bool CheckUserHasSufficientPriviliges(Command <TContext> commandMatch, ParsedCommand parsedCommand) { var permissionCheckList = new List <Module <TContext> >(); var currentModule = commandMatch.DeclaringModule; while (currentModule != null) { permissionCheckList.Add(currentModule); currentModule = currentModule.Parent; } foreach (var toCheck in permissionCheckList) { if (!toCheck.ModuleRequiresPermissionValidation) { continue; } var userCanExecute = ((IModulePermissions <TContext>)toCheck.Instance) .UserHasSufficientPermissions((TContext)parsedCommand.Context); if (!userCanExecute) { return(false); } } return(true); }
private void CommandPassed(Command command, ParsedCommand parsedCommand) { TerminalTimePast(command.GetTerminalTimePast(parsedCommand)); onCommand.Invoke(command, parsedCommand); }
public CommandNotFound(ParsedCommand command) : base(GetMessage(command)) => this.command = command;
internal Command <TContext> MatchCommand(IReadOnlyList <Module <TContext> > modules, ParsedCommand command) { var commandArgs = command.FullArgsStart; if (commandArgs is null) { return(default(Command <TContext>)); } if (commandArgs.ArgType != typeof(string)) { return(default(Command <TContext>)); } var matchModule = modules.FirstOrDefault(x => ModuleIsMatchToString(x, (string)commandArgs.ArgObj)); if (matchModule is null) { return(default(Command <TContext>)); } var matchedSubModule = TryMatchSubModule(matchModule, command); command.CommandArgsStart = matchedSubModule.newStart; var matchedCommand = TryMatchCommand(matchedSubModule.Item2, command); return(matchedCommand); }
public MatchNotFound(ParsedCommand command, Command[] overloads) : base(GetMessage(command, overloads)) { this.command = command; this.overloads = overloads; }
private Command <TContext> TryMatchCommand(Module <TContext> module, ParsedCommand command) { return(module.Commands.FirstOrDefault(x => ArgumentSignatureMatch(x, command))); }
public AmbiguousCommandCall(ParsedCommand command, Command[] matches) : base(GetMessage(command, matches)) { this.command = command; this.matches = matches; }
public static AutoCompleteResults GetAutoCompleteParameters(string commandStart) { AutoCompleteResults results = new AutoCompleteResults(); ParsedCommand parsedCommand = ParseCommand(commandStart); if (parsedCommand.error != null) { results.error = parsedCommand.error; return(results); } Debug.Log("Usage: " + parsedCommand.methodInfo.signature); if (parsedCommand.arguments.Count > parsedCommand.methodInfo.parameterTypes.Length) { results.error = "Too many parameters"; return(results); } int argIndex = Math.Max(0, parsedCommand.arguments.Count - 1) + (parsedCommand.endsWithSpace ? 1 : 0); if (argIndex >= parsedCommand.methodInfo.parameterTypes.Length) { return(results); } Type type = parsedCommand.methodInfo.parameterTypes[argIndex]; if (suggestFunctions.TryGetValue(type, out SuggestFunction suggestFunction)) { string prefix = parsedCommand.arguments.Count > argIndex ? parsedCommand.arguments[argIndex] : ""; if (suggestFunction(prefix, out List <string> suggestions)) { if (suggestions.Count == 0) { results.error = "Parameter not found: " + prefix; return(results); } suggestions.Sort(); results.options.Add(suggestions[0]); for (int i = 1; i < suggestions.Count; i++) { if (suggestions[i] != suggestions[i - 1]) { results.options.Add(suggestions[i]); } } string suggestionPrefix = CommonPrefix(results.options); int argStart = prefix == "" ? commandStart.Length - 1: commandStart.LastIndexOf(prefix) - 1; int delim = IndexOfDelimiter(commandStart[argStart]); if (delim != -1) { argStart--; } else if (suggestionPrefix.IndexOf(' ') != -1) { delim = IndexOfDelimiter('\"'); } if (delim != -1) { suggestionPrefix = inputDelimiters[delim][0] + suggestionPrefix; } results.replacement = commandStart.Substring(0, argStart + 1) + suggestionPrefix; if (results.options.Count == 1) { results.replacement += (delim != -1 ? inputDelimiters[delim][1] + " " : " "); } } } return(results); }
/// <summary> /// Handles a player executing a regular command. A regular command can be executed by any player. /// </summary> /// <param name="ctfBot">The <see cref="CaptureTheFlagBot"/> instance.</param> /// <param name="player">The player executing the command.</param> /// <param name="parsedCommand">The command being executed.</param> /// <returns> /// True if the command was successfully handled, if not, false. A successful handle is when the parsed command is not equal to null and also the ValidCommands string /// array contains the parsed command. /// </returns> public override bool Handle(CaptureTheFlagBot ctfBot, Player player, ParsedCommand parsedCommand) { bool canHandle = base.Handle(ctfBot, player, parsedCommand); if (canHandle) { switch (parsedCommand.Command) { case "amiadmin": { string result = MySqlDatabase.Loaded && MySqlDatabase.GetRow(player.Username).IsAdministrator ? "You are an administrator." : "You are not an administrator."; ctfBot.SendPrivateMessage(player, result); } break; case "coins": { if (MySqlDatabase.Loaded) { PlayerData row = MySqlDatabase.GetRow(player.Username); ctfBot.SendPrivateMessage(player, $"You currently have {row.Statistics.Coins} coin{(row.Statistics.Coins == 1 ? "" : "s")}."); } } break; case "donatecoins": { if (MySqlDatabase.Loaded) { if (parsedCommand.Parameters.Length >= 2) { if (parsedCommand.Parameters[0] != player.Username) { PlayerData playerToDonateData = MySqlDatabase.GetRow(parsedCommand.Parameters[0]); if (playerToDonateData != null) { PlayerData donatorData = MySqlDatabase.GetRow(player.Username); if (int.TryParse(parsedCommand.Parameters[1], out int amount)) { if (donatorData.Statistics.Coins >= amount) { playerToDonateData.Statistics.Coins += amount; donatorData.Statistics.Coins -= amount; ctfBot.SendPrivateMessage(player, $"Success! You donated {amount} coin{(amount == 1 ? "" : "s")} to player {parsedCommand.Parameters[0].ToUpper()}."); } else { ctfBot.SendPrivateMessage(player, "You don't have enough coins to donate that amount!"); } } else { ctfBot.SendPrivateMessage(player, "Third parameter of command is invalid! It must be a number."); } } else { ctfBot.SendPrivateMessage(player, $"Player {parsedCommand.Parameters[0].ToUpper()} does not exist."); } } else { ctfBot.SendPrivateMessage(player, "You can't donate coins to yourself!"); } } else { ctfBot.SendPrivateMessage(player, "Insufficient amount of parameters for command."); } } } break; case "help": { ctfBot.SendPrivateMessage(player, "Command prefixes: . > ! #"); ctfBot.SendPrivateMessage(player, "Regular Commands:"); ctfBot.SendPrivateMessage(player, StringArrayToString(ctfBot.BotCommands[2].ValidCommands)); ctfBot.SendPrivateMessage(player, "Game Commands:"); ctfBot.SendPrivateMessage(player, StringArrayToString(ctfBot.BotCommands[1].ValidCommands)); ctfBot.SendPrivateMessage(player, "Administrator Commands:"); ctfBot.SendPrivateMessage(player, StringArrayToString(ctfBot.BotCommands[0].ValidCommands)); ctfBot.SendPrivateMessage(player, "Tips:"); ctfBot.SendPrivateMessage(player, "- Press arrow keys/WASD keys around an enemy player to attack them."); ctfBot.SendPrivateMessage(player, "- Use hard hat/worker smiley to dig dirt."); ctfBot.SendPrivateMessage(player, "- Use doctor/nurse smiley to heal your teammates."); ctfBot.SendPrivateMessage(player, "- There is an item shop in the clouds."); ctfBot.SendPrivateMessage(player, "- Watch out for traps around the map."); } break; case "spectate": { if (!player.IsPlayingGame && !player.CanToggleGodMode) { ctfBot.SetForceFly(player, !player.IsInGodMode); if (player.IsInGodMode) { player.GoToLobby(ctfBot); } ctfBot.SendPrivateMessage(player, player.IsInGodMode ? "You have left spectate mode." : $"You have entered spectate mode. Type {parsedCommand.Prefix}spectate again to exit out of spectate mode."); } else { string privateMessage = player.IsPlayingGame ? "This command is only available to players not playing!" : "You can toggle God mode! Use that instead."; ctfBot.SendPrivateMessage(player, privateMessage); } } break; case "totalwins": case "totallosses": case "losses": case "wins": { if (MySqlDatabase.Loaded) { PlayerData row = MySqlDatabase.GetRow(player.Username); int resultCount = parsedCommand.Command == "totalwins" || parsedCommand.Command == "wins" ? row.Statistics.TotalWins : row.Statistics.TotalLosses; string type = parsedCommand.Command == "totalwins" || parsedCommand.Command == "wins" ? "won" : "lost"; ctfBot.SendPrivateMessage(player, $"You have {type} {resultCount} time{(row.Statistics.TotalWins == 1 ? "" : "s")}."); } } break; case "totalkills": { if (MySqlDatabase.Loaded) { PlayerData playerData = MySqlDatabase.GetRow(player.Username); ctfBot.SendPrivateMessage(player, $"You have killed a total of {playerData.Statistics.TotalKills} player{(playerData.Statistics.TotalKills == 1 ? "" : "s")}."); } } break; } } else { ctfBot.SendPrivateMessage(player, $"The command \"{parsedCommand.Command}\" is invalid!"); } return(canHandle); }
private bool ParseLine(string line, ParsedLine parsedLine, List <string> recursiveWords = null, ConcatAction?lastAction = null) { List <string> words; if (recursiveWords == null) { words = line.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (words.Count == 0) { parsedLine.LineState = LineState.Empty; return(true); } } else { words = recursiveWords; } if (parsedLine.LineState == LineState.Begin) { var cmd = GetCommand(words[0]); if (cmd == Command.UnknownCommand) { parsedLine.ErrorMsg = $"Unknown command: `{words[0]}`"; return(false); } ParsedCommand parsedCommand = new ParsedCommand { Command = cmd }; parsedLine.ParsedCommands.Add(parsedCommand); parsedLine.LineState = LineState.AfterCommand; words.RemoveAt(0); if (lastAction != null) { parsedLine.ParsedCommands.Last().PrevConcatAction = lastAction.Value; lastAction = null; } if (words.Count == 0) { if (_actions[parsedLine.ParsedCommands.Last().Command].NumOfArgs > 0) { parsedLine.ErrorMsg = $"Missing argument(s) after command : {parsedLine.ParsedCommands.Last().Command} (should get at least {_actions[parsedLine.ParsedCommands.Last().Command].NumOfArgs} arguments but got none)"; return(false); } return(true); } } if (parsedLine.LineState == LineState.AfterCommand) { var args = new List <string>(); int i; for (i = 0; i < words.Count; i++) { if (i == 0) { if (_actions.ContainsKey(parsedLine.ParsedCommands.Last().Command) == false) { parsedLine.ErrorMsg = $"Internal CLI Error : no definition for `{parsedLine.ParsedCommands.Last().Command}`"; return(false); } switch (words[0]) { case "&&": case "||": if (_actions[parsedLine.ParsedCommands.Last().Command].NumOfArgs != 0) { parsedLine.ErrorMsg = $"Missing argument(s) after command : {parsedLine.ParsedCommands.Last().Command}"; return(false); } break; } } if (words[i] != "&&" && words[i] != "||") { args.Add(words[i]); continue; } if (words[i] == "&&") { parsedLine.LineState = LineState.AfterArgs; lastAction = ConcatAction.And; break; } if (words[i] == "||") { parsedLine.LineState = LineState.AfterArgs; lastAction = ConcatAction.Or; break; } // cannot reach here parsedLine.ErrorMsg = "Internal CLI Error"; return(false); } parsedLine.ParsedCommands.Last().Args = args; if (lastAction == null) { if (args.Count < _actions[parsedLine.ParsedCommands.Last().Command].NumOfArgs) { parsedLine.ErrorMsg = $"Missing argument(s) after command : {parsedLine.ParsedCommands.Last().Command} (should get at least {_actions[parsedLine.ParsedCommands.Last().Command].NumOfArgs} arguments but got {args.Count})"; return(false); } return(true); } List <string> newWords = new List <string>(); for (int j = i + 1; j < words.Count; j++) { newWords.Add(words[j]); } parsedLine.LineState = LineState.Begin; return(ParseLine(null, parsedLine, newWords, lastAction)); } return(true); }
private ParsedCommand Parse(string input) { var parsed = new ParsedCommand(); var split = input.Split(new[] { ' ' }, 2); parsed.Name = split[0]; parsed.Parameters = new List<string>(); if (split.Length > 1) { var inQuote = false; var buffer = string.Empty; for (var i = 0; i < split[1].Length; i++) { if (split[1][i] == '"') { if (i == 0 || split[1][i - 1] != '\\') { inQuote = !inQuote; } if (!inQuote) { parsed.Parameters.Add(buffer); } } else if (split[1][i] == ' ' && !inQuote) { parsed.Parameters.Add(buffer); buffer = string.Empty; } else { buffer += split[1][i]; } } if (buffer.Length > 0) { parsed.Parameters.Add(buffer); buffer = string.Empty; } } return parsed; }
public static void AddToCommandLog(ParsedCommand command, ulong guildId) => DatabaseEngine.AddToCommandLog(command, guildId);
private bool HandleManualOperation(out string result, EntityComponent entityComponent, ParsedCommand parsedCommand) { if (!ValidateManualOperation(out result, parsedCommand)) { return(false); } entityComponent.onOutput.AddListener(OnInput); entityComponent.OnInput(this, parsedCommand.arguments[2]); result = $"Manual entry of \"{parsedCommand.arguments[2]}\" to {entityComponent.GetCurrentIdentifier()}"; return(true); }