protected async Task RespondSuccess(string message) { await Ctx.CreateResponseAsync(DSharpPlus.InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder() .AddEmbed(CommandModule.SuccessBase() .WithDescription(message))); }
public void CommandTest() { StringBuilderLogger logger; Logger.LogProvider = logger = new StringBuilderLogger(); using (var module = new CommandModule()) { var context = new TaskContext() { EnvironmentVariables = new Dictionary <string, string>(), SkippedSteps = new HashSet <int>(), WorkingDirectory = "../../../" }; var definition = new CommandModuleDefinition() { FilePath = "dotnet", Arguments = "list reference" }; module.Execute(context, definition); Assert.AreEqual("Executing dotnet list reference", logger.Out.ToString(0, 31)); Logger.ResetProvider(); } }
static void ShowConfigurableProperties(this CommandModule self, object config) { var promoLevel = self.Context.Player?.PromoteLevel ?? MyPromoteLevel.Admin; var properties = GetConfigurableProperties(config, promoLevel).ToArray(); if (!properties.Any()) { self.Context.Respond("No configurable properties"); return; } var msgBuilder = new StringBuilder(); msgBuilder.AppendLine("Config properties:"); foreach (var(property, index) in properties.Indexed()) { var name = "no name"; var description = "no description"; if (property.TryGetAttribute <DisplayAttribute>(out var display)) { name = display.Name.OrNull() ?? name; description = display.Description.OrNull() ?? description; } msgBuilder.AppendLine($"> {index} {property.Name} -- {name}; {description}"); } msgBuilder.AppendLine("> all -- Show the value of all configurable properties"); self.Context.Respond(msgBuilder.ToString()); }
static void ShowConfigurablePropertyValues(this CommandModule self, object config) { var promoLevel = self.Context.Player?.PromoteLevel ?? MyPromoteLevel.Admin; var properties = GetConfigurableProperties(config, promoLevel).ToArray(); if (!properties.Any()) { self.Context.Respond("No configurable properties"); return; } var msgBuilder = new StringBuilder(); msgBuilder.AppendLine("Config properties:"); foreach (var property in properties) { var name = property.Name; var value = property.GetValue(config); msgBuilder.AppendLine($"> {name}: {value}"); } msgBuilder.AppendLine("To update, either `config <index> <value>` or `config <name> <value>`."); self.Context.Respond(msgBuilder.ToString()); }
private static async Task ChecksFailedResponderAsync(CommandErrorEventArgs args, ChecksFailedException e) { var embed = CommandModule.ErrorBase() .WithDescription($"Invalid Permissions: {e.Message}"); await args.Context.RespondAsync(embed : embed); }
private static async Task ArgumentResponderAsync(CommandErrorEventArgs args) { var embed = CommandModule.ErrorBase() .WithDescription($"Invalid Arguments"); await args.Context.RespondAsync(embed : embed); }
public async Task ListFiltersCommandAsync(CommandContext ctx) { var filter = await this._model.FindAsync <GuildFilters>(ctx.Guild.Id); if (filter is null || filter.Filters.Count <= 0) { await RespondBasicErrorAsync("No filter found."); return; } var interact = ctx.Client.GetInteractivity(); var data = ""; foreach (var item in filter.Filters) { data += $"{item.Key} [{item.Value.Item1}]: `{string.Join("`, `", item.Value.Item2)}`\n"; } var embed = CommandModule.SuccessBase() .WithTitle("Filter Name [Filter Severity]: Filter Words"); var pages = interact.GeneratePagesInEmbed(data, DSharpPlus.Interactivity.Enums.SplitType.Line, embed); await interact.SendPaginatedMessageAsync(ctx.Channel, ctx.Member, pages); }
public async Task UrbanDictionaryCommandAsync(CommandContext ctx, [Description("What do you want to serach for?")] string searchTerm) { var res = await UrbanDictionary.Search(searchTerm); if (res is null) { await RespondBasicErrorAsync("Bad API Request."); return; } var item = res.FirstOrDefault(); if (item.Word?.Equals("") ?? false) { await RespondBasicErrorAsync("Failed to reterive any results!"); return; } var embed = CommandModule.SuccessBase() .WithTitle(item.Word) .WithAuthor(item.DefId.ToString(), item.PermaLink) .WithDescription(item.Definition) .AddField("Example:", item.Example) .WithFooter($"\U0001F44D {item.ThumbsUp} | \U0001F44E {item.ThumbsDown}") .WithTimestamp(DateTime.TryParse(item.WrittenOn, out var time) ? time : new DateTime()); await ctx.RespondAsync(embed : embed); }
void GetRocketComponents() { List <GameObject> attachedNetwork = AttachableBuilding.GetAttachedNetwork(this.GetComponent <AttachableBuilding>()); foreach (GameObject gameObject in attachedNetwork) { CommandModule component = gameObject.GetComponent <CommandModule>(); if ((UnityEngine.Object)component != (UnityEngine.Object)null) { relatedCM = component; } } if (relatedCM == null) { return; } LaunchConditionManager conditionManager = relatedCM.gameObject.GetComponent <LaunchConditionManager>(); if (conditionManager == null) { return; } relatedSpacecraft = SpacecraftManager.instance.GetSpacecraftFromLaunchConditionManager(conditionManager); }
static void LogAndRespond(CommandModule self, Exception e) { var errorId = $"{Random.Next(0, 999999):000000}"; self.GetFullNameLogger().Error(e, errorId); self.Context.Respond($"Oops, something broke. #{errorId}. Cause: \"{e.Message}\".", Color.Red); }
public TelegramHandler(CommandModule command, ILog log) { this.command = command; this.log = log; clients = new Dictionary <int, TenantTgClient>(); ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13; }
public CommandModule Unselect(CommandModule current) { if (targetIsHero) { return(new EmoteCommand(current)); } return(null); }
public static async Task RespondCommandDisabledAsync(DiscordChannel executionChannel, string prefix) { var embed = CommandModule.ErrorBase() .WithTitle("Command Disabled") .WithDescription($"Use {prefix}help to see all enabled commands."); await executionChannel.SendMessageAsync(embed : embed); }
public CommandModule init(Entity card, CommandModule parent) { this.minionEntity = card; this.parent = parent; minionIndex = getMinionCount() / 2; return(this); }
public TelegramHandler(CommandModule command, IOptionsMonitor <ILog> option, IServiceProvider serviceProvider) { Command = command; Log = option.CurrentValue; ServiceProvider = serviceProvider; Clients = new Dictionary <int, TenantTgClient>(); ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13; }
public void CommandModule_Gets_Legend_Image() { var commandModule = new CommandModule(null, Configuration, Logger, StreetBot); var imgUrl = commandModule.GetImageUrlForLegend("Hattori"); Logger.Debug(imgUrl); Assert.NotEmpty(imgUrl); }
public static void GetOrSetProperty(this CommandModule self, object config) { if (!self.Context.Args.TryGetFirst(out var propertyNameOrIndex)) { self.ShowConfigurableProperties(config); return; } if (propertyNameOrIndex == "all") { self.ShowConfigurablePropertyValues(config); return; } var promoLevel = self.Context.Player?.PromoteLevel ?? MyPromoteLevel.Admin; var properties = GetConfigurableProperties(config, promoLevel).ToArray(); var propertyName = propertyNameOrIndex; if (int.TryParse(propertyNameOrIndex, out var propertyIndex)) { var maxPropertyIndex = properties.Length - 1; if (maxPropertyIndex < propertyIndex) { self.Context.Respond($"Index out of bounds; max: {maxPropertyIndex}", Color.Red); self.ShowConfigurableProperties(config); return; } propertyName = properties[propertyIndex].Name; } if (!properties.TryGetFirst(p => p.Name == propertyName, out var property)) { self.Context.Respond($"Property not found: \"{propertyName}\"", Color.Red); self.ShowConfigurableProperties(config); return; } if (property.TryGetAttribute(out ConfigPropertyAttribute prop) && !prop.IsVisibleTo(promoLevel)) { self.Context.Respond($"Property not visible: \"{propertyName}\"", Color.Red); self.ShowConfigurableProperties(config); return; } if (promoLevel == MyPromoteLevel.Admin && self.Context.Args.TryGetElementAt(1, out var arg)) { var newValue = ParsePrimitive(property.PropertyType, arg); property.SetValue(config, newValue); } var value = property.GetValue(config); self.Context.Respond($"> {propertyName}: {value}"); }
private void UpdateGraphDotPos(CommandModule rocket) { totalWidth = rectTransform.rect.width; float value = Mathf.Lerp(0f, totalWidth, rocket.rocketStats.GetTotalMass() / maxMass); value = Mathf.Clamp(value, 0f, totalWidth); graphDot.rectTransform.SetLocalPosition(new Vector3(value, 0f, 0f)); graphDotText.text = "-" + Util.FormatWholeNumber(rocket.rocketStats.GetTotalThrust() - rocket.rocketStats.GetRocketMaxDistance()) + "km"; }
private void SendCommand(InputCommand input) { CommandModule result = this.currentModule.Command(input); if (result != null) { this.currentModule = result; } }
/// <summary> /// Synchronizes the state of the "Command" and "CommandModule" table in the database with the currently available commands/modules /// </summary> /// <param name="commandHandler">Reference to the <see cref="Discord.Commands.CommandService"> service containing information about the currently available commands</param> private static void UpdateCommandsInDb(CommandService commandHandler) { using (var db = new Database()) { var modules = commandHandler.Modules; foreach (var module in modules) { var moduleQuery = db.Modules.AsQueryable().Where(mo => mo.Name == module.Name); CommandModule moduleToUse; if (!moduleQuery.Any()) { var newModule = new CommandModule(); newModule.Name = module.Name; db.Modules.Add(newModule); db.SaveChanges(); moduleToUse = newModule; } else { moduleToUse = moduleQuery.First(); } foreach (var command in module.Commands) { if (!db.Commands.AsQueryable().Where(com => com.Name == command.Name).Any()) { var commandToCreate = new Command(); commandToCreate.Name = command.Name; commandToCreate.ModuleId = moduleToUse.ID; db.Commands.Add(commandToCreate); } } db.SaveChanges(); var commandsInDb = db.Modules.Include(mo => mo.Commands).Where(mo => mo.Name == module.Name).FirstOrDefault(); if (commandsInDb != null) { var commandsToDelete = new List <Command>(); foreach (var command in commandsInDb.Commands) { // the command exists in the db, but is not found in the module, we need to delete it if (!module.Commands.Where(co => co.Name == command.Name).Any()) { commandsToDelete.Add(command); } } foreach (var toDelete in commandsToDelete) { // also delete the channel group configuration for this commands, else the foreign keys fail db.CommandInChannelGroups.RemoveRange(db.CommandInChannelGroups.AsQueryable().Where(co => co.CommandID == toDelete.ID)); commandsInDb.Commands.Remove(toDelete); } } } db.SaveChanges(); } }
public void GivenTrigger_WhenMessageEmpty_ReturnsFalse() { string triggerMessage = string.Empty; var module = new CommandModule(); var result = module.Trigger(triggerMessage); Assert.IsFalse(result); }
public void GivenTrigger_WhenContainsTrigger_ReturnsFalse() { const string triggerMessage = "this contain !command"; var module = new CommandModule(); var result = module.Trigger(triggerMessage); Assert.IsFalse(result); }
public void GivenTrigger_WhenMessageStartsWithWord_ReturnsTrue() { const string triggerMessage = "!command do the thing"; var module = new CommandModule(); var result = module.Trigger(triggerMessage); Assert.IsTrue(result); }
public void GivenTrigger_WhenNotTrigger_ReturnsFalse() { const string triggerMessage = "this does not contain a trigger"; var module = new CommandModule(); var result = module.Trigger(triggerMessage); Assert.IsFalse(result); }
public void Draw(CommandModule commandModule) { if ((Object)rectTransform == (Object)null) { rectTransform = graphBar.gameObject.GetComponent <RectTransform>(); } this.commandModule = commandModule; totalWidth = rectTransform.rect.width; UpdateGraphDotPos(commandModule); }
public static async void CatchAndReport(this CommandModule self, Func <Task> f) { try { await f(); } catch (Exception e) { LogAndRespond(self, e); } }
public static void CatchAndReport(this CommandModule self, Action f) { try { f(); } catch (Exception e) { LogAndRespond(self, e); } }
private CommandModule Unselect() { //TODO kiil urself MinionNavigator.HUGE_HACK = -1; CommandModule next = regions[currentRegionIndex].Unselect(this); rightClick(); next.SwitchTo(); return(next); }
public static async void CatchAndReport(this CommandModule self, Func <Task> f) { try { await f(); } catch (Exception e) { LogAndRespond(self, e, m => self.Context.Respond(m, Color.Red)); } }
public static void CatchAndReport(this CommandModule self, Action f) { try { f(); } catch (Exception e) { LogAndRespond(self, e, m => self.Context.Respond(m, Color.Red)); } }