Example #1
0
 public ClientChatEvent(ChatEvent ev)
 {
     EventID = ev.EventID;
     EventData = JinxBotWebApplication.ArgsSerializer.ReadObject(new XmlTextReader(new StringReader(ev.EventData))) as BaseEventArgs;
     Time = ev.Time;
     EventType = (ClientEventType)ev.Type;
 }
Example #2
0
    public void PostEvents(Guid channelID, byte[] mainPasswordHash, ClientEvent[] args)
    {
        var channel = (from ch in Services.DataConnection.Channels
                       where ch.ChannelID == channelID && ch.MainPasswordHash == mainPasswordHash
                       select ch).FirstOrDefault();

        if (channel != null)
        {
            var eventCount = Services.ExistingEvents[channelID].Count;
            if (eventCount > 50)
            {
                var eventsToDelete = (from ev in Services.DataConnection.ChatEvents
                                      where ev.ChannelID == channelID
                                      orderby ev.EventID ascending
                                      select ev).Take(10);
                Services.DataConnection.ChatEvents.DeleteAllOnSubmit(eventsToDelete);
                Services.ExistingEvents[channelID].RemoveRange(0, 10);
            }

            foreach (ClientEvent ev in args)
            {
                ChatEvent newEvent = new ChatEvent() { ChannelID = channelID, EventData = Serialize(ev.EventData), Type = (int)ev.EventType };
                Services.DataConnection.ChatEvents.InsertOnSubmit(newEvent);
                Services.ExistingEvents[channelID].Add(newEvent);
            }
            Services.DataConnection.SubmitChanges();
        }
    }
Example #3
0
        public void onChatReceived(ChatEvent eventObj)
        {
            com.shephertz.app42.gaming.multiplayer.client.SimpleJSON.JSONNode msg =  com.shephertz.app42.gaming.multiplayer.client.SimpleJSON.JSON.Parse(eventObj.getMessage());

            checkUser(eventObj.getSender());

            string sender = eventObj.getSender();
            string parameters = msg ["parameters"].ToString();
            string message = msg ["message"].ToString();

            if( parameters.Length > 0 )
            {
                parameters = parameters.Substring(0, parameters.Length - 1);
                parameters = parameters.Substring(1, parameters.Length - 1);

                appwarp.manageNotification(sender, parameters);
            }
            else if( message.Length > 0 )
            {
                message = message.Substring(0, message.Length - 1);
                message = message.Substring(1, message.Length - 1);

                appwarp.showMessage(message, sender);
            }
        }
        public void onChatReceived(ChatEvent eventObj)
        {
            Log(eventObj.getSender() + " sended " + eventObj.getMessage());
            SimpleJSON.JSONNode msg =  SimpleJSON.JSON.Parse(eventObj.getMessage());

            if(eventObj.getSender() != appwarp.username)
            {
                appwarp.movePlayer(msg["x"].AsFloat,msg["y"].AsFloat,msg["z"].AsFloat);
            }
        }
 private void HandleChatEvent(ChatEvent chatEvent)
 {
     var loweredCharacterName = chatEvent.SourceName.ToLower();
     Queue<SafeAction> queue;
     if (this._chatRecievedResponseQueue.TryGetValue(loweredCharacterName, out queue))
     {
         var action = queue.Dequeue();
         action();
     }
 }
 public void onChatReceived(ChatEvent eventObj)
 {
     Log(eventObj.getSender() + " sended " + eventObj.getMessage());
     com.shephertz.app42.gaming.multiplayer.client.SimpleJSON.JSONNode msg =  com.shephertz.app42.gaming.multiplayer.client.SimpleJSON.JSON.Parse(eventObj.getMessage());
     //msg[0]
     if(eventObj.getSender() != appwarp.username)
     {
         appwarp.movePlayer(msg["x"].AsFloat,msg["y"].AsFloat,msg["z"].AsFloat);
         //Log(msg["x"].ToString()+" "+msg["y"].ToString()+" "+msg["z"].ToString());
     }
 }
 public void onChatReceived(ChatEvent eventObj)
 {
     Log(eventObj.getSender() + " sended " + eventObj.getMessage());
     //			//			SimpleJSON.JSONNode msg =  SimpleJSON.JSON.Parse("aa");//eventObj.getMessage());
     //			//			SimpleJSON.JSONNode msg =  SimpleJSON.JSONNode.Parse(eventObj.getMessage());
     //			SimpleJSON.JObject msg =  SimpleJSON.JSON.Parse(eventObj.getMessage());
     //			//msg[0]
     //			if(eventObj.getSender() != AppWarp.localusername)
     //			{
     ////				AppWarp.movePlayer(msg["x"].AsFloat,msg["y"].AsFloat,msg["z"].AsFloat);
     //				//Log(msg["x"].ToString()+" "+msg["y"].ToString()+" "+msg["z"].ToString());
     //			}
 }
Example #8
0
        public void onChatReceived(ChatEvent eventObj)
        {
            String sender = eventObj.getSender ();
            String message = eventObj.getMessage ();
            history [nextIndex].sender = sender;
            history [nextIndex].message = message;
            nextIndex++;
            if (nextIndex >= Constants.MAX_MSG_HISTORY) {
                nextIndex = 0;
            }

            String lines="";
            for (int i=0; i<Constants.MAX_MSG_HISTORY; i++) {
                if((history[i].message != null) && (history[i].message.Length > 0)){
                    String line = history[i].sender+":"+history[i].message+"\n";
                    lines += line;
                }
            }
            RunOnUiThread(() => updateHistory(lines));
        }
Example #9
0
        public void onChatReceived(ChatEvent eventObj)
        {
            String sender = eventObj.getSender ();
            String message = eventObj.getMessage ();
            history [nextIndex].sender = sender;
            history [nextIndex].message = message;
            nextIndex++;
            if (nextIndex >= Constants.MAX_MSG_HISTORY) {
                nextIndex = 0;
            }

            String lines="";
            for (int i=0; i<Constants.MAX_MSG_HISTORY; i++) {
                if((history[i].message != null) && (history[i].message.Length > 0)){
                    String line = "  "+history[i].sender+":"+history[i].message+"\n";
                    lines += line;
                }
            }
            InvokeOnMainThread (delegate {
                historyLabel.Text = lines;
            });
        }
Example #10
0
 public void onChatReceived(ChatEvent eventObj)
 {
     Log(eventObj.getSender() + " sent Message");
     m_apppwarp.onMsg(eventObj.getSender(), eventObj.getMessage());
 }
Example #11
0
        /// <inheritdoc/>
        public async ValueTask <ChatEventResult> ProcessCommandAsync(TextDeconstructionInformation info, ChatEvent originalChatEvent, IAsyncResponder responder, IReadOnlyDictionary <string, string> settings)
        {
            Contract.Ensures(info != null, "Text deconstruction information is required!");

            var sender = originalChatEvent?.Message.Sender ??
                         throw new ArgumentNullException(nameof(originalChatEvent));

            var item = await _googleCalendarConnector
                       .GetNextMeetingAsync(sender.Email)
                       .ConfigureAwait(false);

            if (item?.Summary == null)
            {
                return(new ChatEventResult("Can not find your next event! You may have no events or the service user account do not see your calendar."));
            }

            var link      = item.ConferenceData?.EntryPoints.FirstOrDefault();
            var startDate = item.Start.DateTime.HasValue ?
                            TimeZoneInfo.ConvertTime(item.Start.DateTime.Value, _currentTimeZoneFactory()).ToString("HH:mm", CultureInfo.InvariantCulture) :
                            null;
            var keyValue = new KeyValue
            {
                Content          = item.Summary,
                ContentMultiline = false,
                BottomLabel      = startDate,
                Icon             = "INVITE",
                Button           = link == null ? null : ChatEventFactory.CreateTextButton("JOIN", link.Uri)
            };

            var card = ChatEventFactory.CreateCard(keyValue);

            return(new ChatEventResult(card));
        }
Example #12
0
 private void command_Race(SSPlayer p, ChatEvent e)
 {
     this.m_Races[0].command_PlayGame(p, e);
 }
Example #13
0
    public void PropagateChatToClients(ChatEvent chatEvent)
    {
        List <ConnectedPlayer> players = PlayerList.Instance.AllPlayers;
        Loudness loud = chatEvent.VoiceLevel;

        //Local chat range checks:
        if (chatEvent.channels.HasFlag(ChatChannel.Local) ||
            chatEvent.channels.HasFlag(ChatChannel.Combat) ||
            chatEvent.channels.HasFlag(ChatChannel.Action))
        {
            for (int i = players.Count - 1; i >= 0; i--)
            {
                if (players[i].Script == null)
                {
                    //joined viewer, don't message them
                    players.RemoveAt(i);
                    continue;
                }

                if (players[i].Script.gameObject == chatEvent.originator)
                {
                    //Always send the originator chat to themselves
                    continue;
                }

                if (players[i].Script.IsGhost && players[i].Script.IsPlayerSemiGhost == false)
                {
                    //send all to ghosts
                    continue;
                }

                if (chatEvent.position == TransformState.HiddenPos)
                {
                    //show messages with no provided position to everyone
                    continue;
                }

                //Send chat to PlayerChatLocation pos, usually just the player object but for AI is its vessel
                var playerPosition = players[i].Script.PlayerChatLocation.OrNull()?.AssumedWorldPosServer()
                                     ?? players[i].Script.gameObject.AssumedWorldPosServer();

                //Do player position to originator distance check
                if (DistanceCheck(playerPosition) == false)
                {
                    //Distance check failed so if we are Ai, then try send action and combat messages to their camera location
                    //as well as if possible
                    if (chatEvent.channels.HasFlag(ChatChannel.Local) == false &&
                        players[i].Script.PlayerState == PlayerScript.PlayerStates.Ai &&
                        players[i].Script.TryGetComponent <AiPlayer>(out var aiPlayer) &&
                        aiPlayer.IsCarded == false)
                    {
                        playerPosition = players[i].Script.gameObject.AssumedWorldPosServer();

                        //Check camera pos
                        if (DistanceCheck(playerPosition))
                        {
                            //Camera can see player, allow Ai to see action/combat messages
                            continue;
                        }
                    }

                    //Player failed distance checks remove them
                    players.RemoveAt(i);
                }

                bool DistanceCheck(Vector3 playerPos)
                {
                    //TODO maybe change this to (chatEvent.position - playerPos).sqrMagnitude > 196f to avoid square root for performance?
                    if (Vector2.Distance(chatEvent.position, playerPos) > 14f)
                    {
                        //Player in the list is too far away for local chat, remove them:
                        return(false);
                    }

                    //Within range, but check if they are in another room or hiding behind a wall
                    if (MatrixManager.Linecast(chatEvent.position, LayerTypeSelection.Walls,
                                               layerMask, playerPos).ItHit)
                    {
                        //If it hit a wall remove that player
                        return(false);
                    }

                    //Player can see the position
                    return(true);
                }
            }


            if (chatEvent.originator != null)
            {
                //Get NPCs in vicinity
                var npcs = Physics2D.OverlapCircleAll(chatEvent.position, 14f, npcMask);
                foreach (Collider2D coll in npcs)
                {
                    var npcPosition = coll.gameObject.AssumedWorldPosServer();
                    if (MatrixManager.Linecast(chatEvent.position, LayerTypeSelection.Walls,
                                               layerMask, npcPosition).ItHit == false)
                    {
                        //NPC is in hearing range, pass the message on: Physics2D.OverlapCircleAll(chatEvent.originator.AssumedWorldPosServer(), 8f, itemsMask);
                        var mobAi = coll.GetComponent <MobAI>();
                        if (mobAi != null)
                        {
                            mobAi.LocalChatReceived(chatEvent);
                        }
                    }
                }

                if (radioCheckIsOnCooldown == false)
                {
                    CheckForRadios(chatEvent);
                }
            }
        }

        for (var i = 0; i < players.Count; i++)
        {
            ChatChannel channels = chatEvent.channels;

            if (channels.HasFlag(ChatChannel.Combat) || channels.HasFlag(ChatChannel.Local) ||
                channels.HasFlag(ChatChannel.System) || channels.HasFlag(ChatChannel.Examine) ||
                channels.HasFlag(ChatChannel.Action))
            {
                //Binary check here to avoid speaking in local when speaking on binary
                if (!channels.HasFlag(ChatChannel.Binary) ||
                    (players[i].Script.IsGhost && players[i].Script.IsPlayerSemiGhost == false))
                {
                    UpdateChatMessage.Send(players[i].GameObject, channels, chatEvent.modifiers, chatEvent.message,
                                           loud, chatEvent.messageOthers,
                                           chatEvent.originator, chatEvent.speaker, chatEvent.stripTags);

                    continue;
                }
            }

            if (players[i].Script == null)
            {
                channels &= ChatChannel.OOC;
            }
            else
            {
                channels &= players[i].Script.GetAvailableChannelsMask(false);
            }

            //if the mask ends up being a big fat 0 then don't do anything
            if (channels != ChatChannel.None)
            {
                UpdateChatMessage.Send(players[i].GameObject, channels, chatEvent.modifiers, chatEvent.message, loud,
                                       chatEvent.messageOthers,
                                       chatEvent.originator, chatEvent.speaker, chatEvent.stripTags);
            }
        }

        if (rconManager != null)
        {
            string message = $"{chatEvent.speaker} {chatEvent.message}";
            if ((namelessChannels & chatEvent.channels) != chatEvent.channels)
            {
                message = $"<b>[{chatEvent.channels}]</b> {message}";
            }

            RconManager.AddChatLog(message);
        }
    }
        protected void Command_Kick( ChatEvent chatEvent )
        {
            ulong remoteUserId = chatEvent.RemoteUserId;
            List<string> commandParts = CommandParser.GetCommandParts( chatEvent.Message );
            int paramCount = commandParts.Count - 1;

            if ( paramCount != 1 )
                return;

            //Get the steam id of the player
            string rawSteamId = commandParts[ 1 ];

            if ( rawSteamId.Length < 3 )
            {
                SendPrivateChatMessage( remoteUserId, "3 or more characters required to kick." );
                return;
            }

            ulong steamId;
            var playerItems = PlayerManager.Instance.PlayerMap.GetPlayerItemsFromPlayerName( rawSteamId );
            if ( playerItems.Count == 0 )
            {
                steamId = PlayerManager.Instance.PlayerMap.GetSteamIdFromPlayerName( rawSteamId );
                if ( steamId == 0 )
                    return;
            }
            else
            {
                if ( playerItems.Count > 1 )
                {
                    SendPrivateChatMessage( remoteUserId, "There is more than one player with the specified name;" );

                    string playersString = playerItems.Aggregate( string.Empty, ( current, playeritem ) => string.Format( "{0}{1} ", current, playeritem.Name ) );

                    SendPrivateChatMessage( remoteUserId, playersString );
                    return;
                }

                steamId = playerItems[ 0 ].SteamId;
                if ( steamId == 0 )
                    return;
            }

            if ( steamId.ToString( ).StartsWith( "9009" ) )
            {
                SendPrivateChatMessage( remoteUserId, string.Format( "Unable to kick player '{0}'.  This player is the server.", steamId ) );
                return;
            }

            PlayerManager.Instance.KickPlayer( steamId );
            SendPrivateChatMessage( remoteUserId, string.Format( "Kicked player '{0}' off of the server", ( playerItems.Count == 0 ? rawSteamId : playerItems[ 0 ].Name ) ) );
        }
Example #15
0
        private void OnPlayerChat(ChatEvent e)
        {
            var player = Scene.SceneTracker.allPlayerEntities.FirstOrDefault(ent => ent.networkId == e.Sender);
            if (player == null) return;
            var steamId = player.source.RemoteEndPoint.SteamId.Id;
            var name = SteamFriends.GetFriendPersonaName(new CSteamID(steamId));

            Interface.Oxide.LogInfo($"{name}: {e.Message}");
        }
Example #16
0
 public MessageChatEvent(ChatEvent chatEvent, bool isFull)
 {
     Event  = chatEvent;
     IsFull = isFull;
 }
Example #17
0
        internal void RespondToChatEvent(Event chatEvent)
        {
            #region Bot Logic
            // Logic for responding to a "PRIVMSG" event
            if (chatEvent.GetType().Equals(typeof(ChatEvent)))
            {
                // Create a reference for the chat data
                ChatEvent chatData    = (ChatEvent)(chatEvent);
                string    message     = chatData.ChatMessage;
                string    user        = chatData.User;
                string    channelName = chatData.Channel;

                Program.nutbotty.Invoke(new Action(() =>
                {
                    Program.nutbotty.chatBox.Text += string.Format("<{0}> {1}" + Environment.NewLine, user, message);
                }));

                #region JOIN and PART commands
                if (message.Equals("!join") && channelName.Equals(Program.BOTNAME))
                {
                    Log.Message(user + " requested " + Program.BOTNAME + " to join their channel.", true);
                    if (!DatabaseHandler.ChannelExists(user))
                    {
                        Channel channel = new Channel(user);
                        DatabaseHandler.InsertChannel(channel);
                        new TwitchChatRoom(chatConnection, whisperConnection, channel);
                        SendChatMessage(Program.BOTNAME + " is now available for " + user + ". Type !commands for a list of commands you can use.");
                    }
                    else
                    {
                        SendChatMessage(Program.BOTNAME + " is already available for " + user + ".");
                    }
                }

                if (message.Equals("!part") && channelName.Equals(Program.BOTNAME))
                {
                    Log.Message(user + " requested " + Program.BOTNAME + " to part their channel.", true);
                    if (DatabaseHandler.ChannelExists(user))
                    {
                        Channel channel = new Channel(user);
                        DatabaseHandler.DeleteChannel(channel.channelName);
                        chatConnection.part(user);
                        SendChatMessage("@" + user + ", thank you for using " + Program.BOTNAME + ".Type !join if you ever want to use " + Program.BOTNAME + " again.");
                    }
                    else
                    {
                        SendChatMessage(Program.BOTNAME + " is not in #" + user + ".");
                    }
                }
                #endregion

                #region Generic Commands
                // Iterate through table rows in database and check if the trigger text matches the message
                for (int i = 0; i < DatabaseHandler.CommandsCount(); i++)
                {
                    //Retrieve command from the database and replace the appropriate strings
                    ChatCommand command = DatabaseHandler.GetCommandAtIndex(i);

                    string responseText = command.ResponseText;
                    responseText = responseText.Replace("$channel", channelName);
                    responseText = responseText.Replace("$user", user);

                    // Check if the command needs to be matched exactly or "loosely"
                    if ((command.MustBeExact && message.Equals(command.TriggerText)) || (!command.MustBeExact && message.Contains(command.TriggerText)))
                    {
                        // Check if the command is universal, or if the command is in the correct channel
                        if (command.IsUniversal || channelName.Equals(command.ChannelName))
                        {
                            // Check if the user is the subscriber (iff the command is subscriber only)
                            if ((command.SubscriberOnly && chatData.UserIsSubscriber) || !(command.SubscriberOnly))
                            {
                                // Check if the user is the moderator (iff the command is moderator only)
                                if ((command.ModeratorOnly && chatData.UserIsModerator) || !(command.ModeratorOnly))
                                {
                                    // Check if the user is the broadcaster (iff the command is broadcaster only)
                                    if ((command.BroadcasterOnly && chatData.UserIsBroadcaster) || !(command.BroadcasterOnly))
                                    {
                                        // Check if the command is whisper only
                                        if (command.WhisperResponse)
                                        {
                                            SendWhisper(user, responseText);
                                        }
                                        else
                                        {
                                            SendChatMessage(responseText);
                                        }
                                    }
                                    else
                                    {
                                        SendWhisper(user, command.TriggerText + " is only available to the broadcaster.");
                                    }
                                }
                                else
                                {
                                    SendWhisper(user, command.TriggerText + " is only available to moderators.");
                                }
                            }
                            else
                            {
                                SendWhisper(user, command.TriggerText + " is only available to subscribers.");
                            }
                        }
                    }
                }
                #endregion

                #region BLOCKED PHRASE Commands
                for (int i = 0; i < DatabaseHandler.PhraseCount(); i++)
                {
                    string phrase = DatabaseHandler.GetPhraseAtIndex(i).phrase;
                    if (message.Contains(phrase))
                    {
                        if (!chatData.UserIsModerator)
                        {
                            SendChatMessageNoAction(".timeout " + user + " 1");
                            SendWhisper(user, "Your messages have been purged from " + channelName + " for using the phrase \"" + phrase + "\".");
                            Log.Message(user + " has been timed out from " + channelName + " for using the phrase \"" + phrase + "\".", true);
                        }
                    }
                }

                // Add a phrase to the BLOCKED_PHRASES table
                if (message.StartsWith("!block "))
                {
                    // Parse the phrase text data
                    string phrase_text = message.Substring("!block ".Length);

                    // If the user is a moderator, add the quote to the database, else do nothing
                    if (chatData.UserIsModerator)
                    {
                        // Assume the command has no arguments, then split on space characters
                        bool     hasArgs = false;
                        string[] args    = message.Split(' ');

                        // If there is at least one argument, continue, otherwise end if
                        if (args.Length > 1)
                        {
                            hasArgs = true;
                        }
                        else
                        {
                            Log.Message("<" + channelName + "> " + user + " attempted to block phrase, but there was not enough arguments.", true);
                        }
                        // Add phrase to database if there were arguments and phrase doesn't already exist in the database
                        if (hasArgs)
                        {
                            if (DatabaseHandler.PhraseExists(phrase_text))
                            {
                                SendChatMessage(user + ", the phrase \"" + phrase_text + "\" is already blocked.");
                                Log.Message("<" + channelName + "> " + user + " attempted to block a phrase, but it already exists --> " + phrase_text, true);
                            }
                            else
                            {
                                BlockedPhrase phrase = new BlockedPhrase(phrase_text);
                                DatabaseHandler.InsertPhrase(phrase);
                                SendChatMessage(user + " blocked the phrase [" + (DatabaseHandler.PhraseCount() - 1) + "]: " + phrase_text);
                                Log.Message("<" + channelName + "> " + user + " blocked a phrase: " + phrase_text, true);
                            }
                        }
                    }
                    else
                    {
                        SendWhisper(user, "!block is only available to moderators");
                        Log.Message(user + " attempted to block a phrase but is not a moderator --> " + phrase_text, true);
                    }
                }

                // Delete a quote to the QUOTE table by searching the QuoteText column
                if (message.StartsWith("!unblock "))
                {
                    // Parse the quote text data
                    string phrase_text = message.Substring("!unblock ".Length);

                    // If the user is a moderator, add the quote to the database, else do nothing
                    if (chatData.UserIsModerator)
                    {
                        // Assume the command has no arguments
                        bool hasArgs = false;
                        // Split the command on space characters
                        string[] args = message.Split(' ');
                        // If there is at least one argument, continue, otherwise end if
                        if (args.Length > 1)
                        {
                            hasArgs = true;
                        }
                        else
                        {
                            Log.Message("<" + channelName + "> " + user + " attempted to unblock a phrase, but there was not enough arguments.", true);
                        }
                        // Add quote to database if there were arguments and the quote exists
                        if (hasArgs)
                        {
                            if (DatabaseHandler.PhraseExists(phrase_text))
                            {
                                DatabaseHandler.DeletePhrase(phrase_text);
                                SendChatMessage(user + " unblocked a phrase: " + phrase_text);
                                Log.Message("<" + channelName + "> " + user + " unblocked a phrase: " + phrase_text, true);
                            }
                            else
                            {
                                SendChatMessage(user + ", that phrase is already unblocked.");
                                Log.Message("<" + channelName + "> " + user + " attempted to block a phrase, but it does not exist --> " + phrase_text, true);
                            }
                        }
                    }
                    else
                    {
                        SendWhisper(user, "!unblock is only available to moderators");
                        Log.Message(user + " attempted to unblock a phrase but is not a moderator --> " + phrase_text, true);
                    }
                }
                #endregion

                #region QUOTE Commands
                // Pull a random quote from the QUOTES table
                Regex quoteRgx    = new Regex(@"^!quote$");
                Regex quoteNumRgx = new Regex(@"^!quote [0-9]{1,}$");
                Quote foundQuote;

                if (quoteRgx.IsMatch(message))
                {
                    int ID = RNG.Next(0, DatabaseHandler.QuoteCount());
                    foundQuote = DatabaseHandler.GetQuoteAtIndex(ID);
                    Log.Message(user + " requested a random quote from the database.", true);
                    SendChatMessage(string.Format("[{0}] {1}", ID, foundQuote.quoteText));
                }
                else if (quoteNumRgx.IsMatch(message))
                {
                    string quoteNum = message.Remove(0, "!quote ".Length);
                    int    ID       = Convert.ToInt32(quoteNum);

                    if (ID >= 0 && ID < DatabaseHandler.QuoteCount())
                    {
                        foundQuote = DatabaseHandler.GetQuoteAtIndex(ID);
                        Log.Message(user + " requested for quote #" + ID + " from the database.", true);
                        SendChatMessage(string.Format("[{0}] {1}", ID, foundQuote.quoteText));
                    }
                    else
                    {
                        SendWhisper(user, "There are only " + DatabaseHandler.QuoteCount() + " quotes in the database.");
                    }
                }
                else if (message.StartsWith("!quote "))
                {
                    string       searchString = message.Remove(0, "!quote ".Length);
                    List <Quote> result       = DatabaseHandler.SearchQuoteList(searchString);

                    if (result.Count > 0)
                    {
                        int ID = RNG.Next(0, result.Count);
                        foundQuote = result[ID];
                        Log.Message(user + " searched quote from the database.", true);
                        SendChatMessage(string.Format("{0}", foundQuote.quoteText));
                    }
                    else
                    {
                        SendWhisper(user, string.Format("The phease '{0}' was not found in the database.", searchString));
                    }
                }

                // Add a quote to the QUOTE table
                if (message.StartsWith("!addquote "))
                {
                    // Parse the quote text data
                    string quoteText = message.Substring("!addquote ".Length);
                    Quote  quote     = new Quote(quoteText, channelName, user, DateTime.Now);

                    // If the user is a moderator, add the quote to the database, else do nothing
                    if (chatData.UserIsModerator)
                    {
                        // Assume the command has no arguments, then split on space characters
                        bool     hasArgs = false;
                        string[] args    = message.Split(' ');

                        // If there is at least one argument, continue, otherwise end if
                        if (args.Length > 1)
                        {
                            hasArgs = true;
                        }
                        else
                        {
                            Log.Message("<" + channelName + "> " + user + " attempted to add quote, but there was not enough arguments.", true);
                        }
                        // Add quote to database if there were arguments and quote doesn't already exist in the database
                        if (hasArgs)
                        {
                            if (DatabaseHandler.QuoteExists(quoteText))
                            {
                                SendChatMessage(user + ", that quote is already in the database.");
                                Log.Message("<" + channelName + "> " + user + " attempted to add quote, but it already exists --> " + quoteText, true);
                            }
                            else
                            {
                                DatabaseHandler.InsertQuote(quote);
                                quoteListHasChanges = true;
                                SendChatMessage(user + " added quote [" + (DatabaseHandler.QuoteCount() - 1) + "]: " + quoteText);
                                Log.Message("<" + channelName + "> " + user + " added quote: " + quoteText, true);
                            }
                        }
                    }
                    else
                    {
                        SendWhisper(user, "!addquote is only available to moderators");
                        Log.Message(user + " attempted to add a quote but is not a moderator --> " + quoteText, true);
                    }
                }

                // Delete a quote to the QUOTE table by searching the QuoteText column
                if (message.StartsWith("!delquote "))
                {
                    // Parse the quote text data
                    string quoteText = message.Substring("!delquote ".Length);

                    // If the user is a moderator, add the quote to the database, else do nothing
                    if (chatData.UserIsModerator)
                    {
                        // Assume the command has no arguments
                        bool hasArgs = false;
                        // Split the command on space characters
                        string[] args = message.Split(' ');
                        // If there is at least one argument, continue, otherwise end if
                        if (args.Length > 1)
                        {
                            hasArgs = true;
                        }
                        else
                        {
                            Log.Message("<" + channelName + "> " + user + " attempted to delete a quote, but there was not enough arguments.", true);
                        }
                        // Add quote to database if there were arguments and the quote exists
                        if (hasArgs)
                        {
                            if (DatabaseHandler.QuoteExists(quoteText))
                            {
                                DatabaseHandler.DeleteQuote(quoteText);
                                quoteListHasChanges = true;
                                SendChatMessage(user + " deleted quote: " + quoteText);
                                Log.Message("<" + channelName + "> " + user + " deleted quote: " + quoteText, true);
                            }
                            else
                            {
                                SendChatMessage(user + ", that quote was not found in the database.");
                                Log.Message("<" + channelName + "> " + user + " attempted to deleted quote, but it does not exist --> " + quoteText, true);
                            }
                        }
                    }
                    else
                    {
                        SendWhisper(user, "!delquote is only available to moderators");
                        Log.Message(user + " attempted to add a quote but is not a moderator --> " + quoteText, true);
                    }
                }

                if (message.Equals("!quotelist"))
                {
                    if (quoteListHasChanges || currenQuotePasteBin.Equals(null))
                    {
                        string pastebinTitle   = Program.BOTNAME + " quote list as of " + DateTime.Now;
                        string pastebinContent = "";

                        List <Quote> quoteList = DatabaseHandler.GetQuoteList();

                        for (int i = 0; i < quoteList.Count; i++)
                        {
                            pastebinContent += "[" + i + "] " + quoteList[i].quoteText + Environment.NewLine;
                        }

                        quoteListHasChanges = false;
                        currenQuotePasteBin = "Click here for a list of quotes ➤ " + Pastebin.Post(pastebinTitle, pastebinContent).Result;
                        SendChatMessage(currenQuotePasteBin);
                    }
                    else
                    {
                        SendChatMessage(currenQuotePasteBin);
                    }
                }
                #endregion

                #region STRAWPOLL Parser
                if (message.Contains("strawpoll.me/"))
                {
                    if (StrawpollParser.GetStrawpollInfo(message) == null)
                    {
                        SendChatMessage(user + ", that is not a valid Strawpoll");
                    }
                    else
                    {
                        SendChatMessage(user + " pasted a Strawpoll ➤ " + StrawpollParser.GetStrawpollInfo(message));
                    }
                }
                #endregion

                #region YOUTUBE Parser
                if (message.Contains("youtube.com/") || message.Contains("youtu.be/"))
                {
                    Console.WriteLine("YouTube Link detected: " + message);
                    if (YouTubeParser.GetYouTubeVideoID(message) != null)
                    {
                        SendChatMessage(user + " pasted a YouTube video ➤ " + YouTubeParser.GetYouTubeInfo(message, YouTubeParser.IS_VIDEO));
                    }
                    if (YouTubeParser.GetYouTubePlaylistID(message) != null)
                    {
                        SendChatMessage(user + " pasted a YouTube playlist ➤ " + YouTubeParser.GetYouTubeInfo(message, YouTubeParser.IS_PLAYLIST));
                    }
                }
                #endregion

                #region GUESSING Commands
                // CeresBot Guesses
                if (message.Contains(@"Round Started. Type !guess") && user.Equals("ceresbot"))
                {
                    int seed = RNG.Next(100);

                    // 30% chance of 45 seconds | 65% chance of 46 seconds | 5% chance of 47 seconds
                    int seconds;
                    if (seed < 30)
                    {
                        seconds = 45;
                    }
                    else if (seed < 95)
                    {
                        seconds = 46;
                    }
                    else
                    {
                        seconds = 47;
                    }

                    // if 45-46 seconds, milliseconds between 0-99, else between 0-25
                    int milliseconds;
                    if (seconds < 47)
                    {
                        milliseconds = RNG.Next(100);
                    }
                    else
                    {
                        milliseconds = RNG.Next(25);
                    }

                    // Make the guess
                    SendChatMessageNoAction("!guess " + seconds + "\"" + milliseconds.ToString("00"));
                }

                // Phantoon guesses
                if (message.Equals("!phantoon"))
                {
                    int[]  rands = new int[2];
                    string label = null;
                    int    total = 0;

                    // Calculate prediction
                    for (int i = 0; i < rands.Length; i++)
                    {
                        rands[i] = RNG.Next(1, 4);
                        total   += rands[i];
                        if (rands[i] == 1)
                        {
                            label = label + " FAST";
                        }
                        else if (rands[i] == 2)
                        {
                            label = label + " MID";
                        }
                        else
                        {
                            label = label + " SLOW";
                        }
                    }

                    // Send chat message
                    if (total <= 2)
                    {
                        SendChatMessage("predicts " + label + ". THE RNG LORDS ARE WITH US PogChamp");
                    }
                    else if (total > 2 && total <= 3)
                    {
                        SendChatMessage("predicts " + label + ". Praise Jesus BloodTrail");
                    }
                    else if (total > 3 && total <= 4)
                    {
                        SendChatMessage("predicts " + label + ". Maybe this won't be a reset after all OMGScoots");
                    }
                    else if (total > 5 && total <= 6)
                    {
                        SendChatMessage("predicts " + label + ". Phantoon please BibleThump");
                    }
                    else if (total == 6)
                    {
                        SendChatMessage("predicts " + label + ". You m**********r. RESET RESET RESET SwiftRage");
                    }
                }

                // Eyedoor guesses
                if (message.Equals("!eyedoor"))
                {
                    int rand = RNG.Next(0, 5);

                    // Send chat message
                    if (rand == 0)
                    {
                        SendChatMessage("predicts... ZERO beams. THE RNG GODS ARE WITH YOU PogChamp");
                    }
                    else if (rand == 1)
                    {
                        SendChatMessage("predicts... ONE beam. Allelujah! BloodTrail");
                    }
                    else if (rand == 2)
                    {
                        SendChatMessage("predicts... TWO beams. You're lucky this time OMGScoots");
                    }
                    else if (rand == 3)
                    {
                        SendChatMessage("predicts... THREE beams. Come on eye door! DansGame");
                    }
                    else if (rand == 4)
                    {
                        SendChatMessage("predicts... FOUR beams. DAFUQ BITCH?! SwiftRage");
                    }
                }
                #endregion

                #region OTHER Commands
                // Show the uptime for the stream. Information is pulled from DecAPI API by Alex Thomassen
                if (message.Equals("!uptime"))
                {
                    string uptime = GetUptime(chatData.Channel);
                    SendChatMessage("@" + user + ": " + uptime);
                    Log.Message(user + " checked the uptime for #" + chatData.Channel + ": " + uptime, true);
                }

                // Check how many points Nutbotty has on ceresbot
                if (message.Contains(Program.BOTNAME) && message.Contains("how many points") && channelName.Equals("oatsngoats"))
                {
                    SendChatMessageNoAction("!points");
                }

                // Commit sudoku
                if (message.Equals("!sudoku"))
                {
                    if (!chatData.UserIsModerator)
                    {
                        SendChatMessageNoAction(".timeout " + user + " 1");
                        SendChatMessage(user + " committed sudoku.");
                    }
                }

                if (message.Equals("!foosdaraid"))
                {
                    for (int i = 0; i < 5; i++)
                    {
                        SendChatMessage("Foosda Raid ( ͡° ͜ʖ ͡°)");
                    }
                }

                // Block thinking emoji
                if (message.Equals("🤔"))
                {
                    SendChatMessageNoAction(".timeout " + user + " 1");
                    SendWhisper(user, "Your messages have been purged from " + channelName + " for using the thinking emoji. Go sit in the corner.");
                    Log.Message(user + " has been timed out from " + channelName + " for using the thinking emoji. Go sit in the corner.", true);
                }

                // FAQ
                if ((message.Contains("What") || message.Contains("what")) && (message.Contains(" rbo") || message.Contains(" RBO") || message.Contains(" rbo ") || message.Contains(" RBO ")))
                {
                    SendChatMessage("RBO stand for Reverse Boss Order. It requires beating the four statue bosses in the following order: Ridley, Draygon, Phantoon, Kraid.");
                }

                if (message.StartsWith("I think") || message.StartsWith("i think"))
                {
                    SendChatMessage("Nobody care what you think, " + user);
                }

                #endregion
            }

            // Logic for responding to an unknown event
            else
            {
                //Log.Message(chatEvent.ToString(), false);
            }
            #endregion
        }
Example #18
0
 private Message newMessage(long chatId, bool isChannel, ChatEvent chatEvent)
 {
     return(new Message(chatEvent.Id, chatEvent.UserId, chatId, null, false, false, false, false, false, isChannel, false, chatEvent.Date, 0, null, 0, 0, 0.0d, 0, string.Empty, 0, 0, null, null));
 }
Example #19
0
            private MessageContent GetMessageContent(ChatEvent item)
            {
                if (item.Action is ChatEventDescriptionChanged descriptionChanged)
                {
                    var text    = new FormattedText(descriptionChanged.NewDescription, new TextEntity[0]);
                    var webPage = string.IsNullOrEmpty(descriptionChanged.OldDescription) ? null : new WebPage {
                        SiteName = Strings.Resources.EventLogPreviousGroupDescription, Description = descriptionChanged.OldDescription
                    };

                    return(new MessageText(text, webPage));
                }
                else if (item.Action is ChatEventUsernameChanged usernameChanged)
                {
                    var link = string.IsNullOrEmpty(usernameChanged.NewUsername) ? string.Empty : MeUrlPrefixConverter.Convert(_protoService, usernameChanged.NewUsername);

                    var text    = new FormattedText(link, new[] { new TextEntity(0, link.Length, new TextEntityTypeUrl()) });
                    var webPage = string.IsNullOrEmpty(usernameChanged.OldUsername) ? null : new WebPage {
                        SiteName = Strings.Resources.EventLogPreviousLink, Description = MeUrlPrefixConverter.Convert(_protoService, usernameChanged.OldUsername)
                    };

                    return(new MessageText(text, webPage));
                }
                else if (item.Action is ChatEventPermissionsChanged permissionChanged)
                {
                    var text     = string.Empty;
                    var entities = new List <TextEntity>();

                    ChatPermissions o = permissionChanged.OldPermissions;
                    ChatPermissions n = permissionChanged.NewPermissions;

                    if (o == null)
                    {
                        o = new ChatPermissions();
                    }
                    if (n == null)
                    {
                        n = new ChatPermissions();
                    }

                    var rights = new StringBuilder(Strings.Resources.EventLogDefaultPermissions);
                    var added  = false;

                    void AppendChange(bool value, string label)
                    {
                        if (!added)
                        {
                            rights.Append('\n');
                            added = true;
                        }

                        rights.Append('\n').Append(value ? '+' : '-').Append(' ');
                        rights.Append(label);
                    }

                    //if (o.IsViewMessages != n.IsViewMessages)
                    //{
                    //    AppendChange(n.IsViewMessages, Strings.Resources.EventLogRestrictedReadMessages);
                    //}
                    if (o.CanSendMessages != n.CanSendMessages)
                    {
                        AppendChange(n.CanSendMessages, Strings.Resources.EventLogRestrictedSendMessages);
                    }
                    if (o.CanSendOtherMessages != n.CanSendOtherMessages)
                    {
                        AppendChange(n.CanSendOtherMessages, Strings.Resources.EventLogRestrictedSendStickers);
                    }
                    if (o.CanSendMediaMessages != n.CanSendMediaMessages)
                    {
                        AppendChange(n.CanSendMediaMessages, Strings.Resources.EventLogRestrictedSendMedia);
                    }
                    if (o.CanSendPolls != n.CanSendPolls)
                    {
                        AppendChange(n.CanSendPolls, Strings.Resources.EventLogRestrictedSendPolls);
                    }
                    if (o.CanAddWebPagePreviews != n.CanAddWebPagePreviews)
                    {
                        AppendChange(n.CanAddWebPagePreviews, Strings.Resources.EventLogRestrictedSendEmbed);
                    }
                    if (o.CanChangeInfo != n.CanChangeInfo)
                    {
                        AppendChange(n.CanChangeInfo, Strings.Resources.EventLogRestrictedChangeInfo);
                    }
                    if (o.CanInviteUsers != n.CanInviteUsers)
                    {
                        AppendChange(n.CanInviteUsers, Strings.Resources.EventLogRestrictedSendEmbed);
                    }
                    if (o.CanPinMessages != n.CanPinMessages)
                    {
                        AppendChange(n.CanPinMessages, Strings.Resources.EventLogRestrictedPinMessages);
                    }

                    text = rights.ToString();

                    return(new MessageText(new FormattedText(text, entities), null));
                }
                else if (item.Action is ChatEventMemberRestricted memberRestricted)
                {
                    var text     = string.Empty;
                    var entities = new List <TextEntity>();

                    var whoUser = _protoService.GetUser(memberRestricted.UserId);
                    ChatMemberStatusRestricted o = null;
                    ChatMemberStatusRestricted n = null;

                    if (memberRestricted.OldStatus is ChatMemberStatusRestricted oldRestricted)
                    {
                        o = oldRestricted;
                    }
                    else if (memberRestricted.OldStatus is ChatMemberStatusBanned oldBanned)
                    {
                        o = new ChatMemberStatusRestricted(false, oldBanned.BannedUntilDate, new ChatPermissions(false, false, false, false, false, false, false, false));
                    }
                    else if (memberRestricted.OldStatus is ChatMemberStatusMember)
                    {
                        o = new ChatMemberStatusRestricted(true, 0, new ChatPermissions(true, true, true, true, true, true, true, true));
                    }

                    if (memberRestricted.NewStatus is ChatMemberStatusRestricted newRestricted)
                    {
                        n = newRestricted;
                    }
                    else if (memberRestricted.NewStatus is ChatMemberStatusBanned newBanned)
                    {
                        n = new ChatMemberStatusRestricted(false, newBanned.BannedUntilDate, new ChatPermissions(false, false, false, false, false, false, false, false));
                    }
                    else if (memberRestricted.NewStatus is ChatMemberStatusMember)
                    {
                        n = new ChatMemberStatusRestricted(true, 0, new ChatPermissions(true, true, true, true, true, true, true, true));
                    }

                    if (!_channel && (n == null || n != null && o != null /*&& n.RestrictedUntilDate != o.RestrictedUntilDate*/))
                    {
                        StringBuilder rights;
                        String        bannedDuration;
                        if (n != null && !n.IsForever())
                        {
                            bannedDuration = "";
                            int duration = n.RestrictedUntilDate - item.Date;
                            int days     = duration / 60 / 60 / 24;
                            duration -= days * 60 * 60 * 24;
                            int hours = duration / 60 / 60;
                            duration -= hours * 60 * 60;
                            int minutes = duration / 60;
                            int count   = 0;
                            for (int a = 0; a < 3; a++)
                            {
                                String addStr = null;
                                if (a == 0)
                                {
                                    if (days != 0)
                                    {
                                        addStr = Locale.Declension("Days", days);
                                        count++;
                                    }
                                }
                                else if (a == 1)
                                {
                                    if (hours != 0)
                                    {
                                        addStr = Locale.Declension("Hours", hours);
                                        count++;
                                    }
                                }
                                else
                                {
                                    if (minutes != 0)
                                    {
                                        addStr = Locale.Declension("Minutes", minutes);
                                        count++;
                                    }
                                }
                                if (addStr != null)
                                {
                                    if (bannedDuration.Length > 0)
                                    {
                                        bannedDuration += ", ";
                                    }
                                    bannedDuration += addStr;
                                }
                                if (count == 2)
                                {
                                    break;
                                }
                            }
                        }
                        else
                        {
                            bannedDuration = Strings.Resources.UserRestrictionsUntilForever;
                        }

                        var str = Strings.Resources.EventLogRestrictedUntil;
                        rights = new StringBuilder(String.Format(str, GetUserName(whoUser, entities, str.IndexOf("{0}")), bannedDuration));
                        var added = false;
                        if (o == null)
                        {
                            o = new ChatMemberStatusRestricted(true, 0, new ChatPermissions(true, true, true, true, true, true, true, true));
                        }
                        if (n == null)
                        {
                            n = new ChatMemberStatusRestricted(true, 0, new ChatPermissions(true, true, true, true, true, true, true, true));
                        }

                        void AppendChange(bool value, string label)
                        {
                            if (!added)
                            {
                                rights.Append('\n');
                                added = true;
                            }

                            rights.Append('\n').Append(value ? '+' : '-').Append(' ');
                            rights.Append(label);
                        }

                        //if (o.IsViewMessages != n.IsViewMessages)
                        //{
                        //    AppendChange(n.IsViewMessages, Strings.Resources.EventLogRestrictedReadMessages);
                        //}
                        if (o.Permissions.CanSendMessages != n.Permissions.CanSendMessages)
                        {
                            AppendChange(n.Permissions.CanSendMessages, Strings.Resources.EventLogRestrictedSendMessages);
                        }
                        if (o.Permissions.CanSendOtherMessages != n.Permissions.CanSendOtherMessages)
                        {
                            AppendChange(n.Permissions.CanSendOtherMessages, Strings.Resources.EventLogRestrictedSendStickers);
                        }
                        if (o.Permissions.CanSendMediaMessages != n.Permissions.CanSendMediaMessages)
                        {
                            AppendChange(n.Permissions.CanSendMediaMessages, Strings.Resources.EventLogRestrictedSendMedia);
                        }
                        if (o.Permissions.CanSendPolls != n.Permissions.CanSendPolls)
                        {
                            AppendChange(n.Permissions.CanSendPolls, Strings.Resources.EventLogRestrictedSendPolls);
                        }
                        if (o.Permissions.CanAddWebPagePreviews != n.Permissions.CanAddWebPagePreviews)
                        {
                            AppendChange(n.Permissions.CanAddWebPagePreviews, Strings.Resources.EventLogRestrictedSendEmbed);
                        }
                        if (o.Permissions.CanChangeInfo != n.Permissions.CanChangeInfo)
                        {
                            AppendChange(n.Permissions.CanChangeInfo, Strings.Resources.EventLogRestrictedChangeInfo);
                        }
                        if (o.Permissions.CanInviteUsers != n.Permissions.CanInviteUsers)
                        {
                            AppendChange(n.Permissions.CanInviteUsers, Strings.Resources.EventLogRestrictedSendEmbed);
                        }
                        if (o.Permissions.CanPinMessages != n.Permissions.CanPinMessages)
                        {
                            AppendChange(n.Permissions.CanPinMessages, Strings.Resources.EventLogRestrictedPinMessages);
                        }

                        text = rights.ToString();
                    }
                    else
                    {
                        String str;
                        if (o == null || memberRestricted.NewStatus is ChatMemberStatusBanned)
                        {
                            str = Strings.Resources.EventLogChannelRestricted;
                        }
                        else
                        {
                            str = Strings.Resources.EventLogChannelUnrestricted;
                        }

                        text = String.Format(str, GetUserName(whoUser, entities, str.IndexOf("{0}")));
                    }

                    return(new MessageText(new FormattedText(text, entities), null));
                }
                else if (item.Action is ChatEventMemberPromoted memberPromoted)
                {
                    var entities = new List <TextEntity>();

                    var whoUser  = _protoService.GetUser(memberPromoted.UserId);
                    var str      = Strings.Resources.EventLogPromoted;
                    var userName = GetUserName(whoUser, entities, str.IndexOf("{0}"));
                    var builder  = new StringBuilder(string.Format(str, userName));
                    var added    = false;

                    ChatMemberStatusAdministrator o = null;
                    ChatMemberStatusAdministrator n = null;

                    if (memberPromoted.OldStatus is ChatMemberStatusAdministrator oldAdmin)
                    {
                        o = oldAdmin;
                    }
                    if (memberPromoted.NewStatus is ChatMemberStatusAdministrator newAdmin)
                    {
                        n = newAdmin;
                    }

                    if (o == null)
                    {
                        o = new ChatMemberStatusAdministrator();
                    }
                    if (n == null)
                    {
                        n = new ChatMemberStatusAdministrator();
                    }

                    void AppendChange(bool value, string label)
                    {
                        if (!added)
                        {
                            builder.Append('\n');
                            added = true;
                        }

                        builder.Append('\n').Append(value ? '+' : '-').Append(' ');
                        builder.Append(label);
                    }

                    if (o.CanChangeInfo != n.CanChangeInfo)
                    {
                        AppendChange(n.CanChangeInfo, _channel ? Strings.Resources.EventLogPromotedChangeChannelInfo : Strings.Resources.EventLogPromotedChangeGroupInfo);
                    }

                    if (_channel)
                    {
                        if (o.CanPostMessages != n.CanPostMessages)
                        {
                            AppendChange(n.CanPostMessages, Strings.Resources.EventLogPromotedPostMessages);
                        }
                        if (o.CanEditMessages != n.CanEditMessages)
                        {
                            AppendChange(n.CanEditMessages, Strings.Resources.EventLogPromotedEditMessages);
                        }
                    }
                    if (o.CanDeleteMessages != n.CanDeleteMessages)
                    {
                        AppendChange(n.CanDeleteMessages, Strings.Resources.EventLogPromotedDeleteMessages);
                    }
                    if (o.CanPromoteMembers != n.CanPromoteMembers)
                    {
                        AppendChange(n.CanPromoteMembers, Strings.Resources.EventLogPromotedAddAdmins);
                    }
                    if (!_channel)
                    {
                        if (o.CanRestrictMembers != n.CanRestrictMembers)
                        {
                            AppendChange(n.CanRestrictMembers, Strings.Resources.EventLogPromotedBanUsers);
                        }
                    }
                    if (o.CanInviteUsers != n.CanInviteUsers)
                    {
                        AppendChange(n.CanInviteUsers, Strings.Resources.EventLogPromotedAddUsers);
                    }
                    if (!_channel)
                    {
                        if (o.CanPinMessages != n.CanPinMessages)
                        {
                            AppendChange(n.CanPinMessages, Strings.Resources.EventLogPromotedPinMessages);
                        }
                    }

                    return(new MessageText(new FormattedText(builder.ToString(), entities), null));
                }

                return(new MessageChatEvent(item, true));
            }
        private void UpdateNotifyMessage()
        {
            if (string.IsNullOrEmpty(tempMessageString) == false)
            {
                SocketEvent receiveMessageData = JsonUtility.FromJson <SocketEvent>(tempMessageString);

                if (receiveMessageData.eventName == "CreateRoom")
                {
                    if (OnCreateRoom != null)
                    {
                        OnCreateRoom(receiveMessageData);
                    }
                    Debug.Log(tempMessageString);
                }
                else if (receiveMessageData.eventName == "JoinRoom")
                {
                    if (OnJoinRoom != null)
                    {
                        OnJoinRoom(receiveMessageData);
                    }


                    if (joinName.text == receiveMessageData.data)
                    {
                        JoinintoChat();
                        leaveButton.SetActive(true);
                        roomNameTextGameob.SetActive(true);
                    }
                    else
                    {
                        roomNameTextGameob.SetActive(false);
                        popupError.SetActive(true);
                        leaveButton.SetActive(true);
                    }
                }
                else if (receiveMessageData.eventName == "LeaveRoom")
                {
                    if (OnLeaveRoom != null)
                    {
                        OnLeaveRoom(receiveMessageData);
                    }
                }
                else if (receiveMessageData.eventName == "Message")
                {
                    Debug.Log("message : " + receiveMessageData.data);
                    if (OnReceiveMessage != null)
                    {
                        OnReceiveMessage(receiveMessageData);
                    }
                }
                else if (receiveMessageData.eventName == "RequestToken")
                {
                    Debug.Log("message : " + receiveMessageData.data);
                }
                else if (receiveMessageData.eventName == "Login")
                {
                    if (OnLogin != null)
                    {
                        OnLogin(receiveMessageData);
                    }


                    LoginEvent userstring = JsonUtility.FromJson <LoginEvent>(receiveMessageData.data);

                    ownuserID = userstring.UserID;
                    ownName   = userstring.Name;

                    Debug.Log(name);


                    RoomUI();
                    loginInterFace.SetActive(false);
                }
                else if (receiveMessageData.eventName == "Register")
                {
                    if (OnRegister != null)
                    {
                        OnRegister(receiveMessageData);
                    }
                }
                else if (receiveMessageData.eventName == "SendMessage")
                {
                    Debug.Log("1");
                    ChatEvent ChatMessage = JsonUtility.FromJson <ChatEvent>(receiveMessageData.data);

                    if (ChatMessage.UserID == ownuserID)
                    {
                        chatBoxText.text += "<align=right>" + ChatMessage.Name + ":<align=right>" + ChatMessage.Message + "\n";
                    }
                    else
                    {
                        chatBoxText.text += "\n<align=left>" + ChatMessage.Name + ":<align=left>" + ChatMessage.Message + "\n";
                    }
                }
                //else if(receiveMessageData.eventName =="Addmoney")
                //{
                //    if (OnAddMoney != null)
                //        OnAddMoney(receiveMessageData);
                //}
                tempMessageString = "";
            }
        }
Example #21
0
        public void onChatReceived(ChatEvent eventObj)
        {
            //Log(eventObj.getSender() + " sent Message");
            //			m_apppwarp.onMsg(eventObj.getSender(), eventObj.getMessage());

            String msg    = eventObj.getMessage();
            String sender = eventObj.getSender();

            Debug.Log("Chat Received : " + msg + " \n Sender : " + sender);

            if (sender.Equals(appwarp.TEXASS_SERVER_NAME) || sender.Equals(appwarp.WA_SERVER_NAME))
            {
                /*	// Get default cards details. Flops, River, Turn*/
                if (msg.StartsWith(GameConstant.RESPONSE_FOR_DEFAULT_CARDS))
                {
                    msg = msg.Replace(GameConstant.RESPONSE_FOR_DEFAULT_CARDS, "");

                    Debug.Log("Default Cards Details : " + msg);

                    JSON_Object jsonResponce = new JSON_Object(msg);
                    manageDefaultCards(sender, jsonResponce);

                    //Get all room player infomations.
                }
                else if (msg.StartsWith(GameConstant.RESPONSE_FOR_PLAYERS_INFO))
                {
                    msg = msg.Replace(GameConstant.RESPONSE_FOR_PLAYERS_INFO, "");
                    JSON_Object jsonResponce = new JSON_Object(msg);
                    managePlayerCards(sender, jsonResponce);
                }
                else if (msg.StartsWith(GameConstant.RESPONSE_FOR_BLIEND_PLAYER))
                {
                    msg = msg.Replace(GameConstant.RESPONSE_FOR_BLIEND_PLAYER, "");
                    JSON_Object jsonResponce = new JSON_Object(msg);
                    manageBliendPlayers(sender, jsonResponce);
                }
                else if (msg.StartsWith(GameConstant.RESPONSE_FOR_ACTION_DONE))
                {
                    msg = msg.Replace(GameConstant.RESPONSE_FOR_ACTION_DONE, "");
                    //managePlayerMoveActionDEBUG.Log("msg : "+ msg);
                    managePlayerMoveAction(sender, msg);
                }
                else if (msg.StartsWith(GameConstant.RESPONSE_FOR_ROUND_COMPLETE))
                {
                    msg = msg.Replace(GameConstant.RESPONSE_FOR_ROUND_COMPLETE, "");
                    manageRoundCompleted(sender, msg);
                }
                else if (msg.StartsWith(GameConstant.RESPONSE_FOR_GAME_COMPLETE))
                {
                    msg = msg.Replace(GameConstant.RESPONSE_FOR_GAME_COMPLETE, "");
                    //				manageGameCompleted (sender, msg);
                    if (sender.Equals(appwarp.TEXASS_SERVER_NAME))
                    {
                        texassGameManager.gameFinished();
                    }
                    else
                    {
                        waGameManager.gameFinished();
                    }
                    WarpClient.GetInstance().stopGame();
                }
                else if (msg.StartsWith(GameConstant.RESPONSE_FOR_DESTRIBUTE_CARD))
                {
                    //					DEBUG.Log("Start Distribution");
                    if (sender.Equals(appwarp.TEXASS_SERVER_NAME))
                    {
                        texassGameManager.distributeCards();
                    }
                    else
                    {
                        waGameManager.distributeCards();
                    }
                }
                else if (msg.StartsWith(GameConstant.RESPONSE_FOR_WINNIER_INFO))
                {
                    msg = msg.Replace(GameConstant.RESPONSE_FOR_WINNIER_INFO, "");

                    generateWinnerPlayers(sender, msg);
                }
                else if (msg.StartsWith(GameConstant.RESPONSE_FOR_GAME_START))
                {
                    msg = msg.Replace(GameConstant.RESPONSE_FOR_GAME_START, "");
                    if (sender.Equals(appwarp.TEXASS_SERVER_NAME))
                    {
                        texassGameManager.initGamePlay();
                    }
                    else
                    {
                        waGameManager.initGamePlay();
                    }
                }
                else if (msg.StartsWith(GameConstant.REQUEST_FOR_WA_POT_WINNER))
                {
                    msg = msg.Replace(GameConstant.REQUEST_FOR_WA_POT_WINNER, "");
                    if (sender.Equals(appwarp.WA_SERVER_NAME))
                    {
                        JSONArray jSONArray = new JSONArray(msg);
                        manageWAPotAmount(jSONArray);
                    }
                }
            }
        }
Example #22
0
 public BoltEntity PlayerFromEvent(ChatEvent e) => Scene.SceneTracker.allPlayerEntities.FirstOrDefault(ent => ent.networkId == e.Sender);
        protected void Command_Delete( ChatEvent chatEvent )
        {
            ulong remoteUserId = chatEvent.RemoteUserId;
            List<string> commandParts = CommandParser.GetCommandParts( chatEvent.Message );
            int paramCount = commandParts.Count - 1;

            //All entities
            if ( paramCount > 1 && commandParts[ 1 ].ToLower( ).Equals( "all" ) )
            {
                //All cube grids that have no beacon or only a beacon with no name
                if ( commandParts[ 2 ].ToLower( ).Equals( "nobeacon" ) )
                {
                    List<CubeGridEntity> entities = SectorObjectManager.Instance.GetTypedInternalData<CubeGridEntity>( );
                    List<CubeGridEntity> entitiesToDispose = new List<CubeGridEntity>( );
                    foreach ( CubeGridEntity entity in entities )
                    {
                        while ( entity.CubeBlocks.Count == 0 )
                        {
                            Thread.Sleep( 20 );
                        }
                        List<CubeBlockEntity> blocks = entity.CubeBlocks;
                        if ( blocks.Count > 0 )
                        {
                            bool foundBeacon = blocks.OfType<BeaconEntity>( ).Any( );
                            if ( !foundBeacon )
                            {
                                entitiesToDispose.Add( entity );
                            }
                        }
                    }

                    foreach ( CubeGridEntity entity in entitiesToDispose )
                    {
                        bool isLinkedShip = false;
                        List<CubeBlockEntity> blocks = entity.CubeBlocks;
                        foreach ( CubeBlockEntity cubeBlock in blocks )
                        {
                            if ( cubeBlock is MergeBlockEntity )
                            {
                                MergeBlockEntity block = (MergeBlockEntity)cubeBlock;
                                if ( block.IsAttached )
                                {
                                    if ( !entitiesToDispose.Contains( block.AttachedCubeGrid ) )
                                    {
                                        isLinkedShip = true;
                                        break;
                                    }
                                }
                            }
                            if ( cubeBlock is PistonEntity )
                            {
                                PistonEntity block = (PistonEntity)cubeBlock;
                                CubeBlockEntity topBlock = block.TopBlock;
                                if ( topBlock != null )
                                {
                                    if ( !entitiesToDispose.Contains( topBlock.Parent ) )
                                    {
                                        isLinkedShip = true;
                                        break;
                                    }
                                }
                            }
                            if ( cubeBlock is RotorEntity )
                            {
                                RotorEntity block = (RotorEntity)cubeBlock;
                                CubeBlockEntity topBlock = block.TopBlock;
                                if ( topBlock != null )
                                {
                                    if ( !entitiesToDispose.Contains( topBlock.Parent ) )
                                    {
                                        isLinkedShip = true;
                                        break;
                                    }
                                }
                            }
                        }
                        if ( isLinkedShip )
                            continue;

                        entity.Dispose( );
                    }

                    SendPrivateChatMessage( remoteUserId, string.Format( "{0} cube grids have been removed", entitiesToDispose.Count ) );
                }
                //All cube grids that have no power
                else if ( commandParts[ 2 ].ToLower( ).Equals( "nopower" ) )
                {
                    List<CubeGridEntity> entities = SectorObjectManager.Instance.GetTypedInternalData<CubeGridEntity>( );
                    List<CubeGridEntity> entitiesToDispose = entities.Where( entity => entity.TotalPower <= 0 ).ToList( );

                    foreach ( CubeGridEntity entity in entitiesToDispose )
                    {
                        entity.Dispose( );
                    }

                    SendPrivateChatMessage( remoteUserId, string.Format( "{0} cube grids have been removed", entitiesToDispose.Count ) );
                }
                else if ( commandParts[ 2 ].ToLower( ).Equals( "floatingobjects" ) )	//All floating objects
                {
                    /*
                    List<FloatingObject> entities = SectorObjectManager.Instance.GetTypedInternalData<FloatingObject>();
                    int floatingObjectCount = entities.Count;
                    foreach (FloatingObject entity in entities)
                    {
                        entity.Dispose();
                    }
                     */

                    int count = 0;
                    MySandboxGame.Static.Invoke( ( ) =>
                                                 {
                                                     HashSet<IMyEntity> entities = new HashSet<IMyEntity>( );
                                                     MyAPIGateway.Entities.GetEntities( entities );
                                                     List<IMyEntity> entitiesToRemove = new List<IMyEntity>( );

                                                     foreach ( IMyEntity entity in entities )
                                                     {
                                                         MyObjectBuilder_Base objectBuilder;
                                                         try
                                                         {
                                                             objectBuilder = entity.GetObjectBuilder( );
                                                         }
                                                         catch
                                                         {
                                                             continue;
                                                         }

                                                         if ( objectBuilder is MyObjectBuilder_FloatingObject )
                                                             entitiesToRemove.Add( entity );
                                                     }

                                                     for ( int r = entitiesToRemove.Count - 1; r >= 0; r-- )
                                                     {
                                                         IMyEntity entity = entitiesToRemove[ r ];
                                                         MyAPIGateway.Entities.RemoveEntity( entity );
                                                         count++;
                                                     }
                                                 } );

                    SendPrivateChatMessage( remoteUserId, count + " floating objects have been removed" );
                }
                else
                {
                    string entityName = commandParts[ 2 ];
                    if ( commandParts.Count > 3 )
                    {
                        for ( int i = 3; i < commandParts.Count; i++ )
                        {
                            entityName += " " + commandParts[ i ];
                        }
                    }

                    int matchingEntitiesCount = 0;
                    List<BaseEntity> entities = SectorObjectManager.Instance.GetTypedInternalData<BaseEntity>( );
                    foreach ( BaseEntity entity in entities )
                    {
                        bool isMatch = Regex.IsMatch( entity.Name, entityName, RegexOptions.IgnoreCase );
                        if ( !isMatch )
                            continue;

                        entity.Dispose( );

                        matchingEntitiesCount++;
                    }

                    SendPrivateChatMessage( remoteUserId, string.Format( "{0} objects have been removed", matchingEntitiesCount ) );
                }
            }

            //All non-static cube grids
            if ( paramCount > 1 && commandParts[ 1 ].ToLower( ).Equals( "ship" ) )
            {
                //That have no beacon or only a beacon with no name
                if ( commandParts[ 2 ].ToLower( ).Equals( "nobeacon" ) )
                {
                    List<CubeGridEntity> entities = SectorObjectManager.Instance.GetTypedInternalData<CubeGridEntity>( );
                    List<CubeGridEntity> entitiesToDispose = new List<CubeGridEntity>( );
                    foreach ( CubeGridEntity entity in entities )
                    {
                        //Skip static cube grids
                        if ( entity.IsStatic )
                            continue;

                        if ( entity.Name.Equals( entity.EntityId.ToString( ) ) )
                        {
                            entitiesToDispose.Add( entity );
                            continue;
                        }

                        List<CubeBlockEntity> blocks = entity.CubeBlocks;
                        if ( blocks.Count > 0 )
                        {
                            bool foundBeacon = entity.CubeBlocks.OfType<BeaconEntity>( ).Any( );
                            if ( !foundBeacon )
                            {
                                entitiesToDispose.Add( entity );
                            }
                        }
                    }

                    foreach ( CubeGridEntity entity in entitiesToDispose )
                    {
                        entity.Dispose( );
                    }

                    SendPrivateChatMessage( remoteUserId, string.Format( "{0} ships have been removed", entitiesToDispose.Count ) );
                }
            }

            //All static cube grids
            if ( paramCount > 1 && commandParts[ 1 ].ToLower( ).Equals( "station" ) )
            {
                //That have no beacon or only a beacon with no name
                if ( commandParts[ 2 ].ToLower( ).Equals( "nobeacon" ) )
                {
                    List<CubeGridEntity> entities = SectorObjectManager.Instance.GetTypedInternalData<CubeGridEntity>( );
                    List<CubeGridEntity> entitiesToDispose = new List<CubeGridEntity>( );
                    foreach ( CubeGridEntity entity in entities )
                    {
                        //Skip non-static cube grids
                        if ( !entity.IsStatic )
                            continue;

                        if ( entity.Name.Equals( entity.EntityId.ToString( ) ) )
                        {
                            entitiesToDispose.Add( entity );
                            continue;
                        }

                        List<CubeBlockEntity> blocks = entity.CubeBlocks;
                        if ( blocks.Count > 0 )
                        {
                            bool foundBeacon = entity.CubeBlocks.OfType<BeaconEntity>( ).Any( );
                            if ( !foundBeacon )
                            {
                                entitiesToDispose.Add( entity );
                            }
                        }
                    }

                    foreach ( CubeGridEntity entity in entitiesToDispose )
                    {
                        entity.Dispose( );
                    }

                    SendPrivateChatMessage( remoteUserId, entitiesToDispose.Count + " stations have been removed" );
                }
            }

            //Prunes defunct player entries in the faction data
            /*
            if (paramCount > 1 && commandParts[1].ToLower().Equals("player"))
            {
                List<MyObjectBuilder_Checkpoint.PlayerItem> playersToRemove = new List<MyObjectBuilder_Checkpoint.PlayerItem>();
                int playersRemovedCount = 0;
                if (commandParts[2].ToLower().Equals("dead"))
                {
                    List<long> playerIds = PlayerMap.Instance.GetPlayerIds();
                    foreach (long playerId in playerIds)
                    {
                        MyObjectBuilder_Checkpoint.PlayerItem item = PlayerMap.Instance.GetPlayerItemFromPlayerId(playerId);
                        if (item.IsDead)
                            playersToRemove.Add(item);
                    }
                    //TODO - This is VERY slow. Need to find a much faster way to do this
                    //TODO - Need to find a way to remove the player entries from the main list, not just from the blocks and factions
                    foreach (var item in playersToRemove)
                    {
                        bool playerRemoved = false;
                        //Check if any of the players we're about to remove own blocks
                        //If so, set the owner to 0 and set the share mode to None
                        foreach (var cubeGrid in SectorObjectManager.Instance.GetTypedInternalData<CubeGridEntity>())
                        {
                            foreach (var cubeBlock in cubeGrid.CubeBlocks)
                            {
                                if (cubeBlock.Owner == item.PlayerId)
                                {
                                    cubeBlock.Owner = 0;
                                    cubeBlock.ShareMode = MyOwnershipShareModeEnum.None;
                                    playerRemoved = true;
                                }
                            }
                        }
                        foreach (var entry in FactionsManager.Instance.Factions)
                        {
                            foreach (var member in entry.Members)
                            {
                                if (member.PlayerId == item.PlayerId)
                                {
                                    entry.RemoveMember(member.PlayerId);
                                    playerRemoved = true;
                                }
                            }
                        }
                        if (playerRemoved)
                            playersRemovedCount++;
                    }
                }
                SendPrivateChatMessage(remoteUserId, "Deleted " + playersRemovedCount.ToString() + " player entries");
            }
            */
            //Prunes defunct faction entries in the faction data
            if ( paramCount > 1 && commandParts[ 1 ].ToLower( ).Equals( "faction" ) )
            {
                List<Faction> factionsToRemove = new List<Faction>( );
                if ( commandParts[ 2 ].ToLower( ).Equals( "empty" ) )
                {
                    factionsToRemove.AddRange( FactionsManager.Instance.Factions.Where( entry => entry.Members.Count == 0 ) );
                }
                if ( commandParts[ 2 ].ToLower( ).Equals( "nofounder" ) )
                {
                    foreach ( var entry in FactionsManager.Instance.Factions )
                    {
                        bool founderMatch = entry.Members.Any( member => member.IsFounder );

                        if ( !founderMatch )
                            factionsToRemove.Add( entry );
                    }
                }
                if ( commandParts[ 2 ].ToLower( ).Equals( "noleader" ) )
                {
                    foreach ( var entry in FactionsManager.Instance.Factions )
                    {
                        bool founderMatch = entry.Members.Any( member => member.IsFounder || member.IsLeader );

                        if ( !founderMatch )
                            factionsToRemove.Add( entry );
                    }
                }

                foreach ( var entry in factionsToRemove )
                {
                    FactionsManager.Instance.RemoveFaction( entry.Id );
                }

                SendPrivateChatMessage( remoteUserId, string.Format( "Deleted {0} factions", factionsToRemove.Count ) );
            }

            //Single entity
            if ( paramCount == 1 )
            {
                string rawEntityId = commandParts[ 1 ];

                try
                {
                    long entityId = long.Parse( rawEntityId );

                    List<BaseEntity> entities = SectorObjectManager.Instance.GetTypedInternalData<BaseEntity>( );
                    foreach ( BaseEntity entity in entities )
                    {
                        if ( entity.EntityId != entityId )
                            continue;

                        entity.Dispose( );
                    }
                }
                catch ( Exception ex )
                {
                    ApplicationLog.BaseLog.Error( ex );
                }
            }
        }
Example #24
0
        /// <inheritdoc/>
        public ValueTask <ChatEventResult> ProcessCommandAsync(TextDeconstructionInformation info, ChatEvent originalChatEvent, IAsyncResponder responder)
        {
            if (info == null)
            {
                return(new ValueTask <ChatEventResult>(
                           new ChatEventResult("I do not understand the sentance.")));
            }

            var notify          = info.TextSentanceChunk.StartsWith("Notify", StringComparison.InvariantCultureIgnoreCase);
            var department      = Regex.Match(info.TextSentanceChunk, "department ['\"]?([\\w\\.\\-_]+)['\"]?$");
            var departmentValue = department.Success && department.Groups.Count == 2 ? department.Groups[1].Value : null;

            _openAirConnector.GetUnsubmittedTimesheetsAsync(DateTime.Today)
            .ContinueWith(task => ProcessNotify(
                              task.Result,
                              departmentValue,
                              notify,
                              new GoogleChatAddress(originalChatEvent),
                              responder as IHangoutsChatConnector));

            return(new ValueTask <ChatEventResult>(
                       new ChatEventResult(text: null)));
        }
        protected void Command_GetId( ChatEvent chatEvent )
        {
            ulong remoteUserId = chatEvent.RemoteUserId;
            List<string> commandParts = CommandParser.GetCommandParts( chatEvent.Message );
            int paramCount = commandParts.Count - 1;

            if ( paramCount > 0 )
            {
                string entityName = commandParts[ 1 ];
                if ( commandParts.Count > 2 )
                {
                    for ( int i = 2; i < commandParts.Count; i++ )
                    {
                        entityName += string.Format( " {0}", commandParts[ i ] );
                    }
                }

                List<BaseEntity> entities = SectorObjectManager.Instance.GetTypedInternalData<BaseEntity>( );
                foreach ( BaseEntity entity in entities )
                {
                    if ( !entity.Name.ToLower( ).Equals( entityName.ToLower( ) ) )
                        continue;

                    SendPrivateChatMessage( remoteUserId, string.Format( "Entity ID is '{0}'", entity.EntityId ) );
                }
            }
        }
Example #26
0
    /// <summary>
    /// Send a Chat Msg from a player to the selected Chat Channels
    /// Server only
    /// </summary>
    public static void AddChatMsgToChat(ConnectedPlayer sentByPlayer, string message, ChatChannel channels)
    {
        var player = sentByPlayer.Script;


        var chatEvent = new ChatEvent
        {
            message    = message,
            modifiers  = (player == null) ? ChatModifier.None : player.GetCurrentChatModifiers(),
            speaker    = (player == null) ? sentByPlayer.Username : player.name,
            position   = ((player == null) ? Vector2.zero : (Vector2)player.gameObject.transform.position),
            channels   = channels,
            originator = sentByPlayer.GameObject
        };

        if (channels.HasFlag(ChatChannel.OOC))
        {
            chatEvent.speaker = sentByPlayer.Username;
            Instance.addChatLogServer.Invoke(chatEvent);
            return;
        }

        //Check if the player is allowed to talk:
        if (player.playerHealth != null)
        {
            if (player.playerHealth.IsCrit || player.playerHealth.IsCardiacArrest)
            {
                if (!player.playerHealth.IsDead)
                {
                    return;
                }
                else
                {
                    channels = ChatChannel.Ghost;
                }
            }
            else
            {
                if (!player.playerHealth.IsDead && !player.IsGhost)
                {
                    {
                        //Control the chat bubble
                        player.playerNetworkActions.CmdToggleChatIcon(true, message, channels);
                    }
                }
            }
        }

        // There could be multiple channels we need to send a message for each.
        // We do this on the server side that local chans can be determined correctly
        foreach (Enum value in Enum.GetValues(channels.GetType()))
        {
            if (channels.HasFlag((ChatChannel)value))
            {
                //Using HasFlag will always return true for flag at value 0 so skip it
                if ((ChatChannel)value == ChatChannel.None)
                {
                    continue;
                }

                if (IsNamelessChan((ChatChannel)value))
                {
                    continue;
                }

                chatEvent.channels = (ChatChannel)value;
                Instance.addChatLogServer.Invoke(chatEvent);
            }
        }
    }
Example #27
0
    public void PropagateChatToClients(ChatEvent chatEvent)
    {
        List <ConnectedPlayer> players = PlayerList.Instance.AllPlayers;

        //Local chat range checks:
        if (chatEvent.channels.HasFlag(ChatChannel.Local) ||
            chatEvent.channels.HasFlag(ChatChannel.Combat) ||
            chatEvent.channels.HasFlag(ChatChannel.Action))
        {
            for (int i = players.Count - 1; i >= 0; i--)
            {
                if (players[i].Script == null)
                {
                    //joined viewer, don't message them
                    players.RemoveAt(i);
                    continue;
                }

                if (players[i].Script.IsGhost && players[i].Script.IsPlayerSemiGhost == false)
                {
                    //send all to ghosts
                    continue;
                }

                if (chatEvent.position == TransformState.HiddenPos)
                {
                    //show messages with no provided position to everyone
                    continue;
                }

                //Send chat to PlayerChatLocation pos, usually just the player object but for AI is its vessel
                var playerPosition = players[i].Script.PlayerChatLocation.OrNull()?.AssumedWorldPosServer()
                                     ?? players[i].Script.gameObject.AssumedWorldPosServer();

                if (Vector2.Distance(chatEvent.position, playerPosition) > 14f)
                {
                    //Player in the list is too far away for local chat, remove them:
                    players.RemoveAt(i);
                }
                else
                {
                    //within range, but check if they are in another room or hiding behind a wall
                    if (MatrixManager.Linecast(chatEvent.position, LayerTypeSelection.Walls
                                               , layerMask, playerPosition).ItHit)
                    {
                        //if it hit a wall remove that player
                        players.RemoveAt(i);
                    }
                }
            }

            //Get NPCs in vicinity
            var npcs = Physics2D.OverlapCircleAll(chatEvent.position, 14f, npcMask);
            foreach (Collider2D coll in npcs)
            {
                var npcPosition = coll.gameObject.AssumedWorldPosServer();
                if (MatrixManager.Linecast(chatEvent.position, LayerTypeSelection.Walls,
                                           layerMask, npcPosition).ItHit == false)
                {
                    //NPC is in hearing range, pass the message on:
                    var mobAi = coll.GetComponent <MobAI>();
                    if (mobAi != null)
                    {
                        mobAi.LocalChatReceived(chatEvent);
                    }
                }
            }
        }

        for (var i = 0; i < players.Count; i++)
        {
            ChatChannel channels = chatEvent.channels;

            if (channels.HasFlag(ChatChannel.Combat) || channels.HasFlag(ChatChannel.Local) ||
                channels.HasFlag(ChatChannel.System) || channels.HasFlag(ChatChannel.Examine) ||
                channels.HasFlag(ChatChannel.Action))
            {
                //Binary check here to avoid speaking in local when speaking on binary
                if (!channels.HasFlag(ChatChannel.Binary) || (players[i].Script.IsGhost && players[i].Script.IsPlayerSemiGhost == false))
                {
                    UpdateChatMessage.Send(players[i].GameObject, channels, chatEvent.modifiers, chatEvent.message, chatEvent.messageOthers,
                                           chatEvent.originator, chatEvent.speaker, chatEvent.stripTags);

                    continue;
                }
            }

            if (players[i].Script == null)
            {
                channels &= ChatChannel.OOC;
            }
            else
            {
                channels &= players[i].Script.GetAvailableChannelsMask(false);
            }

            //if the mask ends up being a big fat 0 then don't do anything
            if (channels != ChatChannel.None)
            {
                UpdateChatMessage.Send(players[i].GameObject, channels, chatEvent.modifiers, chatEvent.message, chatEvent.messageOthers,
                                       chatEvent.originator, chatEvent.speaker, chatEvent.stripTags);
            }
        }

        if (rconManager != null)
        {
            string name = "";
            if ((namelessChannels & chatEvent.channels) != chatEvent.channels)
            {
                name = "<b>[" + chatEvent.channels + "]</b> ";
            }

            RconManager.AddChatLog(name + chatEvent.message);
        }
    }
        protected void Command_Spawn( ChatEvent chatEvent )
        {
            ulong remoteUserId = chatEvent.RemoteUserId;
            List<string> commandParts = CommandParser.GetCommandParts( chatEvent.Message );
            int paramCount = commandParts.Count - 1;

            if ( paramCount > 1 && commandParts[ 1 ].ToLower( ).Equals( "ship" ) )
            {
                if ( commandParts[ 2 ].ToLower( ).Equals( "all" ) )
                {
                }
                if ( commandParts[ 2 ].ToLower( ).Equals( "exports" ) )
                {
                }
                if ( commandParts[ 2 ].ToLower( ).Equals( "cargo" ) )
                {
                    CargoShipManager.Instance.SpawnCargoShipGroup( remoteUserId );
                }
            }
        }
Example #29
0
		public void onChatReceived(ChatEvent eventObj){
			Log(eventObj.getSender() + ":" + eventObj.getMessage());
		}
        protected void Command_SyncSave( ChatEvent chatEvent )
        {
            ulong remoteUserId = chatEvent.RemoteUserId;

            WorldManager.Instance.SaveWorld( );

            SendPrivateChatMessage( remoteUserId, "World has been saved!" );
        }
Example #31
0
    private void PropagateChatToClients(ChatEvent chatEvent)
    {
        List <ConnectedPlayer> players;

        //if (chatEvent.matrix != MatrixInfo.Invalid) //no, bad
        //{
        //get players only on provided matrix
        //players = PlayerList.Instance.GetPlayersOnMatrix(chatEvent.matrix);
        //}
        //else
        //{
        //Try get the matrix first:
        //if (chatEvent.originator != null)
        //{
        //var regiTile = chatEvent.originator.GetComponent<RegisterTile>();
        //if (regiTile != null)
        //{
        //players = PlayerList.Instance.GetPlayersOnMatrix(MatrixManager.Get(regiTile.Matrix));
        //}
        //else
        //{
        //players = PlayerList.Instance.AllPlayers;
        //}
        //}
        //else
        //{
        players = PlayerList.Instance.AllPlayers;
        //}
        //}

        //Local chat range checks:
        if (chatEvent.channels.HasFlag(ChatChannel.Local) || chatEvent.channels.HasFlag(ChatChannel.Combat) ||
            chatEvent.channels.HasFlag(ChatChannel.Action))
        {
            for (int i = players.Count - 1; i >= 0; i--)
            {
                if (players[i].Script == null)
                {
                    //joined viewer, don't message them
                    players.RemoveAt(i);
                    continue;
                }

                if (players[i].Script.IsGhost)
                {
                    //send all to ghosts
                    continue;
                }

                if (chatEvent.position == TransformState.HiddenPos)
                {
                    //show messages with no provided position to everyone
                    continue;
                }

                if (Vector2.Distance(chatEvent.position,
                                     (Vector3)players[i].Script.WorldPos) > 14f)
                {
                    //Player in the list is too far away for local chat, remove them:
                    players.RemoveAt(i);
                }
                else
                {
                    //within range, but check if they are in another room or hiding behind a wall
                    if (Physics2D.Linecast(chatEvent.position,
                                           (Vector3)players[i].Script.WorldPos, layerMask))
                    {
                        //if it hit a wall remove that player
                        players.RemoveAt(i);
                    }
                }
            }

            //Get NPCs in vicinity
            var npcs = Physics2D.OverlapCircleAll(chatEvent.position, 14f, npcMask);
            foreach (Collider2D coll in npcs)
            {
                if (!Physics2D.Linecast(chatEvent.position,
                                        coll.transform.position, layerMask))
                {
                    //NPC is in hearing range, pass the message on:
                    var mobAi = coll.GetComponent <MobAI>();
                    if (mobAi != null)
                    {
                        mobAi.LocalChatReceived(chatEvent);
                    }
                }
            }
        }

        for (var i = 0; i < players.Count; i++)
        {
            ChatChannel channels = chatEvent.channels;

            if (channels.HasFlag(ChatChannel.Combat) || channels.HasFlag(ChatChannel.Local) ||
                channels.HasFlag(ChatChannel.System) || channels.HasFlag(ChatChannel.Examine) ||
                channels.HasFlag(ChatChannel.Action))
            {
                if (!channels.HasFlag(ChatChannel.Binary) || players[i].Script.IsGhost)
                {
                    UpdateChatMessage.Send(players[i].GameObject, channels, chatEvent.modifiers, chatEvent.message, chatEvent.messageOthers,
                                           chatEvent.originator, chatEvent.speaker);

                    continue;
                }
            }

            if (players[i].Script == null)
            {
                channels &= ChatChannel.OOC;
            }
            else
            {
                channels &= players[i].Script.GetAvailableChannelsMask(false);
            }

            //if the mask ends up being a big fat 0 then don't do anything
            if (channels != ChatChannel.None)
            {
                UpdateChatMessage.Send(players[i].GameObject, channels, chatEvent.modifiers, chatEvent.message, chatEvent.messageOthers,
                                       chatEvent.originator, chatEvent.speaker);
            }
        }

        if (rconManager != null)
        {
            string name = "";
            if ((namelessChannels & chatEvent.channels) != chatEvent.channels)
            {
                name = "<b>[" + chatEvent.channels + "]</b> ";
            }

            RconManager.AddChatLog(name + chatEvent.message);
        }
    }
        protected bool ParseChatCommands( string message, ulong remoteUserId = 0 )
        {
            try
            {
                if ( string.IsNullOrEmpty( message ) )
                    return false;

                //Skip if message doesn't have leading forward slash
                if ( message[ 0 ] != '/' )
                    return false;

                List<string> commandParts = CommandParser.GetCommandParts( message );
                if ( commandParts.Count == 0 )
                    return false;

                //Get the base command and strip off the leading slash
                string command = commandParts[ 0 ].ToLower( ).Substring( 1 );
                if ( string.IsNullOrEmpty( command ) )
                    return false;

                //Search for a matching, registered command
                bool foundMatch = false;
                foreach ( ChatCommand chatCommand in m_chatCommands.Keys )
                {
                    try
                    {
                        if ( chatCommand.RequiresAdmin && remoteUserId != 0 && !PlayerManager.Instance.IsUserAdmin( remoteUserId ) )
                            continue;

                        if ( command.Equals( chatCommand.Command.ToLower( ) ) )
                        {
                            ChatEvent chatEvent = new ChatEvent( DateTime.Now, remoteUserId, message );

                            bool discard;
                            PluginManager.HookChatMessage( null, PluginManager.Instance.Plugins, PluginManager.Instance.PluginStates, chatEvent, out discard );

                            if ( !discard )
                                chatCommand.Callback( chatEvent );

                            foundMatch = true;
                            break;
                        }
                    }
                    catch ( Exception ex )
                    {
                        ApplicationLog.BaseLog.Error( ex );
                    }
                }

                return foundMatch;
            }
            catch ( Exception ex )
            {
                ApplicationLog.BaseLog.Error( ex );
                return false;
            }
        }
Example #33
0
 public void AddChatEvent(ChatEvent chatEvent)
 {
     _localEvents.Add(chatEvent);
     //ChatRelay.Instance.RefreshLog();
 }
 public void AddEvent( ChatEvent newEvent )
 {
     m_chatEvents.Add( newEvent );
 }
Example #35
0
        public override bool Invoke(MessageContext context)
        {
            if (context.Direction == MessageDirection.ClientToServer)
            {
                throw new GameProtocolViolationException(context.Client, "Client is not allowed to send SID_CHATEVENT");
            }

            var chatEvent = (ChatEvent)context.Arguments["chatEvent"];

            Buffer = chatEvent.ToByteArray(context.Client.ProtocolType.Type);

            Logging.WriteLine(Logging.LogLevel.Debug, Logging.LogType.Client_Game, context.Client.RemoteEndPoint, string.Format("[{0}] SID_CHATEVENT: {1} ({2:D} bytes)", Common.DirectionToString(context.Direction), ChatEvent.EventIdToString(chatEvent.EventId), 4 + Buffer.Length));

            return(true);
        }
        public void SendPublicChatMessage( string message )
        {
            if ( !MySandboxGameWrapper.IsGameStarted )
                return;
            if ( string.IsNullOrEmpty( message ) )
                return;

            bool commandParsed = ParseChatCommands( message );

            try
            {
                if ( !commandParsed && message[ 0 ] != '/' )
                {
                    Object chatMessageStruct = CreateChatMessageStruct( message );
                    List<ulong> connectedPlayers = PlayerManager.Instance.ConnectedPlayers;
                    foreach ( ulong remoteUserId in connectedPlayers )
                    {
                        if ( !remoteUserId.ToString( ).StartsWith( "9009" ) )
                            ServerNetworkManager.Instance.SendStruct( remoteUserId, chatMessageStruct, chatMessageStruct.GetType( ) );

                        ChatEvent chatEvent = new ChatEvent( ChatEventType.OnChatSent, DateTime.Now, 0, remoteUserId, message, 0 );
                        Instance.AddEvent( chatEvent );
                    }
                    m_chatMessages.Add( string.Format( "Server: {0}", message ) );
                    ApplicationLog.ChatLog.Info( string.Format( "Chat - Server: {0}", message ) );
                }

                //Send a loopback chat event for server-sent messages
                ChatEvent selfChatEvent = new ChatEvent( ChatEventType.OnChatReceived, DateTime.Now, 0, 0, message, 0 );
                Instance.AddEvent( selfChatEvent );

                m_resourceLock.AcquireExclusive( );
                m_chatHistory.Add( selfChatEvent );
                OnChatMessage( 0, "Server", message );
                m_resourceLock.ReleaseExclusive( );
            }
            catch ( Exception ex )
            {
                ApplicationLog.BaseLog.Error( ex );
            }
        }
Example #37
0
    /// <summary>
    /// Send a Chat Msg from a player to the selected Chat Channels
    /// Server only
    /// </summary>
    public static void AddChatMsgToChat(ConnectedPlayer sentByPlayer, string message, ChatChannel channels)
    {
        message = AutoMod.ProcessChatServer(sentByPlayer, message);
        if (string.IsNullOrWhiteSpace(message))
        {
            return;
        }

        var player = sentByPlayer.Script;

        // The exact words that leave the player's mouth (or that are narrated). Already includes HONKs, stutters, etc.
        // This step is skipped when speaking in the OOC channel.
        (string message, ChatModifier chatModifiers)processedMessage = (string.Empty, ChatModifier.None);          // Placeholder values
        bool isOOC = channels.HasFlag(ChatChannel.OOC);

        if (!isOOC)
        {
            processedMessage = ProcessMessage(sentByPlayer, message);
        }

        var chatEvent = new ChatEvent
        {
            message    = isOOC ? message : processedMessage.message,
            modifiers  = (player == null) ? ChatModifier.None : processedMessage.chatModifiers,
            speaker    = (player == null) ? sentByPlayer.Username : player.name,
            position   = (player == null) ? TransformState.HiddenPos : player.WorldPos,
            channels   = channels,
            originator = sentByPlayer.GameObject
        };

        if (channels.HasFlag(ChatChannel.OOC))
        {
            chatEvent.speaker = sentByPlayer.Username;

            var isAdmin = PlayerList.Instance.IsAdmin(sentByPlayer.UserId);

            if (isAdmin)
            {
                chatEvent.speaker = "[Admin] " + chatEvent.speaker;
            }

            if (Instance.OOCMute && !isAdmin)
            {
                return;
            }

            Instance.addChatLogServer.Invoke(chatEvent);

            //Sends OOC message to a discord webhook
            DiscordWebhookMessage.Instance.AddWebHookMessageToQueue(DiscordWebhookURLs.DiscordWebhookOOCURL, message, chatEvent.speaker, ServerData.ServerConfig.DiscordWebhookOOCMentionsID);

            if (!ServerData.ServerConfig.DiscordWebhookSendOOCToAllChat)
            {
                return;
            }

            //Send it to All chat
            DiscordWebhookMessage.Instance.AddWebHookMessageToQueue(DiscordWebhookURLs.DiscordWebhookAllChatURL, $"[{ChatChannel.OOC}]  {message}\n", chatEvent.speaker);

            return;
        }

        // TODO the following code uses player.playerHealth, but ConciousState would be more appropriate.
        // Check if the player is allowed to talk:
        if (player != null && player.playerHealth != null)
        {
            if (!player.IsDeadOrGhost && player.mind.IsMiming && !processedMessage.chatModifiers.HasFlag(ChatModifier.Emote))
            {
                AddWarningMsgFromServer(sentByPlayer.GameObject, "You can't talk because you made a vow of silence.");
                return;
            }

            if (player.playerHealth.IsCrit || player.playerHealth.IsCardiacArrest)
            {
                if (!player.playerHealth.IsDead)
                {
                    return;
                }
                else
                {
                    chatEvent.channels = ChatChannel.Ghost;
                }
            }
            else if (!player.playerHealth.IsDead && !player.IsGhost)
            {
                //Control the chat bubble
                player.playerNetworkActions.CmdToggleChatIcon(true, processedMessage.message, channels, processedMessage.chatModifiers);
            }
        }

        InvokeChatEvent(chatEvent);
    }
Example #38
0
    private void PropagateChatToClients(ChatEvent chatEvent)
    {
        List <ConnectedPlayer> players;

        if (chatEvent.matrix != MatrixInfo.Invalid)
        {
            //get players only on provided matrix
            players = PlayerList.Instance.GetPlayersOnMatrix(chatEvent.matrix);
        }
        else
        {
            players = PlayerList.Instance.AllPlayers;
        }

        //Local chat range checks:
        if (chatEvent.channels == ChatChannel.Local || chatEvent.channels == ChatChannel.Combat ||
            chatEvent.channels == ChatChannel.Action)
        {
            //			var speaker = PlayerList.Instance.Get(chatEvent.speaker);
            RaycastHit2D hit;
            LayerMask    layerMask = LayerMask.GetMask("Walls", "Door Closed");
            for (int i = 0; i < players.Count(); i++)
            {
                if (Vector2.Distance(chatEvent.position,                 //speaker.GameObject.transform.position,
                                     players[i].GameObject.transform.position) > 14f)
                {
                    //Player in the list is too far away for local chat, remove them:
                    players.Remove(players[i]);
                }
                else
                {
                    //within range, but check if they are in another room or hiding behind a wall
                    if (Physics2D.Linecast(chatEvent.position,                     //speaker.GameObject.transform.position,
                                           players[i].GameObject.transform.position, layerMask))
                    {
                        //if it hit a wall remove that player
                        players.Remove(players[i]);
                    }
                }
            }

            //Get NPCs in vicinity
            var npcMask = LayerMask.GetMask("NPC");
            var npcs    = Physics2D.OverlapCircleAll(chatEvent.position, 14f, npcMask);
            foreach (Collider2D coll in npcs)
            {
                if (!Physics2D.Linecast(chatEvent.position,
                                        coll.transform.position, layerMask))
                {
                    //NPC is in hearing range, pass the message on:
                    var mobAi = coll.GetComponent <MobAI>();
                    if (mobAi != null)
                    {
                        mobAi.LocalChatReceived(chatEvent);
                    }
                }
            }
        }

        for (var i = 0; i < players.Count; i++)
        {
            ChatChannel channels = chatEvent.channels;

            if (channels.HasFlag(ChatChannel.Combat) || channels.HasFlag(ChatChannel.Local) ||
                channels.HasFlag(ChatChannel.System) || channels.HasFlag(ChatChannel.Examine) ||
                channels.HasFlag(ChatChannel.Action))
            {
                if (!channels.HasFlag(ChatChannel.Binary))
                {
                    UpdateChatMessage.Send(players[i].GameObject, channels, chatEvent.modifiers, chatEvent.message, chatEvent.messageOthers,
                                           chatEvent.originator, chatEvent.speaker);
                    continue;
                }
            }

            if (players[i].Script == null)
            {
                channels &= ChatChannel.OOC;
            }
            else
            {
                channels &= players[i].Script.GetAvailableChannelsMask(false);
            }

            //if the mask ends up being a big fat 0 then don't do anything
            if (channels != ChatChannel.None)
            {
                UpdateChatMessage.Send(players[i].GameObject, channels, chatEvent.modifiers, chatEvent.message, chatEvent.messageOthers,
                                       chatEvent.originator, chatEvent.speaker);
            }
        }

        if (RconManager.Instance != null)
        {
            string name = "";
            if ((namelessChannels & chatEvent.channels) != chatEvent.channels)
            {
                name = "<b>[" + chatEvent.channels + "]</b> ";
            }

            RconManager.AddChatLog(name + chatEvent.message);
        }
    }
        protected void Command_Stop( ChatEvent chatEvent )
        {
            ulong remoteUserId = chatEvent.RemoteUserId;
            List<string> commandParts = CommandParser.GetCommandParts( chatEvent.Message );
            int paramCount = commandParts.Count - 1;

            if ( paramCount != 1 )
                return;

            if ( commandParts[ 1 ].ToLower( ).Equals( "all" ) )
            {
                List<BaseEntity> entities = SectorObjectManager.Instance.GetTypedInternalData<BaseEntity>( );
                int entitiesStoppedCount = 0;
                foreach ( BaseEntity entity in entities )
                {
                    double linear = Math.Round( ( (Vector3)entity.LinearVelocity ).LengthSquared( ), 1 );
                    double angular = Math.Round( ( (Vector3)entity.AngularVelocity ).LengthSquared( ), 1 );

                    if ( linear > 0 || angular > 0 )
                    {
                        entity.LinearVelocity = Vector3.Zero;
                        entity.AngularVelocity = Vector3.Zero;

                        entitiesStoppedCount++;
                    }
                }
                SendPrivateChatMessage( remoteUserId, string.Format( "{0} entities are no longer moving or rotating", entitiesStoppedCount ) );
            }
            else
            {
                string rawEntityId = commandParts[ 1 ];

                try
                {
                    long entityId = long.Parse( rawEntityId );

                    List<BaseEntity> entities = SectorObjectManager.Instance.GetTypedInternalData<BaseEntity>( );
                    foreach ( BaseEntity entity in entities )
                    {
                        if ( entity.EntityId != entityId )
                            continue;

                        entity.LinearVelocity = Vector3.Zero;
                        entity.AngularVelocity = Vector3.Zero;

                        SendPrivateChatMessage( remoteUserId, string.Format( "Entity '{0}' is no longer moving or rotating", entity.EntityId ) );
                    }
                }
                catch ( Exception ex )
                {
                    ApplicationLog.BaseLog.Error( ex );
                }
            }
        }
Example #40
0
 /// <summary>
 /// Called on the server whenever a localchat event has been heard
 /// by the NPC
 /// </summary>
 public virtual void LocalChatReceived(ChatEvent chatEvent)
 {
 }
        protected void Command_Teleport( ChatEvent chatEvent )
        {
            ulong remoteUserId = chatEvent.RemoteUserId;
            List<string> commandParts = CommandParser.GetCommandParts( chatEvent.Message );
            int paramCount = commandParts.Count - 1;

            if ( paramCount == 2 )
            {
                string rawEntityId = commandParts[ 1 ];
                string rawPosition = commandParts[ 2 ];

                try
                {
                    long entityId = long.Parse( rawEntityId );

                    string[ ] rawCoordinateValues = rawPosition.Split( ',' );
                    if ( rawCoordinateValues.Length < 3 )
                        return;

                    float x = float.Parse( rawCoordinateValues[ 0 ] );
                    float y = float.Parse( rawCoordinateValues[ 1 ] );
                    float z = float.Parse( rawCoordinateValues[ 2 ] );

                    List<BaseEntity> entities = SectorObjectManager.Instance.GetTypedInternalData<BaseEntity>( );
                    foreach ( BaseEntity entity in entities )
                    {
                        if ( entity.EntityId != entityId )
                            continue;

                        Vector3D newPosition = new Vector3D( x, y, z );
                        entity.Position = newPosition;

                        SendPrivateChatMessage( remoteUserId, string.Format( "Entity '{0}' has been moved to '{1}'", entity.EntityId, newPosition ) );
                    }
                }
                catch ( Exception ex )
                {
                    ApplicationLog.BaseLog.Error( ex );
                }
            }
        }
Example #42
0
    private void onChatServerMsg(EventBase e)
    {
        ChatEvent evt = (ChatEvent)e;

        PushMessageCache(evt.channel_type, evt.name, evt.msg);
    }
        protected void ReceiveChatMessage( ulong remoteUserId, string message, ChatEntryTypeEnum entryType )
        {
            string playerName = PlayerMap.Instance.GetPlayerNameFromSteamId( remoteUserId );

            bool commandParsed = ParseChatCommands( message, remoteUserId );

            if ( !commandParsed && entryType == ChatEntryTypeEnum.ChatMsg )
            {
                m_chatMessages.Add( string.Format( "{0}: {1}", playerName, message ) );
                ApplicationLog.ChatLog.Info( "Chat - Client '{0}': {1}", playerName, message );
            }

            ChatEvent chatEvent = new ChatEvent( ChatEventType.OnChatReceived, DateTime.Now, remoteUserId, 0, message, 0 );
            Instance.AddEvent( chatEvent );

            m_resourceLock.AcquireExclusive( );
            m_chatHistory.Add( chatEvent );
            OnChatMessage( remoteUserId, playerName, message );
            m_resourceLock.ReleaseExclusive( );
        }
Example #44
0
        private object IOnPlayerChat(ChatEvent evt)
        {
            if (evt.Message.Trim().Length <= 1)
            {
                return(true);
            }

            BoltEntity entity = BoltNetwork.FindEntity(evt.Sender);

            if (entity == null)
            {
                return(null);
            }

            IPlayer player = entity.IPlayer;

            if (player == null)
            {
                return(null);
            }

            // Set player name if available
            player.Name = entity.GetState <IPlayerState>().name?.Sanitize() ?? (!string.IsNullOrEmpty(player.Name) ? player.Name : "Unnamed"); // TODO: Localization

            // Is it a chat command?
            string str = evt.Message.Substring(0, 1);

            if (!str.Equals("/") && !str.Equals("!"))
            {
                // Call hooks for plugins
                object chatSpecific  = Interface.Call("OnPlayerChat", entity, evt.Message);
                object chatCovalence = Interface.Call("OnUserChat", player, evt.Message);
                object canChat       = chatSpecific is null ? chatCovalence : chatSpecific;
                if (canChat != null)
                {
                    return(true);
                }

                Interface.Oxide.LogInfo($"[Chat] {player.Name}: {evt.Message}");
                return(null);
            }

            // Replace ! with / for Covalence handling
            evt.Message = '/' + evt.Message.Substring(1);

            // Parse the command
            ParseCommand(evt.Message.Substring(1), out string cmd, out string[] args);
            if (cmd == null)
            {
                return(null);
            }

            // Call hooks for plugins
            object commandSpecific  = Interface.Call("OnPlayerCommand", entity, cmd, args);
            object commandCovalence = Interface.Call("OnUserCommand", player, cmd, args);
            object canBlock         = commandSpecific is null ? commandCovalence : commandSpecific;

            if (canBlock != null)
            {
                return(true);
            }

            // Is this a covalence command?
            if (Covalence.CommandSystem.HandleChatMessage(player, evt.Message))
            {
                return(true);
            }

            // TODO: Handle non-universal commands

            player.Reply(string.Format(lang.GetMessage("UnknownCommand", this, player.Id), cmd));
            return(true);
        }
        public void SendPrivateChatMessage( ulong remoteUserId, string message )
        {
            if ( !MySandboxGameWrapper.IsGameStarted )
                return;
            if ( string.IsNullOrEmpty( message ) )
                return;

            try
            {
                if ( remoteUserId != 0 )
                {
                    Object chatMessageStruct = CreateChatMessageStruct( message );
                    ServerNetworkManager.Instance.SendStruct( remoteUserId, chatMessageStruct, chatMessageStruct.GetType( ) );
                }

                m_chatMessages.Add( string.Format( "Server: {0}", message ) );

                ApplicationLog.ChatLog.Info( string.Format( "Chat - Server: {0}", message ) );

                ChatEvent chatEvent = new ChatEvent( ChatEventType.OnChatSent, DateTime.Now, 0, remoteUserId, message, 0 );
                Instance.AddEvent( chatEvent );

                m_resourceLock.AcquireExclusive( );
                m_chatHistory.Add( chatEvent );
                OnChatMessage( 0, "Server", message );
                m_resourceLock.ReleaseExclusive( );
            }
            catch ( Exception ex )
            {
                ApplicationLog.BaseLog.Error( ex );
            }
        }
Example #46
0
        /// <inheritdoc/>
        public ValueTask <ChatEventResult> ProcessCommandAsync(TextDeconstructionInformation info, ChatEvent originalChatEvent, IAsyncResponder responder, IReadOnlyDictionary <string, string> settings)
        {
            var notify             = info.TextSentanceChunk.StartsWith("Notify", StringComparison.InvariantCultureIgnoreCase);
            var departmentValue    = info.Entities.GetValueOrDefault(nameof(Department))?.FirstOrDefault()?.Replace(". ", ".", StringComparison.InvariantCulture);
            var customersValue     = info.Entities.GetValueOrDefault(nameof(Customer), new string[0]);
            var period             = OpenAirText.GetPeriod(info.Entities.GetValueOrDefault("Period")?.FirstOrDefault());
            var state              = OpenAirText.GetTimesheetState(info.Entities.GetValueOrDefault("State")?.FirstOrDefault());
            var today              = DateTime.Today;
            var date               = period == OpenAirPeriodTypes.LastWeek ? today.AddDays(-((int)today.DayOfWeek + 1)) : today;
            var senderEmail        = originalChatEvent.Message.Sender.Email;
            var customersSetting   = settings.GetAsArray(Default.DefaultExcludedClientKey);
            var customersToExclude = customersValue.Concat(customersSetting ?? new string[0]).ToArray();
            var notifyByEmail      = settings.GetValueOrDefault(Default.NotifyByEmailKey)?.ToLowerInvariant() == "true";

            if (state == TimesheetStates.None)
            {
                return(new ValueTask <ChatEventResult>(
                           new ChatEventResult("Provide a state of the time sheets, like unsubmitted or unapproved!")));
            }

            NotifyAsync(date, state, senderEmail, customersToExclude, departmentValue, notify, notifyByEmail, new GoogleChatAddress(originalChatEvent), responder as IHangoutsChatConnector);

            return(new ValueTask <ChatEventResult>(
                       new ChatEventResult(text: null)));
        }
        protected void Command_Clear( ChatEvent chatEvent )
        {
            ulong remoteUserId = chatEvent.RemoteUserId;
            List<string> commandParts = CommandParser.GetCommandParts( chatEvent.Message );
            int paramCount = commandParts.Count - 1;

            if ( paramCount != 1 )
                return;

            List<CubeGridEntity> cubeGrids = SectorObjectManager.Instance.GetTypedInternalData<CubeGridEntity>( );
            int queueCount = 0;
            foreach ( var cubeGrid in cubeGrids )
            {
                foreach ( CubeBlockEntity cubeBlock in cubeGrid.CubeBlocks )
                {
                    if ( commandParts[ 1 ].ToLower( ).Equals( "productionqueue" ) && cubeBlock is ProductionBlockEntity )
                    {
                        ProductionBlockEntity block = (ProductionBlockEntity)cubeBlock;
                        block.ClearQueue( );
                        queueCount++;
                    }
                    if ( commandParts[ 1 ].ToLower( ).Equals( "refineryqueue" ) && cubeBlock is RefineryEntity )
                    {
                        RefineryEntity block = (RefineryEntity)cubeBlock;
                        block.ClearQueue( );
                        queueCount++;
                    }
                    if ( commandParts[ 1 ].ToLower( ).Equals( "assemblerqueue" ) && cubeBlock is AssemblerEntity )
                    {
                        AssemblerEntity block = (AssemblerEntity)cubeBlock;
                        block.ClearQueue( );
                        queueCount++;
                    }
                }
            }

            SendPrivateChatMessage( remoteUserId, "Cleared the production queue of " + queueCount + " blocks" );
        }
    private void UpdateClientChat(string message, ChatChannel channels)
    {
        ChatEvent chatEvent = new ChatEvent(message, channels, true);

        ChatLog.Add(chatEvent);
    }
        protected void Command_Export( ChatEvent chatEvent )
        {
            ulong remoteUserId = chatEvent.RemoteUserId;
            List<string> commandParts = CommandParser.GetCommandParts( chatEvent.Message );
            int paramCount = commandParts.Count - 1;

            if ( paramCount == 1 )
            {
                string rawEntityId = commandParts[ 1 ];

                try
                {
                    long entityId = long.Parse( rawEntityId );

                    List<BaseEntity> entities = SectorObjectManager.Instance.GetTypedInternalData<BaseEntity>( );
                    foreach ( BaseEntity entity in entities )
                    {
                        if ( entity.EntityId != entityId )
                            continue;

                        string modPath = MyFileSystem.ModsPath;
                        if ( !Directory.Exists( modPath ) )
                            break;

                        string fileName = entity.Name.ToLower( );
                        Regex rgx = new Regex( "[^a-zA-Z0-9]" );
                        string cleanFileName = rgx.Replace( fileName, string.Empty );

                        string exportPath = Path.Combine( modPath, "Exports" );
                        if ( !Directory.Exists( exportPath ) )
                            Directory.CreateDirectory( exportPath );
                        FileInfo exportFile = new FileInfo( Path.Combine( exportPath, cleanFileName + ".sbc" ) );
                        entity.Export( exportFile );

                        SendPrivateChatMessage( remoteUserId, string.Format( "Entity '{0}' has been exported to Mods/Exports", entity.EntityId ) );
                    }
                }
                catch ( Exception ex )
                {
                    ApplicationLog.BaseLog.Error( ex );
                }
            }
        }
 public void AddToChatLogServer(ChatEvent chatEvent)
 {
     PropagateChatToClients(chatEvent);
     RefreshLog();
 }
        protected void Command_Import( ChatEvent chatEvent )
        {
            List<string> commandParts = CommandParser.GetCommandParts( chatEvent.Message );
            int paramCount = commandParts.Count - 1;

            if ( paramCount == 1 )
            {
                try
                {
                    string fileName = commandParts[ 1 ];
                    Regex rgx = new Regex( "[^a-zA-Z0-9]" );
                    string cleanFileName = rgx.Replace( fileName, string.Empty );

                    string modPath = MyFileSystem.ModsPath;
                    if ( Directory.Exists( modPath ) )
                    {
                        string exportPath = Path.Combine( modPath, "Exports" );
                        if ( Directory.Exists( exportPath ) )
                        {
                            FileInfo importFile = new FileInfo( Path.Combine( exportPath, cleanFileName ) );
                            if ( importFile.Exists )
                            {
                                string objectBuilderTypeName = string.Empty;
                                using ( XmlReader reader = XmlReader.Create( importFile.OpenText( ) ) )
                                {
                                    while ( reader.Read( ) )
                                    {
                                        if ( reader.NodeType == XmlNodeType.XmlDeclaration )
                                            continue;

                                        if ( reader.NodeType != XmlNodeType.Element )
                                            continue;

                                        objectBuilderTypeName = reader.Name;
                                        break;
                                    }
                                }

                                if ( string.IsNullOrEmpty( objectBuilderTypeName ) )
                                    return;

                                switch ( objectBuilderTypeName )
                                {
                                    case "MyObjectBuilder_CubeGrid":
                                        CubeGridEntity cubeGrid = new CubeGridEntity( importFile );
                                        SectorObjectManager.Instance.AddEntity( cubeGrid );
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }
                    }
                }
                catch ( Exception ex )
                {
                    ApplicationLog.BaseLog.Error( ex );
                }
            }
        }
Example #52
0
 public override void LocalChatReceived(ChatEvent chatEvent)
 {
     ProcessLocalChat(chatEvent);
     base.LocalChatReceived(chatEvent);
 }
        protected void Command_List( ChatEvent chatEvent )
        {
            ulong remoteUserId = chatEvent.RemoteUserId;
            List<string> commandParts = CommandParser.GetCommandParts( chatEvent.Message );
            int paramCount = commandParts.Count - 1;

            if ( paramCount != 1 )
                return;

            if ( commandParts[ 1 ].ToLower( ).Equals( "all" ) )
            {
                List<BaseEntity> entities = SectorObjectManager.Instance.GetTypedInternalData<BaseEntity>( );
                ApplicationLog.BaseLog.Info( "Total entities: '" + entities.Count + "'" );

                SendPrivateChatMessage( remoteUserId, "Total entities: '" + entities.Count + "'" );
            }
            if ( commandParts[ 1 ].ToLower( ).Equals( "cubegrid" ) )
            {
                List<CubeGridEntity> entities = SectorObjectManager.Instance.GetTypedInternalData<CubeGridEntity>( );
                ApplicationLog.BaseLog.Info( "Cubegrid entities: '" + entities.Count + "'" );

                SendPrivateChatMessage( remoteUserId, "Cubegrid entities: '" + entities.Count + "'" );
            }
            if ( commandParts[ 1 ].ToLower( ).Equals( "character" ) )
            {
                List<CharacterEntity> entities = SectorObjectManager.Instance.GetTypedInternalData<CharacterEntity>( );
                ApplicationLog.BaseLog.Info( "Character entities: '" + entities.Count + "'" );

                SendPrivateChatMessage( remoteUserId, "Character entities: '" + entities.Count + "'" );
            }
            if ( commandParts[ 1 ].ToLower( ).Equals( "voxelmap" ) )
            {
                List<VoxelMap> entities = SectorObjectManager.Instance.GetTypedInternalData<VoxelMap>( );
                ApplicationLog.BaseLog.Info( "Voxelmap entities: '" + entities.Count + "'" );

                SendPrivateChatMessage( remoteUserId, "Voxelmap entities: '" + entities.Count + "'" );
            }
            if ( commandParts[ 1 ].ToLower( ).Equals( "meteor" ) )
            {
                List<Meteor> entities = SectorObjectManager.Instance.GetTypedInternalData<Meteor>( );
                ApplicationLog.BaseLog.Info( "Meteor entities: '" + entities.Count + "'" );

                SendPrivateChatMessage( remoteUserId, "Meteor entities: '" + entities.Count + "'" );
            }
            if ( commandParts[ 1 ].ToLower( ).Equals( "floatingobject" ) )
            {
                List<FloatingObject> entities = SectorObjectManager.Instance.GetTypedInternalData<FloatingObject>( );
                ApplicationLog.BaseLog.Info( "Floating object entities: '" + entities.Count + "'" );

                SendPrivateChatMessage( remoteUserId, "Floating object entities: '" + entities.Count + "'" );
            }
        }
Example #54
0
    /// <summary>
    /// Send a Chat Msg from a player to the selected Chat Channels
    /// Server only
    /// </summary>
    public static void AddChatMsgToChat(ConnectedPlayer sentByPlayer, string message, ChatChannel channels)
    {
        message = AutoMod.ProcessChatServer(sentByPlayer, message);
        if (string.IsNullOrWhiteSpace(message))
        {
            return;
        }

        var player = sentByPlayer.Script;

        //Check to see whether this player is allowed to send on the chosen channels
        if (player != null)
        {
            channels &= player.GetAvailableChannelsMask(true);
        }
        else
        {
            //If player is null, must be in lobby therefore lock to OOC
            channels = ChatChannel.OOC;
        }

        if (channels == ChatChannel.None)
        {
            return;
        }

        // The exact words that leave the player's mouth (or that are narrated). Already includes HONKs, stutters, etc.
        // This step is skipped when speaking in the OOC channel.
        (string message, ChatModifier chatModifiers)processedMessage = (string.Empty, ChatModifier.None);          // Placeholder values
        bool isOOC = channels.HasFlag(ChatChannel.OOC);

        if (!isOOC)
        {
            processedMessage = ProcessMessage(sentByPlayer, message);
        }

        var chatEvent = new ChatEvent
        {
            message    = isOOC ? message : processedMessage.message,
            modifiers  = (player == null) ? ChatModifier.None : processedMessage.chatModifiers,
            speaker    = (player == null) ? sentByPlayer.Username : player.playerName,
            position   = (player == null) ? TransformState.HiddenPos : player.PlayerChatLocation.AssumedWorldPosServer(),
            channels   = channels,
            originator = (player == null) ? sentByPlayer.GameObject : player.PlayerChatLocation
        };

        if (channels.HasFlag(ChatChannel.OOC))
        {
            chatEvent.speaker = StripAll(sentByPlayer.Username);

            var isAdmin = PlayerList.Instance.IsAdmin(sentByPlayer.UserId);

            if (isAdmin)
            {
                chatEvent.speaker = "<color=red>[A]</color> " + chatEvent.speaker;
            }
            else if (PlayerList.Instance.IsMentor(sentByPlayer.UserId))
            {
                chatEvent.speaker = "<color=#6400ff>[M]</color> " + chatEvent.speaker;
            }

            if (Instance.OOCMute && !isAdmin)
            {
                return;
            }

            //http/https links in OOC chat
            if (isAdmin || !GameManager.Instance.AdminOnlyHtml)
            {
                if (htmlRegex.IsMatch(chatEvent.message))
                {
                    var messageParts = chatEvent.message.Split(' ');

                    var builder = new StringBuilder();

                    foreach (var part in messageParts)
                    {
                        if (!htmlRegex.IsMatch(part))
                        {
                            builder.Append(part);
                            builder.Append(" ");
                            continue;
                        }

                        builder.Append($"<link={part}><color=blue>{part}</color></link> ");
                    }

                    chatEvent.message = builder.ToString();

                    //TODO have a config file available to whitelist/blacklist links if all players are allowed to post links
                    //disables client side tag protection to allow <link=></link> tag
                    chatEvent.stripTags = false;
                }
            }

            ChatRelay.Instance.PropagateChatToClients(chatEvent);

            var strippedSpeaker = StripTags(chatEvent.speaker);

            //Sends OOC message to a discord webhook
            DiscordWebhookMessage.Instance.AddWebHookMessageToQueue(DiscordWebhookURLs.DiscordWebhookOOCURL, message, strippedSpeaker, ServerData.ServerConfig.DiscordWebhookOOCMentionsID);

            if (!ServerData.ServerConfig.DiscordWebhookSendOOCToAllChat)
            {
                return;
            }

            //Send it to All chat
            DiscordWebhookMessage.Instance.AddWebHookMessageToQueue(DiscordWebhookURLs.DiscordWebhookAllChatURL, $"[{ChatChannel.OOC}]  {message}\n", strippedSpeaker);

            return;
        }

        // TODO the following code uses player.playerHealth, but ConciousState would be more appropriate.
        // Check if the player is allowed to talk:
        if (player != null)
        {
            if (player.playerHealth != null)
            {
                if (!player.IsDeadOrGhost && player.mind.IsMiming && !processedMessage.chatModifiers.HasFlag(ChatModifier.Emote))
                {
                    AddWarningMsgFromServer(sentByPlayer.GameObject, "You can't talk because you made a vow of silence.");
                    return;
                }

                if (player.playerHealth.IsCrit)
                {
                    if (!player.playerHealth.IsDead)
                    {
                        return;
                    }
                    else
                    {
                        chatEvent.channels = ChatChannel.Ghost;
                    }
                }
                else if (!player.playerHealth.IsDead && !player.IsGhost)
                {
                    //Control the chat bubble
                    player.playerNetworkActions.ServerToggleChatIcon(true, processedMessage.message, channels, processedMessage.chatModifiers);
                }
            }
        }

        InvokeChatEvent(chatEvent);
    }
 public void onChatReceived(ChatEvent eventObj)
 {
     Log(eventObj.getSender() + " said " + eventObj.getMessage());
     m_apppwarp.onMsg(eventObj.getSender(), eventObj.getMessage());
 }
 public void onChatReceived(ChatEvent eventObj)
 {
 }
Example #57
0
 public BoltEntity PlayerFromEvent(ChatEvent e) => Scene.SceneTracker.allPlayerEntities.FirstOrDefault(ent => ent.networkId == e.Sender);
Example #58
0
 private void AddToChatLogServer(ChatEvent chatEvent)
 {
     PropagateChatToClients(chatEvent);
 }
 public void onChatReceived(ChatEvent eventObj)
 {
     //_game_page.showResult("chat from " + eventObj.getSender() + " msg " + eventObj.getMessage() + " id "+eventObj.getLocationId() + eventObj.isLocationLobby());
     //WarpClient.GetInstance().GetLiveLobbyInfo();
 }
Example #60
0
        public static void On_Chat(ConsoleSystem.Arg arg)
        {
            if (arg.ArgsStr.StartsWith("\"/") && !arg.ArgsStr.StartsWith("\"/ "))
            {
                On_Command(arg);
                return;
            }

            if (!ConVar.Chat.enabled)
            {
                arg.ReplyWith("Chat is disabled.");
            }
            else
            {
                if (arg.ArgsStr == "\"\"")
                {
                    return;
                }

                BasePlayer basePlayer = arg.Player();
                if (!basePlayer)
                {
                    return;
                }

                ChatEvent pChat = new ChatEvent(Server.GetPlayer(basePlayer), arg);

                string str = arg.GetString(0, "text");

                if (str.Length > 128)
                {
                    str = str.Substring(0, 128);
                }

                if (str.Length <= 0)
                {
                    return;
                }


                if (ConVar.Chat.serverlog)
                {
                    ServerConsole.PrintColoured(new object[] {
                        ConsoleColor.DarkYellow,
                        basePlayer.displayName + ": ",
                        ConsoleColor.DarkGreen,
                        str
                    });
                    ConVar.Server.Log("Log.Chat.txt", string.Format("{0}/{1}: {2}\r\n", basePlayer.userID, basePlayer.displayName, str));
                    Debug.Log(string.Format("[CHAT] {0}: {1}", basePlayer.displayName, str));
                }

                string arg2 = "#5af";
                if (basePlayer.IsAdmin())
                {
                    arg2 = "#af5";
                }

                if (DeveloperList.IsDeveloper(basePlayer))
                {
                    arg2 = "#fa5";
                }

                OnNext("On_Chat", pChat);

                string text2 = string.Format("<color={2}>{0}</color>: {1}", basePlayer.displayName.Replace('<', '[').Replace('>', ']'), pChat.FinalText, arg2);

                if (pChat.FinalText != "")
                {
                    Logger.ChatLog(pChat.BroadcastName, pChat.OriginalText);
                    arg.ReplyWith(pChat.Reply);

                    if (ConVar.Server.globalchat)
                    {
                        ConsoleSystem.Broadcast("chat.add", basePlayer.userID, text2, 1);
                    }
                    else
                    {
                        float num = 2500;
                        foreach (Connection current in Net.sv.connections)
                        {
                            if (current.player != null)
                            {
                                float sqrMagnitude = (current.player.transform.position - basePlayer.transform.position).sqrMagnitude;
                                if (sqrMagnitude <= num)
                                {
                                    ConsoleSystem.SendClientCommand(current, "chat.add", basePlayer.userID, text2, Mathf.Clamp01(num - sqrMagnitude + 0.2f));
                                }
                            }
                        }
                    }
                }
            }
        }