Beispiel #1
0
        protected override void HandleCommand(IChatClient chatClient, CommandReceivedEventArgs eventArgs)
        {
            if (eventArgs == null)
            {
                throw new ArgumentNullException(nameof(eventArgs));                    // How!?!?
            }
            string roleRequest = eventArgs.Arguments?.ElementAtOrDefault(0);

            ChatUser chatUser = eventArgs.ChatUser;

            if (!_heistGame.IsGameRunning)
            {
                _heistGame.AttemptToCreateGame(chatClient, chatUser);
            }
            if (roleRequest == null)
            {
                JoinHeistRandom(chatClient, chatUser);
            }
            else if (Enum.TryParse(roleRequest, true, out HeistRoles role))
            {
                JoinHeistByRole(chatClient, chatUser, role);
            }
            else
            {
                chatClient.SendMessage("I don't know what role you wanted to be. Try again?");
            }
        }
Beispiel #2
0
        private void BrokerOnCommandReceived(object sender, CommandReceivedEventArgs e)
        {
            var response = JsonConvert.DeserializeObject <JObject>(_webClient.DownloadString("http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=how+its+made"));
            var url      = response["data"]["image_url"];

            e.ReplyTarget.Send(url.ToString());
        }
        /*function that close the server
         */
        public void CloseServer()
        {
            this.m_logging.Log("Now server is closing", MessageTypeEnum.INFO);
            CommandReceivedEventArgs commandRecievedEventArgs = new CommandReceivedEventArgs((int)CommandEnum.CloseCommand, null, "");

            this.CommandRecieved?.Invoke(this, commandRecievedEventArgs);
        }
        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 string TryToExecute(CommandReceivedEventArgs eventArgs,
                                            Survivor survivor)
        {
            string teamArg = eventArgs.Arguments.ElementAtOrDefault(1);

            if (teamArg == null || !int.TryParse(teamArg, out int teamId))
            {
                return(NO_TEAM_ERROR);
            }

            var team = _gameRepository.Single(TeamPolicy.ById(teamId));

            if (team == null)
            {
                return(NO_TEAM_ERROR);
            }

            if (team.Join(survivor))
            {
                _gameRepository.Update(team);
                return($"Welcome to the {team.Name} team, {survivor.DisplayName}!");
            }

            return("Failed to join team.");
        }
Beispiel #6
0
        /// <summary>
        /// Handles the <see cref="E:CommandRecieved" /> event.
        /// A command from the server, for now - just "close" command
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">An EventArgs that contains the event data.</param>
        public void OnCommandReceived(object sender, CommandReceivedEventArgs e)
        {
            bool result;

            //check if command is meant for its directory,
            //if yes – handle command (for now will just be to close handler)};
            if (e.RequestDirPath.Equals(m_path) || e.RequestDirPath.Equals("*"))
            {
                //check if the command is close
                if (e.CommandID == (int)CommandEnum.RemoveHandler)
                {
                    //close
                    closeHandler();
                }

                else
                {
                    // the string will return the new path if result = true,
                    //and will return the error message if the result = false
                    string resultOfCommand = m_controller.ExecuteCommand(
                        e.CommandID, e.Args, out result);

                    if (result == false)
                    {
                        m_logging.Log(resultOfCommand, MessageTypeEnum.FAIL);
                    }
                    else
                    {
                        m_logging.Log("copy image from " + m_path + " to "
                                      + resultOfCommand + " successes", MessageTypeEnum.INFO);
                    }
                }
            }
        }
Beispiel #7
0
        private void Broker_CommandReceived(object sender, CommandReceivedEventArgs e)
        {
            var    client = sender as IClient;
            double temp;

            try
            {
                temp = double.Parse(e.Command.Arguments[0]);
            }
            catch (Exception)
            {
                e.ReplyTarget.Send(".temperature <temp> -- converts <temp> from C to F and F to C");
                return;
            }

            if (Math.Abs(temp) == 420)
            {
                e.ReplyTarget.Send("SMOKE WEED EVERY DAY DONT GIVE A F**K");
                return;
            }
            if (Math.Abs(temp) > 500)
            {
                e.ReplyTarget.Send("2 hot 4 u");
                return;
            }

            var c = (temp - 32) * (5.0 / 9.0);
            var f = (temp * (9.0 / 5.0)) + 32;

            e.ReplyTarget.Send(string.Format("{0:0.0}F is {1:0.0}C. {0:0.0}C is {2:0.0}F.", temp, c, f));
        }
Beispiel #8
0
        protected override void HandleCommand(IChatClient chatClient, CommandReceivedEventArgs eventArgs)
        {
            int offset;

            if (eventArgs.Arguments.Count == 0)
            {
                offset = 0;
            }
            else
            {
                if (!int.TryParse(eventArgs?.Arguments?.ElementAtOrDefault(0), out int chatUserOffset) || chatUserOffset > 18 || chatUserOffset < -18)
                {
                    chatClient.SendMessage("UTC offset must be a whole number between -18 and +18");
                    return;
                }
                offset = chatUserOffset;
            }

            DateTimeZone timeZone = DateTimeZone.ForOffset(Offset.FromHours(offset));

            List <Instant> streamTimes = Repository.List(DataItemPolicy <ScheduleEntity> .All()).Select(x => x.Instant).ToList();

            string message = $"Our usual schedule (at UTC {offset}) is: " + string.Join(", ", streamTimes.Select(x => GetTimeDisplay(x, timeZone)));

            chatClient.SendMessage(message);
        }
        public override string TryToExecute(CommandReceivedEventArgs eventArgs,
                                            Survivor survivor)
        {
            string itemKey = eventArgs.Arguments.ElementAtOrDefault(1);

            if (itemKey == null || itemKey.Length != 1 || !char.IsLetter(itemKey, 0))
            {
                return(BAD_ARGUMENT_MESSAGE);
            }

            int itemIndex = itemKey.ToUpper().Single() - 'A';

            if (itemIndex < 0 || itemIndex > 4)
            {
                return(OUT_OF_RANGE_MESSAGE);
            }

            InventoryItem soldItem = survivor.SellItem(itemIndex);

            if (soldItem != null)
            {
                _repository.Update(survivor);
                return(string.Format(SOLD_FORMAT_STRING, soldItem.Name));
            }

            return(OUT_OF_RANGE_MESSAGE);
        }
Beispiel #10
0
        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>
        /// The event occur upon receiving a command.
        /// </summary>
        /// <param name="sender"></param> The command sender (invoker).
        /// <param name="e"></param> The argumetns.
        public void OnCommandRecieved(object sender, CommandReceivedEventArgs e)
        {
            string msg;
            bool   result = true;

            if (e.CommandID == CommandEnum.CloseCommand)
            {
                if (e.RequestDirPath != dirPath)
                {
                    return;
                }
                msg = "Directory " + dirPath + " is closing";
                dirWatcher.EnableRaisingEvents = false;
                DirectoryClose?.Invoke(this, new DirectoryCloseEventArgs(e.RequestDirPath, msg));
                //logger.Log(msg, MessageTypeEnum.INFO);
            }
            else
            {
                if (!IsSubFile(e.RequestDirPath))
                {
                    return;
                }
                msg = controller.ExecuteCommand(e.CommandID, e.Args, out result);
            }
            logger.Log(msg, GetMessageType(result));
        }
Beispiel #12
0
        private void Broker_CommandReceived(object sender, CommandReceivedEventArgs e)
        {
            var client = sender as IClient;

            // do lazy initialization of images so we dont slowdown startup for a stupid plugin
            if (_images.Count == 0)
            {
                var web = new HtmlWeb();
                var doc = web.Load("http://www.textfiles.com/underconstruction/");

                var imageNodes = doc.DocumentNode.SelectNodes("//img/@src");

                _images = (from image in imageNodes select image.GetAttributeValue("src", "help")).ToList();
            }

            var imgName = _images[_random.Next(_images.Count)];
            var imgUrl  = $"{baseUrl}{imgName}";

            if (client?.InlineOrOembedSupported == true)
            {
                var img = new ImageAttachment()
                {
                    Name       = "UNDERCONSTRUCTION.gif",
                    DataStream = _webClient.OpenRead(imgUrl)
                };
                e.ReplyTarget.Send(String.Empty, img);
            }
            else
            {
                e.ReplyTarget.Send(imgUrl);
            }
        }
Beispiel #13
0
        protected override void HandleCommand(IChatClient chatClient, CommandReceivedEventArgs eventArgs)
        {
            string argumentOne = eventArgs?.Arguments?.ElementAtOrDefault(0);

            var operationToUse = Operations.SingleOrDefault(x => x.ShouldExecute(argumentOne));

            if (operationToUse != null)
            {
                string message = operationToUse.TryToExecute(eventArgs);
                chatClient.SendMessage(message);
                return;
            }

            switch (argumentOne)
            {
            case null:
                HandleRandomQuoteRequest(chatClient);
                break;

            default:
                if (int.TryParse(argumentOne, out int requestQuoteId))
                {
                    HandleQuoteRequest(chatClient, requestQuoteId);
                }

                break;
            }
        }
        private void BrokerOnCommandReceived(object sender, CommandReceivedEventArgs e)
        {
            var client = sender as IClient;
            var drn    = RollD6() + RollD6();

            e.ReplyTarget.Send(drn.ToString());
        }
Beispiel #15
0
 public void BrokerOnCommandReceived(object sender, CommandReceivedEventArgs e)
 {
     if (_fortunes.ContainsKey(e.Command.Command))
     {
         e.ReplyTarget.Send(_fortunes[e.Command.Command][_random.Next(_fortunes.Count)]);
     }
 }
Beispiel #16
0
        private void Broker_CommandReceived(object sender, CommandReceivedEventArgs e)
        {
            var client = sender as IClient;

            if (e.Command.Arguments.Count == 0)
            {
                e.ReplyTarget.Send($"need some code to run");
                return;
            }

            var options = new Dictionary <string, string>
            {
                { "code", string.Join(" ", e.Command.Arguments) },
                { "options", "" },
                { "compiler", "python-2.7.3" },
                { "compiler-option-raw", "" }
            };

            var optStr = JsonConvert.SerializeObject(options);

            var resultStr = _ws.UploadString("http://melpon.org/wandbox/api/compile.json", optStr);

            var result = JsonConvert.DeserializeObject <Dictionary <string, string> >(resultStr);

            if (int.Parse(result["status"]) != 0)
            {
                e.ReplyTarget.Send(result["program_error"]);
            }
            else
            {
                e.ReplyTarget.Send(result["program_output"]);
            }
        }
Beispiel #17
0
 private void CommandService_CommandReceived(object sender, CommandReceivedEventArgs commandReceived)
 {
     if (commandReceived.Command is DemoCommands command && command == DemoCommands.ColorChange)
     {
         materialComponent.Material = materials[(++currentMaterialIdx) % materials.Length];
     }
 }
Beispiel #18
0
        public void Stop()
        {
            //Sends the CLOSE command
            CommandReceivedEventArgs args = new CommandReceivedEventArgs(CommandEnum.Close, null, "");

            OnCommandReceived(args);
        }
        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(CommandWordPolicy.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, EventArgs.Empty);
            }
            else
            {
                chatClient.SendMessage(HelpText);
            }
        }
Beispiel #20
0
 private void BrokerOnCommandDispatching(object sender, CommandReceivedEventArgs e)
 {
     if (e.ReplyTarget is DiscordChannel)
     {
         ((DiscordChannel)e.ReplyTarget).SendIsTyping();
     }
 }
Beispiel #21
0
        public virtual void Process(IChatClient chatClient, CommandReceivedEventArgs eventArgs)
        {
            IEnumerable <string> findTokens = StaticResponse.FindTokens();
            string textToSend = ReplaceTokens(StaticResponse, findTokens, eventArgs);

            chatClient.SendMessage(textToSend);
        }
        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("");
            }
        }
Beispiel #23
0
        protected override void HandleCommand(IChatClient chatClient, CommandReceivedEventArgs eventArgs)
        {
            string taxedUser         = eventArgs?.Arguments?.ElementAtOrDefault(0)?.NoAt();
            string coinsToTakeString = eventArgs?.Arguments?.ElementAtOrDefault(1);

            if (string.IsNullOrWhiteSpace(taxedUser) || string.IsNullOrWhiteSpace(coinsToTakeString))
            {
                chatClient.SendMessage(HelpText);
                return;
            }

            if (int.TryParse(coinsToTakeString, out int coinsToTake))
            {
                if (_chatUserCollection.ReduceCoins(taxedUser, coinsToTake))
                {
                    chatClient.SendMessage($"Our taxation department says you owe, {coinsToTake} coins, {taxedUser}. Thanks!");
                }
                else
                {
                    chatClient.SendMessage($"{taxedUser} failed to pay the {coinsToTake} coins.");
                }
            }
            else
            {
                chatClient.SendMessage($"Is that even a number, {eventArgs?.ChatUser?.DisplayName}?");
            }
        }
        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)
        {
            var word         = eventArgs?.Arguments?.ElementAtOrDefault(1)?.ToLowerInvariant();
            var newAlias     = eventArgs?.Arguments?.ElementAtOrDefault(2)?.ToLowerInvariant();
            var typeName     = _repository.Single(CommandWordPolicy.ByWord(word))?.FullTypeName;
            var existingWord = _repository.Single(CommandWordPolicy.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 newCommand = new CommandWordEntity
            {
                CommandWord  = newAlias,
                FullTypeName = typeName,
                IsPrimary    = false
            };

            _repository.Create(newCommand);

            return($"Created new command alias '!{newAlias}' for '!{word}'.");
        }
Beispiel #26
0
        public override void Process(IChatClient chatClient, CommandReceivedEventArgs eventArgs)
        {
            string bonusReceiver = (eventArgs?.Arguments?.ElementAtOrDefault(0) ?? "").NoAt();
            string bonusGiver    = eventArgs?.ChatUser?.DisplayName;

            if (bonusGiver.EqualsIns(bonusReceiver))
            {
                chatClient.SendMessage($"Did you seriously think this would work, {bonusGiver}");
                return;
            }

            if (int.TryParse(eventArgs?.Arguments?.ElementAtOrDefault(1), out int amount))
            {
                if (amount < 0)
                {
                    chatClient.SendMessage($"Quit messing around, {bonusGiver}. You can't give negative amounts.");
                    return;
                }

                _currencyGenerator.AddCurrencyTo(new List <string> {
                    bonusReceiver
                }, amount);                                                                 // TODO: prevent overflow
                chatClient.SendMessage($"Added {amount} coins to @{bonusReceiver}.");
            }
        }
        public override string TryToExecute(CommandReceivedEventArgs eventArgs)
        {
            var    chatUser    = eventArgs.ChatUser;
            string channelName = eventArgs.Arguments?.ElementAtOrDefault(1);

            if (chatUser.CanUserRunCommand(UserRole.Mod))
            {
                if (string.IsNullOrWhiteSpace(channelName))
                {
                    return($"Please specify a valid channel name, @{chatUser.DisplayName}");
                }

                StreamerEntity entity = _repository.Single(StreamerEntityPolicy.ByChannel(channelName));
                if (entity == null)
                {
                    _repository.Create(new StreamerEntity {
                        ChannelName = channelName
                    });
                    return($"Added {channelName} to our list of streams! Thanks, {chatUser.DisplayName} !");
                }

                return($"We already have {channelName} in our list of streams!");
            }

            return($"You aren't allowed to add new streams, @{chatUser.DisplayName}.");
        }
        public void Process(IChatClient chatClient, CommandReceivedEventArgs eventArgs)
        {
            string coinGiver       = eventArgs?.ChatUser?.DisplayName;
            string coinReceiver    = eventArgs?.Arguments?.ElementAtOrDefault(0).NoAt();
            string coinsToGiveText = eventArgs?.Arguments?.ElementAtOrDefault(1);

            if (string.IsNullOrWhiteSpace(coinReceiver) || string.IsNullOrWhiteSpace(coinsToGiveText) || string.IsNullOrWhiteSpace(coinGiver))
            {
                chatClient.SendMessage(HelpText);
                return;
            }

            if (int.TryParse(coinsToGiveText, out int coinsToGive))
            {
                if (coinsToGive < 2)
                {
                    chatClient.SendMessage("Cheapskate. You should consider giving more coins...");
                    return;
                }

                if (_chatUserCollection.TryGiveCoins(coinGiver, coinReceiver, coinsToGive))
                {
                    chatClient.SendMessage($"Taking {coinsToGive} coins from {coinGiver} and giving them to {coinReceiver}.");
                }
                else
                {
                    chatClient.SendMessage("Failed to send coins.");
                }
            }
            else
            {
                chatClient.SendMessage($"Is that even a number, {coinGiver}?");
            }
        }
Beispiel #29
0
        /// <summary>
        /// Called when [remove].
        /// </summary>
        /// <param name="obj">The object.</param>
        private void OnRemove(object obj)
        {
            string[] args = { this.model.SelectedHandler };
            CommandReceivedEventArgs eventArgs = new CommandReceivedEventArgs((int)CommandEnum.CloseCommand, args, null);

            this.model.Connection.Write(eventArgs);
        }
        protected override void HandleCommand(IChatClient chatClient, CommandReceivedEventArgs eventArgs)
        {
            Survivor survivor       = _gameRepository.GetOrCreate(eventArgs.ChatUser);
            var      inventoryItems = survivor.InventoryItems.Select(HeldItemDto.FromInventoryItem);

            _notification.StartGame(survivor.DisplayName, survivor.UserId, inventoryItems);
        }
        void client_CommandReceived(object sender, CommandReceivedEventArgs e)
        {
            Dispatcher.BeginInvoke((Action)(() =>
            {
                try {

                    var type = typeof(IFAPIStatus).Assembly.GetType(e.Response.Type);

                    if (type == typeof(APIAircraftState))
                    {
                        var state = Serializer.DeserializeJson<APIAircraftState>(e.CommandString);

                        Console.WriteLine(state.VerticalSpeed);

                        // convert to fpm
                        state.VerticalSpeed = float.Parse(Convert.ToString(state.VerticalSpeed * 200, CultureInfo.InvariantCulture.NumberFormat), CultureInfo.InvariantCulture.NumberFormat); // multiply by 200, this somehow gets it accurate..

                        airplaneStateGrid.DataContext = null;
                        airplaneStateGrid.DataContext = state;
                        pAircraftState = state;
                        if (FMSControl.autoFplDirectActive) { FMSControl.updateAutoNav(state); }
                        AircraftStateControl.AircraftState = state;
                        AttitudeIndicator.updateAttitude(state.Pitch, state.Bank);
                       updateLandingRoll(state);
                    }
                    else if (type == typeof(GetValueResponse))
                    {
                        var state = Serializer.DeserializeJson<GetValueResponse>(e.CommandString);

                        Console.WriteLine("{0} -> {1}", state.Parameters[0].Name, state.Parameters[0].Value);
                    }
                    else if (type == typeof(LiveAirplaneList))
                    {
                        LiveAirplaneList airplaneList = Serializer.DeserializeJson<LiveAirplaneList>(e.CommandString);
                        //airplaneDataGrid.ItemsSource = airplaneList.Airplanes;
                    }
                    else if (type == typeof(FacilityList))
                    {
                        var facilityList = Serializer.DeserializeJson<FacilityList>(e.CommandString);

                        //facilitiesDataGrid.ItemsSource = facilityList.Facilities;
                    }
                    else if (type == typeof(IFAPIStatus))
                    {
                        var status = Serializer.DeserializeJson<IFAPIStatus>(e.CommandString);

                    }
                    else if (type == typeof(APIATCMessage))
                    {
                        var msg = Serializer.DeserializeJson<APIATCMessage>(e.CommandString);
                        // TODO client.ExecuteCommand("Live.GetCurrentCOMFrequencies");
                    }
                    else if (type == typeof(APIFrequencyInfoList))
                    {
                        var msg = Serializer.DeserializeJson<APIFrequencyInfoList>(e.CommandString);
                    }
                    else if (type == typeof(ATCMessageList))
                    {
                        var msg = Serializer.DeserializeJson<ATCMessageList>(e.CommandString);
                        atcMessagesDataGrid.ItemsSource = msg.ATCMessages;

                    }
                    else if (type == typeof(APIFlightPlan))
                    {
                        var msg = Serializer.DeserializeJson<APIFlightPlan>(e.CommandString);
                        Console.WriteLine("Flight Plan: {0} items", msg.Waypoints.Length);
                        FMSControl.fplReceived(msg); //Update FMS with FPL from IF.
                        foreach (var item in msg.Waypoints)
                        {
                            Console.WriteLine(" -> {0} {1} - {2}, {3}", item.Name, item.Code, item.Latitude, item.Longitude);
                        }
                    }
                } catch (System.NullReferenceException) {
                    Console.WriteLine("Disconnected from server!");
                    //Let the client handle the lost connection.
                    //connectionStatus = false;
                }
            }));
        }
 private void client_Disconnected(object sender, CommandReceivedEventArgs e)
 {
     Dispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate () { connectionLost(); });
 }
Beispiel #33
0
        void client_CommandReceived(object sender, CommandReceivedEventArgs e)
        {
            Dispatcher.BeginInvoke((Action)(() =>
            {
                if (e.Response != null)
                {
                    var type = Type.GetType(e.Response.Type);

                    if (type == typeof(APIAircraftState))
                    {
                        var state = Serializer.DeserializeJson<APIAircraftState>(e.CommandString);

                        string jsonFormatted = JValue.Parse(e.CommandString).ToString(Formatting.Indented);
                        rawAircraftStateTextBlock.Text = jsonFormatted;

                        airplaneStateGrid.DataContext = null;
                        airplaneStateGrid.DataContext = state;
                    }
                    else if (type == typeof(APIAircraftInfo))
                    {
                        var state = Serializer.DeserializeJson<APIAircraftInfo>(e.CommandString);
                    }
                    else if (type == typeof(GetValueResponse))
                    {
                        var state = Serializer.DeserializeJson<GetValueResponse>(e.CommandString);

                        Console.WriteLine("{0} -> {1}", state.Parameters[0].Name, state.Parameters[0].Value);
                    }
                    else if (type == typeof(LiveAirplaneList))
                    {
                        var airplaneList = Serializer.DeserializeJson<LiveAirplaneList>(e.CommandString);

                        airplaneDataGrid.ItemsSource = airplaneList.Airplanes;
                    }
                    else if (type == typeof(FacilityList))
                    {
                        var facilityList = Serializer.DeserializeJson<FacilityList>(e.CommandString);

                        facilitiesDataGrid.ItemsSource = facilityList.Facilities;
                    }
                    else if (type == typeof(IFAPIStatus))
                    {
                        var status = Serializer.DeserializeJson<IFAPIStatus>(e.CommandString);

                        versionTextBlock.Text = status.AppVersion;
                        userNameTextBlock.Text = status.LoggedInUser;
                        deviceNameTextBlock.Text = status.DeviceName;
                        displayResolutionTextBlock.Text = string.Format("{0}x{1}", status.DisplayWidth, status.DisplayHeight);
                    }
                    else if (type == typeof(APIATCMessage))
                    {
                        var msg = Serializer.DeserializeJson<APIATCMessage>(e.CommandString);

                        atcMessagesListBox.Items.Add(msg.Message);

                        client.ExecuteCommand("Live.GetCurrentCOMFrequencies");
                    }
                    else if (type == typeof(APIFrequencyInfoList))
                    {
                        var msg = Serializer.DeserializeJson<APIFrequencyInfoList>(e.CommandString);
                        frequenciesDataGrid.ItemsSource = msg.Frequencies;
                    }
                    else if (type == typeof(ATCMessageList))
                    {
                        var msg = Serializer.DeserializeJson<ATCMessageList>(e.CommandString);
                        atcMessagesDataGrid.ItemsSource = msg.ATCMessages;
                    }
                    else if (type == typeof(WeatherReports))
                    {
                        var msg = Serializer.DeserializeJson<WeatherReports>(e.CommandString);

                        weatherListbox.ItemsSource = msg.Reports;
                    }
                    else if (type == typeof(APIFlightPlan))
                    {
                        var msg = Serializer.DeserializeJson<APIFlightPlan>(e.CommandString);
                        Console.WriteLine("Flight Plan: {0} items", msg.Waypoints.Length);

                        foreach (var item in msg.Waypoints)
                        {
                            Console.WriteLine(" -> {0} {1} - {2}, {3}", item.Name, item.Code, item.Latitude, item.Longitude);
                        }
                    }
                    else if (type == typeof(TextResponse))
                    {
                        var msg = Serializer.DeserializeJson<TextResponse>(e.CommandString);
                        AddLogText(msg.Text);
                    }
                }
            }));
        }
Beispiel #34
0
        public static bool ServerModCommand(int player, string text)
        {
            if (text.StartsWith("/"))
            {
                string[] parts = text.Split(new char[] { ' ' }, 3);
                string cmd = parts[0].ToLower();
                if (!MainMod.HasPermission(player, cmd))
                {
                    if (Session.Sessions[player].IsLoggedIn)
                    {
                        Session.Sessions[player].SendError("You do not have permission for this command.");
                    }
                    else if (Database.IsUserRegistered(MainMod.Player[player].name))
                    {
                        Session.Sessions[player].SendError("Try logging in before using this command");
                    }
                    else
                    {
                        Session.Sessions[player].SendError("You do not have permission for this command.");
                    }
                }
                else
                {
                    if (PreCommandReceived != null)
                    {
                        CommandReceivedEventArgs e = new CommandReceivedEventArgs(player, text);
                        PreCommandReceived.Invoke(null, e);
                        if (e.Canceled)
                        {
                            return true;
                        }
                    }
                    if (CommandReceived != null)
                    {
                        CommandReceivedEventArgs e = new CommandReceivedEventArgs(player, text);
                        CommandReceived.Invoke(null, e);
                        if (e.Canceled)
                        {
                            return true;
                        }
                    }

                    //MainMod.Notice("Command: " + MainMod.Player[player].name + ": " + text);

                    switch (cmd)
                    {
                        case "/tp":
                        case "/tele":
                        case "/goto":
                            if (parts.Length > 1)
                            {
                                OnTeleCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/opme":
                            if (parts.Length > 1)
                            {
                                OnOpMeCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error. Usage: /opme {password}");
                            }
                            break;

                        case "/tphere":
                        case "/telehere":
                        case "/bring":
                            if (parts.Length > 1)
                            {
                                OnTeleHereCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/playing":
                        case "/list":
                        case "/who":
                            OnListCommand(player);
                            break;

                        case "/motd":
                            if (parts.Length > 1)
                            {
                                OnMOTDCommand(player, parts[1]);
                            }
                            else
                            {
                                OnMOTDCommand(player);
                            }
                            break;

                        case "/warp":
                            if (parts.Length > 1)
                            {
                                OnWarpCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax error.");
                            }
                            break;

                        case "/setwarp":
                            if (parts.Length > 1)
                            {
                                OnSetWarpCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax error.");
                            }
                            break;

                        case "/p":
                        case "/party":
                            if (parts.Length > 1)
                            {
                                OnPartyCommand(player, text.Replace(parts[0], ""));
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/easteregg":
                            Session.Sessions[player].SendError("Oh come on, that's too obvious! Try again! You're close though!");
                            break;

                        case "/easteregg2":
                            Session.Sessions[player].SendText("That's it! Pinkie Pie would be proud of you if she were real!");
                            break;

                        case "/setgroup":
                            Console.WriteLine(parts.Length);
                            if (parts.Length > 2)
                            {
                                OnSetGroupCommand(player, parts[1], parts[2]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/w":
                        case "/whisper":
                        case "/tell":
                            if (parts.Length > 1)
                            {
                                OnWhisperCommand(player, text.Replace(parts[0], ""));
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/reply":
                        case "/r":
                            if (parts.Length > 1)
                            {
                                OnReplyCommand(player, text.Replace(parts[0], "")); // ... that or have an if statement, or have one command >_>
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/me":
                            if (parts.Length > 1)
                            {
                                OnMeCommand(player, text.Substring(4));
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/mute":
                        case "/silence":
                            if (parts.Length > 1)
                            {
                                OnMuteCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/kick":
                            if (parts.Length > 1)
                            {
                                OnKickCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/butterfingers": // Thank you Dinnerbone and script-o-matic.net for this idea ;D
                            if (parts.Length > 1)
                            {
                                OnButterfingersCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/stupidize": // Thank you Dinnerbone and script-o-matic.net for this idea ;D
                            if (parts.Length > 1)
                            {
                                OnDumbCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/ban":
                            if (parts.Length > 1)
                            {
                                OnBanCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/about":
                            Session.Sessions[player].SendText("Server is powered by tMod v" + MainMod.tModVersion);
                            break;

                        case "/reloadlua":
                            LuaHandler.ReloadLua();
                            break;

                        case "/pardon":
                        case "/unban":
                            if (parts.Length > 1)
                            {
                                OnUnBanCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/d":
                        case "/drop":
                        case "/item":
                        case "/i":
                        case "/give":
                            if (parts.Length > 1)
                            {
                                OnDropCommand(player, text.Replace(parts[0] + " ", ""));
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/npc":
                        case "/summon":
                        case "/spawn":
                        case "/mob":
                            if (parts.Length > 1)
                            {
                                OnSummonCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/plugin":
                            if (parts.Length > 2)
                            {
                                OnPluginCommand(player, parts[2], parts[1]);
                            }
                            break;

                        case "/help":
                            if (parts.Length > 1)
                            {
                                OnHelpCommand(player, parts[1]);
                            }
                            else
                            {
                                OnHelpCommand(player);
                            }
                            break;

                        case "/destruction":
                        case "/allowbreak":
                            OnDestructionCommand(player);
                            break;

                        case "/construction":
                        case "/allowbuild":
                            OnConstructionCommand(player);
                            break;

                        case "/say":
                        case "/broadcast":
                            if (parts.Length > 1)
                            {
                                OnSayCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/moderate":
                            OnModerateCommand(player);
                            break;

                        case "/meteor":
                        case "/stars":
                        case "/invasion":
                        case "/bloodmoon":
                        case "/hardcore":
                        case "/infinvasion":
                            break;

                        case "/butcher":
                            if (parts.Length > 1)
                            {
                                OnButcherCommand(player, parts[1]);
                            }
                            else
                            {
                                OnButcherCommand(player);
                            }
                            break;

                        case "/kill":
                            if (parts.Length > 1)
                            {
                                OnKillCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/giveheart":
                        case "/hearts":
                        case "/heal":
                            if (parts.Length > 1)
                            {
                                OnHealCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/war":
                        case "/pvp":
                        case "/peace":
                        case "/peaceful":
                            OnPeacefulCommand(player);
                            break;

                        case "/requireregister":
                            OnRequireRegisterCommand(player);
                            break;

                        case "/blockregister":
                            OnBlockRegisterCommand(player);
                            break;

                        case "/allowregister":
                            if (parts.Length > 1)
                            {
                                OnAllowRegisterCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/dynamite":
                        case "/allowbomb":
                            OnDynamiteCommand(player);
                            break;

                        case "/kickdynamite":
                            OnKickDynamiteCommand(player);
                            break;

                        case "/bandynamite":
                            OnBanDynamiteCommand(player);
                            break;

                        case "/save":
                            OnSaveCommand(player);
                            break;

                        case "/shutdown":
                        case "/stop":
                            OnStopCommand(player);
                            break;

                        case "/op":
                            if (parts.Length > 1)
                            {
                                OnOpCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/deop":
                            if (parts.Length > 1)
                            {
                                OnDeopCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/mod":
                            if (parts.Length > 1)
                            {
                                OnModCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/demod":
                            if (parts.Length > 1)
                            {
                                OnDemodCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/time":
                            if (parts.Length > 1)
                            {
                                OnTimeCommand(player, parts[1]);
                            }
                            else
                            {
                                OnTimeCommand(player);
                            }
                            break;

                        case "/day":
                            OnDayCommand(player);
                            break;

                        case "/night":
                            OnNightCommand(player);
                            break;

                        case "/dusk":
                            OnDuskCommand(player);
                            break;

                        case "/noon":
                            OnNoonCommand(player);
                            break;

                        case "/midnight":
                            OnMidnightCommand(player);
                            break;

                        case "/freezetime":
                            OnFreezeTimeCommand(player);
                            break;

                        case "/whowas":
                            if (parts.Length > 1)
                            {
                                OnWhoWasCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/whois":
                        case "/ip":
                            if (parts.Length > 1)
                            {
                                OnIpCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/reload":
                        case "/rehash":
                            OnReloadCommand(player);
                            break;

                        case "/password":
                            if (parts.Length > 1)
                            {
                                OnPasswordCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/lava":
                        case "/allowlava":
                            OnLavaCommand(player);
                            break;

                        case "/water":
                        case "/allowwater":
                            OnWaterCommand(player);
                            break;

                        case "/spike":
                        case "/allowspike":
                            OnSpikeCommand(player);
                            break;

                        case "/rollback":
                            if (parts.Length > 1)
                            {
                                OnRollbackCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/rban":
                            if (parts.Length > 1)
                            {
                                OnRBan(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/check":
                            OnCheckCommand(player);
                            break;

                        case "/register":
                            if (parts.Length > 1)
                            {
                                OnRegisterCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/deregister":
                            if (parts.Length > 1)
                            {
                                OnDeregisterCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/spawnrate":
                        case "/sr":
                        case "/srate":
                            if (parts.Length > 1)
                            {
                                OnSpawnRateCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/maxspawns":
                        case "/ms":
                        case "/mspawns":
                            if (parts.Length > 1)
                            {
                                OnMaxSpawnsCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/id":
                        case "/identify":
                        case "/login":
                            if (parts.Length > 1)
                            {
                                OnIdentifyCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/changepw":
                        case "/changepassword":
                        case "/changelogin":
                            if (parts.Length > 1)
                            {
                                OnChangeCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/maxslots":
                            if (parts.Length > 1)
                            {
                                OnMaxSlotsCommand(player, parts[1]);
                            }
                            else
                            {
                                Session.Sessions[player].SendError("Syntax Error.");
                            }
                            break;

                        case "/trim":
                            OnTrimCommand(player);
                            break;

                        case "/truncate":
                            OnTruncateCommand(player);
                            break;

                        default:
                            Session.Sessions[player].SendError("Command does not exist.");
                            break;
                    }
                }
                return true;
            }
            else
            {
                return false;
            }
        }