public void Sending_command_with_same_command_id_as_thre_previous_command_should_have_no_effect() { InitializeEnvironment(); var commandService = new CommandService(); commandService.RegisterExecutorsInAssembly(typeof(FetureTests).Assembly); NcqrsEnvironment.SetDefault<ISnapshottingPolicy>(new SimpleSnapshottingPolicy(2)); var noteId = Guid.NewGuid(); var updateCommandId = Guid.NewGuid(); var createNewCommand = new CreateNewNoteCommand(Guid.NewGuid()) { NoteId = noteId, Text = "Note One" }; commandService.Execute(createNewCommand); var updateCommand = new ChangeNoteTextCommand(updateCommandId) { NoteId = noteId, NewText = "Note One Modified" }; commandService.Execute(updateCommand); updateCommand = new ChangeNoteTextCommand(updateCommandId) { NoteId = noteId, NewText = "Note One Modified Once Again" }; commandService.Execute(updateCommand); var uowFactory = NcqrsEnvironment.Get<IUnitOfWorkFactory>(); using (var uow = uowFactory.CreateUnitOfWork(Guid.NewGuid())) { var note = (Note)uow.GetById(typeof(Note), noteId, null); note.Text.Should().Be("Note One Modified"); } }
private static ICommandService InitializeCommandService() { var service = new CommandService(); service.RegisterExecutor(new CreateNewVoyageCommandExecutor()); return service; }
private static ICommandService InitializeCommandService() { var service = new CommandService(); service.RegisterExecutor(new AttributeMappedCommandExecutor<CreatePersonCommand>()); service.RegisterExecutor(new AttributeMappedCommandExecutor<ChangeNameCommand>()); return service; }
public Configuration(SetValidationCommandInterceptor interceptor) { var commandService = new CommandService(); commandService.Configure(); commandService.AddInterceptor(interceptor); Register<ICommandService>(commandService); }
private static ICommandService InitCommandService() { var service = new CommandService(); service.RegisterExecutorsInAssembly(typeof(CreateInvoicePayment).Assembly); service.AddInterceptor(new ThrowOnExceptionInterceptor()); return service; }
public void Save_WithNullEntity_ThrowsArgumentNullException(Mock<IUnitOfWork> unitOfWork, Mock<IRepository> repository) { // Given var sut = new CommandService<object>(unitOfWork.Object, repository.Object); // When, Then Assert.Throws(typeof(ArgumentNullException), () => sut.Save(null)); }
public void Execute_With_Invalid_WorkindDirectory_Should_ReturnFailure () { ICommandRequest request = Substitute.For<ICommandRequest>(); request.WorkingDirectory.Returns(""); var service = new CommandService(); var result = service.Execute(request); Assert.IsFalse(result.Success); }
private static ICommandService InitializeCommandService() { var service = new CommandService(); service.RegisterExecutor(new ScheduleNewMeetingCommandExecutor()); service.RegisterExecutor(new AddCommentCommandExecutor()); return service; }
public void Constructor_SutIsCommandService(Mock<IUnitOfWork> unitOfWork, Mock<IRepository> repository) { // When var sut = new CommandService<object>(unitOfWork.Object, repository.Object); // Then Assert.IsAssignableFrom<ICommandService<object>>(sut); }
private static ICommandService InitializeCommandService() { var mapper = new AttributeBasedCommandMapper(); var service = new CommandService(); service.RegisterExecutor(typeof(CreatePersonCommand), new UoWMappedCommandExecutor(mapper)); service.RegisterExecutor(typeof(ChangeNameCommand), new UoWMappedCommandExecutor(mapper)); return service; }
public void Setup() { var service = new CommandService(); Map.Command<AggregateRootTargetUpdateTitleCommand>().ToAggregateRoot<AggregateRootTarget>().WithId(cmd => cmd.Id, guid => GetAggregateRoot()).ToCallOn((cmd, aggroot) => aggroot.UpdateTitle(cmd.Title)).RegisterWith(service); Map.Command<AggregateRootTargetCreateNewCommand>().ToAggregateRoot<AggregateRootTarget>().CreateNew((cmd) => new AggregateRootTarget(cmd.Title)).StoreIn((cmd, aggroot) => AggRoot = aggroot).RegisterWith(service); TheService = service; }
private static ICommandService InitializeCommandService() { var commandAssembly = typeof(CreateCustomer).Assembly; var service = new CommandService(); service.RegisterExecutorsInAssembly(commandAssembly); return service; }
private static ICommandService InitializeCommandService() { var commandAssembly = typeof(CreateNewNote).Assembly; var service = new CommandService(); service.RegisterExecutorsInAssembly(commandAssembly); service.AddInterceptor(new ThrowOnExceptionInterceptor()); return service; }
public void MapCommands(CommandService commandService) { Map.Command<CreateTermCommand>() .ToAggregateRoot<Term>() .CreateNew(cmd => new Term(cmd.TermId, cmd.Abbreviation, cmd.Name, cmd.StartDate, cmd.EndDate)) .RegisterWith(commandService); }
public static void Start() { NcqrsEnvironment.SetDefault<IEventStore>(new TableOnlyStore("MainTest")); //NcqrsEnvironment.SetDefault<IEventStore>(new MsSqlServerEventStore(@"Server=.\SQLExpress;Initial Catalog=MyNotesEventStore;Integrated Security=SSPI")); CommandService c = new CommandService(); c.RegisterExecutorsInAssembly(typeof(CreateNoteCommand).Assembly); NcqrsEnvironment.SetDefault<ICommandService>(c); }
public override void Load() { Kernel.Bind<IUniqueIdentifierGenerator>() .To<GuidCombGenerator>(); var eventStoreConnectionString = ConfigurationManager.ConnectionStrings["EventStore"].ConnectionString; Kernel.Bind<IEventStore>() .ToMethod(ctx => new MsSqlServerEventStore(eventStoreConnectionString)) .InSingletonScope(); Kernel.Bind<IEventBus>() .ToMethod(ctx => new InProcessEventBus().RegisterDenormalizers(Kernel)) .InSingletonScope(); Kernel.Bind<IAggregateRootCreationStrategy>() .To<NinjectAggregateRootCreationStrategy>() .InSingletonScope(); Kernel.Bind<IDomainRepository>() .To<DomainRepository>() .InSingletonScope(); Kernel.Bind<ICommandServiceInterceptor>() .To<ValidationCommandInterceptor>() .InSingletonScope(); Kernel.Bind<ICommandServiceInterceptor>() .To<SetValidationCommandInterceptor>() .InSingletonScope(); Kernel.Bind<ICommandService>() .ToMethod(ctx => { var cs = new CommandService(); cs.Configure(); var interceptors = ctx.Kernel.GetAll<ICommandServiceInterceptor>(); foreach (var interceptor in interceptors) cs.AddInterceptor(interceptor); return cs; }) .InSingletonScope(); Kernel.Bind<IMapMaker>() .ToMethod(ctx => ctx.Kernel.Get<NHibernateMapMaker>()); Kernel.Bind<Map>() .ToMethod(ctx => ctx.Kernel.Get<IMapMaker>().MakeMap()) .InSingletonScope(); Kernel.Bind<IDialect>() .ToMethod(ctx => new MsSqlDialect(ctx.Kernel.Get<Map>())) .InSingletonScope(); }
public FluentCommandMappingTests() { var service = new CommandService(); Map.Command<AggregateRootTargetStaticCreateCommand>().ToAggregateRoot<AggregateRootTarget>().CreateNew((cmd) => AggregateRootTarget.CreateNew(cmd.Title)).StoreIn((cmd, aggroot) => AggRoot = aggroot).RegisterWith(service); Map.Command<AggregateRootTargetUpdateTitleCommand>().ToAggregateRoot<AggregateRootTarget>().WithId(cmd => cmd.Id, (guid, knownVersion) => GetAggregateRoot()).ToCallOn((cmd, aggroot) => aggroot.UpdateTitle(cmd.Title)).RegisterWith(service); Map.Command<AggregateRootTargetCreateNewCommand>().ToAggregateRoot<AggregateRootTarget>().CreateNew((cmd) => new AggregateRootTarget(cmd.Title)).StoreIn((cmd, aggroot) => AggRoot = aggroot).RegisterWith(service); Map.Command<AggregateRootTargetCreateOrUpdateTitleCommand>().ToAggregateRoot<AggregateRootTarget>().UseExistingOrCreateNew(cmd => cmd.Id, (guid, knownVersion) => GetAggregateRoot(guid), (cmd) => new AggregateRootTarget(cmd.Id, cmd.Title)).ToCallOn((cmd, aggroot) => aggroot.UpdateTitle(cmd.Title)).RegisterWith(service); TheService = service; }
public override void Load() { Kernel.Bind<IKernel>().ToConstant(Kernel); var commandService = new CommandService(); commandService.Configure(); commandService.AddInterceptor(new ValidationCommandInterceptor()); Kernel.Bind<ICommandService>().ToConstant(commandService); Kernel.Bind<IAggregateRootCreationStrategy>().To<NinjectAggregateRootCreationStrategy>(); Kernel.Bind<IClock>().To<DateTimeBasedClock>(); }
public void Save_WithEntity_DelegatesToRepository( Mock<IUnitOfWork> unitOfWork, Mock<IRepository> repository, object entity) { // Given var sut = new CommandService<object>(unitOfWork.Object, repository.Object); // When sut.Save(entity); // Then repository.Verify(m => m.Save(entity)); }
public void MapCommands(CommandService commandService) { Map.Command<CreateTopicCodeCommand>() .ToAggregateRoot<TopicCode>() .CreateNew(cmd => new TopicCode(cmd.Abbreviation, cmd.Description)) .RegisterWith(commandService); Map.Command<ChangeTopicCodeAbbreviationCommand>() .ToAggregateRoot<TopicCode>() .WithId(cmd => cmd.TopicCodeId) .ToCallOn((cmd, topicCode) => topicCode.ChangeAbbreviation(cmd.Abbreviation)) .RegisterWith(commandService); Map.Command<ChangeTopicCodeDescriptionCommand>() .ToAggregateRoot<TopicCode>() .WithId(cmd => cmd.TopicCodeId) .ToCallOn((cmd, topicCode) => topicCode.ChangeDescription(cmd.Description)) .RegisterWith(commandService); }
public CommandServiceBaseTests() { var service = new CommandService(); ExecutorForCommandWithExecutor = MockRepository.GenerateMock<ICommandExecutor<CommandWithExecutor>>(); ExecutorForCommandWithExecutorThatThrowsException = MockRepository.GenerateMock<ICommandExecutor<CommandWithExecutorThatThrowsException>>(); Interceptor1 = MockRepository.GenerateMock<ICommandServiceInterceptor>(); Interceptor2 = MockRepository.GenerateMock<ICommandServiceInterceptor>(); ExecutorForCommandWithExecutorThatThrowsException.Stub(e=>e.Execute(null)).IgnoreArguments().Throw(new Exception()); service.RegisterExecutor(ExecutorForCommandWithExecutor); service.RegisterExecutor(ExecutorForCommandWithExecutorThatThrowsException); service.AddInterceptor(Interceptor1); service.AddInterceptor(Interceptor2); TheService = service; }
public ICommandResponse SetupGitRepos (InitialGitStatus status) { var argument = string.Empty; switch (status) { case InitialGitStatus.BareAheadOfHome: argument = " bare"; break; case InitialGitStatus.HomeAheadOfBare: argument = " home"; break; default: break; } var script = TestConstants.ScriptDirName + TestConstants.CreateRepoScript + argument; ICommandRequest request = new CommandRequest (); request.WorkingDirectory = TestConstants.ScriptDirPath; request.Name = "bash"; request.Arguments = script; var service = new CommandService (new BashGitCommandOutputStrategy ()); var result = service.Execute (request); return result; }
public BotCommands(CommandService commandService) { cmdService = commandService; }
public static IServiceCollection AddModix(this IServiceCollection services) { services.AddSingleton( provider => new DiscordSocketClient(config: new DiscordSocketConfig { AlwaysDownloadUsers = true, LogLevel = LogSeverity.Debug, MessageCacheSize = provider .GetRequiredService <IOptions <ModixConfig> >() .Value .MessageCacheSize //needed to log deletions })); services.AddSingleton <IDiscordSocketClient>(provider => provider.GetRequiredService <DiscordSocketClient>().Abstract()); services.AddSingleton <IDiscordClient>(provider => provider.GetRequiredService <DiscordSocketClient>()); services.AddSingleton( provider => new DiscordRestClient(config: new DiscordRestConfig { LogLevel = LogSeverity.Debug, })); services.AddSingleton(_ => { var service = new CommandService( new CommandServiceConfig { LogLevel = LogSeverity.Debug, DefaultRunMode = RunMode.Sync, CaseSensitiveCommands = false, SeparatorChar = ' ' }); service.AddTypeReader <IEmote>(new EmoteTypeReader()); service.AddTypeReader <DiscordUserEntity>(new UserEntityTypeReader()); service.AddTypeReader <AnyGuildMessage <IUserMessage> >(new AnyGuildMessageTypeReader <IUserMessage>()); service.AddTypeReader <TimeSpan>(new TimeSpanTypeReader(), true); service.AddTypeReader <DiscordUserOrMessageAuthorEntity>(new UserOrMessageAuthorEntityTypeReader()); return(service); }) .AddScoped <Modix.Common.Messaging.INotificationHandler <MessageReceivedNotification>, CommandListeningBehavior>(); services.AddSingleton <DiscordSerilogAdapter>(); services .AddModixCore() .AddModixMessaging() .AddModixModeration() .AddModixPromotions() .AddCodePaste() .AddCommandHelp() .AddGuildStats() .AddMentions() .AddModixTags() .AddStarboard() .AddAutoRemoveMessage() .AddEmojiStats() .AddImages() .AddGiveaways(); services.AddScoped <IQuoteService, QuoteService>(); services.AddSingleton <IBehavior, MessageLinkBehavior>(); services.AddSingleton <IBehavior, AttachmentBlacklistBehavior>(); services.AddScoped <DocsMasterRetrievalService>(); services.AddMemoryCache(); services.AddScoped <IPopularityContestService, PopularityContestService>(); services.AddScoped <WikipediaService>(); services.AddScoped <StackExchangeService>(); services.AddScoped <DocumentationService>(); services.AddScoped <IBehaviourConfigurationRepository, BehaviourConfigurationRepository>(); services.AddScoped <IBehaviourConfigurationService, BehaviourConfigurationService>(); services.AddSingleton <IBehaviourConfiguration, BehaviourConfiguration>(); services.AddScoped <IModerationActionEventHandler, ModerationLoggingBehavior>(); services.AddScoped <INotificationHandler <PromotionActionCreatedNotification>, PromotionLoggingHandler>(); services.AddHostedService <ModixBot>(); return(services); }
public void MapCommands(CommandService commandService) { Map.Command<CreateSectionCommand>() .ToAggregateRoot<Section>() .CreateNew(cmd => { var uow = UnitOfWorkContext.Current; var course = uow.GetById<Course>(cmd.CourseId); var term = uow.GetById<Term>(cmd.TermId); return new Section(cmd.SectionId, term, course, cmd.SectionNumber); }) .RegisterWith(commandService); Map.Command<ChangeSectionLocationCommand>() .ToAggregateRoot<Section>() .WithId(cmd => cmd.SectionId) .ToCallOn((cmd, section) => { var uow = UnitOfWorkContext.Current; var location = uow.GetById<Location>(cmd.LocationId); var tdcjTopicCode = uow.GetById<TopicCode>(cmd.TDCJTopicCodeId); section.ChangeLocation(location, tdcjTopicCode); }) .RegisterWith(commandService); Map.Command<ChangeSectionCreditTypeCommand>() .ToAggregateRoot<Section>() .WithId(cmd => cmd.SectionId) .ToCallOn((cmd, section) => section.ChangeCreditType(cmd.CreditType)) .RegisterWith(commandService); Map.Command<ChangeSectionDatesCommand>() .ToAggregateRoot<Section>() .WithId(cmd => cmd.SectionId) .ToCallOn((cmd, section) => section.ChangeDates(cmd.StartDate, cmd.EndDate)) .RegisterWith(commandService); Map.Command<ChangeSectionNumberCommand>() .ToAggregateRoot<Section>() .WithId(cmd => cmd.SectionId) .ToCallOn((cmd, section) => section.ChangeSectionNumber(cmd.SectionNumber)) .RegisterWith(commandService); Map.Command<ChangeSectionCEUsCommand>() .ToAggregateRoot<Section>() .WithId(cmd => cmd.SectionId) .ToCallOn((cmd, section) => section.ChangeCEUs(cmd.CEUs)) .RegisterWith(commandService); Map.Command<ChangeSectionTitleCommand>() .ToAggregateRoot<Section>() .WithId(cmd => cmd.SectionId) .ToCallOn((cmd, section) => section.ChangeTitle(cmd.NewTitle)) .RegisterWith(commandService); Map.Command<ChangeSectionTermCommand>() .ToAggregateRoot<Section>() .WithId(cmd => cmd.SectionId) .ToCallOn((cmd, section) => { var uow = UnitOfWorkContext.Current; var term = uow.GetById<Term>(cmd.TermId); section.ChangeTerm(term); }) .RegisterWith(commandService); }
public async Task StartAsync() { try { Log.Logger = new LoggerConfiguration() .WriteTo.Sentry(o => { o.Dsn = new Dsn(Config.Bot.SentryDsn); o.Environment = Config.Bot.Environment; o.MinimumBreadcrumbLevel = LogEventLevel.Verbose; o.MinimumEventLevel = LogEventLevel.Error; o.SendDefaultPii = true; o.AttachStacktrace = true; }) .MinimumLevel.Verbose() .WriteTo.File("logs/rabbot.log", rollingInterval: RollingInterval.Day) .WriteTo.Console() .CreateLogger(); var config = new DiscordSocketConfig { TotalShards = 1, LogLevel = LogSeverity.Verbose, MessageCacheSize = 1000, ExclusiveBulkDelete = true }; var services = new ServiceCollection() .AddSingleton(_client = new DiscordShardedClient(config)) .AddSingleton(_commandService = new CommandService(new CommandServiceConfig { DefaultRunMode = RunMode.Async, LogLevel = LogSeverity.Verbose, CaseSensitiveCommands = false, ThrowOnError = false })) .AddSingleton <TwitchService>() .AddSingleton <YouTubeVideoService>() .AddSingleton <CommandHandler>() .AddSingleton <StartupService>() .AddSingleton <AudioService>() .AddSingleton <LoggingService>() .AddSingleton <Logging>() .AddSingleton <StreakService>() .AddSingleton <AttackService>() .AddSingleton <LevelService>() .AddSingleton <MuteService>() .AddSingleton <WarnService>() .AddSingleton <EventService>() .AddSingleton <ApiService>() .AddSingleton <DiscordApiService>() .AddSingleton <InteractiveService>() .AddSingleton <EasterEventService>() .AddSingleton <ImageService>() .AddSingleton <CacheService>() .AddSingleton <RuleAcceptService>() .AddSingleton <Helper>(); //Add logging ConfigureServices(services); //Build services var serviceProvider = services.BuildServiceProvider(); //Instantiate logger/tie-in logging serviceProvider.GetRequiredService <LoggingService>(); // Run Migrations var db = DatabaseService.Instance.Open(); _logger.Information($"Checking database={db.GetType().Name}..."); using (db) { if (db.Database.GetPendingMigrations().Any()) { _logger.Information($"Applying database={db.GetType().Name} migrations..."); db.Database.Migrate(); } else { _logger.Information($"{db.GetType().Name} is up2date!"); } } //Start the bot await serviceProvider.GetRequiredService <StartupService>().StartAsync(); //Load up services serviceProvider.GetRequiredService <CommandHandler>(); serviceProvider.GetRequiredService <TwitchService>(); serviceProvider.GetRequiredService <YouTubeVideoService>(); serviceProvider.GetRequiredService <StreakService>(); serviceProvider.GetRequiredService <AttackService>(); serviceProvider.GetRequiredService <LevelService>(); serviceProvider.GetRequiredService <Logging>(); serviceProvider.GetRequiredService <MuteService>(); serviceProvider.GetRequiredService <WarnService>(); serviceProvider.GetRequiredService <EventService>(); serviceProvider.GetRequiredService <ApiService>(); serviceProvider.GetRequiredService <EasterEventService>(); serviceProvider.GetRequiredService <ImageService>(); serviceProvider.GetRequiredService <CacheService>(); serviceProvider.GetRequiredService <RuleAcceptService>(); serviceProvider.GetRequiredService <Helper>(); new Task(() => RunConsoleCommand(), TaskCreationOptions.LongRunning).Start(); //Block this program until it is closed. await Task.Delay(-1); } catch (Exception e) { _logger.Error(e, $"Error in {nameof(StartAsync)}"); Console.WriteLine($"Startup failed. Please check the config file."); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); Environment.Exit(0); } }
public CommandGroup(string baseCommand, CommandService commandService) { _baseCommand = baseCommand; _commandService = commandService; }
public void Setup() { var service = new CommandService(); service.RegisterExecutor(new AttributeMappedCommandExecutor<AggregateRootTargetUpdateTitleCommand>()); service.RegisterExecutor(new AttributeMappedCommandExecutor<AggregateRootTargetCreateNewCommand>()); service.RegisterExecutor(new AttributeMappedCommandExecutor<ComplexAggregateRootTargetCreateNewCommand1>()); service.RegisterExecutor(new AttributeMappedCommandExecutor<ComplexAggregateRootTargetCreateNewCommand2>()); service.RegisterExecutor(new AttributeMappedCommandExecutor<ComplexAggregateRootTargetCreateNewCommand3>()); service.RegisterExecutor(new AttributeMappedCommandExecutor<ComplexAggregateRootTargetCreateNewCommand4>()); TheService = service; }
public void MapCommands(CommandService commandService) { Map.Command<CreateCreditCourseCommand>() .ToAggregateRoot<Course>() .CreateNew(cmd => { var clock = NcqrsEnvironment.Get<IClock>(); return new Course( cmd.CourseId, cmd.Rubric, cmd.CourseNumber, cmd.Title, cmd.Types, clock); }) .RegisterWith(commandService); Map.Command<CreateContinuingEducationCourseCommand>() .ToAggregateRoot<Course>() .CreateNew(cmd => { var clock = NcqrsEnvironment.Get<IClock>(); return new Course( cmd.CourseId, cmd.Rubric, cmd.CourseNumber, cmd.Title, cmd.Type, cmd.EffectiveDate, cmd.ApprovedBy, clock); }) .RegisterWith(commandService); Map.Command<ChangeCIPCommand>() .ToAggregateRoot<Course>() .WithId(cmd => cmd.CourseId) .ToCallOn((cmd, course) => course.AssignCIP(cmd.CIP)) .RegisterWith(commandService); Map.Command<ChangeApprovalNumberCommand>() .ToAggregateRoot<Course>() .WithId(cmd => cmd.CourseId) .ToCallOn((cmd, course) => course.AssignApprovalNumber(cmd.ApprovalNumber)) .RegisterWith(commandService); Map.Command<ChangeCourseTitleCommand>() .ToAggregateRoot<Course>() .WithId(cmd => cmd.CourseId) .ToCallOn((cmd, course) => course.ChangeCourseTitle(cmd.NewTitle)) .RegisterWith(commandService); Map.Command<ChangeCourseLongTitleCommand>() .ToAggregateRoot<Course>() .WithId(cmd => cmd.CourseId) .ToCallOn((cmd, course) => course.ChangeCourseLongTitle(cmd.NewLongTitle)) .RegisterWith(commandService); Map.Command<ChangeCourseDescriptionCommand>() .ToAggregateRoot<Course>() .WithId(cmd => cmd.CourseId) .ToCallOn((cmd, course) => course.ChangeDescription(cmd.NewDescription)) .RegisterWith(commandService); Map.Command<ActivateCourseCommand>() .ToAggregateRoot<Course>() .WithId(cmd => cmd.CourseId) .ToCallOn((cmd, course) => course.Activate()) .RegisterWith(commandService); Map.Command<DeactivateCourseCommand>() .ToAggregateRoot<Course>() .WithId(cmd => cmd.CourseId) .ToCallOn((cmd, course) => course.Deactivate()) .RegisterWith(commandService); Map.Command<MakeCoursePendingCommand>() .ToAggregateRoot<Course>() .WithId(cmd => cmd.CourseId) .ToCallOn((cmd, course) => course.MakePending()) .RegisterWith(commandService); Map.Command<MakeCourseObsoleteCommand>() .ToAggregateRoot<Course>() .WithId(cmd => cmd.CourseId) .ToCallOn((cmd, course) => course.MakeObsolete()) .RegisterWith(commandService); Map.Command<AddCourseTypeToCourseCommand>() .ToAggregateRoot<Course>() .WithId(cmd => cmd.CourseId) .ToCallOn((cmd, course) => course.AddCourseType(cmd.Type)) .RegisterWith(commandService); Map.Command<RemoveCourseTypeFromCourseCommand>() .ToAggregateRoot<Course>() .WithId(cmd => cmd.CourseId) .ToCallOn((cmd, course) => course.RemoveCourseType(cmd.Type)) .RegisterWith(commandService); Map.Command<ChangeCourseCreditTypeCommand>() .ToAggregateRoot<Course>() .WithId(cmd => cmd.CourseId) .ToCallOn((cmd, course) => course.ChangeCreditType(cmd.Type)) .RegisterWith(commandService); Map.Command<ChangeCourseCEUsCommand>() .ToAggregateRoot<Course>() .WithId(cmd => cmd.CourseId) .ToCallOn((cmd, course) => course.ChangeCEUs(cmd.CEUs)) .RegisterWith(commandService); Map.Command<ChangeCourseTopicCodeCommand>() .ToAggregateRoot<Course>() .WithId(cmd => cmd.CourseId) .ToCallOn((cmd, course) => { var uow = UnitOfWorkContext.Current; var topicCode = (TopicCode) uow.GetById(typeof (TopicCode), cmd.TopicCodeId, null); course.ChangeTopicCode(topicCode); }) .RegisterWith(commandService); }
public CommandsController(IOptions <Settings> settings) { this.commandService = new CommandService(settings); }
public StoopidTimeTypeReader(DiscordSocketClient client, CommandService cmds) : base(client, cmds) { }
public GuildAccountService(LiteDBHandler storage, CommandService commands) { _storage = storage; _commands = commands; }
public HelpCommands() { _commandService = MainProgram.commands; _embed = new EmbedBuilder(); }
public CommandHandler(DiscordSocketClient client, CommandService commands) { this._client = client; this.Commands = commands; }
public HelpCommands(CommandService commandService) { this._commandService = commandService; }
public DiscordVoiceChatObserver(CommandService commandService, IServiceProvider moduleServiceProvider) : base(commandService, moduleServiceProvider) { }
/// <summary> /// Initializes a new instance of the <see cref="EventHandler"/> class. /// </summary> /// <param name="client"> /// The client. /// </param> /// <param name="config"> /// The config. /// </param> /// <param name="service"> /// The service. /// </param> /// <param name="commandService"> /// The command service. /// </param> public EventHandler(DiscordShardedClient client, ConfigModel config, IServiceProvider service, CommandService commandService) { Client = client; Config = config; Provider = service; CommandService = commandService; CancellationToken = new CancellationTokenSource(); }
public async Task RunAsync() { // check for invalid run state if (_Client != null) { if (_Client.ConnectionState == ConnectionState.Connecting || _Client.ConnectionState == ConnectionState.Connected) { return; } } // increment the runcounter Utils.RunCountNew(); // set the empty variables, override the preset variables _Client = new DiscordSocketClient(_ClientConfig); _Commands = new CommandService(); _Services = InstallServices(); _RetryConnection = true; _Running = false; // while for client connection while (true) { try { // re read the config to be sure its correct Config.Read(); // client connection await _Client.LoginAsync(TokenType.Bot, _Config.BotToken); // client startup await _Client.StartAsync(); // command init await InstallCommands(); // set running state to true _Running = true; break; } catch { // f****d up something before this point (probably the config, dickhead. Make sure there is a ',' after each line) await Log(new LogMessage(LogSeverity.Error, "RunAsync", "Failed to connect.")); if (_RetryConnection == false) { return; } // making sure the client retries to connect and doesnt escape the while await Task.Delay(_RetryInterval); } } // while for breaking the connection in case it disconnects while (_Running) { await Task.Delay(_RunningInterval); } if (_Client.ConnectionState == ConnectionState.Connecting || _Client.ConnectionState == ConnectionState.Connected) { try { _Client.StopAsync().Wait(); } catch { } } }
public CommandsController(CommandService commandService) { _commandService = commandService; }
public Discord_bot(IServiceProvider services, CommandService command) { _services = services; _commands = command; }
public Help(CommandService service) { _service = service; }
public DiscordConnectionObserver(CommandService commandService, IServiceProvider moduleServiceProvider) : base(commandService, moduleServiceProvider) { }
public Services(CommandService commands = null, DiscordSocketClient client = null, String logLevel = null) { _commands = commands ?? new CommandService(); _client = client ?? new DiscordSocketClient(); _logLevel = logLevel; }
public async Task RunBot() { _Client = new DiscordSocketClient(new DiscordSocketConfig { WebSocketProvider = WS4NetProvider.Instance, MessageCacheSize = 10, AlwaysDownloadUsers = true }); _Commands = new CommandService(new CommandServiceConfig { CaseSensitiveCommands = false }); await InstallCommands(); _Bot.FavoriteColor = new Discord.Color(Settings.FavColor.R, Settings.FavColor.G, Settings.FavColor.B); int GuildCount = 0; _Client.GuildUnavailable += (g) => { _GUI.RemoveGuild(g); if (_Client.ConnectionState != ConnectionState.Disconnecting) { _Log.Warning($"Guild {g.Name} is unavailable"); NotifyIcon.ShowBalloonTip(30, "Warning!", "G: {g.Name} is unavailable", ToolTipIcon.Warning); } return(Task.CompletedTask); }; _Client.GuildAvailable += (g) => { GuildCount++; if (_GUI.Form != null) { _GUI.AddGuild(g); } if (_Bot.Ready == false & GuildCount == _Client.Guilds.Count) { _Bot.Ready = true; if (Settings.Startup == "Hide All") { NotifyIcon.ShowBalloonTip(30, "Connected", "Selfbot is ONLINE!", ToolTipIcon.Info); } string Message = ""; switch (_Client.CurrentUser.Id) { case 190590364871032834: Message = "Hi master Builderb"; break; case 213621714909659136: Message = "Bubbie's butt is bubbly"; break; case 155490847494897664: Message = "Julia + Novus <3"; break; case 107827535479353344: Message = "Julia + Novus <3"; break; case 213627387206828032: Message = "Towergay confirmed"; break; case 149928344811601920: Message = "Builderb pats Chat the neko"; break; case 267007263359631380: Message = "Thanks for testing"; break; case 190376235128455168: Message = "Get back in the salt mines!"; break; case 217215496267890689: Message = "Far Far Aw.. Aiir"; break; case 160168328520794112: Message = "Hazed you noob"; break; case 257815520680738816: Message = "Keith... Lemon!"; break; default: Message = $"Hi {_Client.CurrentUser.Username}"; break; } TimeSpan Startup = DateTime.Now - _Bot.StartupTime; _Log.Custom($"{Message} | Selfbot ready {_Client.Guilds.Count()} guilds | Loaded fully in {Startup.Seconds} Seconds", ConsoleColor.Green); } return(Task.CompletedTask); }; _Client.MessageReceived += (m) => { if (_GUI.Form != null) { if (m.Author.Id == _Client.CurrentUser.Id) { _GUI.Form.Embed_SendActive.Enabled = true; if (m.Channel is IPrivateChannel) { _GUI.Form.SetActive("DM", 1, m.Channel.Name, m.Channel.Id); _GUI.Form.Embed_SendActive.Text = "Active DM"; } else { var GU = m.Author as IGuildUser; if (GU.GetPermissions(m.Channel as ITextChannel).EmbedLinks == true) { _GUI.Form.SetActive(GU.Guild.Name, GU.Guild.Id, m.Channel.Name, m.Channel.Id); _GUI.Form.Embed_SendActive.Text = "Active"; } else { _GUI.Form.SetActive(GU.Guild.Name, 2, m.Channel.Name, m.Channel.Id); _GUI.Form.Embed_SendActive.Text = "No Perms"; } } } } return(Task.CompletedTask); }; _Client.JoinedGuild += (g) => { if (g.Owner == null) { _Log.Guild($"Joined > {g.Name} ({g.Id}) - Unknown Owner???"); } else { _Log.Guild($"Joined > {g.Name} ({g.Id}) - Owner {g.Owner.Username}"); } if (_GUI.Form != null) { _GUI.AddGuild(g); } return(Task.CompletedTask); }; _Client.LeftGuild += (g) => { if (g.Owner == null) { _Log.Guild($"Left > {g.Name} ({g.Id}) - Unknown Owner???"); } else { _Log.Guild($"Left > {g.Name} ({g.Id}) - Owner {g.Owner.Username}"); } if (_GUI.Form != null) { _GUI.RemoveGuild(g); } return(Task.CompletedTask); }; _Client.Connected += () => { Console.Title = "Discore Selfbot - Online!"; if (_Bot.Ready == true) { _Log.Selfbot("CONNECTED!"); } else { _Log.Selfbot("CONNECTED! - Loading guilds please wait"); UptimeTimer.Interval = 60000; UptimeTimer.Elapsed += UptimeTick; UptimeTimer.Start(); using (Stream ImageStream = AvatarIconDownload.OpenRead(_Client.CurrentUser.GetAvatarUrl())) { Bitmap b = (Bitmap)System.Drawing.Image.FromStream(ImageStream); IntPtr pIcon = b.GetHicon(); Icon i = Icon.FromHandle(pIcon); _GUI.Avatar = i; if (_GUI.Form != null) { if (Settings.Startup == "Show GUI And Console") { _GUI.Form.Text = _Client.CurrentUser.Username; _GUI.Form.Icon = i; _GUI.Form.Guilds_Loading.Maximum = _Client.Guilds.Count; } } } } return(Task.CompletedTask); }; _Client.Disconnected += (e) => { if (_GUI.Form != null) { _GUI.Form.Guilds_Bar.Items.Clear(); _GUI.GuildIDCache.Clear(); } Console.Title = "Discore Selfbot - Offline!"; _Log.Warning("DISCONNECTED!"); return(Task.CompletedTask); }; try { await _Client.LoginAsync(TokenType.User, _Bot.Token); await _Client.StartAsync(); if (Program.Settings.Startup == "Show GUI And Console") { _GUI.Open(); } } catch (Exception ex) { if (Settings.Startup == "Hide All") { NotifyIcon.ShowBalloonTip(30, "Error!", "Selfbot could not connect", ToolTipIcon.Error); var handle = GetConsoleWindow(); ShowWindow(handle, SW_SHOW); } if (ex.Message.Contains("401")) { _Log.Error("Invalid Token"); } else { _Log.Error(ex.Message); } } await Task.Delay(-1); }
public Other(CommandService commands, LogService logService) { _cmdService ??= commands; _logService ??= logService; }
public Help(CommandService commandService) { _cmdService = commandService; }
// Parameters injected automatically by IServiceProvider public CommandHandler(IConfigurationRoot config, DiscordSocketClient discordClient, CommandService cmdService, IServiceProvider serviceProvider) { _config = config; _discordClient = discordClient; _cmdService = cmdService; _serviceProvider = serviceProvider; _discordClient.MessageReceived += HandleCommandAsync; }
private static ICommandService CreateCommandService() { var service = new CommandService(); return service; }
private static void Main() { Console.OutputEncoding = Encoding.Unicode; try { File.WriteAllText("data/config_example.json", JsonConvert.SerializeObject(new Configuration(), Formatting.Indented)); if (!File.Exists("data/config.json")) { File.Copy("data/config_example.json", "data/config.json"); } File.WriteAllText("credentials_example.json", JsonConvert.SerializeObject(new Credentials(), Formatting.Indented)); } catch { Console.WriteLine("Failed writing credentials_example.json or data/config_example.json"); } try { Config = JsonConvert.DeserializeObject <Configuration>(File.ReadAllText("data/config.json")); Config.Quotes = JsonConvert.DeserializeObject <List <Quote> >(File.ReadAllText("data/quotes.json")); Config.PokemonTypes = JsonConvert.DeserializeObject <List <PokemonType> >(File.ReadAllText("data/PokemonTypes.json")); } catch (Exception ex) { Console.WriteLine("Failed loading configuration."); Console.WriteLine(ex); Console.ReadKey(); return; } try { //load credentials from credentials.json Creds = JsonConvert.DeserializeObject <Credentials>(File.ReadAllText("credentials.json")); } catch (Exception ex) { Console.WriteLine($"Failed to load stuff from credentials.json, RTFM\n{ex.Message}"); Console.ReadKey(); return; } //if password is not entered, prompt for password if (string.IsNullOrWhiteSpace(Creds.Token)) { Console.WriteLine("Token blank. Please enter your bot's token:\n"); Creds.Token = Console.ReadLine(); } Console.WriteLine(string.IsNullOrWhiteSpace(Creds.GoogleAPIKey) ? "No google api key found. You will not be able to use music and links won't be shortened." : "Google API key provided."); Console.WriteLine(string.IsNullOrWhiteSpace(Creds.TrelloAppKey) ? "No trello appkey found. You will not be able to use trello commands." : "Trello app key provided."); Console.WriteLine(Config.ForwardMessages != true ? "Not forwarding messages." : "Forwarding private messages to owner."); Console.WriteLine(string.IsNullOrWhiteSpace(Creds.SoundCloudClientID) ? "No soundcloud Client ID found. Soundcloud streaming is disabled." : "SoundCloud streaming enabled."); Console.WriteLine(string.IsNullOrWhiteSpace(Creds.OsuAPIKey) ? "No osu! api key found. Song & top score lookups will not work. User lookups still available." : "osu! API key provided."); BotMention = $"<@{Creds.BotId}>"; //create new discord client and log Client = new DiscordClient(new DiscordConfigBuilder() { MessageCacheSize = 10, ConnectionTimeout = int.MaxValue, LogLevel = LogSeverity.Warning, LogHandler = (s, e) => Console.WriteLine($"Severity: {e.Severity}" + $"ExceptionMessage: {e.Exception?.Message ?? "-"}" + $"Message: {e.Message}"), }); //create a command service var commandService = new CommandService(new CommandServiceConfigBuilder { AllowMentionPrefix = false, CustomPrefixHandler = m => 0, HelpMode = HelpMode.Disabled, ErrorHandler = async(s, e) => { if (e.ErrorType != CommandErrorType.BadPermissions) { return; } if (string.IsNullOrWhiteSpace(e.Exception?.Message)) { return; } try { await e.Channel.SendMessage(e.Exception.Message).ConfigureAwait(false); } catch { } } }); //add command service Client.AddService <CommandService>(commandService); //create module service var modules = Client.AddService <ModuleService>(new ModuleService()); //add audio service Client.AddService <AudioService>(new AudioService(new AudioServiceConfigBuilder() { Channels = 2, EnableEncryption = false, Bitrate = 128, })); //install modules modules.Add(new HelpModule(), "Help", ModuleFilter.None); modules.Add(new AdministrationModule(), "Administration", ModuleFilter.None); modules.Add(new UtilityModule(), "Utility", ModuleFilter.None); modules.Add(new PermissionModule(), "Permissions", ModuleFilter.None); modules.Add(new Conversations(), "Conversations", ModuleFilter.None); modules.Add(new GamblingModule(), "Gambling", ModuleFilter.None); modules.Add(new GamesModule(), "Games", ModuleFilter.None); #if !NADEKO_RELEASE modules.Add(new MusicModule(), "Music", ModuleFilter.None); #endif modules.Add(new SearchesModule(), "Searches", ModuleFilter.None); modules.Add(new NSFWModule(), "NSFW", ModuleFilter.None); modules.Add(new ClashOfClansModule(), "ClashOfClans", ModuleFilter.None); modules.Add(new PokemonModule(), "Pokegame", ModuleFilter.None); modules.Add(new TranslatorModule(), "Translator", ModuleFilter.None); modules.Add(new CustomReactionsModule(), "Customreactions", ModuleFilter.None); if (!string.IsNullOrWhiteSpace(Creds.TrelloAppKey)) { modules.Add(new TrelloModule(), "Trello", ModuleFilter.None); } //run the bot Client.ExecuteAndWait(async() => { await Task.Run(() => { Console.WriteLine("Specific config started initializing."); var x = SpecificConfigurations.Default; Console.WriteLine("Specific config done initializing."); }); PermissionsHandler.Initialize(); try { await Client.Connect(Creds.Token, TokenType.Bot).ConfigureAwait(false); } catch (Exception ex) { Console.WriteLine($"Token is wrong. Don't set a token if you don't have an official BOT account."); Console.WriteLine(ex); Console.ReadKey(); return; } #if NADEKO_RELEASE await Task.Delay(220000).ConfigureAwait(false); #else await Task.Delay(1000).ConfigureAwait(false); #endif Console.WriteLine("-----------------"); Console.WriteLine(await NadekoStats.Instance.GetStats().ConfigureAwait(false)); Console.WriteLine("-----------------"); OwnerPrivateChannels = new List <Channel>(Creds.OwnerIds.Length); foreach (var id in Creds.OwnerIds) { try { OwnerPrivateChannels.Add(await Client.CreatePrivateChannel(id).ConfigureAwait(false)); } catch { Console.WriteLine($"Failed creating private channel with the owner {id} listed in credentials.json"); } } Client.ClientAPI.SendingRequest += (s, e) => { var request = e.Request as Discord.API.Client.Rest.SendMessageRequest; if (request == null) { return; } // meew0 is magic request.Content = request.Content?.Replace("@everyone", "@everyοne").Replace("@here", "@һere") ?? "_error_"; if (string.IsNullOrWhiteSpace(request.Content)) { e.Cancel = true; } }; #if NADEKO_RELEASE Client.ClientAPI.SentRequest += (s, e) => { Console.WriteLine($"[Request of type {e.Request.GetType()} sent in {e.Milliseconds}]"); var request = e.Request as Discord.API.Client.Rest.SendMessageRequest; if (request == null) { return; } Console.WriteLine($"[Content: { request.Content }"); }; #endif NadekoBot.Ready = true; NadekoBot.OnReady(); Console.WriteLine("Ready!"); //reply to personal messages and forward if enabled. Client.MessageReceived += Client_MessageReceived; }); Console.WriteLine("Exiting..."); Console.ReadKey(); }
public async Task Messages(SocketMessage arg, DiscordSocketClient _Client, CommandService _Service, string BotCommandPrefix) { SocketUserMessage Msg = arg as SocketUserMessage; int ArgPos = 0; try { if (Msg.Content == "" || Msg.Author.IsBot) { return; } else { Console.WriteLine("[" + Msg.Timestamp.ToLocalTime().ToString().Substring(11, 8) + "] - [" + Msg.Channel + "] - [" + Msg.Author + "] - " + Msg.Content); } } catch (Exception) { return; } if (Msg.HasStringPrefix(BotCommandPrefix, ref ArgPos)) { var Context = new SocketCommandContext(_Client, Msg); var result = await _Service.ExecuteAsync(Context, ArgPos, null); if (!result.IsSuccess) { EmbedBuilder embedBuilder = new EmbedBuilder() .WithTitle(result.ErrorReason) .WithColor(Color.DarkRed); await Context.Channel.SendMessageAsync("", false, embedBuilder.Build()); } } else { if (!Directory.Exists("./Accounts")) { Directory.CreateDirectory("./Accounts"); } if (!Directory.Exists("./Logs")) { Directory.CreateDirectory("./Logs"); } if (!File.Exists("./Accounts/" + arg.Author.Id)) { File.WriteAllText("./Accounts/" + arg.Author.Id, "<Username>" + arg.Author + "</>\n" + "<MuteState>" + "false" + "</>\n"); } string Date = DateTime.UtcNow.ToLocalTime().ToString().Substring(0, 10).Replace("/", "-"); if (!File.Exists("./Logs/MsgLogs " + Date)) { var MsgLogs = File.Create("./Logs/MsgLogs " + Date); MsgLogs.Close(); } string ActualContent = File.ReadAllText("./Logs/MsgLogs " + Date); string NewContent = ActualContent + "\n[" + arg.Timestamp + "][" + arg.Author.Id + "][" + arg.Author + "][" + arg.Channel + "]" + arg.Content + "[]"; byte[] Encode = UnicodeEncoding.Unicode.GetBytes(NewContent); NewContent = UnicodeEncoding.Unicode.GetString(Encode); File.WriteAllText("./Logs/MsgLogs " + Date, NewContent); string AccountDatas = File.ReadAllText("./Accounts/" + arg.Author.Id); bool MuteState = bool.Parse(new ParserTool().Parse(AccountDatas, "<MuteState>", "</>")); if (MuteState) { await arg.DeleteAsync(); } } }
public CommandHandler(DiscordSocketClient client, IServiceProvider services) { _commands = new CommandService(); _client = client; _services = services; }
public GamblingModule(DiscordSocketClient client, CommandService service) { _client = client; _service = service; }
public HelpModule(CommandService commandService) { _commandService = commandService; }
public TagModule(DiscordShardedClient client, CommandService service) { _service = service; _client = client; }
// Retrieve client and CommandService instance via ctor public CommandHandler(DiscordSocketClient client, CommandService commands) { _commands = commands; _client = client; }
// This is a special type of module that doesn't need a service, since we link // it directly here. This adds the help functionality and the logic simply checks // for current tags and displays them if available. This requires that you have // both name and summary tags for each module and it's commmands that you want // to display here. public HelpModule(CommandService commands, IServiceProvider provider) { _commands = commands; _provider = provider; }