Exemple #1
0
    def __init__(self, uniqueid):
        self._uniqueid = uniqueid
        self._races = _RaceContainer(self)
        self._items = _ItemContainer(self)
        self._userid = None
        self._index = None
        self._player = None
        self._ready = False
        self._is_bot = uniqueid.startswith('BOT_')
        self._privileges = privileges['players'].get(uniqueid, {})

        self._id = None
        self._name = None
        self._current_race = None
        self._lastconnect = None

        self.data = {}

        try:
            self._index = index_from_uniqueid(uniqueid)
        except ValueError:
            name = None
        else:
            self._userid = userid_from_index(self._index)

            Player._cache_userids[self.userid] = self
            Player._cache_indexes[self.index] = self

            name = playerinfo_from_index(self.index).name

        if not _thread.unloading:
            database_manager.execute('player get', (uniqueid, ),
                                     callback=self._query_get_player,
                                     name=name)
Exemple #2
0
def on_client_disconnect(index):
    # This can occur if the player leaves the server before OnClientActive was called
    try:
        uniqueid = uniqueid_from_playerinfo(playerinfo_from_index(index))
    except ValueError:
        return

    wcsplayer = Player(uniqueid)

    # If we failed to get the correct uniqueid for some reason, do not proceed
    assert wcsplayer.uniqueid == uniqueid, (wcsplayer.uniqueid, uniqueid)

    OnPlayerDelete.manager.notify(wcsplayer)

    for delay in _delays.pop(wcsplayer.userid, []):
        delay.cancel()

    del Player._cache_userids[wcsplayer.userid]
    del Player._cache_indexes[wcsplayer.index]

    if wcsplayer.ready:
        wcsplayer._lastconnect = time()
        wcsplayer.save()

    database_manager.callback(wcsplayer._query_save)
Exemple #3
0
    def __call__(self, *args):
        """Verify the player's authorization."""
        # Does the player's authorization need to be checked?
        if self.check_auth:

            # Is the player authorized?
            if not auth_manager.is_player_authorized(
                    playerinfo_from_index(args[1]), self.level,
                    self.permission, self.flag):

                # Is there fail callback?
                if self.fail_callback is not None:

                    # Use try/except in case the fail
                    # callback encounters an error
                    try:

                        # Call the fail callback
                        self.fail_callback(*args)

                    # Was an error encountered?
                    except:

                        # Print the exception to the console
                        except_hooks.print_exception()

                # Return a False value, since the player is not authorized
                return False

        # Call the callback and return its value
        return self.callback(*args)
Exemple #4
0
    def __call__(self, *args):
        """Verify the player's authorization."""
        # Does the player's authorization need to be checked?
        if self.check_auth:

            # Is the player authorized?
            if not auth_manager.is_player_authorized(
                playerinfo_from_index(args[1]), self.level, self.permission,
                    self.flag):

                # Is there fail callback?
                if self.fail_callback is not None:

                    # Use try/except in case the fail
                    # callback encounters an error
                    try:

                        # Call the fail callback
                        self.fail_callback(*args)

                    # Was an error encountered?
                    except:

                        # Print the exception to the console
                        except_hooks.print_exception()

                # Return a False value, since the player is not authorized
                return False

        # Call the callback and return its value
        return self.callback(*args)
Exemple #5
0
def _init_player(index):
    """Initialize a bank player from an index."""
    steamid = playerinfo_from_index(index).steamid
    balance = _database.load_balance(steamid)
    if balance is None:
        balance = 0
    return Player(index, balance=balance)
Exemple #6
0
    def send(self, *args, **kwargs):
        """Send the message to the given users."""
        # Get a recipient filter of the given users
        recipient = RecipientFilter(*(args or self.users))

        # Any parameter to translate?
        if self._translatable_parameters:

            # Get a default dictionnary to store the players
            languages = defaultdict(set)

            # Get a mapping of the given tokens
            tokens = ChainMap(kwargs, self.tokens)

            # Loop through all indexes
            for index in recipient:

                if playerinfo_from_index(index).is_fake_client():
                    continue

                # Add the current index
                languages[get_client_language(index)].add(index)

            # Loop through all languages
            for language, users in languages.items():

                # Get a dictionnary to store the translated strings
                translated_parameters = dict()

                # Loop through all translatable parameter
                for parameter_name in self._translatable_parameters:

                    # Get the current parameter value
                    parameter_value = self[parameter_name]

                    # Is the current parameter not translatable?
                    if not isinstance(parameter_value, TranslationStrings):

                        # No need to go further
                        continue

                    # Translate the current parameter
                    translated_parameters[
                        parameter_name] = parameter_value.get_string(
                        language, **tokens)

                # Update the recipient filter
                recipient.update(*users)

                # Send the message
                self._send_message(
                    recipient, **ChainMap(translated_parameters, self))

        # Otherwise
        else:

            # Send the message
            self._send_message(recipient, **self)
Exemple #7
0
def _init_player(index):
    """Initialize a bank player from an index."""
    steamid = playerinfo_from_index(index).steamid
    balance = _database.load_balance(steamid)
    if balance is not None:
        _messages['Welcome Back'].send(index, balance=balance)
    else:
        balance = 0
    return Player(index, balance=balance)
Exemple #8
0
    def playerinfo(self):
        """Return player information.

        :rtype: PlayerInfo
        """
        if self._playerinfo is None:
            playerinfo = playerinfo_from_index(self.index)
            object.__setattr__(self, '_playerinfo', playerinfo)
        return self._playerinfo
Exemple #9
0
def respawn_bots(game_event):
        userid = game_event.get_int("userid")
        index = index_from_userid(userid)
        player = Player(index)
        playerinfo = playerinfo_from_index(index)
        if playerinfo.is_fake_client():
            SayText2("Respawning {0}".format(player.name)).send()
            Delay(2, player=Player(index))
            player.respawn()
Exemple #10
0
def player_spawn(game_event):
        userid = game_event.get_int("userid")
        index = index_from_userid(userid)
        player = Player(index)
        playerinfo = playerinfo_from_index(index)
        if playerinfo.is_fake_client():
            player.health += BOT_EXTRA_HP
        else:
            player.health += EXTRA_HP
    def playerinfo(self):
        """Return player information.

        :rtype: PlayerInfo
        """
        if self._playerinfo is None:
            playerinfo = playerinfo_from_index(self.index)
            object.__setattr__(self, '_playerinfo', playerinfo)
        return self._playerinfo
Exemple #12
0
    def __new__(cls, index):
        """Set the "entities" attribute and set the PlayerInfo."""
        # Get the "self" object using the super class' __new__
        self = super(PlayerEntity, cls).__new__(cls, index)

        # Set the player's playerinfo attribute
        self._playerinfo = playerinfo_from_index(self.index)

        # Return the instance
        return self
Exemple #13
0
    def _chosen_value(self, menu, index, option):
        """Store the player's chosen value for the setting."""
        # Get the client's uniqueid
        uniqueid = uniqueid_from_playerinfo(playerinfo_from_index(index))

        # Set the player's setting
        _player_settings_storage[uniqueid][self.convar] = option.value

        # Send the player a message about their changed setting
        _message.send(index, convar=self.convar, value=option.value)
Exemple #14
0
    def from_index(cls, index):
        wcsplayer = cls._cache_indexes.get(index)

        if wcsplayer is None:
            playerinfo = playerinfo_from_index(index)
            uniqueid = uniqueid_from_playerinfo(playerinfo)

            wcsplayer = cls._cache_indexes[index] = cls(uniqueid)

        return wcsplayer
Exemple #15
0
def get_client_language(index):
    """Return the language of the given client.

    :param int index: Index of the client.
    """
    from players.helpers import playerinfo_from_index
    playerinfo = playerinfo_from_index(index)
    if playerinfo.is_fake_client() or 'BOT' in playerinfo.steamid:
        return ''

    return engine_server.get_client_convar_value(index, 'cl_language')
Exemple #16
0
    def from_userid(cls, userid):
        wcsplayer = cls._cache_userids.get(userid)

        if wcsplayer is None:
            index = index_from_userid(userid)
            playerinfo = playerinfo_from_index(index)
            uniqueid = uniqueid_from_playerinfo(playerinfo)

            wcsplayer = cls._cache_userids[userid] = cls(uniqueid)

        return wcsplayer
Exemple #17
0
def get_client_language(index):
    """Return the language of the given client.

    :param int index: Index of the client.
    """
    from players.helpers import playerinfo_from_index
    playerinfo = playerinfo_from_index(index)
    if playerinfo.is_fake_client() or 'BOT' in playerinfo.steamid:
        return ''

    return engine_server.get_client_convar_value(index, 'cl_language')
Exemple #18
0
def target_filter(filterby, source=None, multitarget=True):
    """Processes a target string and resolves it to one or more players
    Args:
        filterby: A string filterby in the form of
                Name: "<playername>" ex: "necavi"
                Userid: "#<index>" ex: "#5"
                Multi-Filter: "@<filterby>" ex "@me"
        source: A player to consider the source, used for filters such as @me
    Returns:
        A list of players that fit the filterby string
        :param source:
        :param filterby:
        :param multitarget:
    """
    playerlist = []
    if filterby == "":
        pass
    elif multitarget and filterby[0] == "@":
        if len(filterby) > 1 and filterby[1] == "!":
            if source is not None and len(filterby) > 2 and filterby[2:] == "me":
                source_index = source
                for index in PlayerIter():
                    if index != source_index:
                        playerlist.append(index)
            else:
                try:
                    playerlist = [x for x in PlayerIter(not_filters=filterby[2:])]
                except FilterError:
                    pass
        else:
            if source is not None and filterby[1:] == "me":
                playerlist.append(source)
            else:
                try:
                    playerlist = [x for x in PlayerIter(is_filters=filterby[1:])]
                except FilterError:
                    pass
    elif filterby[0] == "#":
        index = filterby[1:]
        if index.isnumeric():
            try:
                playerlist.append(index_from_userid(int(index)))
            except ValueError:
                pass
    else:
        for index in PlayerIter():
            playerinfo = playerinfo_from_index(index)
            filterby = filterby.casefold()
            if filterby in playerinfo.get_name().casefold():
                playerlist.append(index)
    return playerlist if multitarget else playerlist[0] if len(playerlist) == 1 else None
Exemple #19
0
    def _categorize_players_by_language(player_indexes):
        """Categorize players by their language.

        Return a dict in the following format:
        {<language>: set([<player index>, ...])}
        """
        languages = collections.defaultdict(set)
        for index in player_indexes:
            if playerinfo_from_index(index).is_fake_client():
                # No need to send a user message to bots
                continue

            languages[get_client_language(index)].add(index)

        return languages
Exemple #20
0
    def _categorize_players_by_language(player_indexes):
        """Categorize players by their language.

        Return a dict in the following format:
        {<language>: set([<player index>, ...])}
        """
        languages = collections.defaultdict(set)
        for index in player_indexes:
            if playerinfo_from_index(index).is_fake_client():
                # No need to send a user message to bots
                continue

            languages[get_client_language(index)].add(index)

        return languages
Exemple #21
0
    def __init__(self, index):
        self.index = index
        self.salt = None

        playerinfo = playerinfo_from_index(index)
        uniqueid = uniqueid_from_playerinfo(playerinfo)

        if uniqueid != playerinfo.steamid:
            raise ValueError(
                "Cannot initialize MOTDPlayer for bots or LAN players")

        self.steamid64 = str(SteamID.parse(playerinfo.steamid).to_uint64())

        self._next_session_id = 1
        self._sessions = {}
        self._loaded = False
Exemple #22
0
def on_tf_chat_message(msg, index, team_only):
    if index and not team_only:
        content = msg.command_string

        for pattern, censor in censors:
            content = pattern.sub(censor, content)

        #tf_messages.append(msg.command_string)
        player_info = playerinfo_from_index(index)
        if player_info.is_dead():
            room.send_message("**[TF2] \*DEAD\* " + player_info.name + "**: " +
                              content)
        else:
            room.send_message("**[TF2] " + player_info.name + "**: " + content)

    return True
Exemple #23
0
def _new_player(index):
    """Create and prepare a new :class:`rpg.player.Player` instance.

    Initializes the player object with instances of each RPG skill.

    :param int index:
        Index of the player entity
    :returns rpg.player.Player:
        The RPG player entity
    """
    steamid = playerinfo_from_index(index).steamid
    player_data = _database.load_player_data(steamid)
    player = rpg.player.Player(index, *player_data)
    for skill_cls in rpg.skills.skills:
        skill_data = _database.load_skill_data(steamid, skill_cls.class_id)
        player.skills.append(skill_cls(*skill_data))
    return player
Exemple #24
0
def _new_player(index):
    """Create and prepare a new :class:`rpg.player.Player` instance.

    Initializes the player object with instances of each RPG skill.

    :param int index:
        Index of the player entity
    :returns rpg.player.Player:
        The RPG player entity
    """
    steamid = playerinfo_from_index(index).steamid
    player_data = _database.load_player_data(steamid)
    player = rpg.player.Player(index, *player_data)
    for skill_cls in rpg.skills.skills:
        skill_data = _database.load_skill_data(steamid, skill_cls.class_id)
        player.skills.append(skill_cls(*skill_data))
    return player
Exemple #25
0
    def get_setting(self, index):
        """Return the setting value for the given player index."""
        # Get the client's convar value
        value = engine_server.get_client_convar_value(index, self.convar)

        # Try to typecast the value, suppressing ValueErrors
        with suppress(ValueError):

            # Typecast the given value
            value = self._type(value)

            # Is the given value a proper one for the convar?
            if self._is_valid_setting(value):

                # If so, return the value
                return value

        # Get the client's uniqueid
        uniqueid = uniqueid_from_playerinfo(playerinfo_from_index(index))

        # Is the uniqueid in the setting's storage dictionary?
        if uniqueid in _player_settings_storage:

            # Is the convar in the clients's dictionary?
            if self.convar in _player_settings_storage[uniqueid]:

                # Get the client's value for the convar
                value = _player_settings_storage[uniqueid][self.convar]

                # Try to typecast the value, suppressing ValueErrors
                with suppress(ValueError):

                    # Typecast the given value
                    value = self._type(value)

                    # Is the given value a proper one for the convar?
                    if self._is_valid_setting(value):

                        # Return the value
                        return value

        # Return the default value
        return self.default
Exemple #26
0
def is_player_stuck(player_index, origin):
    '''Return whether or not the given player is stuck in solid.'''

    # Get the player's PlayerInfo instance...
    player_info = playerinfo_from_index(player_index)

    # Get the player's origin...
    #origin = player_info.origin

    # Get a Ray object based on the player physic box...
    ray = Ray(origin, origin, player_info.mins, player_info.maxs)

    # Get a new GameTrace instance...
    trace = GameTrace()

    # Do the trace...
    engine_trace.trace_ray(ray, ContentMasks.PLAYER_SOLID,
                           TraceFilterSimple(PlayerIter()), trace)

    # Return whether or not the trace did hit...
    return trace.did_hit()
def saycommand_rank(command, index, team_only):
    playerinfo = playerinfo_from_index(index)
    rank = leetcoin_client.getPlayerRank(convertSteamIDToCommunityID(playerinfo.get_networkid_string()))
    SayText2(message="" + rank + "").send(index)
def saycommand_test(command, index, team_only): #playerinfo, teamonly, command
    playerinfo = playerinfo_from_index(index)
    balance = leetcoin_client.getPlayerBalance(convertSteamIDToCommunityID(playerinfo.get_networkid_string()))
    SayText2(message="" + balance + "").send(index)
Exemple #29
0
    def playerinfo(self):
        """Return player information.

        :rtype: PlayerInfo
        """
        return playerinfo_from_index(self.index)
Exemple #30
0
 def get_player_permissions(self, index):
     """.. seealso:: :meth:`get_player_permissions_from_steamid`"""
     return self.get_player_permissions_from_steamid(
         playerinfo_from_index(index).steamid)
Exemple #31
0
def report_disconnect(index):
    player_info = playerinfo_from_index(index)
    if not player_info.is_fake_client():
        room.send_message(player_info.name + " disconnected")
Exemple #32
0
 def playerinfo(self):
     """Return the player's :class:`PlayerInfo` object."""
     if self._playerinfo is None:
         playerinfo = playerinfo_from_index(self.index)
         object.__setattr__(self, '_playerinfo', playerinfo)
     return self._playerinfo
Exemple #33
0
    def playerinfo(self):
        """Return the player's IPlayerInfo instance."""
        if self._playerinfo is None:
            self._playerinfo = playerinfo_from_index(self.index)

        return self._playerinfo
Exemple #34
0
 def get_player_permissions(self, index):
     """.. seealso:: :meth:`get_player_permissions_from_steamid`"""
     return self.get_player_permissions_from_steamid(playerinfo_from_index(index).steamid)
Exemple #35
0
def on_client_active(index):
    wcsplayer = Player(uniqueid_from_playerinfo(playerinfo_from_index(index)))

    wcsplayer._userid = userid_from_index(index)
    wcsplayer._index = index
Exemple #36
0
    def get_setting(self, index):
        '''Returns the setting value for the given player index'''

        # Get the convar's value
        convar = self.prefix + self.name.lower().replace(' ', '_')

        # Get the client's convar value
        value = EngineServer.get_client_convar_value(index, convar)

        # Use try/except to typecast the value
        try:

            # Typecast the given value
            value = self._type(value)

        # Was an exception encountered?
        except ValueError:

            # Do nothing if the error occurred
            pass

        # Was no exception encountered?
        else:

            # Is the given value a proper one for the convar?
            if self._is_valid_setting(value):

                # If so, return the value
                return value

        # Get the client's uniqueid
        uniqueid = uniqueid_from_playerinfo(playerinfo_from_index(index))

        # Is the uniqueid in the setting's storage dictionary?
        if uniqueid in _PlayerSettingsStorage:

            # Is the convar in the clients's dictionary?
            if convar in _PlayerSettingsStorage[uniqueid]:

                # Get the client's value for the convar
                value = _PlayerSettingsStorage[uniqueid][convar]

                # Use try/except to typecast the value
                try:

                    # Typecast the given value
                    value = self._type(value)

                # Was an exception encountered?
                except ValueError:

                    # Do nothing if the error occurred
                    pass

                # Was no exception encountered?
                else:

                    # Is the given value a proper one for the convar?
                    if self._is_valid_setting(value):

                        # Return the value
                        return value

        # Return the default value
        return self.default
Exemple #37
0
 def playerinfo(self):
     """Return the player's :class:`PlayerInfo` object."""
     if self._playerinfo is None:
         playerinfo = playerinfo_from_index(self.index)
         object.__setattr__(self, "_playerinfo", playerinfo)
     return self._playerinfo