public async Task AddTwoTournamentDirectors() { const ulong firstUserId = 123; const ulong secondUserId = 1234; MessageStore messageStore = new MessageStore(); ICommandContext context = this.CreateCommandContext(messageStore); GlobalTournamentsManager globalManager = new GlobalTournamentsManager(); AddTournamentDirectorDirectly(globalManager, firstUserId); BotCommandHandler commandHandler = new BotCommandHandler(context, globalManager); IGuildUser guildUser = this.CreateGuildUser(secondUserId); await commandHandler.AddTournamentDirectorAsync(guildUser, DefaultTournamentName); string expectedMessage = BotStrings.AddTournamentDirectorSuccessful( DefaultTournamentName, DefaultGuildName); messageStore.VerifyChannelMessages(expectedMessage); TournamentsManager manager = globalManager.GetOrAdd(DefaultGuildId, id => new TournamentsManager()); Assert.IsTrue( manager.TryGetTournament(DefaultTournamentName, out ITournamentState state), "Could not find tournament."); Assert.IsTrue(state.IsDirector(firstUserId), "First director was not added."); Assert.IsTrue(state.IsDirector(secondUserId), "Second director was not added."); }
public async Task ScheduleRequiresMultipleEmbeds() { const int teamsCount = 50; const int readersCount = teamsCount / 2; MessageStore messageStore = new MessageStore(); ICommandContext context = this.CreateCommandContext(messageStore, guildId: DefaultGuildId); GlobalTournamentsManager globalManager = new GlobalTournamentsManager(); TournamentsManager manager = globalManager.GetOrAdd(DefaultGuildId, id => new TournamentsManager()); HashSet <Team> teams = new HashSet <Team>( Enumerable.Range(1, teamsCount).Select(id => new Team() { Name = $"#Team{id}" })); HashSet <Reader> readers = new HashSet <Reader>( Enumerable.Range(1, readersCount).Select(id => new Reader() { Id = (ulong)id, Name = $"#Reader{id}" })); RoundRobinScheduleFactory factory = new RoundRobinScheduleFactory(1, 0); Schedule schedule = factory.Generate(teams, readers); ITournamentState state = new TournamentState(DefaultGuildId, "T"); state.Schedule = schedule; manager.AddOrUpdateTournament(state.Name, state, (name, oldState) => oldState); Assert.IsTrue( manager.TrySetCurrentTournament(state.Name, out string errorMessage), $"Failed to set the tournament: '{errorMessage}'"); globalManager.GetOrAdd(DefaultGuildId, id => manager); BotCommandHandler commandHandler = new BotCommandHandler(context, globalManager); await commandHandler.GetScheduleAsync(); Assert.IsTrue( messageStore.ChannelEmbeds.Count > 1, $"Expected more than 1 embed, got {messageStore.ChannelEmbeds.Count}"); string allEmbeds = string.Join('\n', messageStore.ChannelEmbeds); for (int round = 0; round < schedule.Rounds.Count; round++) { Assert.IsTrue( allEmbeds.Contains(BotStrings.RoundNumber(round + 1)), $"Round {round + 1} not found in the embeds. Embeds: '{allEmbeds}'"); foreach (Game game in schedule.Rounds[round].Games) { string expectedGame = BotStrings.ScheduleLine( game.Reader.Name, game.Teams.Select(team => team.Name).ToArray()); Assert.IsTrue( allEmbeds.Contains(expectedGame), $"Game '{expectedGame}' not foudn in embed. Embed: '{allEmbeds}'"); } } }
public CommandData(PluginHandle target, BotCommandHandler commandHandler, CommandDataAttributes attributes) { Target = target; Commands = attributes.CommandAttribute.Commands; CommandHandler = commandHandler; Attribute = attributes.CommandAttribute; Help = attributes.HelpAttribute; if (attributes.RoleAttribute != null) DefaultRole = attributes.RoleAttribute.Role.ToString(); }
public Bot(IActionScheduler actionScheduler, IAnswerSearchEngine answerSearchEngine, IConnectedClients clients, IBotClient botDataClient, IBotSettings settings) { Settings = settings; ActionScheduler = actionScheduler; AnswerSearchEngine = answerSearchEngine; BotDataClient = botDataClient; AnswerSearchEngine.SetApiKey(Settings.AnswerSearchApiKey); ConnectedClients = clients.ChatClients; CommandHandler = new BotCommandHandler(this); _ = ScheduleRepeatedMessages(); }
public async Task NoCurrentTournament() { MessageStore messageStore = new MessageStore(); ICommandContext context = this.CreateCommandContext(messageStore); GlobalTournamentsManager globalManager = new GlobalTournamentsManager(); BotCommandHandler commandHandler = new BotCommandHandler(context, globalManager); await commandHandler.GetCurrentTournamentAsync(); string expectedMessage = BotStrings.UnableToPerformCommand(TournamentStrings.NoCurrentTournamentRunning); messageStore.VerifyDirectMessages(expectedMessage); }
private IServiceProvider ConfigureServices() { //setup and add command service. cHandler = new BotCommandHandler(); cProcessor = new BotCommandProcessor(); var services = new ServiceCollection() .AddSingleton(Client) .AddSingleton(BotConfig) .AddSingleton(cHandler); var provider = new DefaultServiceProviderFactory().CreateServiceProvider(services); return(provider); }
public async Task RemoveFromNonexistentTournament() { const ulong otherId = DefaultUserId + 1; MessageStore messageStore = new MessageStore(); ICommandContext context = this.CreateCommandContext(messageStore); GlobalTournamentsManager globalManager = new GlobalTournamentsManager(); BotCommandHandler commandHandler = new BotCommandHandler(context, globalManager); IGuildUser guildUser = this.CreateGuildUser(otherId); await commandHandler.RemoveTournamentDirectorAsync(guildUser, DefaultTournamentName); string expectedMessage = BotStrings.TournamentDoesNotExist(DefaultTournamentName, DefaultGuildName); messageStore.VerifyChannelMessages(expectedMessage); }
public async Task GetCurrentTournament() { MessageStore messageStore = new MessageStore(); ICommandContext context = this.CreateCommandContext(messageStore); GlobalTournamentsManager globalManager = new GlobalTournamentsManager(); this.AddCurrentTournament(globalManager); BotCommandHandler commandHandler = new BotCommandHandler(context, globalManager); await commandHandler.GetCurrentTournamentAsync(); string expectedMessage = BotStrings.CurrentTournamentInGuild(DefaultGuildName, DefaultTournamentName); messageStore.VerifyDirectMessages(expectedMessage); }
private static void CreateHandler( HashSet <ulong> existingUserIds, ulong channelId, ulong userId, out BotCommandHandler handler, out GameState currentGame, out MessageStore messageStore) { GameStateManager manager = new GameStateManager(); manager.TryCreate(DefaultChannelId, out currentGame); messageStore = new MessageStore(); ICommandContext commandContext = CreateCommandContext( messageStore, existingUserIds, channelId, userId); handler = new BotCommandHandler(commandContext, manager, currentGame, Mock.Of <ILogger>()); }
public async Task ClearAllRemovesGame() { GameStateManager manager = new GameStateManager(); manager.TryCreate(DefaultChannelId, out GameState currentGame); MessageStore messageStore = new MessageStore(); ICommandContext commandContext = CreateCommandContext( messageStore, DefaultIds, DefaultChannelId, DefaultReaderId); BotCommandHandler handler = new BotCommandHandler(commandContext, manager, currentGame, Mock.Of <ILogger>()); await handler.ClearAll(); Assert.IsFalse( manager.TryGet(DefaultChannelId, out GameState game), "Game should have been removed from the manager."); Assert.AreEqual(1, messageStore.ChannelMessages.Count, "Unexpected number of messages sent."); }
private async Task OnDisconnected(Exception arg) { try { await cHandler.RemoveCommandService(); cHandler = null; cProcessor = null; } catch (Exception ex) { ErrorLog.WriteError(ex); Console.WriteLine(ex.Message); } Console.WriteLine("Disconnected"); Console.WriteLine(arg.Message); Ready = false; }
public async Task RemoveNonexistentTournamentDirector() { const ulong otherId = DefaultUserId + 1; MessageStore messageStore = new MessageStore(); ICommandContext context = this.CreateCommandContext(messageStore); GlobalTournamentsManager globalManager = new GlobalTournamentsManager(); BotCommandHandler commandHandler = new BotCommandHandler(context, globalManager); AddTournamentDirectorDirectly(globalManager, DefaultUserId); IGuildUser guildUser = this.CreateGuildUser(otherId); await commandHandler.RemoveTournamentDirectorAsync(guildUser, DefaultTournamentName); string expectedMessage = BotStrings.UserNotTournamentDirector(DefaultTournamentName, DefaultGuildName); messageStore.VerifyChannelMessages(expectedMessage); TournamentsManager manager = globalManager.GetOrAdd(DefaultGuildId, id => new TournamentsManager()); Assert.IsTrue( manager.TryGetTournament(DefaultTournamentName, out ITournamentState state), "Could not find tournament."); Assert.IsFalse(state.IsDirector(otherId), "Director should not have been added."); }
public async Task AddSameTournamentDirectors() { MessageStore messageStore = new MessageStore(); ICommandContext context = this.CreateCommandContext(messageStore); GlobalTournamentsManager globalManager = new GlobalTournamentsManager(); AddTournamentDirectorDirectly(globalManager, DefaultUserId); BotCommandHandler commandHandler = new BotCommandHandler(context, globalManager); IGuildUser guildUser = this.CreateGuildUser(DefaultUserId); await commandHandler.AddTournamentDirectorAsync(guildUser, DefaultTournamentName); string expectedMessage = BotStrings.UserAlreadyTournamentDirector(DefaultTournamentName, DefaultGuildName); messageStore.VerifyChannelMessages(expectedMessage); TournamentsManager manager = globalManager.GetOrAdd(DefaultGuildId, id => new TournamentsManager()); Assert.IsTrue( manager.TryGetTournament(DefaultTournamentName, out ITournamentState state), "Could not find tournament."); Assert.IsTrue(state.IsDirector(DefaultUserId), "User should still be a director."); }
/// <summary> /// Gets the a plugin handle for the handler. /// </summary> /// <param name="method">The method.</param> /// <returns>Plugin handle.</returns> public static PluginHandle Get(BotCommandHandler method) { return HandleCache.GetValueOrAdd(method.Target.GetType(), () => new PluginHandle(method)); }
public override bool ShouldProcess(MessageEntityEx data, PollMessage context) { return(BotCommandHandler.ShouldProcess(this, data, context)); }
/// <summary> /// BOT Model /// </summary> /// <param name="accessToken">True if user exists</param> /// <param name="userName">User name</param> /// <param name="email">Email id</param> /// <param name="userData">User specific data</param> /// <param name="manager">Manager for handling data</param> /// <param name="cloudmanager">Manager to access cloud resources</param> public BotModel(string accessToken, string userName, BotData userData, string email, BotCommandHandler commandHandler, DataManager manager) { this.UserName = userName; this.AccessToken = accessToken; this.UserData = userData; this.DataFactory = manager; this.Email = email; this.CommandHandler = commandHandler; }
/// <summary> /// POST: api/Messages /// Receive a message from a user and reply to it /// </summary> public async Task <HttpResponseMessage> Post([FromBody] Activity activity) { try { if (activity.Type == ActivityTypes.Message) { string result = string.Empty; ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl)); Activity replyMessage = activity.CreateReply("Expensify is typing..."); replyMessage.Type = ActivityTypes.Typing; await this.SendTypingResponse(connector, replyMessage); try { var handler = new BotCommandHandler(); var utilities = new BotUtil(activity, handler); if (utilities.State > 2) { result = await handler.GetReply(activity, utilities.UserName, utilities.ClientState, utilities.State); } if (string.IsNullOrEmpty(result)) { result = await utilities.GetReply(this.DatabaseFactory); } } catch (SerializationException ex) { this.TrackTelemetry(ex); if (ex.InnerException != null) { result = $"{ex.GetType().Name} : {ex.Message}"; } } catch (Exception ex) { this.TrackTelemetry(ex); if (ex.InnerException != null) { result = $"{ex.GetType().Name} : {ex.Message}"; } //result = "Thanks. :)"; //result = "Sorry, we have faced an issue. Can you please reframe the sentence and ask me again."; } if (!string.IsNullOrEmpty(result)) { replyMessage.Type = ActivityTypes.Message; replyMessage.Text = result; await connector.Conversations.ReplyToActivityAsync(replyMessage); } } else { await this.HandleSystemMessage(activity); } } catch { } var response = Request.CreateResponse(HttpStatusCode.OK); return(response); }
/// <summary> /// Executes a explicit bot command /// </summary> /// <param name="message"></param> /// <param name="parser"></param> /// <returns></returns> private async Task DoCommand(IChatMessage message, MessageParser parser) { var executor = new BotCommandHandler(this, message, parser); await executor.Execute(); }
/// <summary> /// Prevents a default instance of the <see cref="PluginHandle"/> class from being created. /// </summary> /// <param name="method">The method.</param> private PluginHandle(BotCommandHandler method) { Initialize(method); }
public async Task SimplestSchedule() { const string readerName = "#Reader"; const string firstTeamName = "#TeamA"; const string secondTeamName = "#TeamB"; MessageStore messageStore = new MessageStore(); ICommandContext context = this.CreateCommandContext(messageStore, guildId: DefaultGuildId); GlobalTournamentsManager globalManager = new GlobalTournamentsManager(); TournamentsManager manager = globalManager.GetOrAdd(DefaultGuildId, id => new TournamentsManager()); HashSet <Team> teams = new HashSet <Team>() { new Team() { Name = firstTeamName }, new Team() { Name = secondTeamName } }; HashSet <Reader> readers = new HashSet <Reader>() { new Reader() { Id = 0, Name = readerName } }; RoundRobinScheduleFactory factory = new RoundRobinScheduleFactory(2, 0); Schedule schedule = factory.Generate(teams, readers); ITournamentState state = new TournamentState(DefaultGuildId, "T"); state.Schedule = schedule; manager.AddOrUpdateTournament(state.Name, state, (name, oldState) => oldState); Assert.IsTrue( manager.TrySetCurrentTournament(state.Name, out string errorMessage), $"Failed to set the tournament: '{errorMessage}'"); globalManager.GetOrAdd(DefaultGuildId, id => manager); BotCommandHandler commandHandler = new BotCommandHandler(context, globalManager); await commandHandler.GetScheduleAsync(); Assert.AreEqual(1, messageStore.ChannelEmbeds.Count, "Unexpected number of embeds"); string embed = messageStore.ChannelEmbeds[0]; for (int round = 0; round < schedule.Rounds.Count; round++) { Assert.IsTrue( embed.Contains(BotStrings.RoundNumber(round + 1)), $"Round {round + 1} not found in embed. Embed: '{embed}'"); string expectedGame = BotStrings.ScheduleLine( readerName, schedule.Rounds[round].Games[0].Teams.Select(team => team.Name).ToArray()); Assert.IsTrue( embed.Contains(expectedGame), $"Game '{expectedGame}' not foudn in embed. Embed: '{embed}'"); } }