Skip to content

Hiven Types


List of represented Types

List of Type Description
Attachment Represents a Hiven message attachment containing a file
Context Represents a Command Context for a triggered command that was registered prior
Embed Represents an embed message object either customised or from a website
Entity Represents a Hiven Entity inside a House which can contain Rooms
Feed Represents the feed that is displayed on Hiven specifically for the user
House Represents a Hiven House which can contain rooms and entities
Invite Represents an Invite to a Hiven House
Member Represents a House Member on Hiven which contains the Hiven User, role-data and member-data
Mention Represents an mention for a user in Hiven
DeletedMessage Represents a Deleted Message in a Room
Message Represents a standard Hiven message sent by a user
PrivateRoom Represents a private chat room with only one user
PrivateGroupRoom Represents a private group chat room with multiple users
Relationship Represents a user-relationship with another user or bot
TextRoom Represents a Hiven Room inside a House
User Represents the standard Hiven User
UserTyping Represents a Hiven User typing in a room

openhivenpy.types.attachment.Attachment

Represents a Hiven Message Attachment containing a file

filename: str property readonly

json_schema

media_url: str property readonly

raw: dict property readonly

Methods

__init__(self, data, client) special

Represents a Hiven Message Attachment containing a file

:param data: Data that should be used to create the object :param client: The HivenClient

Source code in openhivenpy\types\attachment.py
def __init__(self, data: dict, client: HivenClient):
    """
    Represents a Hiven Message Attachment containing a file

    :param data: Data that should be used to create the object
    :param client: The HivenClient
    """
    try:
        self._filename = data.get('filename')
        self._media_url = data.get('media_url')
        self._raw = data.get('raw')

    except Exception as e:
        raise InitializationError(f"Failed to initialise {self.__class__.__name__}") from e
    else:
        self._client = client

format_obj_data(data) classmethod

Validates the data and appends data if it iis missing that would be required for the creation of an instance.

:param data: Data that should be validated and used to form the object :return: The modified dictionary, which can then be used to create a new class instance

Source code in openhivenpy\types\attachment.py
@classmethod
def format_obj_data(cls, data: dict) -> dict:
    """
    Validates the data and appends data if it iis missing that would be
    required for the creation of an instance.

    :param data: Data that should be validated and used to form the object
    :return: The modified dictionary, which can then be used to create a 
     new class instance
    """
    data['raw'] = {**data.pop('raw', {}), **data}
    return cls.validate(data)

json_validator(data)

openhivenpy.types.context.Context

Represents a Command Context for a triggered command that was registered prior

author: Optional[User] property readonly

house: Optional[House] property readonly

json_schema

room: Optional[TextRoom] property readonly

timestamp: Optional[datetime.datetime] property readonly

Methods

__init__(self, data, client) special

Represents a Command Context for a triggered command that was registered prior

:param data: Data that should be used to create the object :param client: The HivenClient

Source code in openhivenpy\types\context.py
def __init__(self, data: dict, client: HivenClient):
    """
    Represents a Command Context for a triggered command that was
    registered prior

    :param data: Data that should be used to create the object
    :param client: The HivenClient
    """
    try:
        self._room = data.get('room')
        self._author = data.get('author')
        self._house = data.get('house')
        self._timestamp = data.get('timestamp')

    except Exception as e:
        raise InitializationError(f"Failed to initialise {self.__class__.__name__}") from e
    else:
        self._client = client

format_obj_data(data) classmethod

Validates the data and appends data if it is missing that would be required for the creation of an instance.


Does NOT contain other objects and only their ids!

:param data: Data that should be validated and used to form the object :return: The modified dictionary, which can then be used to create a new class instance

Source code in openhivenpy\types\context.py
@classmethod
def format_obj_data(cls, data: dict) -> dict:
    """
    Validates the data and appends data if it is missing that would be 
    required for the creation of an instance.

    ---

    Does NOT contain other objects and only their ids!

    :param data: Data that should be validated and used to form the object
    :return: The modified dictionary, which can then be used to create a 
     new class instance
    """
    data = cls.validate(data)
    data['timestamp'] = utils.safe_convert(int, data.get('timestamp'))

    if not data.get('room_id') and data.get('room'):
        room = data.pop('room')
        if type(room) is dict:
            room = room.get('id', None)
        elif isinstance(room, DataClassObject):
            room = getattr(room, 'id', None)
        else:
            room = None

        if room is None:
            raise InvalidPassedDataError("The passed room is not in the correct format!", data=data)
        else:
            data['room_id'] = room

    if not data.get('house_id') and data.get('house'):
        house = data.pop('house')
        if type(house) is dict:
            house = house.get('id', None)
        elif isinstance(house, DataClassObject):
            house = getattr(house, 'id', None)
        else:
            house = None

        if house is None:
            raise InvalidPassedDataError("The passed house is not in the correct format!", data=data)
        else:
            data['house_id'] = house

    if not data.get('author_id') and data.get('author'):
        author = data.pop('author')
        if type(author) is dict:
            author = author.get('id', None)
        elif isinstance(author, DataClassObject):
            author = getattr(author, 'id', None)
        else:
            author = None

        if author is None:
            raise InvalidPassedDataError("The passed author is not in the correct format!", data=data)
        else:
            data['author_id'] = author

    data['room'] = data['room_id']
    data['author'] = data['author_id']
    data['house'] = data['house_id']
    return data

json_validator(data)

openhivenpy.types.embed.Embed

Represents an embed message object either customised or from a website

description: Optional[str] property readonly

image: Optional[str] property readonly

json_schema

title: Optional[str] property readonly

type: Optional[int] property readonly

url: Optional[str] property readonly

Methods

__init__(self, data, client) special

Represents an embed message object either customised or from a website

:param data: Data that should be used to create the object :param client: The HivenClient

Source code in openhivenpy\types\embed.py
def __init__(self, data: dict, client: HivenClient):
    """
    Represents an embed message object either customised or from a website

    :param data: Data that should be used to create the object
    :param client: The HivenClient
    """
    try:
        self._url = data.get('url')
        self._type = data.get('type')
        self._title = data.get('title')
        self._image = data.get('image')
        self._description = data.get('description')

    except Exception as e:
        raise InitializationError(f"Failed to initialise {self.__class__.__name__}") from e
    else:
        self._client = client

format_obj_data(data) classmethod

Validates the data and appends data if it is missing that would be required for the creation of an instance.

:param data: Data that should be validated and used to form the object :return: The modified dictionary, which can then be used to create a new class instance

Source code in openhivenpy\types\embed.py
@classmethod
def format_obj_data(cls, data: dict) -> dict:
    """
    Validates the data and appends data if it is missing that would be
    required for the creation of an instance.

    :param data: Data that should be validated and used to form the object
    :return: The modified dictionary, which can then be used to create a 
    new class instance
    """
    return cls.validate(data)

json_validator(data)

openhivenpy.types.entity.Entity

Represents a Hiven Entity inside a House which can contain Rooms

Attributes

house: Optional[House] property readonly

house_id: str property readonly

id: str property readonly

json_schema

name: str property readonly

position: int property readonly

resource_pointers: Optional[List[TextRoom, dict]] property readonly

Objects contained inside the entity. If dict is returned it's a type that is not yet included in the lib

type: Optional[int] property readonly

Methods

__init__(self, data, client) special

Represents a Hiven Entity inside a House which can contain Rooms

:param data: Data that should be used to create the object :param client: The HivenClient

Source code in openhivenpy\types\entity.py
def __init__(self, data: dict, client: HivenClient):
    """
    Represents a Hiven Entity inside a House which can contain Rooms

    :param data: Data that should be used to create the object
    :param client: The HivenClient
    """
    try:
        super().__init__()
        self._type = data.get('type')
        self._position = data.get('position')
        self._resource_pointers = data.get('resource_pointers')
        self._name = data.get('name')
        self._id = data.get('id')
        self._house_id = data.get('house_id')
        self._house = data.get('house')

    except Exception as e:
        raise InitializationError(f"Failed to initialise {self.__class__.__name__}") from e
    else:
        self._client = client

__repr__(self) special

Source code in openhivenpy\types\entity.py
def __repr__(self) -> str:
    info = [
        ('name', self.name),
        ('id', self.id),
        ('position', self.position),
        ('type', self.type)
    ]
    return '<Entity {}>'.format(' '.join('%s=%s' % t for t in info))

format_obj_data(data) classmethod

Validates the data and appends data if it is missing that would be required for the creation of an instance.


Does NOT contain other objects and only their ids!

:param data: Data that should be validated and used to form the object :return: The modified dictionary, which can then be used to create a new class instance

Source code in openhivenpy\types\entity.py
@classmethod
def format_obj_data(cls, data: dict) -> dict:
    """
    Validates the data and appends data if it is missing that would be 
    required for the creation of an instance.

    ---

    Does NOT contain other objects and only their ids!

    :param data: Data that should be validated and used to form the object
    :return: The modified dictionary, which can then be used to create a 
     new class instance
    """
    if not data.get('house_id') and data.get('house'):
        house = data.pop('house')
        if type(house) is dict:
            house_id = house.get('id')
        elif isinstance(house, DataClassObject):
            house_id = getattr(house, 'id', None)
        else:
            house_id = None

        if house_id is None:
            raise InvalidPassedDataError("The passed house is not in the correct format!", data=data)
        else:
            data['house_id'] = house_id

    data['house'] = data.get('house_id')
    data = cls.validate(data)
    return data

get_cached_data(self)

Fetches the most recent data from the cache based on the instance id

Source code in openhivenpy\types\entity.py
def get_cached_data(self) -> Optional[dict]:
    """ Fetches the most recent data from the cache based on the instance id """
    return self._client.storage['entities'].get(self.id)

json_validator(data)

openhivenpy.types.feed.Feed

Represents the feed that is displayed on Hiven specifically for the user

__init__(self, data, client) special

Source code in openhivenpy\types\feed.py
def __init__(self, data: dict, client: HivenClient):
    ...

__repr__(self) special

Source code in openhivenpy\types\feed.py
def __repr__(self) -> str:
    info = [
        ('unknown', "")
    ]
    return '<Feed {}>'.format(' '.join('%s=%s' % t for t in info))

__str__(self) special

Source code in openhivenpy\types\feed.py
def __str__(self) -> str:
    return repr(self)

openhivenpy.types.house.House

Represents a Hiven House which can contain rooms and entities

banner: Optional[str] property readonly

client_member: Optional[Member] property readonly

default_permissions: Optional[int] property readonly

entities: Optional[List[Entity]] property readonly

json_schema

members: Optional[List[Member]] property readonly

owner: Optional[Member] property readonly

roles: Optional[list] property readonly

users: Optional[List[Member]] property readonly

Methods

__init__(self, data, client) special

Source code in openhivenpy\types\house.py
def __init__(self, data: dict, client: HivenClient):
    try:
        self._roles = data.get('roles')
        self._roles_data = self._roles
        self._entities: list = data.get('entities')
        self._default_permissions = data.get('default_permissions')
        self._members: dict = data.get('members')
        self._member_data = self._members
        self._client_member = data.get('client_member')
        self._banner = data.get('banner')
        self._owner = data.get('owner')
        self._client = client

    except Exception as e:
        raise InitializationError(f"Failed to initialise {self.__class__.__name__}") from e
    super().__init__(data, client)

create_entity(self, name) async

Creates a entity in the house with the specified name.

:param name: The name of the new entity :return: The newly created Entity Instance

Source code in openhivenpy\types\house.py
async def create_entity(self, name: str) -> Optional[Entity]:
    """
    Creates a entity in the house with the specified name.

    :param name: The name of the new entity
    :return: The newly created Entity Instance
    """
    try:
        resp = await self._client.http.post(
            endpoint=f"/houses/{self.id}/entities",
            json={'name': name, 'type': 1}
        )
        raw_data = await resp.json()

        data = raw_data.get('data')

        # Fetching all existing ids
        existing_entity_ids = [e['id'] for e in self.entities]
        for d in data:
            id_ = d.get('id')
            if id_ not in existing_entity_ids:
                d = Entity.format_obj_data(d)
                _entity = Entity(d, self._client)
                self._entities.append(_entity)
                return _entity

    except Exception as e:
        utils.log_traceback(
            brief=f"Failed to create category '{name}' in house {repr(self)}:",
            exc_info=sys.exc_info()
        )
        # TODO! Raise exception
        return None

create_invite(self, max_uses) async

Creates an invite for the current house.

:param max_uses: Maximal uses for the invite code :return: The invite url if successful.

Source code in openhivenpy\types\house.py
async def create_invite(self, max_uses: int) -> Optional[Invite]:
    """
    Creates an invite for the current house. 

    :param max_uses: Maximal uses for the invite code
    :return: The invite url if successful.
    """
    try:
        from . import Invite
        resp = await self._client.http.post(
            endpoint=f"/houses/{self.id}/invites",
            json={"max_uses": max_uses}
        )
        raw_data = await resp.json()

        data = raw_data.get('data')
        data = Invite.format_obj_data(data)
        return Invite(data, self._client)

    except Exception as e:
        utils.log_traceback(
            brief=f"Failed to create invite for house {repr(self)}",
            exc_info=sys.exc_info()
        )
        # TODO! Raise exception
        return None

create_room(self, name, parent_entity_id=None) async

Creates a Room in the house with the specified name.

:return: A Room Instance for the Hiven Room that was created if successful else None

Source code in openhivenpy\types\house.py
async def create_room(self, name: str, parent_entity_id: Optional[int] = None) -> Optional[TextRoom]:
    """
    Creates a Room in the house with the specified name. 

    :return: A Room Instance for the Hiven Room that was created if successful else None
    """
    try:
        from . import TextRoom
        default_entity = utils.get(self.entities, name="Rooms")
        json = {
            'name': name,
            'parent_entity_id': parent_entity_id if parent_entity_id else default_entity.id
        }

        # Creating the room using the api
        resp = await self._client.http.post(f"/houses/{self._id}/rooms", json=json)
        raw_data = await resp.json()

        data = TextRoom.format_obj_data(raw_data.get('data'))
        return TextRoom(data, self._client)

    except Exception as e:
        utils.log_traceback(
            brief=f"Failed to create room '{name}' in house {repr(self)}:",
            exc_info=sys.exc_info()
        )
        # TODO! Raise exception
        return None

delete(self) async

Deletes the house if permissions are sufficient!

:return: The house ID if successful else None

Source code in openhivenpy\types\house.py
async def delete(self) -> Optional[str]:
    """
    Deletes the house if permissions are sufficient!

    :return: The house ID if successful else None
    """
    try:
        await self._client.http.delete(f"/houses/{self.id}")
        return self.id

    except Exception as e:
        utils.log_traceback(
            brief=f"Failed to delete House {repr(self)}",
            exc_info=sys.exc_info()
        )
        # TODO! Raise exception
        return None

edit(self, **kwargs) async

Changes the houses data on Hiven.

Available options: name, icon(base64)

:return: True if the request was successful else False

Source code in openhivenpy\types\house.py
async def edit(self, **kwargs) -> bool:
    """
    Changes the houses data on Hiven.

    Available options: name, icon(base64)

    :return: True if the request was successful else False
    """
    try:
        for key, data in kwargs.items():
            if key in ['name']:
                await self._client.http.patch(
                    endpoint=f"/houses/{self.id}", json={key: data}
                )
                return True
            else:
                raise NameError("The passed value does not exist in the House!")

    except Exception as e:
        keys = "".join(key + " " for key in kwargs.keys()) if kwargs != {} else ''
        utils.log_traceback(
            brief=f"Failed edit request of values '{keys}' in house {repr(self)}:",
            exc_info=sys.exc_info()
        )
        # TODO! Raise exception
        return False

find_entity(self, entity_id)

Fetches the raw data of a entity

:param entity_id: The id of the entity which should be fetched :return: The data in the cache if it was found

Source code in openhivenpy\types\house.py
def find_entity(self, entity_id: str) -> Optional[dict]:
    """
    Fetches the raw data of a entity

    :param entity_id: The id of the entity which should be fetched
    :return: The data in the cache if it was found
    """
    return self._client.storage['entities'].get(entity_id)

find_member(self, member_id)

Fetches the raw data of a member

:param member_id: The id of the member which should be fetched :return: The data in the cache if it was found

Source code in openhivenpy\types\house.py
def find_member(self, member_id: str) -> Optional[dict]:
    """
    Fetches the raw data of a member

    :param member_id: The id of the member which should be fetched
    :return: The data in the cache if it was found
    """
    return self._member_data.get(member_id)

find_room(self, room_id)

Fetches the raw data of a room

:param room_id: The id of the room which should be fetched :return: The data in the cache if it was found

Source code in openhivenpy\types\house.py
def find_room(self, room_id: str) -> Optional[dict]:
    """
    Fetches the raw data of a room

    :param room_id: The id of the room which should be fetched
    :return: The data in the cache if it was found
    """
    return self._client.storage['rooms']['house'].get(room_id)

format_obj_data(data) classmethod

Validates the data and appends data if it is missing that would be required for the creation of an instance.


Does NOT contain other objects and only their ids!

:param data: Data that should be validated and used to form the object :return: The modified dictionary, which can then be used to create a new class instance

Source code in openhivenpy\types\house.py
@classmethod
def format_obj_data(cls, data: dict) -> dict:
    """
    Validates the data and appends data if it is missing that would be 
    required for the creation of an instance.

    ---

    Does NOT contain other objects and only their ids!

    :param data: Data that should be validated and used to form the object
    :return: The modified dictionary, which can then be used to create a 
     new class instance
    """
    data = LazyHouse.format_obj_data(data)
    data = cls.validate(data)
    return data

get_entity(self, entity_id)

Fetches a entity from the cache based on the id

:return: The Entity Instance if it exists else returns None

Source code in openhivenpy\types\house.py
def get_entity(self, entity_id: str) -> Optional[Entity]:
    """
    Fetches a entity from the cache based on the id

    :return: The Entity Instance if it exists else returns None
    """
    try:
        from . import Entity
        cached_entity = self.find_entity(entity_id)
        if cached_entity:
            return Entity(cached_entity, self._client)

        return None

    except Exception as e:
        utils.log_traceback(
            brief=f"Failed to get the member with id {entity_id}:",
            exc_info=sys.exc_info()
        )
        # TODO! Raise exception
        return None

get_member(self, member_id)

Fetches a member from the cache based on the id

:return: The Member Instance if it exists else returns None

Source code in openhivenpy\types\house.py
def get_member(self, member_id: str) -> Optional[Member]:
    """
    Fetches a member from the cache based on the id

    :return: The Member Instance if it exists else returns None
    """
    try:
        from . import Member

        cached_member = self.find_member(member_id)
        if cached_member:
            return Member(cached_member, self._client)

        return None

    except Exception as e:
        utils.log_traceback(
            brief=f"Failed to get the member with id {member_id}:",
            exc_info=sys.exc_info()
        )
        # TODO! Raise exception
        raise

get_room(self, room_id)

Fetches a room from the cache based on the id

:return: The Room Instance if it exists else returns None

Source code in openhivenpy\types\house.py
def get_room(self, room_id: str) -> Optional[TextRoom]:
    """
    Fetches a room from the cache based on the id

    :return: The Room Instance if it exists else returns None
    """
    try:
        from . import TextRoom
        cached_room = self.find_room(room_id)
        if cached_room:
            return TextRoom(cached_room, self._client)

        return None

    except Exception as e:
        utils.log_traceback(
            brief=f"Failed to get the room with id {room_id} in house {repr(self)}:",
            exc_info=sys.exc_info()
        )
        # TODO! Raise exception
        return None

json_validator(data)

leave(self) async

Leaves the house

:return: True if it was successful else False

Source code in openhivenpy\types\house.py
async def leave(self) -> bool:
    """
    Leaves the house

    :return: True if it was successful else False
    """
    try:
        await self._client.http.delete(endpoint=f"/users/@me/houses/{self.id}")
        return True

    except Exception as e:
        utils.log_traceback(
            brief=f"Failed to leave {repr(self)}:",
            exc_info=sys.exc_info()
        )
        # TODO! Raise exception
        return False

openhivenpy.types.invite.Invite

Represents an Invite to a Hiven House

code: Optional[int] property readonly

created_at: Optional[str] property readonly

house: Optional[House] property readonly

house_id: Optional[str] property readonly

house_members: Optional[int] property readonly

json_schema

max_age: Optional[int] property readonly

max_uses: Optional[int] property readonly

type: Optional[int] property readonly

url: Optional[str] property readonly

Methods

__init__(self, data, client) special

Source code in openhivenpy\types\invite.py
def __init__(self, data: dict, client: HivenClient):
    try:
        self._code = data.get('code')
        self._url = data.get('url')
        self._created_at = data.get('created_at')
        self._house_id = data.get('house_id')
        self._max_age = data.get('max_age')
        self._max_uses = data.get('max_uses')
        self._type = data.get('type')
        self._house = data.get('house')
        self._house_members = data.get('house_members')

    except Exception as e:
        raise InitializationError(f"Failed to initialise {self.__class__.__name__}") from e
    else:
        self._client = client

__repr__(self) special

Source code in openhivenpy\types\invite.py
def __repr__(self) -> str:
    info = [
        ('code', self.code),
        ('url', self.url),
        ('created_at', self.created_at),
        ('house_id', self.house_id),
        ('type', self.type),
        ('max_age', self.max_age),
        ('max_uses', self.max_uses),
    ]
    return '<Invite {}>'.format(' '.join('%s=%s' % t for t in info))

format_obj_data(data) classmethod

Validates the data and appends data if it is missing that would be required for the creation of an instance.


Does NOT contain other objects and only their ids!

:param data: Data that should be validated and used to form the object :return: The modified dictionary, which can then be used to create a new class instance

Source code in openhivenpy\types\invite.py
@classmethod
def format_obj_data(cls, data: dict) -> dict:
    """
    Validates the data and appends data if it is missing that would be
    required for the creation of an instance.

    ---

    Does NOT contain other objects and only their ids!

    :param data: Data that should be validated and used to form the object
    :return: The modified dictionary, which can then be used to create a 
     new class instance
    """
    if data.get('invite') is not None:
        invite = data.get('invite')
    else:
        invite = data
    data['code'] = invite.get('code')
    data['url'] = "https://hiven.house/{}".format(data['code'])
    data['created_at'] = invite.get('created_at')
    data['max_age'] = invite.get('max_age')
    data['max_uses'] = invite.get('max_uses')
    data['type'] = invite.get('type')
    data['house_members'] = data.get('counts', {}).get('house_members')

    if not invite.get('house_id') and invite.get('house'):
        house = invite.pop('house')
        if type(house) is dict:
            house_id = house.get('id')
        elif isinstance(house, DataClassObject):
            house_id = getattr(house, 'id', None)
        else:
            house_id = None

        if house_id is None:
            raise InvalidPassedDataError("The passed house is not in the correct format!", data=data)
        else:
            data['house_id'] = house_id

    data['type'] = int(data['type'])
    data['house'] = data.get('house_id')
    data = cls.validate(data)
    return data

json_validator(data)

openhivenpy.types.member.Member

Represents a House Member on Hiven which contains the Hiven User, role-data and member-data

Attributes

house: Optional[House] property readonly

house_id: Optional[str] property readonly

id: Optional[str] property readonly

Unique string id of the user

joined_at: Optional[str] property readonly

joined_house_at: Optional[str] property readonly

json_schema

roles: Optional[List[dict]] property readonly

user_id: Optional[str] property readonly

Methods

__init__(self, data, client) special

Source code in openhivenpy\types\member.py
def __init__(self, data: dict, client: HivenClient):
    super().__init__(data.get('user'), client)
    try:
        data = {**data.get('user'), **data}
        self._user_id = data.get('user_id')
        self._house_id = data.get('house_id')
        self._joined_at = data.get('joined_at')
        self._roles = data.get('roles')
        self._house = data.get('house')

    except Exception as e:
        raise InitializationError(
            f"Failed to initialise {self.__class__.__name__}"
        ) from e

__repr__(self) special

Source code in openhivenpy\types\member.py
def __repr__(self) -> str:
    info = [
        ('username', self.username),
        ('name', self.name),
        ('id', self.id),
        ('icon', self.icon),
        ('header', self.header),
        ('bot', self.bot),
        ('house_id', self.house_id),
        ('joined_house_at', self.joined_house_at)
    ]
    return '<Member {}>'.format(' '.join('%s=%s' % t for t in info))

format_obj_data(data) classmethod

Validates the data and appends data if it is missing that would be required for the creation of an instance.


Does NOT contain other objects and only their ids!

:param data: Data that should be validated and used to form the object :return: The modified dictionary, which can then be used to create a new class instance

Source code in openhivenpy\types\member.py
@classmethod
def format_obj_data(cls, data: dict) -> dict:
    """
    Validates the data and appends data if it is missing that would be 
    required for the creation of an instance.

    ---

    Does NOT contain other objects and only their ids!

    :param data: Data that should be validated and used to form the object
    :return: The modified dictionary, which can then be used to create a 
     new class instance
    """
    if not data.get('house_id') and data.get('house'):
        house = data.pop('house')
        if type(house) is dict:
            house_id = house.get('id')
        elif isinstance(house, DataClassObject):
            house_id = getattr(house, 'id', None)
        else:
            house_id = None

        if house_id is None:
            raise InvalidPassedDataError(
                "The passed house is not in the correct format!", data=data
            )
        else:
            data['house_id'] = house_id

    elif not data.get('house_id') and not data.get('house'):
        raise InvalidPassedDataError(
            "house_id and house missing from required data", data=data
        )

    data['house'] = data.get('house_id')
    data = cls.validate(data)
    return data

json_validator(data)

kick(self) async

Kicks a user from the house.

The client needs permissions to kick, or else this will raise HivenException.Forbidden

:return: True if the request was successful :raises Forbidden: If the request failed to execute

Source code in openhivenpy\types\member.py
async def kick(self) -> bool:
    """
    Kicks a user from the house.

    The client needs permissions to kick, or else this will raise
    `HivenException.Forbidden`

    :return: True if the request was successful
    :raises Forbidden: If the request failed to execute
    """
    try:
        resp = await self._client.http.delete(
            f"/{self._house_id}/members/{self._user_id}"
        )
        if not resp.status < 300:
            raise HTTPForbiddenError()
        else:
            return True
    except HTTPForbiddenError:
        raise

    except Exception as e:
        utils.log_traceback(
            brief=f"Failed to kick the member due to an exception "
                  "occurring:",
            exc_info=sys.exc_info()
        )
        # TODO! Raise exception
        return False

openhivenpy.types.mention.Mention

Represents an mention for a user in Hiven

author: Optional[User] property readonly

author_id: Optional[str] property readonly

json_schema

timestamp: Optional[datetime.datetime] property readonly

user: Optional[User] property readonly

user_id: Optional[str] property readonly

Methods

__init__(self, data, client) special

Source code in openhivenpy\types\mention.py
def __init__(self, data: dict, client: HivenClient):
    try:
        self._timestamp = data.get('timestamp')
        self._user = data.get('user')
        self._user_id = data.get('user_id')
        self._author = data.get('author')
        self._author_id = data.get('author_id')

    except Exception as e:
        raise InitializationError(f"Failed to initialise {self.__class__.__name__}") from e
    else:
        self._client = client

format_obj_data(data) classmethod

Validates the data and appends data if it is missing that would be required for the creation of an instance.


Does NOT contain other objects and only their ids!

:param data: Data that should be validated and used to form the object :return: The modified dictionary, which can then be used to create a new class instance

Source code in openhivenpy\types\mention.py
@classmethod
def format_obj_data(cls, data: dict) -> dict:
    """
    Validates the data and appends data if it is missing that would be 
    required for the creation of an instance.

    ---

    Does NOT contain other objects and only their ids!

    :param data: Data that should be validated and used to form the object
    :return: The modified dictionary, which can then be used to create a 
     new class instance
    """
    if not data.get('user_id') and data.get('user'):
        user = data.pop('user')
        if type(user) is dict:
            user = user.get('id', None)
        elif isinstance(user, DataClassObject):
            user = getattr(user, 'id', None)
        else:
            user = None

        if user is None:
            raise InvalidPassedDataError("The passed user is not in the correct format!", data=data)
        else:
            data['user'] = user

    if not data.get('author_id') and data.get('author'):
        author = data.pop('author')
        if type(author) is dict:
            author = author.get('id', None)
        elif isinstance(author, DataClassObject):
            author = getattr(author, 'id', None)
        else:
            author = None

        if author is None:
            raise InvalidPassedDataError("The passed author is not in the correct format!", data=data)
        else:
            data['author'] = author

    data['author'] = data.get('author_id')
    data['user'] = data.get('user_id')
    data = cls.validate(data)
    return data

json_validator(data)

openhivenpy.types.message.DeletedMessage

Represents a Deleted Message in a Room

house_id: Optional[str] property readonly

json_schema

message_id: Optional[str] property readonly

room_id: Optional[str] property readonly

Methods

__init__(self, data, client) special

Source code in openhivenpy\types\message.py
def __init__(self, data: dict, client: HivenClient):
    try:
        self._message_id = data.get('message_id')
        self._house_id = data.get('house_id')
        self._room_id = data.get('room_id')

    except Exception as e:
        raise InitializationError(f"Failed to initialise {self.__class__.__name__}") from e
    else:
        self._client = client

__str__(self) special

Source code in openhivenpy\types\message.py
def __str__(self):
    return f"Deleted message in room {self.room_id}"

format_obj_data(data) classmethod

Validates the data and appends data if it is missing that would be required for the creation of an instance.

:param data: Data that should be validated and used to form the object :return: The modified dictionary, which can then be used to create a new class instance

Source code in openhivenpy\types\message.py
@classmethod
def format_obj_data(cls, data: dict) -> dict:
    """
    Validates the data and appends data if it is missing that would be
    required for the creation of an
    instance.

    :param data: Data that should be validated and used to form the object
    :return: The modified dictionary, which can then be used to create a 
     new class instance
    """
    data = cls.validate(data)
    data['message_id'] = data['id']
    return data

json_validator(data)

openhivenpy.types.message.Message

Represents a standard Hiven message sent by a user

attachment: Optional[Attachment] property readonly

author: Optional[User] property readonly

author_id: Optional[str] property readonly

bucket: Optional[int] property readonly

content: Optional[str] property readonly

created_at: Optional[str] property readonly

device_id: Optional[str] property readonly

edited_at: Optional[str] property readonly

embed: Embed property readonly

exploding: Optional[bool] property readonly

exploding_age: Optional[int] property readonly

house: Optional[House] property readonly

house_id: Optional[str] property readonly

id: Optional[str] property readonly

json_schema

mentions: Optional[List[Mention]] property readonly

room: Optional[TextRoom] property readonly

room_id: Optional[str] property readonly

timestamp: Optional[datetime.datetime] property readonly

type: Optional[int] property readonly

Methods

__init__(self, data, client) special

Source code in openhivenpy\types\message.py
def __init__(self, data: dict, client: HivenClient):
    try:
        self._id = data.get('id')
        self._author = data.get('author')
        self._author_id = data.get('author_id')
        self._attachment: Union[dict, Attachment] = data.get('attachment')
        self._content = data.get('content')
        self._timestamp = data.get('timestamp')
        self._edited_at = data.get('edited_at')
        self._mentions = data.get('mentions')
        self._type = data.get('type')  # I believe, 0 = normal message, 1 = system.
        self._exploding = data.get('exploding')
        self._house_id = data.get('house_id')
        self._house = data.get('house')
        self._room_id = data.get('room_id')
        self._room = data.get('room')
        self._embed = data.get('embed')
        self._bucket = data.get('bucket')
        self._device_id = data.get('device_id')
        self._exploding_age = data.get('exploding_age')

    except Exception as e:
        raise InitializationError(f"Failed to initialise {self.__class__.__name__}") from e
    else:
        self._client = client

__repr__(self) special

Source code in openhivenpy\types\message.py
def __repr__(self) -> str:
    info = [
        ('id', self.id),
        ('content', self.content),
        ('author', repr(self.author)),
        ('room', repr(self.room)),
        ('type', self.type),
        ('exploding', self.exploding),
        ('edited_at', self.edited_at)
    ]
    return '<Message {}>'.format(' '.join('%s=%s' % t for t in info))

__str__(self) special

Source code in openhivenpy\types\message.py
def __str__(self) -> str:
    return f"<Message id='{self.id}' from '{self.author.name}'>"

delete(self, delay=None) async

Deletes the message. Raises Forbidden if not allowed.

:param delay: Delay until deleting the message as read (in seconds) :return: A DeletedMessage object if successful

Source code in openhivenpy\types\message.py
async def delete(self, delay: float = None) -> bool:
    """
    Deletes the message. Raises Forbidden if not allowed.

    :param delay: Delay until deleting the message as read (in seconds)
    :return: A DeletedMessage object if successful
    """
    try:
        if delay is not None:
            await asyncio.sleep(delay=delay)

        resp = await self._client.http.delete(
            endpoint=f"/rooms/{self.room_id}/messages/{self.id}"
        )

        if not resp.status < 300:
            raise HTTPForbiddenError()
        else:
            return True

    except Exception as e:
        utils.log_traceback(
            brief=f"Failed to delete the message {repr(self)}:",
            exc_info=sys.exc_info()
        )
        # TODO! Raise exception

edit(self, content) async

Edits a message on Hiven

:return: True if the request was successful else False

Source code in openhivenpy\types\message.py
async def edit(self, content: str) -> bool:
    """
    Edits a message on Hiven

    :return: True if the request was successful else False
    """
    try:
        await self._client.http.patch(
            endpoint=f"/rooms/{self.room_id}/messages/{self.id}", json={'content': content}
        )
        return True

    except Exception as e:
        utils.log_traceback(
            brief=f"Failed to edit message {repr(self)}",
            exc_info=sys.exc_info()
        )
        return False

format_obj_data(data) classmethod

Validates the data and appends data if it is missing that would be required for the creation of an instance.


Does NOT contain other objects and only their ids!

:param data: Data that should be validated and used to form the object :return: The modified dictionary, which can then be used to create a new class instance

Source code in openhivenpy\types\message.py
@classmethod
def format_obj_data(cls, data: dict) -> dict:
    """
    Validates the data and appends data if it is missing that would be
    required for the creation of an
    instance.

    ---

    Does NOT contain other objects and only their ids!

    :param data: Data that should be validated and used to form the object
    :return: The modified dictionary, which can then be used to create a 
     new class instance
    """
    # I believe, 0 = normal message, 1 = system.
    data['type'] = utils.safe_convert(int, data.get('type'), None)
    data['bucket'] = utils.safe_convert(int, data.get('bucket'), None)
    data['exploding_age'] = utils.safe_convert(int,
                                               data.get('exploding_age'),
                                               None)
    data['timestamp'] = utils.safe_convert(int, data.get('timestamp'))

    data = cls.validate(data)

    if not data.get('room_id') and data.get('room'):
        room_ = data.pop('room')
        if type(room_) is dict:
            room_ = room_.get('id', None)
        elif isinstance(room_, DataClassObject):
            room_ = getattr(room_, 'id', None)
        elif type(data.get('room_id')) is str:
            room_ = data['room_id']
        else:
            room_ = None

        if room_ is None:
            raise InvalidPassedDataError("The passed room is not in the correct format!", data=data)
        else:
            data['room_id'] = room_

    if not data.get('house_id') and data.get('house'):
        house_ = data.pop('house')
        if type(house_) is dict:
            house_ = house_.get('id', None)
        elif isinstance(house_, DataClassObject):
            house_ = getattr(house_, 'id', None)
        elif type(data.get('house_id')) is str:
            house_ = data['house_id']
        else:
            house_ = None

        data['house_id'] = house_

    if not data.get('author_id') and data.get('author'):
        author = data.pop('author')
        if type(author) is dict:
            author = author.get('id', None)
        elif isinstance(author, DataClassObject):
            author = getattr(author, 'id', None)
        elif type(data.get('author_id')) is str:
            author = data['author_id']
        else:
            author = None

        if author is None:
            raise InvalidPassedDataError("The passed author is not in the correct format!", data=data)
        else:
            data['author'] = author

    data['author'] = data['author_id']
    data['house'] = data['house_id']
    data['room'] = data['room_id']
    data['device_id'] = utils.safe_convert(str, data.get('device_id'), None)
    return data

json_validator(data)

mark_as_read(self, delay=None) async

Marks the message as read. This doesn't need to be done for bot clients.

:param delay: Delay until marking the message as read (in seconds) :return: True if the request was successful else False

Source code in openhivenpy\types\message.py
async def mark_as_read(self, delay: float = None) -> bool:
    """
    Marks the message as read. This doesn't need to be done for bot clients.

    :param delay: Delay until marking the message as read (in seconds)
    :return: True if the request was successful else False
    """
    try:
        if delay is not None:
            await asyncio.sleep(delay=delay)
        await self._client.http.post(
            endpoint=f"/rooms/{self.room_id}/messages/{self.id}/ack"
        )
        return True

    except Exception as e:
        utils.log_traceback(
            brief=f"Failed to mark message as read {repr(self)}:",
            exc_info=sys.exc_info()
        )
        # TODO! Raise exception

openhivenpy.types.private_room.PrivateRoom

Represents a private chat room with only one user

client_user: Optional[User] property readonly

description: Optional[str] property readonly

emoji: Optional[str] property readonly

id: Optional[str] property readonly

json_schema

last_message_id: Optional[str] property readonly

name: Optional[str] property readonly

recipient: Optional[User] property readonly

recipient_id: Optional[str] property readonly

type: Optional[int] property readonly

Methods

__init__(self, data, client) special

Source code in openhivenpy\types\private_room.py
def __init__(self, data: dict, client: HivenClient):
    try:
        self._id = data.get('id')
        self._last_message_id = data.get('last_message_id')
        self._recipient = data.get('recipient')
        self._recipient_id = data.get('recipient_id')
        self._name = data.get('name')
        self._description = data.get('description')
        self._emoji = data.get('emoji')
        self._type = data.get('type')
        self._client_user = client.client_user

    except Exception as e:
        raise InitializationError(f"Failed to initialise {self.__class__.__name__}") from e
    else:
        self._client = client

__repr__(self) special

Source code in openhivenpy\types\private_room.py
def __repr__(self) -> str:
    info = [
        ('id', self.id),
        ('last_message_id', self.last_message_id),
        ('recipients', self.recipient),
        ('type', self.type)
    ]
    return '<PrivateRoom {}>'.format(' '.join('%s=%s' % t for t in info))

format_obj_data(data) classmethod

Validates the data and appends data if it is missing that would be required for the creation of an instance.


Does NOT contain other objects and only their ids!

:param data: Data that should be validated and used to form the object :return: The modified dictionary, which can then be used to create a new class instance

Source code in openhivenpy\types\private_room.py
@classmethod
def format_obj_data(cls, data: dict) -> dict:
    """
    Validates the data and appends data if it is missing that would be 
    required for the creation of an instance.

    ---

    Does NOT contain other objects and only their ids!

    :param data: Data that should be validated and used to form the object
    :return: The modified dictionary, which can then be used to create a
     new class instance
    """
    data = cls.validate(data)

    name = ""
    if not data.get('recipient_id') and data.get('recipients'):
        recipient = data.pop('recipients')[0]
        if type(recipient) is dict:
            name = recipient.get('name', None)
            recipient = recipient.get('id', None)
        elif isinstance(recipient, DataClassObject):
            name = getattr(recipient, 'name', None)
            recipient = getattr(recipient, 'id', None)
        else:
            recipient = None
            name = None

        if recipient is None:
            raise InvalidPassedDataError("The passed recipient/s is/are not in the correct format!", data=data)
        else:
            data['recipient_id'] = recipient

    data['recipient'] = data['recipient_id']

    # If the passed recipient object does not contain the name parameter it will be fetched later from the client
    # based on the id
    if name:
        data['name'] = f"Private chat with {name}"
    else:
        data['name'] = None
    return data

get_cached_data(self)

Fetches the most recent data from the cache based on the instance id

Source code in openhivenpy\types\private_room.py
def get_cached_data(self) -> Optional[dict]:
    """ Fetches the most recent data from the cache based on the instance id """
    return self._client.storage['rooms']['private']['single'][self.id]

json_validator(data)

send(self, content, delay=None) async

Sends a message in the private room.

:param content: Content of the message :param delay: Delay until sending the message (in seconds) :return: Returns a Message Instance if successful.

Source code in openhivenpy\types\private_room.py
async def send(
        self, content: str, delay: float = None
) -> Optional[Message]:
    """
    Sends a message in the private room. 

    :param content: Content of the message
    :param delay: Delay until sending the message (in seconds)
    :return: Returns a Message Instance if successful.
    """
    # TODO! Requires functionality check!
    try:
        if delay is not None:
            await asyncio.sleep(delay=delay)
        resp = await self._client.http.post(
            endpoint=f"/rooms/{self.id}/messages", json={"content": content}
        )

        raw_data = await resp.json()

        # Raw_data not in correct format => needs to access data field
        data = raw_data.get('data')

        data = message.Message.format_obj_data(data)
        msg = message.Message(data, self._client)
        return msg

    except Exception as e:
        utils.log_traceback(
            brief=f"Failed to send message in room {repr(self)}:",
            exc_info=sys.exc_info()
        )
        # TODO! Raise exception
        return None

start_call(self, delay=None) async

openhivenpy.types.PrivateRoom.start_call()

Starts a call with the user in the private room

:param delay: Delay until calling (in seconds) :return: True if successful

Source code in openhivenpy\types\private_room.py
async def start_call(self, delay: float = None) -> bool:
    """openhivenpy.types.PrivateRoom.start_call()

    Starts a call with the user in the private room

    :param delay: Delay until calling (in seconds)
    :return: True if successful
    """
    try:
        if delay is not None:
            await asyncio.sleep(delay=delay)

        resp = await self._client.http.post(f"/rooms/{self.id}/call")

        data = await resp.json()
        if data.get('data'):
            return True
        else:
            return False

    except Exception as e:
        utils.log_traceback(
            brief=f"Failed to start call in room {repr(self)}:",
            exc_info=sys.exc_info()
        )
        # TODO! Raise exception
        return False

openhivenpy.types.private_room.PrivateGroupRoom

Represents a private group chat room with multiple users

client_user: Optional[User] property readonly

description: Optional[int] property readonly

emoji: Optional[str] property readonly

id: Optional[str] property readonly

json_schema

last_message_id: Optional[str] property readonly

name: Optional[str] property readonly

recipients: Optional[List[User]] property readonly

type: Optional[int] property readonly

Methods

__init__(self, data, client) special

Source code in openhivenpy\types\private_room.py
def __init__(self, data: dict, client: HivenClient):
    try:
        self._id = data.get('id')
        self._last_message_id = data.get('last_message_id')
        self._recipients = data.get('recipients')
        self._name = data.get('name')
        self._description = data.get('description')
        self._emoji = data.get('emoji')
        self._type = data.get('type')
        self._client_user = client.client_user

    except Exception as e:
        utils.log_traceback(
            brief=f"Failed to initialise {self.__class__.__name__}:",
            exc_info=sys.exc_info()
        )
        raise InitializationError(f"Failed to initialise {self.__class__.__name__}") from e
    else:
        self._client = client

__repr__(self) special

Source code in openhivenpy\types\private_room.py
def __repr__(self) -> str:
    info = [
        ('id', self.id),
        ('last_message_id', self.last_message_id),
        ('recipients', self.recipients),
        ('type', self.type)
    ]
    return '<PrivateGroupRoom {}>'.format(' '.join('%s=%s' % t for t in info))

format_obj_data(data) classmethod

Validates the data and appends data if it is missing that would be required for the creation of an instance.


Does NOT contain other objects and only their ids!

:param data: Data that should be validated and used to form the object :return: The modified dictionary, which can then be used to create a new class instance

Source code in openhivenpy\types\private_room.py
@classmethod
def format_obj_data(cls, data: dict) -> dict:
    """
    Validates the data and appends data if it is missing that would be 
    required for the creation of an instance.

    ---

    Does NOT contain other objects and only their ids!

    :param data: Data that should be validated and used to form the object
    :return: The modified dictionary, which can then be used to create a
     new class instance
    """
    data = cls.validate(data)
    data['name'] = f"Private chat with {data['recipients'][0]['name']}"

    if type(data.get('recipients')) is list:
        data['recipients'] = [i['id'] for i in data['recipients']]

    return data

get_cached_data(self)

Fetches the most recent data from the cache based on the instance id

Source code in openhivenpy\types\private_room.py
def get_cached_data(self) -> Optional[dict]:
    """
    Fetches the most recent data from the cache based on the instance id
    """
    return self._client.storage['rooms']['private']['group'][self.id]

json_validator(data)

send(self, content, delay=None) async

Sends a message in the private room.

:param content: Content of the message :param delay: Seconds to wait until sending the message (in seconds) :return: A Message instance if successful else None

Source code in openhivenpy\types\private_room.py
async def send(self, content: str, delay: float = None) -> Optional[Message]:
    """
    Sends a message in the private room.

    :param content: Content of the message
    :param delay: Seconds to wait until sending the message (in seconds)
    :return: A Message instance if successful else None
    """
    try:
        if delay is not None:
            await asyncio.sleep(delay=delay)
        resp = await self._client.http.post(
            endpoint=f"/rooms/{self.id}/messages",
            json={"content": content}
        )

        raw_data = await resp.json()

        # Raw_data not in correct format => needs to access data field
        data = raw_data.get('data')

        data = message.Message.format_obj_data(data)
        msg = message.Message(data, self._client)
        return msg

    except Exception as e:
        utils.log_traceback(
            brief=f"Failed to send message in room {repr(self)}:",
            exc_info=sys.exc_info()
        )
        # TODO! Raise exception
        return None

start_call(self, delay=None) async

openhivenpy.types.PrivateGroupRoom.start_call()

Starts a call with the user in the private room

:param delay: Delay until calling (in seconds) :return: True if successful

Source code in openhivenpy\types\private_room.py
async def start_call(self, delay: float = None) -> bool:
    """openhivenpy.types.PrivateGroupRoom.start_call()

    Starts a call with the user in the private room

    :param delay: Delay until calling (in seconds)
    :return: True if successful
    """
    try:
        if delay is not None:
            await asyncio.sleep(delay=delay)
        await self._client.http.post(f"/rooms/{self.id}/call")
        return True

    except Exception as e:
        utils.log_traceback(
            brief=f"Failed to start call in {repr(self)}:",
            exc_info=sys.exc_info()
        )
        # TODO! Raise exception
        return False

openhivenpy.types.relationship.Relationship

Represents a user-relationship with another user or bot


Possible Types:

0 - No Relationship

1 - Outgoing Friend Request

2 - Incoming Friend Request

3 - Friend

4 - Restricted User

5 - Blocked User

id: Optional[str] property readonly

json_schema

type: Optional[int] property readonly

user: Optional[User] property readonly

user_id: Optional[str] property readonly

Methods

__init__(self, data, client) special

Source code in openhivenpy\types\relationship.py
def __init__(self, data: dict, client: HivenClient):
    try:
        self._user_id = data.get('user_id')
        self._user = data.get('user')
        self._type = data.get('type')
        self._last_updated_at = data.get('last_updated_at')

    except Exception as e:
        raise InitializationError(f"Failed to initialise {self.__class__.__name__}") from e
    else:
        self._client = client

__repr__(self) special

Source code in openhivenpy\types\relationship.py
def __repr__(self) -> str:
    info = [
        ('id', self.id),
        ('user_id', self.user_id),
        ('user', repr(self.user)),
        ('type', self.type)
    ]
    return '<Relationship {}>'.format(' '.join('%s=%s' % t for t in info))

format_obj_data(data) classmethod

Validates the data and appends data if it is missing that would be required for the creation of an instance.


Does NOT contain other objects and only their ids!

:param data: Data that should be validated and used to form the object :return: The modified dictionary, which can then be used to create a new class instance

Source code in openhivenpy\types\relationship.py
@classmethod
def format_obj_data(cls, data: dict) -> dict:
    """
    Validates the data and appends data if it is missing that would be 
    required for the creation of an instance.

    ---

    Does NOT contain other objects and only their ids!

    :param data: Data that should be validated and used to form the object
    :return: The modified dictionary, which can then be used to create a
     new class instance
    """
    data = cls.validate(data)
    data['type'] = utils.safe_convert(int, data.get('type'))

    if not data.get('user_id') and data.get('user'):
        user = data.pop('user')
        if type(user) is dict:
            user_id = user.get('id')
        elif isinstance(user, DataClassObject):
            user_id = getattr(user, 'id', None)
        else:
            user_id = None

        if user_id is None:
            raise InvalidPassedDataError("The passed user is not in the correct format!", data=data)
        else:
            data['user_id'] = user_id
    elif not data.get('user_id') and not data.get('user'):
        raise InvalidPassedDataError("user_id and user missing from required data", data=data)

    data['user'] = data['user_id']
    return data

get_cached_data(self)

Fetches the most recent data from the cache based on the instance id

Source code in openhivenpy\types\relationship.py
def get_cached_data(self) -> Optional[dict]:
    """ Fetches the most recent data from the cache based on the instance id """
    return self._client.storage['relationships'][self.user_id]

json_validator(data)

openhivenpy.types.textroom.TextRoom

Represents a Hiven Room inside a House


Possible Types:

0 - Text

1 - Portal

description: Optional[str] property readonly

emoji: Optional[str] property readonly

house: Optional[House] property readonly

house_id: Optional[str] property readonly

id: Optional[str] property readonly

json_schema

name: Optional[str] property readonly

position: Optional[int] property readonly

type: Optional[int] property readonly

Methods

__init__(self, data, client) special

Source code in openhivenpy\types\textroom.py
def __init__(self, data: dict, client: HivenClient):
    try:
        self._id = data.get('id')
        self._name = data.get('name')
        self._house_id = data.get('house_id')
        self._position = data.get('position')
        self._type = data.get('type')
        self._emoji = data.get('emoji')
        self._description = data.get('description')
        self._last_message_id = data.get('last_message_id')
        self._house = data.get('house')

    except Exception as e:
        raise InitializationError(f"Failed to initialise {self.__class__.__name__}") from e
    else:
        self._client = client

__repr__(self) special

Source code in openhivenpy\types\textroom.py
def __repr__(self) -> str:
    info = [
        ('name', self.name),
        ('id', self.id),
        ('house_id', self.house_id),
        ('position', self.position),
        ('type', self.type),
        ('emoji', self.emoji),
        ('description', self.description)
    ]
    return str('<Room {}>'.format(' '.join('%s=%s' % t for t in info)))

edit(self, **kwargs) async

Changes the rooms data on Hiven

Available options: emoji, name, description

:return: True if the request was successful else False

Source code in openhivenpy\types\textroom.py
async def edit(self, **kwargs) -> bool:
    """
    Changes the rooms data on Hiven

    Available options: emoji, name, description

    :return: True if the request was successful else False
    """
    try:
        for key in kwargs.keys():
            if key in ['emoji', 'name', 'description']:
                await self._client.http.patch(f"/rooms/{self.id}", json={key: kwargs.get(key)})

                return True
            else:
                raise NameError("The passed value does not exist in the Room!")

    except Exception as e:
        keys = "".join(key + " " for key in kwargs.keys()) if kwargs != {} else ''
        utils.log_traceback(
            brief=f"Failed to change the values {keys} in room {repr(self)}: ",
            exc_info=sys.exc_info()
        )
        # TODO! Raise exception
        return False

format_obj_data(data) classmethod

Validates the data and appends data if it is missing that would be required for the creation of an instance.

:param data: Data that should be validated and used to form the object :return: The modified dictionary, which can then be used to create a new class instance

Source code in openhivenpy\types\textroom.py
@classmethod
def format_obj_data(cls, data: dict) -> dict:
    """
    Validates the data and appends data if it is missing that would be
    required for the creation of an instance.

    :param data: Data that should be validated and used to form the object
    :return: The modified dictionary, which can then be used to create a 
     new class instance
    """
    if not data.get('house_id') and data.get('house'):
        house = data.pop('house')
        if type(house) is dict:
            house_id = house.get('id')
        elif isinstance(house, DataClassObject):
            house_id = getattr(house, 'id', None)
        else:
            house_id = None

        if house_id is None:
            raise InvalidPassedDataError("The passed house is not in the correct format!", data=data)
        else:
            data['house_id'] = house_id

    data['house'] = data['house_id']
    data = cls.validate(data)
    return data

get_cached_data(self)

Fetches the most recent data from the cache based on the instance id

Source code in openhivenpy\types\textroom.py
def get_cached_data(self) -> Optional[dict]:
    """ Fetches the most recent data from the cache based on the instance id """
    return self._client.storage['rooms']['house'][self.id]

get_recent_messages(self) async

Gets the recent messages from the current room

:return: A list of all messages in form of Message instances if successful.

Source code in openhivenpy\types\textroom.py
async def get_recent_messages(self) -> Optional[List[Message]]:
    """
    Gets the recent messages from the current room

    :return: A list of all messages in form of Message instances if successful.
    """
    try:
        raw_data = await self._client.http.get(f"/rooms/{self.id}/messages")
        raw_data = await raw_data.json()

        data = raw_data.get('data')

        messages_ = []
        for _ in data:
            msg = Message(_, self._client)
            messages_.append(msg)

        return messages_

    except Exception as e:
        utils.log_traceback(
            brief=f"Failed to create invite for house {repr(self)}:",
            exc_info=sys.exc_info()
        )
        # TODO! Raise exception
        return None

json_validator(data)

send(self, content, delay=None) async

Sends a message in the current room.

:param content: Content of the message :param delay: Seconds to wait until sending the message (in seconds) :return: A new message object if the request was successful

Source code in openhivenpy\types\textroom.py
async def send(self, content: str, delay: float = None) -> Optional[Message]:
    """
    Sends a message in the current room.

    :param content: Content of the message
    :param delay: Seconds to wait until sending the message (in seconds)
    :return: A new message object if the request was successful
    """
    try:
        if delay is not None:
            await asyncio.sleep(delay=delay)
        resp = await self._client.http.post(
            f"/rooms/{self.id}/messages",
            json={"content": content}
        )
        raw_data = await resp.json()

        # Raw_data not in correct format => needs to access data field
        data = raw_data.get('data')
        data = Message.format_obj_data(data)
        return Message(data, self._client)

    except Exception as e:
        utils.log_traceback(
            brief=f"Failed to send message in room {repr(self)}",
            exc_info=sys.exc_info()
        )
        # TODO! Raise exception
        return None

start_typing(self) async

Adds the client to the list of users typing

:return: True if the request was successful else False

Source code in openhivenpy\types\textroom.py
async def start_typing(self) -> bool:
    """
    Adds the client to the list of users typing

    :return: True if the request was successful else False
    """
    try:
        await self._client.http.post(f"/rooms/{self.id}/typing")

        return True

    except Exception as e:
        utils.log_traceback(
            brief=f"Failed to create invite for house {repr(self)}:",
            exc_info=sys.exc_info()
        )
        # TODO! Raise exception
        return False

openhivenpy.types.user.User

Represents the regular extended Hiven User

blocked: Optional[bool] property readonly

email: Optional[str] property readonly

json_schema

location: Optional[str] property readonly

mfa_enabled: Optional[bool] property readonly

presence: Optional[str] property readonly

website: Optional[str] property readonly

Methods

__init__(self, data, client) special

Source code in openhivenpy\types\user.py
def __init__(self, data: dict, client: HivenClient):
    try:
        super().__init__(data, client)
        self._location = data.get('location')
        self._website = data.get('website')
        self._blocked = data.get('blocked')
        self._presence = data.get('presence')
        self._email = data.get('email')
        self._mfa_enabled = data.get('mfa_enabled')

    except Exception as e:
        raise InitializationError(
            f"Failed to initialise {self.__class__.__name__}"
        ) from e

__repr__(self) special

Source code in openhivenpy\types\user.py
def __repr__(self) -> str:
    info = [
        ('username', self.username),
        ('name', self.name),
        ('id', self.id),
        ('icon', self.icon),
        ('header', self.header),
        ('bot', self.bot)
    ]
    return '<User {}>'.format(' '.join('%s=%s' % t for t in info))

format_obj_data(data) classmethod

Validates the data and appends data if it is missing that would be required for the creation of an instance.

:param data: Data that should be validated and used to form the object :return: The modified dictionary, which can then be used to create a new class instance

Source code in openhivenpy\types\user.py
@classmethod
def format_obj_data(cls, data: dict) -> dict:
    """
    Validates the data and appends data if it is missing that would be 
    required for the creation of an instance.

    :param data: Data that should be validated and used to form the object
    :return: The modified dictionary, which can then be used to create a 
     new class instance
    """
    data = LazyUser.format_obj_data(data)
    data = cls.validate(data)
    return data

get_cached_data(self)

Fetches the most recent data from the cache based on the instance id

Source code in openhivenpy\types\user.py
def get_cached_data(self) -> Optional[dict]:
    """ Fetches the most recent data from the cache based on the instance id """
    return self._client.storage['users'][self.id]

json_validator(data)

openhivenpy.types.usertyping.UserTyping

Represents a Hiven User typing in a room

author: Optional[User] property readonly

author_id: Optional[str] property readonly

house: Optional[House] property readonly

house_id: Optional[str] property readonly

room: Optional[TextRoom] property readonly

room_id: Optional[str] property readonly

timestamp: Optional[datetime.datetime] property readonly

__init__(self, data, client) special

Source code in openhivenpy\types\usertyping.py
def __init__(self, data: dict, client: HivenClient):
    try:
        self._author = data.get('author')
        self._room = data.get('room')
        self._house = data.get('house')
        self._author_id = data.get('author_id')
        self._house_id = data.get('house_id')
        self._room_id = data.get('room_id')
        self._timestamp = data.get('timestamp')

    except Exception as e:
        raise InitializationError(
            f"Failed to initialise {self.__class__.__name__}"
        ) from e
    else:
        self._client = client

__repr__(self) special

Source code in openhivenpy\types\usertyping.py
def __repr__(self) -> str:
    info = [
        ('house_id', self.house_id),
        ('author_id', self.author_id),
        ('room_id', self.room_id),
        ('author', repr(self.author))
    ]
    return '<Typing {}>'.format(' '.join('%s=%s' % t for t in info))

Last update: 2021-08-21