private void CreateStatsCommand(string arguments) { if (string.IsNullOrEmpty(arguments)) { _command = new StatsCommand(); this.State = ParserState.ReadyToDispatch; return; } string[] argumentsArray; argumentsArray = arguments.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); switch (argumentsArray[0]) { case "settings": case "items": case "sizes": case "slabs": _command = new StatsCommand(argumentsArray[0]); this.State = ParserState.ReadyToDispatch; break; default: CreateInvalidCommand(); break; } }
public async Task GetStatisticsPerPeriod(StatsCommand statsCommand, Contexts contexts) { var period = this._reportsService.SelectPeriod(statsCommand); if (this.implementedBySplitter.Contains(period)) { var query = new GetMessagesStatisticsQuery(period); var result = await this._queryBus.ExecuteAsync(query); var periodStats = result.PeriodStatistics.Where(x => x.Count > 0); return; } var getMessages = new GetMessagesQuery(contexts.Server.Id); var messages = this._queryBus.Execute(getMessages).Messages.ToList(); var report = this._reportsService.CreateReport(messages, period); Log.Information("Generated statistics for time range {start} {end}", report.TimeRange.Start, report.TimeRange.End); #if DEBUG PrintDebugStats(report); #endif var stream = await this._chartsService.GetImageStatisticsPerPeriod(report); var messagesService = this._messagesServiceFactory.Create(contexts); await messagesService.SendFile("Statistics.png", stream); }
private Task <(Stream Chart, ResultMessage Message)> GetStatisticsPerMinute(StatsCommand command, Contexts contexts) { var time = this._configurationService.GetConfigurationItem <TimeBehindStatisticsPerMinute>(contexts.Server.Id).Value; var request = new StatisticsRequest(contexts.Server.Id, time, command.User, command.Channel); return(this._periodStatisticsService.PerMinute(request)); }
public StatsCommandTest() { _command = new StatsCommand(); _originalWriter = Console.Out; try { _storeFixtures = ImmutableArray.Create <StoreFixture>( new DefaultStoreFixture(false), new RocksDBStoreFixture(), new MonoRocksDBStoreFixture() ); } catch (TypeInitializationException) { throw new SkipException("RocksDB is not available."); } foreach (var storeFixture in _storeFixtures) { var guid = Guid.NewGuid(); storeFixture.Store.SetCanonicalChainId(guid); storeFixture.Store.PutBlock(storeFixture.Block1); storeFixture.Store.AppendIndex(guid, storeFixture.Block1.Hash); storeFixture.Store.PutTransaction(storeFixture.Transaction1); } }
public void CreateStatsCommand() { string argument = null; if (_requestHeader.KeyLength > 0) { argument = MemcachedEncoding.BinaryConverter.GetString(_rawData, 0, _requestHeader.KeyLength); } _command = new StatsCommand(argument); }
public StatsCommand BuildFromString(long chatId, string text) { // /stats 11.02.2017 12.03.2017 // /stats // /stats сегодня // /stats вчера // /stats неделя // /stats месяц var tokens = text.Split(' '); if (tokens.Length == 2) { var modifier = tokens[1]; if (modifier.Equals("сегодня", StringComparison.OrdinalIgnoreCase)) { return(new StatsCommand(chatId, StatsType.Today)); } if (modifier.Equals("вчера", StringComparison.OrdinalIgnoreCase)) { return(new StatsCommand(chatId, StatsType.Yesterday)); } if (modifier.Equals("неделя", StringComparison.OrdinalIgnoreCase)) { return(new StatsCommand(chatId, StatsType.Week)); } if (modifier.Equals("месяц", StringComparison.OrdinalIgnoreCase)) { return(new StatsCommand(chatId, StatsType.Month)); } } if (tokens.Length > 2) { // /stats 11.02.2017 12.03.2017 if (!DateTime.TryParseExact(tokens[1], "dd.MM.yy", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out var from)) { throw new FormatException("Формат для даты: dd.mm.yy. Пример: 29.01.17"); } if (!DateTime.TryParseExact(tokens[2], "dd.MM.yy", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out var to)) { throw new FormatException("Формат для даты: dd.mm.yy. Пример: 29.01.17"); } var command = new StatsCommand(chatId, from, to); return(command); } return(new StatsCommand(chatId, StatsType.Today)); }
private Task <(Stream Chart, ResultMessage Message)> GetStatistics(StatsCommand command, Contexts contexts) { var task = command switch { _ when command.Minute => this.GetStatisticsPerMinute(command, contexts), _ when command.Hour => this.GetStatisticsPerHour(command, contexts), _ when command.Day => this.GetStatisticsPerDay(command, contexts), _ when command.Week => this.GetStatisticsPerWeek(command, contexts), _ when command.Month => this.GetStatisticsPerMonth(command, contexts), _ when command.Quarter => this.GetStatisticsPerQuarter(command, contexts), _ => this.GetStatisticsPerHour(command, contexts) }; return(task); }
public async Task Stats(StatsCommand command, Contexts contexts) { var(chart, message) = await this.GetStatistics(command, contexts); if (command.Direct) { await Task.Run(() => this._directMessagesService.TrySendFile(contexts.User.Id, "Statistics.png", chart)) .ContinueWith(x => this._directMessagesService.TrySendEmbedMessage(contexts.User.Id, message.Title, string.Empty, message.GetArguments())); } else { var messagesService = this._messagesServiceFactory.Create(contexts); await Task.Run(() => messagesService.SendFile("Statistics.png", chart)) .ContinueWith(x => messagesService.SendEmbedMessage(message.Title, string.Empty, message.GetArguments())); } }
public static byte[] BuildStatsResponse(StatsCommand command) { DataStream stream = new DataStream(); Hashtable stats = command.OperationResult.Value as Hashtable; IDictionaryEnumerator ie = stats.GetEnumerator(); string key = ""; byte [] value = null; while (ie.MoveNext()) { key = ie.Key as string; value = MemcachedEncoding.BinaryConverter.GetBytes(ie.Value as string); stream.Write(BuildResposne(command.Opcode, BinaryResponseStatus.no_error, command.Opaque, 0, key, value, null)); } stream.Write(BuildResposne(command.Opcode, BinaryResponseStatus.no_error, command.Opaque, 0, null, null, null)); return(stream.ReadAll()); }
public Period SelectPeriod(StatsCommand command) { if (command.Hour) { return(Period.Hour); } else if (command.Day) { return(Period.Day); } else if (command.Week) { return(Period.Week); } else if (command.Month) { return(Period.Month); } return(Period.Day); }
static int Execute(ConsoleCommand cmd) { ICommand command = new NullCommand(); switch (cmd.Name) { case null: return(0); case "exit": command = new ExitCommand(); break; case "find": command = new FindCommand(cmd); break; case "route": command = new RouteCommand(cmd); break; case "multiroute": command = new MultiRouteCommand(cmd); break; case "stats": command = new StatsCommand(); break; default: Console.WriteLine("Unrecognised command."); return(0); } return(command.Execute()); }
public async Task <string> GetStatsStringAsync(StatsCommand command, CancellationToken cancellationToken) { var sb = new StringBuilder(); var stats = (await _repository.GetStatsAsync(command, cancellationToken)); var period = command.GetStringTypeModifier(); if (stats.Count == 0) { return($@"{period} все молчали ¯\_(ツ)_/¯"); } sb.AppendLine($"Топ тунеядцев {period}"); var place = 1; foreach (var(userInfo, count) in stats.UserStats) { sb.AppendLine($"{place++}. {userInfo}: {count}"); } sb.AppendLine(); var othersCount = 0; foreach (var(messageType, count) in stats.ChatStats) { switch (messageType) { case MessageType.Text: sb.AppendLine($"Текстовых сообщений: {count}"); break; case MessageType.Photo: sb.AppendLine($"Фоток: {count}"); break; case MessageType.Audio: sb.AppendLine($"Аудио: {count}"); break; case MessageType.Video: sb.AppendLine($"Видео: {count}"); break; case MessageType.Voice: sb.AppendLine($"Голосовых сообщений: {count}"); break; case MessageType.Sticker: sb.AppendLine($"Стикеров: {count}"); break; case MessageType.Document: sb.AppendLine($"Гифки, документы: {count}"); break; case MessageType.Location: sb.AppendLine($"Локации: {count}"); break; case MessageType.ChatMembersAdded: if (count > 0) { sb.AppendLine($"Добавлено в чатик: {count}"); } break; case MessageType.ChatMemberLeft: sb.AppendLine($"Выпилились из чатика: {count} =("); break; default: othersCount += count; break; } } if (othersCount > 0) { sb.AppendLine($"Других: {othersCount}"); } if (command.Type == StatsType.Week) { sb.AppendLine(); sb.AppendLine("По дням"); foreach (var(date, count) in stats.WeekStats) { sb.AppendLine($"{date}: {count}"); } } return(sb.ToString()); }
public StatsController(StatsCommand statsCommand) { this.statsCommand = statsCommand; }
static void Main(string[] args) { string url = "irc.chat.twitch.tv"; int port = 80; string user = "******"; string oAuthToken = System.IO.File.ReadAllText(@"token.txt"); // token.txt must be in the same folder as EXE string channel = "lobosjr"; //Set up one IrcClient, only one is required it allows better cooldown managerment and traffic will //never cause this code to run slower then any twitch cool down for bots. TwitchClientFactory icf = new TwitchClientFactory(); ITwitchClient client = icf.create(url, port, user, oAuthToken, channel, 600, new OperationRequestEventRaiser(), new PrivMessageEventRaiser(), new WhisperMessageEventRaiser()); client.DefaultMessageHandler += (o, e) => { Console.WriteLine(string.Format("System: {0}", e.Raw)); }; //Set up Legacy Item -> IEquipment converter. LegacyItemEquipmentConverter liec = new LegacyItemEquipmentConverter(); //Set up Equipment repository, if legacy then this will load all items from old files and convert them //into IEquipment in memory. IEquipmentRepository equipmentRepository = LegacyEquipmentRepository .getInstance(liec, LegacyEquipmentRepository.LEGACY_ITEM_BRIDGE_FILE_PATH, LegacyEquipmentRepository.LEGACY_ITEM_PREFIX_FILE_PATH); //Set up Player Repository, Factory and default ILevelObservers ILevelObserver levelUpNotifier = new LevelupNotifier(client); PlayerFactory pf = new PlayerFactory(3, 20, levelUpNotifier); ILevelObserver classChoiceNotifier = new ClassChoiceNotifier(client, pf, 3); pf.GetCurrentDefaultObservers().Add(classChoiceNotifier); IPlayerRepository playerRepo = LegacyPlayerRepository.getInstance(3, 20, pf, equipmentRepository, LegacyPlayerRepository.LEGACY_USER_COINS_FILE_PATH, LegacyPlayerRepository.LEGACY_USER_XP_FILE_PATH, LegacyPlayerRepository.LEGACY_USER_CLASS_FILE_PATH, "players.json"); //Set up Adventure repository. IAdventureRepository adventureRepository = LegacyAdventureRepository .getInstance(LegacyAdventureRepository.LEGACY_DUNGEON_BRIDGE_FILE_PATH, LegacyAdventureRepository.LEGACY_DUNGEON_FILE_PATH_PREFIX, equipmentRepository); //Set up Adventure manager who's Run() func should be used to run adventures on a daemon thread IAdventureManager adventureManager = new AdventureManager(client, 3); new Thread(() => { Thread.CurrentThread.Name = "Adventure Manager"; Thread.CurrentThread.IsBackground = true; adventureManager.Run(); }).Start(); //Set up Party Pool, this keeps track of current parties. IPartyPool partyPool = new PartyPool(client); //Set up Group finder, use the current adventure managers queue. Decide party size capacity for // group finder. GroupFinderFactory gff = new GroupFinderFactory(); IGroupFinder groupFinder = gff.Create(partyPool, 3, adventureRepository, adventureManager); //Set up FutureTask Registry which will keep track of time based operations FutureTaskRegistry futureTaskRegistry = new FutureTaskRegistry(); //Set up Custom Command Factory and Repository for the Command Manager allowing //for saved custom commands to be used aswell as providing capability for new //custom commands to be created from chat(broadcaster/mod only). CustomCommandFactory ccf = new CustomCommandFactory(); CustomCommandRepository ccr = new CustomCommandRepository(); CommandManager commandManager = new CommandManager(client, ccf, ccr); //Initialise all commands to be added to the command manager, seperated by //the source of the request, either PRVMSG or WHISPER. #region Initialisation of Commands #region General Commands UptimeCommand uptime = new UptimeCommand(); Command <IPrivRequest> broadcasting = new BroadcastingFlagCommand(user, playerRepo, pf, uptime, client, futureTaskRegistry, 1, 3, 2, TimeSpan.FromMinutes(30)); Command <IPrivRequest> time = new TimeCommand(); Command <IPrivRequest> playlist = new PlaylistCommand("http://open.spotify.com/user/1251282601/playlist/2j1FVSjJ4zdJiqGQgXgW3t"); Command <IPrivRequest> opinion = new OpinionCommand(); Command <IPrivRequest> pun = new PunCommand(); Command <IPrivRequest> quote = new QuoteCommand(); Command <IPrivRequest> raffle = new RaffleCommand(client, 5, futureTaskRegistry); #endregion #region RPG Commands #region General Command <IWhisperRequest> stats = new StatsCommand(pf, playerRepo); Command <IWhisperRequest> inventory = new InventoryCommand(pf, playerRepo); Command <IWhisperRequest> item = new ItemCommand(equipmentRepository, pf, playerRepo); Command <IWhisperRequest> equip = new EquipCommand(equipmentRepository, pf, playerRepo); Command <IWhisperRequest> unequip = new UnequipCommand(equipmentRepository, pf, playerRepo); Command <IWhisperRequest> shop = new ShopCommand(); Command <IWhisperRequest> classChoice = new ClassChoice(pf, playerRepo, 3); Command <IWhisperRequest> gloat = new GloatCommand(client, pf, playerRepo); Command <IWhisperRequest> respec = new RespecCommand(pf, playerRepo); Command <IWhisperRequest> daily = new DailyCommand(pf, playerRepo); Command <IWhisperRequest> queue = new QueueCommand(groupFinder, pf, playerRepo); Command <IWhisperRequest> leaveQueue = new LeaveQueueCommand(groupFinder, pf, playerRepo); Command <IWhisperRequest> queueTime = new QueueTimeCommand(groupFinder, pf, playerRepo); #endregion #region Party Commands Command <IWhisperRequest> createParty = new CreatePartyCommand(partyPool, pf, playerRepo); Command <IWhisperRequest> pendingInvite = new PendingInvite(partyPool, pf, playerRepo); Command <IWhisperRequest> leaveParty = new LeavePartyCommand(pf, playerRepo); #region Party Leader Commands Command <IWhisperRequest> partyAdd = new AddPartyCommand(client, pf, playerRepo); Command <IWhisperRequest> partyKick = new KickPartyCommand(client, pf, playerRepo); Command <IWhisperRequest> partyStart = new StartPartyCommand(groupFinder, pf, playerRepo); Command <IWhisperRequest> partyPromote = new PromotePartyCommand(client, pf, playerRepo); #endregion #endregion #region Broadcaster only Command <IWhisperRequest> addPlayerXp = new AddPlayerXP(pf, playerRepo); Command <IWhisperRequest> addPlayerCoin = new AddPlayerCoin(pf, playerRepo); Command <IWhisperRequest> setPlayerLevel = new SetPlayerLevel(pf, playerRepo); #endregion #endregion #endregion commandManager.AddAll(uptime, broadcasting, time, playlist, opinion, pun, quote, raffle); commandManager.AddAll(stats, inventory, item, equip, unequip, shop, classChoice, gloat, respec, daily, queue, leaveQueue, queueTime, createParty, pendingInvite, leaveParty, partyAdd, partyKick, partyStart, partyPromote, addPlayerXp, addPlayerCoin, setPlayerLevel); //Provide Handles for events raised by client, multiple handles can be added //allow for parsing of PRVMSG chat for mirroring certain messages. #region Client Event Handling client.AddOperationHandler += commandManager.Handle; client.CancelOperationHandler += commandManager.Handle; client.DeleteOperationHandler += commandManager.Handle; client.EditOperationHandler += commandManager.Handle; client.InfoOperationHandler += commandManager.Handle; client.PrivHandler += (o, e) => { Console.WriteLine(string.Format("{0}: {1}", e.User, e.Message)); }; client.PrivRequestHandler += commandManager.Handle; client.WhisperHandler += (o, e) => { Console.WriteLine(string.Format("Whisper {0}: {1}", e.User, e.Message)); }; client.WhisperRequestHandler += commandManager.Handle; #endregion //new thread for sending messages back to twitch server. new Thread(() => { Thread.CurrentThread.Name = "Twitch Client"; Thread.CurrentThread.IsBackground = true; client.Run(); }).Start(); futureTaskRegistry.Run(); }
public async Task <Stats> GetStatsAsync(StatsCommand command, CancellationToken cancellationToken) { var stats = new Stats(); var perUserStat = new Dictionary <int, int>(); foreach (var day in EachDay(command.From, command.To)) { var daySnapshot = await _messagesCollection.Document(command.ChatId) .Collection(day.ToString("yyyy/MM/dd")) .GetSnapshotAsync(cancellationToken); foreach (var user in daySnapshot.Documents) { var userId = Convert.ToInt32(user.Id); var fields = user.ConvertTo <Dictionary <string, int> >(); foreach (var(messageType, count) in fields) { var type = Enum.Parse <MessageType>(messageType); if (!stats.ChatStats.ContainsKey(type)) { stats.ChatStats.Add(type, count); } else { stats.ChatStats[type] += count; } if (!perUserStat.ContainsKey(userId)) { perUserStat.Add(userId, count); } else { perUserStat[userId] += count; } if (!stats.WeekStats.ContainsKey(day.DayOfWeek)) { stats.WeekStats.Add(day.DayOfWeek, count); } else { stats.WeekStats[day.DayOfWeek] += count; } } } } var orderedStats = perUserStat.OrderByDescending(s => s.Value); foreach (var(userId, count) in orderedStats) { var userSnapshot = await _usersCollection.Document(userId.ToString("D")).GetSnapshotAsync(cancellationToken); userSnapshot.TryGetValue <string>("FirstName", out var firstName); userSnapshot.TryGetValue <string>("LastName", out var lastName); userSnapshot.TryGetValue <string>("UserName", out var userName); var userInfo = new UserInfo(userId, userName, firstName, lastName); stats.UserStats.Add(userInfo, count); } return(stats); }