/// <summary> /// Checks if the given command is known by the bot. /// </summary> /// <param name="command"></param> /// <returns></returns> public bool IsCommandKnown(string command) { IBotCommand cmd = _commands.Find(x => x.GetCommand().Equals(command, StringComparison.OrdinalIgnoreCase)); return(cmd != null); }
public async Task <IActionResult> Update([FromBody] BotUpdateInput input) { UserEntity user = _userRepository.FindUser(input.Message.Chat.Id.ToString()); _messageRepository.InsertMessage(new MessageEntity() { UserId = user?.Id, ChatId = input.Message.Chat.Id.ToString(), Text = input.Message.Text, Date = DateTime.Now }); string commandString = (input.Message.Text + " ").Split(' ')[0].TrimStart('/'); if (!commands.ContainsKey(commandString)) { await _messageService.SendMessageAsync(input.Message.Chat.Id.ToString(), "Invalid command!"); } else { Type commandType = commands[commandString]; IBotCommand command = HttpContext.RequestServices.GetService(commandType) as IBotCommand; await command.ExecuteAsync(input); } return(Ok()); }
private CommandUsage AttemptToRunCommand(CommandReceivedEventArgs e, IBotCommand botCommand, IChatClient chatClient1, IList <string> args) { try { _logger.LogInformation($"{e.ChatUser.DisplayName} is running the {botCommand.GetType().Name} command."); if (e.ChatUser.CanRunCommand(botCommand)) { if (args.Any()) { e.Arguments.Clear(); foreach (string arg in args) { e.Arguments.Add(arg); } } return(botCommand.Process(chatClient1, e)); } chatClient1.SendMessage( $"Sorry, {e.ChatUser.DisplayName}! You don't have permission to use the !{e.CommandWord} command."); } catch (Exception exception) { _logger.LogError(exception, "Failed to run a command."); } return(new CommandUsage(e.ChatUser.DisplayName, DateTimeOffset.UtcNow, botCommand)); }
private ResponseTrigger CommandText(IBotCommand command) { var response = command.GetResponseQuote(); response.WithButtons = command.WithButtons; return(command.GetResponseQuote()); }
public void Process(IChatClient chatClient, CommandReceivedEventArgs eventArgs) { if (eventArgs.Arguments.Count == 0) { ShowAvailableCommands(chatClient, eventArgs.ChatUser); return; } string argOne = eventArgs?.Arguments?.ElementAtOrDefault(0); if (argOne == "?") { chatClient.SendMessage($"Use !help to see available commands. To request help for a specific command just type !help [commandname] example: !help hangman"); return; } if (argOne == "↑, ↑, ↓, ↓, ←, →, ←, →, B, A, start, select") { chatClient.SendMessage("Please be sure to drink your ovaltine."); } IBotCommand requestedCommand = _allCommands.SingleOrDefault(x => x.CommandText.Equals(argOne, StringComparison.InvariantCultureIgnoreCase)); if (requestedCommand != null) { chatClient.SendMessage(requestedCommand.HelpText); } }
/// <summary> /// Commands the bot to set specific settings. /// </summary> /// <param name="command">Bot command.</param> /// <returns>A Task object associated with the async operation.</returns> protected async Task CommandSet(IBotCommand command) { var parts = command.RequestText.Split(' '); if (parts.Length < 3) { command.ResponseText = $"{CommonResx.Usage}: set <setting> <value>"; } switch (parts[1].ToLowerInvariant()) { case "culture": try { var cultureInfo = new CultureInfo(parts[2]); Thread.CurrentThread.CurrentCulture = cultureInfo; Thread.CurrentThread.CurrentUICulture = cultureInfo; CultureInfo.DefaultThreadCurrentCulture = cultureInfo; CultureInfo.DefaultThreadCurrentUICulture = cultureInfo; command.ResponseText = string.Format(SetResx.CultureChangedTo, cultureInfo.EnglishName); } catch (Exception exc) { var message = $"{SetResx.ErrorSettingCulture}: {exc.Message}"; this.Logger?.Error(message, exc); command.ResponseText = message; } break; } await Task.CompletedTask; }
public override string TryToExecute(CommandReceivedEventArgs eventArgs) { string commandWord = eventArgs?.Arguments?.ElementAtOrDefault(1); ChatUser chatUser = eventArgs.ChatUser; try { if (!chatUser.CanUserRunCommand(UserRole.Mod)) { return("You need to be a moderator to delete a command."); } SimpleCommand command = _repository.Single(CommandPolicy.ByCommandText(commandWord)); if (command == null) { return($"I didn't find a !{commandWord} command."); } IBotCommand botCommand = _allCommands.SingleOrDefault(x => x.ShouldExecute(commandWord)); if (botCommand != null) { _allCommands.Remove(botCommand); } _repository.Remove(command); return($"Removing the !{commandWord} command."); } catch (Exception e) { Console.WriteLine(e); return(""); } }
public void CommandReceivedHandler(object sender, CommandReceivedEventArgs e) { if (sender is IChatClient chatClient) { string userDisplayName = e.ChatUser.DisplayName; _usageTracker.PurgeExpiredUserCommandCooldowns(DateTimeOffset.Now); var previousUsage = _usageTracker.GetByUserDisplayName(userDisplayName); if (previousUsage != null) { if (!previousUsage.WasUserWarned) { chatClient.SendMessage($"Whoa {userDisplayName}! Slow down there cowboy!"); previousUsage.WasUserWarned = true; } return; } IBotCommand botCommand = _commandMessages.FirstOrDefault(c => c.ShouldExecute(e.CommandWord)); if (botCommand != null) { AttemptToRunCommand(e, botCommand, chatClient); _usageTracker.RecordUsage(new CommandUsage(userDisplayName, DateTimeOffset.Now, false)); } } }
public bool Equals(IBotCommand other) { if (other == null) return false; return other.GetCommand() == GetCommand(); }
private async void OnMessage(object sender, MessageEventArgs arguments) { var message = arguments.Message; if (message.Text != null) { try { string command = ExtractCommand(message.Text); IBotCommand handler = CommandSelector.MapCommandToHandler(command); await handler.Handle(message, this._botClient, this._pokeApiClient); } catch (Exception exception) { // Workaround since C# does not support multi catch as in Java if (exception is UnknownCommandException || exception is NoCommandHandlerException) { await this._botClient.SendTextMessageAsync( chatId : message.Chat, text : "Unfortunately the bot does not support this command. Enter /help or /start for more options." ); } else { Console.WriteLine(exception.Message); Console.WriteLine(exception.StackTrace); await this._botClient.SendTextMessageAsync( chatId : message.Chat, text : "500 - Internal Server Error" ); } } } }
public void CommandReceivedHandler(object sender, CommandReceivedEventArgs e) { if (!(sender is IChatClient chatClient)) { return; } IBotCommand botCommand = _commandMessages.FirstOrDefault(c => c.ShouldExecute(e.CommandWord)); if (botCommand == null) { return; } var cooldown = _usageTracker.GetActiveCooldown(e.ChatUser, botCommand); switch (cooldown) { case NoCooldown none: ProcessTheCommand(e, chatClient, botCommand); break; case UserCooldown userCooldown: chatClient.SendDirectMessage(e.ChatUser.DisplayName, userCooldown.Message); break; case UserCommandCooldown userCommandCooldown: chatClient.SendDirectMessage(e.ChatUser.DisplayName, userCommandCooldown.Message); break; case CommandCooldown commandCooldown: chatClient.SendMessage(commandCooldown.Message); break; } }
/// <summary> /// Commands the bot to return the status of the bot. /// </summary> /// <param name="command">Bot command.</param> /// <returns>A Task object associated with the async operation.</returns> protected async Task CommandStatus(IBotCommand command) { var status = new StringBuilder(); var lastType = BotType.Unknown; // bots foreach (var bot in this.bots.OrderBy(b => b.Type)) { if (bot.Type != lastType) { status.Append($"[{bot.Type}] "); lastType = bot.Type; } status.Append($"{bot.GetHashCode()} "); } // web server var webState = this.webServerRunning ? CommonResx.Running : CommonResx.Stopped; status.Append($"[{CommonResx.WebServer}] {webState}"); command.ResponseText = status.ToString(); await Task.CompletedTask; }
public override void Process(IChatClient chatClient, CommandReceivedEventArgs eventArgs) { try { // !RemoveCommand Twitter string commandText = eventArgs.Arguments?[0]; SimpleCommand command = _repository.Single(CommandPolicy.ByCommandText(commandText)); if (command == null) { chatClient.SendMessage($"I didn't find a !{commandText} command."); } chatClient.SendMessage($"Removing the !{commandText} command."); _repository.Remove(command); IBotCommand botCommand = _allCommands.SingleOrDefault(x => x.CommandText.Equals(commandText)); if (botCommand != null) { _allCommands.Remove(botCommand); } } catch (Exception e) { Console.WriteLine(e); } }
/// <inheritdoc/> public async Task QueueResponse(IBotCommand cmd) { this.Logger?.Debug(DebugResx.EnqueuingResponse); if (cmd.Bot != null) { await cmd.Bot.QueueResponse(cmd); } }
private void DoTheThing(CommandReceivedEventArgs e, IChatClient chatClient, IBotCommand botCommand) { CommandUsage commandUsage = AttemptToRunCommand(e, botCommand, chatClient); var commandUsageEntity = new CommandUsageEntity(e.CommandWord, botCommand.GetType().FullName, e.ChatUser.UserId, e.ChatUser.DisplayName, chatClient.GetType().Name); _repository.Create(commandUsageEntity); _usageTracker.RecordUsage(commandUsage); }
public bool Equals(IBotCommand other) { if (other == null) { return(false); } return(GetCommand() == other.GetCommand()); }
/// <summary> /// Add a command to manager. /// Throws <see cref="ArgumentException"/> when a command with same prefix exists. /// </summary> /// <param name="command">the command</param> /// <exception cref="ArgumentException"/> public void RegisterCommand(IBotCommand command) { if (commands.Any(x => x.Prefix == command.Prefix)) { throw new ArgumentException($"A command with prefix \"{ command.Prefix }\" already exists.", nameof(command)); } commands.Add(command); }
private void AliasModified(object sender, CommandAliasModifiedEventArgs e) { IBotCommand command = _commandList.GetCommandByFullTypeName(e.FullTypeName); if (command is BaseCommand baseCommand) { baseCommand.NotifyWordsModified(); } }
public void CommandReceivedHandler(object sender, CommandReceivedEventArgs e) { if (!(sender is IChatClient chatClient)) { return; } string userDisplayName = e.ChatUser.DisplayName; //List<CommandUsage> globalCooldownUsages = _usageTracker.GetUsagesByUserSubjectToGlobalCooldown(userDisplayName, DateTimeOffset.UtcNow); //if (globalCooldownUsages != null && globalCooldownUsages.Any() && !e.ChatUser.IsInThisRoleOrHigher(UserRole.Mod)) //{ // if (!globalCooldownUsages.Any(x => x.WasUserWarned)) // { // chatClient.SendMessage($"Whoa {userDisplayName}! Slow down there cowboy!"); // globalCooldownUsages.ForEach(x => x.WasUserWarned = true); // } // return; //} IBotCommand botCommand = _commandMessages.FirstOrDefault(c => c.ShouldExecute(e.CommandWord)); if (botCommand == null) { return; } var cooldown = _usageTracker.GetActiveCooldown(e.ChatUser, botCommand); chatClient.SendMessage(cooldown.Message); // TODO: prevent running the command if there was a cooldown switch (cooldown) { case NoCooldown none: break; case UserCooldown userCooldown: chatClient.SendDirectMessage(e.ChatUser.DisplayName, userCooldown.Message); break; case UserCommandCooldown userCommandCooldown: chatClient.SendDirectMessage(e.ChatUser.DisplayName, userCommandCooldown.Message); break; case CommandCooldown commandCooldown: chatClient.SendMessage(commandCooldown.Message); break; default: break; } DoTheThing(e, chatClient, botCommand); }
public void SetUp() { fakeCommand = A.Fake <IBotCommand>(); commandsList = new List <IBotCommand>(); commandsList.Add(fakeCommand); A.CallTo(() => fakeCommand.Name).Returns(fakeCommandName); database = A.Fake <IDatabase <IRecipe> >(); _bot = new Bot(commandsList); }
public async Task <IBotCommand> Execute(IBotCommand cmd, IJuvoClient client) { var term = string.Join(' ', cmd.RequestText.Split(' ').Skip(1).ToArray()); var document = await this.context.OpenAsync($"{BingUri}{term}"); var cell = document.Body.SelectSingleNode(PathToDef); cmd.ResponseText = $"{term}: {cell.TextContent}"; return(cmd); }
/// <summary> /// Adds a command to the bot engine /// </summary> /// <param name="command">The command to add</param> /// <returns><c>true</c> if the command was successfully initialized and added, /// otherwise <c>false</c></returns> public bool AddCommand(IBotCommand command) { var success = command.Initialize(this); if (success) { CommandMap[command.Shortcut] = command; } return(success); }
/// <summary> /// Adds a new command to the bot. /// </summary> /// <param name="command"></param> private void AddCommand(IBotCommand command) { if (_commands.Contains(command)) { return; } _log.Info("Command added: " + command.GetCommand()); _commands.Add(command); }
private void CommandReceivedHandler(object sender, CommandReceivedEventArgs e) { if (sender is IChatClient chatClient) { IBotCommand botCommand = _commandMessages.FirstOrDefault(c => c.CommandText.ToLowerInvariant() == e.CommandWord.ToLowerInvariant()); if (botCommand != null) { AttemptToRunCommand(e, botCommand, chatClient); } } }
public Result CanCommandBeExecuted(CommandContainer args) { IBotCommand command = _serviceProvider.GetCommand(args.CommandName); var descriptor = command.GetBotCommandDescriptorAttribute(); Result canExecute = command.CanExecute(args); return(canExecute.IsSuccess ? Result.Ok() : Result.Fail( $"Command [{descriptor.CommandName}] cannot be executed: {canExecute}")); }
/// <summary> /// Queues command for the bot to execute or pass on. /// </summary> /// <param name="cmd">Command object.</param> public void QueueCommand(IBotCommand cmd) { Debug.Assert(cmd != null, $"{nameof(cmd)} == null"); Debug.Assert(!string.IsNullOrEmpty(cmd.RequestText), $"{nameof(cmd.RequestText)} != null/empty"); lock (this.commandQueue) { this.commandQueue.Enqueue(cmd); } this.Logger?.Info(DebugResx.CommandEnqueued); }
private ResponseTrigger CommandGoogle(IBotCommand command) { var row = _commandTextGoogle.GetRandomRowGSheets(new GSheetQuery() { Ranges = new[] { command.TableName } }); var response = command.GetResponse(row); response.Trigger = command.Trigger; response.WithButtons = command.WithButtons; return(response); }
public async Task <IBotMessage> ExecuteCommand(CommandContainer args) { IBotCommand command = _serviceProvider.GetCommand(args.CommandName); try { return(await command.Execute(args)); } catch (Exception e) { LoggerHolder.Instance.Error("Command execution failed. Command: {args.CommandName}; arguments: {string.Join(", ", args.Arguments)}"); throw; } }
private static Task InvokeMethod(IBotCommand command, Contexts contexts, ControllerInfo controllerInfo, MethodInfo method) { Log.Information("Invoke in controller {controller} method {method}", controllerInfo.Controller.GetType().Name, method.Name); using (LogContext.PushProperty("Method", method.Name)) { var runningMethod = method.Invoke(controllerInfo.Controller, new object[] { command, contexts }); if (runningMethod is Task task) { return(task); } } return(Task.CompletedTask); }
private async Task ExecuteCommand(IBotCommand command, CommandEventArgs args) { Logger.Info($"Executing command '{command.Command}'"); try { await args.Channel.DeleteMessages(new[] { args.Message }); await command.ExecuteAsync(args); } catch (Exception ex) { Logger.Error(ex.Message, ex); } }
/// <summary> /// Runs the given command. /// </summary> /// <param name="command"></param> /// <returns></returns> public string RunCommand(string command, string[] args) { IBotCommand cmd = _commands.Find(x => x.GetCommand().Equals(command, StringComparison.OrdinalIgnoreCase)); if (cmd == null) { return("Hiba: nincs ilyen parancs."); } _log.Info("Running command: " + command); StatisticsCollector.GetInstance().IncrementExecutedCommandCount(); return(cmd.RunAction(args)); }
/// <summary> /// Adds a new command to the bot. /// </summary> /// <param name="command"></param> private void AddCommand(IBotCommand command) { if (_commands.Contains(command)) return; _log.Info("Command added: " + command.GetCommand()); _commands.Add(command); }
public bool Equals(IBotCommand other) { return other.GetCommand() == GetCommand(); }
public void PrintHelpSyntaxForCommand(IrcEventArgs ircEventArgs, IBotCommand command) { foreach (var helpsyntax in command.GetHelpSyntax(ircEventArgs)) { SendMessage(helpsyntax, ircEventArgs.Data.Nick); } }
protected void AddCommand(IStorageManager storageManager, IBotCommand command) { command.Storage = storageManager.StorageFor(command.Id); command.Initialize(); _commands.Add(command); }