public ClassCommand(string name, IList <IExpression> baseExpressions, ICommand body) { this.name = name; this.body = body; this.baseExpressions = baseExpressions; this.doc = CommandUtilities.GetDocString(this.body); }
public async Task CreateTagAsync( [Example("espeon")] string name, [Example("is really cool")][Remainder] string value) { var module = Context.Command.Module; var paths = module.FullAliases.Select(alias => string.Concat(alias, " ", name)); if (CommandUtilities.EnumerateAllCommands(module).Any( command => command.FullAliases.Any( alias => paths.Any(path => path.Equals(alias, StringComparison.CurrentCultureIgnoreCase))))) { await ReplyAsync(TAG_RESERVED_WORD, name); return; } var guildTags = await DbContext.IncludeAndFindAsync <GuildTags, GuildTag, ulong>( Context.Guild.Id.RawValue, tags => tags.Values); var tag = guildTags.Values .FirstOrDefault(tag1 => tag1.Key.Equals(name, StringComparison.CurrentCultureIgnoreCase)); if (tag != null) { await ReplyAsync(GUILDTAG_ALREADY_EXISTS, name); return; } guildTags.Values.Add(new GuildTag(Context.Guild.Id, name, value, Context.User.Id)); await DbContext.UpdateAsync(guildTags); await ReplyAsync(TAG_CREATED, name); }
private async Task HandleMessageReceivedAsync(MessageReceivedEventArgs args) { _ = Executor.ExecuteAsync(async() => await _autoResponse.OnMessageReceivedAsync(args)); _ = Executor.ExecuteAsync(async() => await _dad.OnMessageReceivedAsync(args)); _ = Executor.ExecuteAsync(async() => await _reaction.OnMessageReceivedAsync(args)); _ = Executor.ExecuteAsync(async() => await _moderation.OnMessageReceivedAsync(args)); _ = Executor.ExecuteAsync(async() => await _owo.OnMessageReceivedAsync(args)); _ = Executor.ExecuteAsync(async() => await _counting.OnMessageReceivedAsync(args)); if (CommandUtilities.HasPrefix(args.Message.Content, Config.CommandPrefix, out var cmd)) { var sw = Stopwatch.StartNew(); var res = await _service.ExecuteAsync(cmd, args.Context, DepressedBot.ServiceProvider); sw.Stop(); if (res is CommandNotFoundResult) { return; } var targetCommand = _service.GetAllCommands() .FirstOrDefault(x => x.FullAliases.ContainsIgnoreCase(cmd)) ?? _service.GetAllCommands() .FirstOrDefault(x => x.FullAliases.ContainsIgnoreCase(cmd.Split(' ')[0])); await OnCommandAsync(targetCommand, res, args.Context, sw); } }
private async Task CommandHandler(SocketMessage msg) { // Do not respond to bot accounts or system messages. if (!(msg is SocketUserMessage message) || msg.Author.IsBot) { return; } // Respond to both mentions and your prefix. #warning Ensure that this configuration variable is set. if (!CommandUtilities.HasPrefix(message.Content, _config["prefix"], out var output)) { return; } var context = new DiscordCommandContext(_client, message, _services); IResult res = await _commands.ExecuteAsync(output, context); switch (res) { case FailedResult fRes: _logger.LogError("Command execution failed with reason: {0}", fRes.Reason); break; } }
public override Command Create() { var command = new Command("create-user", "Creates a new user for the current tenant."); command.AddOption(new Option <string>( new[] { "--username", "-u" }, description: "New username.", getDefaultValue: () => string.Empty)); command.AddOption(new Option <string>( new[] { "--email", "-e" }, description: "User's email address.", getDefaultValue: () => string.Empty)); command.AddOption(new Option <string>( new[] { "--password", "-p" }, description: "User's password.", getDefaultValue: () => string.Empty)); command.Handler = CommandHandler.Create((IHost host, Parameters parameters) => host.Services.GetRequiredService <CommandRunner>().ExecuteAsync( parameters with { Username = CommandUtilities.ValueOrPrompt(parameters.Username, "Username: "******"Username is required.", false), Email = CommandUtilities.ValueOrPrompt(parameters.Email, "Email: ", "Email is required.", false), Password = CommandUtilities.ValueOrPrompt(parameters.Password, "Password: "******"Password is required.", true), })); return(command); }
public CommandBarControl NewButtonObsolete(IContext context, string caption, int index, string binding, object newItemValue) { var validValueTypes = new[] { typeof(ScriptBlock), typeof(string) }; if (null == newItemValue || !validValueTypes.Contains(newItemValue.GetType())) { var validNames = String.Join(", ", validValueTypes.ToList().ConvertAll(t => t.FullName).ToArray()); throw new ArgumentException( "new item values for command bar buttons must be one of the following types: " + validNames); } index = Math.Max(index, 1); ShellCommand shellCommand = CommandUtilities.GetOrCreateCommand( context, _commandBar.Application as DTE2, caption, newItemValue ); if (!String.IsNullOrEmpty(binding)) { shellCommand.Bindings = new[] { (object)binding }; } Command command = shellCommand.AsCommand(); var ctl = command.AddControl(_commandBar, index) as CommandBarControl; return(ctl); }
private async Task HandleMessageAsync(SocketMessage message) { if (!CommandUtilities.HasPrefix(message.Content, config["prefix"], StringComparison.OrdinalIgnoreCase, out string output)) { return; } if (!(message.Channel is SocketTextChannel textChannel) || !(message.Author is SocketGuildUser guildUser)) { await message.Channel.SendMessageAsync(embed : EmbedUtils.UnsupportedEnvironment); return; } if (!guildUser.Guild.CurrentUser.GetPermissions(textChannel).SendMessages) { return; } var context = new ScrapContext(client, message as SocketUserMessage, provider); var result = await commands.ExecuteAsync(output, context); if (!(result is FailedResult failedResult)) { return; } if (failedResult is CommandNotFoundResult) { return; } await message.Channel.SendMessageAsync(embed : EmbedUtils.FailedResultEmbed(failedResult)); }
public async Task <bool> ExecuteCommand(string input) { if (!CommandUtilities.HasPrefix(input, '/', out string output)) { return(false); } IResult result = await _service.ExecuteAsync(output, new CustomCommandContext(input)); if (result is FailedResult failedResult) { switch (result) { case CommandNotFoundResult err: return(false); case TypeParseFailedResult err: IRC.Messages.AddSystemMessage($"Type error in `{err.Parameter}` excepted type: `{err.Parameter.Type}` got: `{err.Value.GetType()}`"); break; case ArgumentParseFailedResult err: IRC.Messages.AddSystemMessage(err.FailureReason); break; } } return(true); }
public override Command Create() { var command = new Command("authenticate", "Authenticates with the API."); command.AddOption(new Option <string>( new[] { "--username", "-u" }, description: "Your username.", getDefaultValue: () => string.Empty)); command.AddOption(new Option <string>( new[] { "--company", "-c" }, description: "Your company.", getDefaultValue: () => string.Empty)); command.AddOption(new Option <string>( new[] { "--password", "-p" }, description: "Your password.", getDefaultValue: () => string.Empty)); command.Handler = CommandHandler.Create((IHost host, Parameters parameters) => host.Services.GetRequiredService <CommandRunner>().ExecuteAsync( parameters with { Username = CommandUtilities.ValueOrPrompt(parameters.Username, "Username: "******"Username is required.", false), Company = CommandUtilities.ValueOrPrompt(parameters.Company, "Company: ", "Company is required.", false), Password = CommandUtilities.ValueOrPrompt(parameters.Password, "Password: "******"Password is required.", true), })); return(command); }
public async ValueTask <AdminCommandResult> GetCommandsAsync(Module module) { var commands = CommandUtilities.EnumerateAllCommands(module); var groups = commands.GroupBy(x => x.FullAliases[0]).ToList(); var pages = DefaultPaginator.GeneratePages(groups, 1024, group => new StringBuilder() .Append(Markdown.Bold(FormatCommands(group))) .AppendNewline(Localize($"info_command_{group.Key.Replace(' ', '_')}")).ToString(), builderFunc: () => new LocalEmbedBuilder().WithSuccessColor() .WithTitle(Localize("info_module_commands", Markdown.Code(module.Name)))); /* * var pages = DefaultPaginator.GeneratePages(groups, 15, group => new EmbedFieldBuilder() * // .WithName(new StringBuilder(Config.DefaultPrefix) * // .AppendJoin($"\n{Config.DefaultPrefix}", group.First().FullAliases).Tag) * .WithName(FormatCommands(group)) * .WithValue(Localize($"info_command_{group.Key.Replace(' ', '_')}")), * embedFunc: builder => builder.WithSuccessColor() * .WithTitle(Localize("info_module_commands", Format.Code(module.Name)))); */ if (pages.Count > 1) { await Pagination.SendPaginatorAsync(Context.Channel, new DefaultPaginator(pages, 0), pages[0]); return(CommandSuccess()); } return(CommandSuccess(embed: pages[0].Embed)); }
private static void GenerateCommandMarkdown(CommandService commandService) { var builder = new StringBuilder(); foreach (var module in commandService.TopLevelModules.OrderBy(x => x.Name)) { builder.AppendNewline($"## {module.Name}") .AppendNewline(module.Description) .AppendNewline("|Command|Description|") .AppendNewline("|---|---|"); foreach (var command in CommandUtilities.EnumerateAllCommands(module)) { builder.Append('|') .Append(string.Join("<br>", command.FullAliases.Select(x => Markdown.Code($"{PREFIX}{x}{command.FormatArguments()}")))) .Append('|') .Append(command.Description.Replace("\n", "<br>")); foreach (var parameter in command.Parameters) { builder.Append("<br>") .Append(Markdown.Code(parameter.Name)) .Append(": ") .Append(parameter.Description.Replace("\n", "<br>")) .Append(parameter.IsOptional ? $" {Markdown.Bold("(optional)")}" : string.Empty); } builder.AppendNewline("|"); } } Directory.CreateDirectory("docs"); File.WriteAllText("docs/Command-List.md", builder.ToString()); }
public async Task ExecuteAsync(DownloadMonitorCommand.Parameters parameters) { await this.ensureAuthenticated.ExecuteAsync(); var inputFolder = this.getCreatedOutputFolder.Execute(parameters.InputFolder); var outputFolder = this.getCreatedOutputFolder.Execute(parameters.OutputFolder); using var cts = CommandUtilities.CreateCommandCancellationTokenSource(); var channel = Channel.CreateUnbounded <QueuedDownloadToken>(); try { var monitorDownloadsTask = this.monitorDownloads.ExecuteAsync( channel.Writer, inputFolder, cts.Token); await this.processDownloads.ExecuteAsync( channel.Reader, targetFolder : outputFolder, generateCsv : parameters.GenerateCsv, keepBinary : parameters.KeepBinary, postProcessorPath : parameters.PostProcessor, postProcessorArguments : parameters.PostProcessorArguments, cancellationToken : cts.Token); await monitorDownloadsTask; } catch (Exception t) when(ExceptionUtilities.IsFromCancellation(t)) { // Download monitoring was cancelled. } }
public override Command Create() { var command = new Command("connect", "Connects to an API endpoint."); command.AddOption(new Option <string>( new[] { "--endpoint", "-e" }, description: $"The API endpoint to connect to (defaults to {ConnectionManager.DefaultApiEndpoint}).", getDefaultValue: () => ConnectionManager.DefaultApiEndpoint)); command.AddOption(new Option <string>( new[] { "--client-id", "-c" }, description: $"Your client ID, as provided by Canopy Simulations.", getDefaultValue: () => string.Empty)); command.AddOption(new Option <string>( new[] { "--client-secret", "-s" }, description: $"Your client secret, as provided by Canopy Simulations.", getDefaultValue: () => string.Empty)); command.Handler = CommandHandler.Create((IHost host, Parameters parameters) => host.Services.GetRequiredService <CommandRunner>().ExecuteAsync( parameters with { ClientId = CommandUtilities.ValueOrPrompt(parameters.ClientId, "Client ID: ", "Client ID is required.", false), ClientSecret = CommandUtilities.ValueOrPrompt(parameters.ClientSecret, "Client Secret: ", "Client Secret is required.", true), })); return(command); }
protected virtual ValueTask <(string Prefix, string Output)> FindPrefixAsync(CachedUserMessage message) { if (CommandUtilities.HasAnyPrefix(message.Content, Prefixes, out var prefix, out var output)) { return(new ValueTask <(string, string)>((prefix, output))); } return(default);
public async Task HandleAsync(MessageReceivedEventArgs args) { if (!(args.Message is CachedUserMessage message) || message.Author.IsBot || string.IsNullOrWhiteSpace(message.Content)) { return; } var prefixes = new List <string> { _config.DefaultPrefix }; LocalizedLanguage language; using var ctx = new AdminDatabaseContext(_provider); if (message.Channel is IGuildChannel guildChannel) { Guild guild = null; if (!_languages.TryGetValue(guildChannel.GuildId, out language)) { guild = await ctx.GetOrCreateGuildAsync(guildChannel.GuildId); _languages[guild.Id] = language = guild.Language; } if (!_guildPrefixes.TryGetValue(guildChannel.GuildId, out var customPrefixes)) { guild ??= await ctx.GetOrCreateGuildAsync(guildChannel.GuildId); _guildPrefixes[guild.Id] = customPrefixes = guild.CustomPrefixes; } prefixes.AddRange(customPrefixes); } else if (!_languages.TryGetValue(message.Author.Id, out language)) { var user = await ctx.GetOrCreateGlobalUserAsync(message.Author.Id); _languages[user.Id] = language = user.Language; } if (!CommandUtilities.HasAnyPrefix(message.Content, prefixes, StringComparison.OrdinalIgnoreCase, out var prefix, out var input)) { return; } var context = new AdminCommandContext(message, prefix, language, _provider); IResult result; if (!context.IsPrivate && await ctx.CommandAliases .FirstOrDefaultAsync(x => x.GuildId == context.Guild.Id && input.StartsWith(x.Alias, StringComparison.InvariantCultureIgnoreCase)) is { } alias) { result = await _commands.ExecuteAsync(alias, input, context); }
public async Task StartAsync() { string discordToken = ""; await Client.LoginAsync(TokenType.Bot, discordToken); // Login to discord await Client.StartAsync(); // Start message receiving Client.Log += x => { Console.WriteLine(x.Message); return(Task.CompletedTask); }; Commands.CommandErrored += (result, ctx, provider) => { Console.WriteLine(result.Exception.ToString()); return(Task.CompletedTask); }; Client.MessageReceived += async s => { if (!(s is SocketUserMessage msg)) { return; //Do some checks } if (msg.Author.IsBot) { return; } if (msg.Author.Id == Client.CurrentUser.Id) { return; } var context = new ExampleCommandContext(msg); if (!CommandUtilities.HasAnyPrefix(msg.Content, new[] { "!" }, StringComparison.OrdinalIgnoreCase, out string usedPrefix, out string cmd)) { return; } var result = await Commands.ExecuteAsync(cmd, context, Provider); //Try to run Command if (result is FailedResult failResult) { await context.Channel.SendMessageAsync(failResult.Reason); } return; }; await Task.Delay(-1); //Wait forever to keep the bot running }
public async Task <bool> TryExecuteCommandAsync(SocketUserMessage userMessage) { if (userMessage.Source != MessageSource.User || string.IsNullOrWhiteSpace(userMessage.Content)) { return(false); } var prefixes = new List <string> { _config.DefaultPrefix, $"<@{_client.CurrentUser.Id}> ", $"<@!{_client.CurrentUser.Id}> " }; LocalizedLanguage language; using (var ctx = new AdminDatabaseContext(_provider)) { if (userMessage.Channel is IGuildChannel guildChannel) { var guild = await ctx.GetOrCreateGuildAsync(guildChannel.GuildId); prefixes.AddRange(guild.CustomPrefixes); language = guild.Language; } else { var user = await ctx.GetOrCreateGlobalUserAsync(userMessage.Author.Id); language = user.Language; } } if (!CommandUtilities.HasAnyPrefix(userMessage.Content, prefixes, StringComparison.OrdinalIgnoreCase, out var prefix, out var input)) { return(false); } var context = new AdminCommandContext(userMessage, prefix, language, _provider); var result = await _commands.ExecuteAsync(input, context, _provider); if (!(result is FailedResult failedResult)) { return(true); } // TODO: localized error messages, log var error = new StringBuilder() .Append(failedResult switch { ParameterChecksFailedResult parameterChecksResult => string.Join('\n', parameterChecksResult.FailedChecks.Select(x => x.Error)), ChecksFailedResult checkResult => string.Join('\n', checkResult.FailedChecks.Select(x => x.Error)), ExecutionFailedResult execResult => GenerateException(execResult.Exception), CommandNotFoundResult _ => string.Empty, _ => failedResult.Reason }).ToString();
private Task CommandExecutionFailedAsync(CommandExecutionFailedEventArgs e) { if (e.Result.CommandExecutionStep == CommandExecutionStep.Command && e.Result.Exception is ContextTypeMismatchException contextTypeMismatchException) { var message = "A command context type mismatch occurred while attempting to execute {0}. " + "The module expected {1}, but got {2}."; var args = new List <object>(5) { e.Result.Command.Name, contextTypeMismatchException.ExpectedType, contextTypeMismatchException.ActualType }; // If the expected type is a DiscordGuildCommandContext, the actual type is a DiscordCommandContext, and the module doesn't have guild restrictions. if (typeof(DiscordGuildCommandContext).IsAssignableFrom(contextTypeMismatchException.ExpectedType) && typeof(DiscordCommandContext).IsAssignableFrom(contextTypeMismatchException.ActualType) && !CommandUtilities.EnumerateAllChecks(e.Result.Command.Module).Any(x => x is RequireGuildAttribute)) { message += " Did you forget to decorate the module with {3}?"; args.Add(nameof(RequireGuildAttribute)); } // If the expected type is a custom made context. if (contextTypeMismatchException.ExpectedType != typeof(DiscordGuildCommandContext) && contextTypeMismatchException.ExpectedType != typeof(DiscordCommandContext)) { message += " If you have not overridden {4}, you must do so and have it return the given context type. " + "Otherwise ensure it returns the correct context types."; args.Add(nameof(CreateCommandContext)); } Logger.LogError(message, args.ToArray()); } else { if (e.Result.Exception is OperationCanceledException && StoppingToken.IsCancellationRequested) { // Means the bot is stopping and any exceptions caused by cancellation we can ignore. return(Task.CompletedTask); } Logger.LogError(e.Result.Exception, e.Result.FailureReason); } if (e.Context is not DiscordCommandContext context) { return(Task.CompletedTask); } _ = InternalHandleFailedResultAsync(context, e.Result); return(Task.CompletedTask); }
public async Task ExecuteAsync(Parameters parameters) { await this.ensureAuthenticated.ExecuteAsync(); if (!parameters.Target.Exists) { throw new RecoverableException("Folder not found: " + parameters.Target.FullName); } var cts = CommandUtilities.CreateCommandCancellationTokenSource(); await this.processLocalStudyResults.ExecuteAsync(parameters.Target.FullName, !parameters.KeepOriginal, cts.Token); }
public async Task AddCommandAsync([Summary("Name of the command you're creating")] string cmdName, [Summary("What you want the command to say")][Remainder] string cmdContent) { string result = await CommandUtilities.AddCommandAsync(cmdName, cmdContent, _commandService); if (result == "success") { await ReplyAsync($"Created command !{cmdName}"); } else { await ReplyAsync(result); } }
public async Task RegisterCommandsAsync() { _client.MessageReceived += HandleCommandAsync; await _commands.AddModulesAsync(Assembly.GetEntryAssembly()); //Load pre-existing custom commands if possible if (DataStorage.LoadCommandsFromFile()) { foreach (CustomCommand cmd in DataStorage.customCommands) { await CommandUtilities.CreatCommandAsync(cmd.commandName, cmd.commandContent, _commands); } } }
public async Task HandleMessageAsync(MessageReceivedEventArgs args) { if (Config.EnabledFeatures.Blacklist) { await _blacklist.DoAsync(args); } if (Config.EnabledFeatures.Antilink) { await _antilink.DoAsync(args); } if (Config.EnabledFeatures.PingChecks) { await _pingchecks.DoAsync(args); } var prefixes = new List <string> { args.Data.Configuration.CommandPrefix, $"<@{args.Context.Client.CurrentUser.Id}> ", $"<@!{args.Context.Client.CurrentUser.Id}> " }; if (CommandUtilities.HasAnyPrefix(args.Message.Content, prefixes, StringComparison.OrdinalIgnoreCase, out _, out var cmd)) { var sw = Stopwatch.StartNew(); var result = await _commandService.ExecuteAsync(cmd, args.Context); if (result is CommandNotFoundResult) { return; } sw.Stop(); await _commandsService.OnCommandAsync(new CommandCalledEventArgs(result, args.Context, sw)); if (args.Data.Configuration.DeleteMessageOnCommand) { if (!await args.Message.TryDeleteAsync()) { _logger.Warn(LogSource.Service, $"Could not act upon the DeleteMessageOnCommand setting for {args.Context.Guild.Name} as the bot is missing the required permission, or another error occured."); } } } else { await _quoteService.DoAsync(args); } }
public override Command Create() { var command = new Command("get-configs", "Lists or downloads configs of the specified type."); command.AddOption(new Option <string>( new[] { "--config-type", "-t" }, description: $"The config type to request (e.g. car).", getDefaultValue: () => string.Empty)); command.AddOption(new Option <string>( new[] { "--user-id", "-uid" }, description: $"Filter by user ID.", getDefaultValue: () => string.Empty)); command.AddOption(new Option <string>( new[] { "--username", "-u" }, description: $"Filter by username.", getDefaultValue: () => string.Empty)); command.AddOption(new Option <DirectoryInfo?>( new[] { "--output-folder", "-o" }, description: $"The output folder in which to save the files (optional).", getDefaultValue: () => null)); command.AddOption(new Option <string>( new[] { "--sim-version", "-v" }, description: $"Get config for specific schema version (optional).", getDefaultValue: () => string.Empty)); command.AddOption(new Option <bool>( new[] { "--unwrap" }, description: $"Unwrap the config (removes metadata such as sim version required for importing).", getDefaultValue: () => false)); command.AddOption(new Option <bool>( new[] { "--format", "-f" }, description: $"Format the config JSON.", getDefaultValue: () => false)); command.Handler = CommandHandler.Create(async(IHost host, Parameters parameters) => await host.Services.GetRequiredService <IGetConfigs>().ExecuteAsync( parameters with { ConfigType = CommandUtilities.ValueOrPrompt(parameters.ConfigType, "Config Type: ", "Config type is required.", false), })); return(command); }
public async Task MessageReceived(SlackMessage message) { if (message.User.IsBot) { return; } if (!CommandUtilities.HasPrefix(message.Text, $"<@{_connection.Self.Id}> ", out var output)) { return; } var context = new CustomCommandContext(message, _connection); await _commandService.ExecuteAsync(output, context, _serviceProvider); }
private async Task OnMessageReceivedAsync(MessageCreateEventArgs e) { if (e.Author.IsBot) { return; } try { var ctxBase = new FoxContext(e, _services); _ = Task.Run(() => ExecuteReminderAsync(e)); _ = Task.Run(() => ExecuteCustomCommandAsync(ctxBase)); if (ctxBase.DatabaseContext.User.IsBlacklisted) { return; } var prefixes = ctxBase.DatabaseContext.Guild.Prefixes; if (ctxBase.Message.MentionedUsers.Contains(ctxBase.Client.CurrentUser) && ctxBase.Message.Content.Contains("prefix", StringComparison.OrdinalIgnoreCase)) { await ctxBase.RespondAsync($"Prefixes for this guild: {string.Join(", ", prefixes.Select(x => $"`{x}`"))}"); } if (!CommandUtilities.HasAnyPrefix(e.Message.Content, prefixes, StringComparison.OrdinalIgnoreCase, out var prefix, out var content)) { return; } var context = new FoxCommandContext(ctxBase, prefix); var result = await _commands.ExecuteAsync(content, context, _services); if (result.IsSuccessful) { return; } await HandleCommandErroredAsync(result, context); } catch (Exception ex) { _logger.Print(LogLevel.Critical, "Handler", ex.StackTrace); } }
private async Task ClientOnMessageReceived(SocketMessage arg) { if (!(arg is SocketUserMessage msg)) { return; } if (arg.Author.IsBot) { return; } if (!CommandUtilities.HasPrefix(arg.Content, ";", StringComparison.CurrentCultureIgnoreCase, out var output)) { return; } await _command.ExecuteAsync(output, new SocketCommandContext(_client, msg, msg.Author), _provider); }
private async void HandleMessageAsync(object sender, MessageEventArgs args) { var message = args.Message; if (!CommandUtilities.HasPrefix(message.Text, _config["prefix"], out string output)) { return; } var context = new BotContext(_client, message, _provider); var result = await _commands.ExecuteAsync(output, context); if (result is FailedResult failedResult) { await _client.SendTextMessageAsync(message.Chat, failedResult.Reason); } }
public override Command Create() { var command = new Command("hash", "Hashes a given string. Defaults to SHA256."); command.AddArgument(new Argument <string>( "input", description: "The input string to hash.", getDefaultValue: () => string.Empty)); command.Handler = CommandHandler.Create((IHost host, Parameters parameters) => host.Services.GetRequiredService <CommandRunner>().ExecuteAsync( parameters with { Input = CommandUtilities.ValueOrPrompt(parameters.Input, "Input string: ", "Input string is required.", false), })); return(command); }
internal async Task ParseMessage(string message, Client source, sbyte position = 0) { if (!CommandUtilities.HasPrefix(message, '/', out string output)) { await this.BroadcastAsync($"<{source.Player.Username}> {message}", position); return; } //TODO command logging var context = new ObsidianContext(source, this, this.Services); IResult result = await Commands.ExecuteAsync(output, context); if (!result.IsSuccessful) { await context.Player.SendMessageAsync($"{ChatColor.Red}Command error: {(result as FailedResult).Reason}", position); } }
public async Task ParseMessage(string message, Client source, byte position = 0) { if (!CommandUtilities.HasPrefix(message, '/', out string output)) { _chatmessages.Enqueue(new QueueChat() { Message = $"<{source.Player.Username}> {message}", Position = position }); Logger.LogMessage($"<{source.Player.Username}> {message}"); return; } var context = new CommandContext(source, this); IResult result = await Commands.ExecuteAsync(output, context); if (!result.IsSuccessful) { await context.Player.SendMessageAsync($"{ChatColor.Red}Command error: {(result as FailedResult).Reason}", position); } }