public override string TryToExecute(CommandReceivedEventArgs eventArgs) { var word = eventArgs?.Arguments? .ElementAtOrDefault(1)?.ToLowerInvariant(); try { var commandEntity = _repository.Single(CommandPolicy.ByWord(word)); if (commandEntity == null) { return($"The alias '!{word}' doesn't exist."); } int numberRemoved = commandEntity.Aliases .RemoveAll(a => a.Word == word); if (numberRemoved != 1) { return(GetErrorMessage(word)); } _repository.Update(commandEntity); return($"The alias '!{word}' has been deleted."); } catch (Exception e) { _logger.LogError(e, GetErrorMessage(word)); return(GetErrorMessage(word)); } }
public override void Process(IChatClient chatClient, CommandReceivedEventArgs eventArgs) { try { // !AddCommand Twitter "https://twitter.com/DevChatter_" Everyone SimpleCommand command = eventArgs.Arguments.ToSimpleCommand(); if (command == null) { chatClient.SendMessage("Failed to create command."); chatClient.SendMessage(HelpText); return; } if (_repository.Single(CommandPolicy.ByCommandText(command.CommandText)) != null) { chatClient.SendMessage($"There's already a command using !{command.CommandText}"); return; } chatClient.SendMessage($"Adding a !{command.CommandText} command for {command.RoleRequired}. It will respond with {command.StaticResponse}."); _repository.Create(command); _allCommands.Add(command); } catch (Exception e) { Console.WriteLine(e); } }
protected override void HandleCommand(IChatClient chatClient, CommandReceivedEventArgs eventArgs) { var oper = eventArgs?.Arguments?.ElementAtOrDefault(0)?.ToLowerInvariant(); var word = eventArgs?.Arguments?.ElementAtOrDefault(1)?.ToLowerInvariant(); if (string.IsNullOrEmpty(oper) || string.IsNullOrEmpty(word)) { chatClient.SendMessage(HelpText); return; } var typeName = Repository.Single(CommandPolicy.ByWord(word))?.FullTypeName; if (typeName == null) { chatClient.SendMessage($"The command '!{word}' doesn't exist."); return; } var operationToUse = _operations.SingleOrDefault(x => x.ShouldExecute(oper)); if (operationToUse != null) { string resultMessage = operationToUse.TryToExecute(eventArgs); chatClient.SendMessage(resultMessage); CommandAliasModified?.Invoke(this, new CommandAliasModifiedEventArgs(typeName)); } else { chatClient.SendMessage(HelpText); } }
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); } }
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(""); } }
protected override CommandPolicy PolicyCreateOrValidate(CommandPolicy incomingPolicy) { var pol = base.PolicyCreateOrValidate(incomingPolicy); pol.MasterJobEnabled = true; pol.MasterJobNegotiationChannelIdOutgoing = ChannelId; return(pol); }
public void PartialCommandContractWithChannelIdSet() { var policy = new CommandPolicy(); policy.ChannelId = "fredo"; CommandHarness <CommandHarnessTest1> harness; harness = new CommandHarness <CommandHarnessTest1>(() => new CommandHarnessTest1(policy)); harness.Start(); Assert.IsTrue(harness.RegisteredCommands.Count == 1); }
public static IServiceCollection AddSimpleCommandsFromRepository( this IServiceCollection services, IRepository repository) { List <SimpleCommand> simpleCommands = repository.List(CommandPolicy.All()); foreach (SimpleCommand simpleCommand in simpleCommands) { services.AddSingleton <IBotCommand>(simpleCommand); } return(services); }
public static ContainerBuilder AddSimpleCommandsFromRepository( this ContainerBuilder builder, IRepository repository) { List <SimpleCommand> simpleCommands = repository.List(CommandPolicy.All()); foreach (SimpleCommand simpleCommand in simpleCommands) { builder.RegisterInstance(simpleCommand).As <IBotCommand>(); } return(builder); }
public override string TryToExecute(CommandReceivedEventArgs eventArgs) { if (eventArgs?.Arguments == null || eventArgs.Arguments.Count < 3) { return(HelpText); } var word = eventArgs.Arguments[1].ToLowerInvariant(); var newAlias = eventArgs.Arguments[2].ToLowerInvariant(); var arguments = eventArgs.Arguments.Skip(3).ToList(); var commandEntity = _repository.Single(CommandPolicy.ByWord(word)); var existingWord = _repository.Single(CommandPolicy.ByWord(newAlias)); if (string.IsNullOrEmpty(newAlias)) { return("You seem to be missing the new alias you want to set."); } if (existingWord != null) { return($"The command word '!{existingWord.CommandWord}' already exists."); } var alias = new AliasEntity { Word = newAlias, Command = commandEntity, }; for (int i = 0; i < arguments.Count; i++) { alias.Arguments.Add(new AliasArgumentEntity { Argument = arguments[i], Alias = alias, Index = i }); } commandEntity.Aliases.Add(alias); _repository.Update(commandEntity); return($"Created new command alias '!{newAlias}' for '!{word}'."); }
public void PartialCommandContractWithNoChannelIdSet() { var policy = new CommandPolicy(); policy.ChannelId = null; CommandHarness <CommandHarnessTest1> harness; try { harness = new CommandHarness <CommandHarnessTest1>(() => new CommandHarnessTest1(policy)); harness.Start(); } catch (Exception ex) { Assert.IsTrue(ex is CommandChannelIdNullException); } }
public void TestMasterJob() { var policy = new CommandPolicy() { ChannelId = "default", JobSchedulesEnabled = true, CommandContractAttributeInherit = true, JobScheduleAttributeInherit = true }; //Default state. var harness = new CommandHarness <MasterJobCommandTop>(policy); harness.MasterJobNegotiationEnable(); harness.Start(); Assert.IsTrue(harness.RegisteredSchedules.Count == 1); Assert.IsTrue(harness.Dependencies.Scheduler.Count == 2); Assert.IsTrue(harness.RegisteredCommandMethods.Count == 2); Assert.IsFalse(harness.HasCommand(("one", "base"))); Assert.IsFalse(harness.HasSchedule("1base")); //Wait for the master job to go live. harness.MasterJobStart(); //Check that the MasterJob commands and schedules have been registered. Assert.IsTrue(harness.RegisteredSchedules.Count == 2); Assert.IsTrue(harness.Dependencies.Scheduler.Count == 3); Assert.IsTrue(harness.RegisteredCommandMethods.Count == 3); Assert.IsTrue(harness.HasCommand(("one", "top"))); Assert.IsTrue(harness.HasSchedule("1top")); Assert.IsTrue(harness.HasCommand(("one", "base"))); Assert.IsTrue(harness.HasSchedule("1base")); //Stop the master job harness.MasterJobStop(); //Check that the master job commands have been removed. Assert.IsTrue(harness.RegisteredSchedules.Count == 1); Assert.IsTrue(harness.Dependencies.Scheduler.Count == 2); Assert.IsTrue(harness.RegisteredCommandMethods.Count == 2); Assert.IsFalse(harness.HasCommand(("one", "base"))); Assert.IsFalse(harness.HasSchedule("1base")); }
private static (List <CommandEntity> WordsToAdd, List <CommandEntity> WordsToRemove) GetCommandWordChanges(IRepository repository) { const string conventionSuffix = "Command"; // Access the assembly to make sure it's loaded Assembly assembly = typeof(BlastCommand).Assembly; Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); IEnumerable <TypeInfo> allCommandTypes = assemblies.SelectMany(x => x.DefinedTypes); DefaultCommandData commandData = GetDefaultData(); var concreteCommands = allCommandTypes .Where(x => typeof(IBotCommand).IsAssignableFrom(x)) .Where(x => !x.IsAbstract) .Where(x => !x.IsSubclassOf(typeof(DataEntity))) .Where(x => x.FullName.EndsWith(conventionSuffix)) .ToList(); List <CommandEntity> commandEntities = repository.List(CommandPolicy.All()); List <string> commandTypes = commandEntities.Select(x => x.FullTypeName).ToList(); CommandEntity CommandEntityFromTypeAndDefaultData(TypeInfo commandType) { var entity = commandData.Commands.SingleOrDefault(x => x.FullTypeName == commandType.FullName) ?? new CommandEntity { FullTypeName = commandType.FullName, }; entity.CommandWord = commandType.Name.Substring(0, commandType.Name.Length - conventionSuffix.Length); return(entity); } List <CommandEntity> missingDefaults = concreteCommands .Where(x => !commandTypes.Contains(x.FullName)) .Select(CommandEntityFromTypeAndDefaultData) .ToList(); var entitiesToRemove = commandEntities.Where(x => concreteCommands.All(c => c.FullName != x.FullTypeName)).ToList(); return(missingDefaults, entitiesToRemove); }
public void FailNoResponseChannel() { var policy = new CommandPolicy() { ChannelId = "default", OutgoingRequestsEnabled = true }; var harness = new CommandHarness <OutgoingCommandRoot>(policy); try { harness.Start(); } catch (Exception ex) { Assert.IsTrue(ex is CommandStartupException); } }
public void OutgoingTests() { var policy = new CommandPolicy() { ChannelId = "default" , JobSchedulesEnabled = true , OutgoingRequestMaxProcessingTimeDefault = TimeSpan.FromSeconds(1) , OutgoingRequestDefaultTimespan = TimeSpan.FromSeconds(1) , OutgoingRequestsEnabled = true , ResponseChannelId = "incoming" }; var harness = new CommandHarness <OutgoingCommandRoot>(policy); bool timed_out = false; var mre = new ManualResetEventSlim(); harness.Service.OnOutgoingRequest += (object sender, OutgoingRequestEventArgs e) => { }; harness.Service.OnOutgoingRequestTimeout += (object sender, OutgoingRequestEventArgs e) => { timed_out = true; mre.Set(); }; harness.Start(); //Create the timeout poll Task.Run(async() => { while (!timed_out) { harness.OutgoingTimeoutScheduleExecute(); await Task.Delay(100); } }); harness.ScheduleExecute("1base"); mre.Wait(); Assert.IsTrue(timed_out); }
public void PartialCommandContractWithChannelIdSet() { int countTotal = 0; int countOutgoing = 0; int countResponse = 0; var policy = new CommandPolicy() { ChannelId = "fredo", OutgoingRequestsEnabled = true, ResponseChannelId = "getback" }; var harness = new CommandHarness <CommandHarness1>(policy); harness.Start(); Assert.IsTrue(harness.RegisteredCommandMethods.Count == 2); bool ok = false; harness .Intercept((ctx) => ok = true, CommandHarnessTrafficDirection.Outgoing, ("one", null, null)) .Intercept((ctx) => Interlocked.Increment(ref countTotal)) .Intercept((ctx) => Interlocked.Increment(ref countOutgoing), header: ("one", null, null)) .Intercept((ctx) => Interlocked.Increment(ref countResponse), header: ("getback", null, null)) .InterceptOutgoing((c) => { string rString = null; c.RequestPayloadTryGet <string>(out rString); c.ResponseSet <string>(200, "over and out", "Hello mum"); }) ; harness.ScheduleExecute("1"); harness.Dispatcher.Process(("fredo", "two", "three"), "Helloe"); harness.Dispatcher.Process(("one", "two"), "Helloe", responseHeader: ("2", "3")); Assert.IsTrue(harness.TrafficPayloadOutgoing.Count == 2); Assert.IsTrue(ok); Assert.IsTrue(countTotal == 7); Assert.IsTrue(countOutgoing == 2); }
public void TestInheritance() { var policy = new CommandPolicy() { ChannelId = "default", JobSchedulesEnabled = true, CommandContractAttributeInherit = true, JobScheduleAttributeInherit = true }; //Default state. var harness = new CommandHarness <CommandTop>(policy); harness.Start(); Assert.IsTrue(harness.RegisteredSchedules.Count == 2); Assert.IsTrue(harness.RegisteredCommandMethods.Count == 2); Assert.IsTrue(harness.HasCommand(("one", "top"))); Assert.IsTrue(harness.HasSchedule("1top")); Assert.IsTrue(harness.HasCommand(("one", "base"))); Assert.IsTrue(harness.HasSchedule("1base")); }
public override string TryToExecute(CommandReceivedEventArgs eventArgs) { var word = eventArgs?.Arguments?.ElementAtOrDefault(1)?.ToLowerInvariant(); var commandEntity = _repository.Single(CommandPolicy.ByWord(word)); if (commandEntity == null) { return($"The command word '!{word}' doesn't exist."); } int numberRemoved = commandEntity.Aliases.RemoveAll(a => a.Word == word); if (numberRemoved != 1) { return($"Something went wrong when trying to delete {word}."); } _repository.Update(commandEntity); return($"The command '!{commandEntity.CommandWord}' has been deleted."); }
public override string TryToExecute(CommandReceivedEventArgs eventArgs) { string commandWord = eventArgs?.Arguments?.ElementAtOrDefault(1); string staticResponse = eventArgs?.Arguments?.ElementAtOrDefault(2); string roleText = eventArgs?.Arguments?.ElementAtOrDefault(3); ChatUser chatUser = eventArgs.ChatUser; try { if (!chatUser.CanUserRunCommand(UserRole.Mod)) { return("You need to be a moderator to add a command."); } if (!Enum.TryParse(roleText, true, out UserRole role)) { role = UserRole.Everyone; } SimpleCommand command = new SimpleCommand(commandWord, staticResponse, role); if (_repository.Single(CommandPolicy.ByCommandText(command.CommandText)) != null) { return($"There's already a command using !{command.CommandText}"); } _repository.Create(command); _allCommands.Add(command); return($"Adding a !{command.CommandText} command for {command.RoleRequired}. It will respond with {command.StaticResponse}."); } catch (Exception e) { Console.WriteLine(e); return(""); } }
/// <summary> /// Initializes a new instance of the <see cref="CommandRoot"/> class. /// </summary> /// <param name="policy">The optional command policy. If this is null, then the policy will be created.</param> public CommandRoot(CommandPolicy policy = null) : base(policy) { }
/// <summary> /// Initializes a new instance of the <see cref="MasterCommandRoot"/> class. /// </summary> /// <param name="policy">The optional command policy. If this is null, then the policy will be created.</param> public OutgoingCommandRoot(CommandPolicy policy = null) : base(policy) { }
/// <summary> /// Initializes a new instance of the <see cref="CommandTop"/> class. /// </summary> /// <param name="policy">The optional command policy. If this is null, then the policy will be created.</param> public CommandTop(CommandPolicy policy = null) : base(policy) { }
public CommandHarness1(CommandPolicy policy = null) : base(policy) { }
public TestMasterJob2(string channel) : base(CommandPolicy.ToMasterJob(channel)) { }
public DelayedProcessingJob() : base(CommandPolicy.ToJob(TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(1), null, isLongRunningJob: false)) { }
public EventTestCommand(CommandPolicy policy = null) : base(policy) { }
/// <summary> /// Initializes a new instance of the <see cref="MasterCommandTop"/> class. /// </summary> /// <param name="policy">The optional command policy. If this is null, then the policy will be created.</param> public MasterJobCommandTop(CommandPolicy policy = null) : base(policy) { }