Skip to content

Hiven Types


Important

Note that each type has a property that is cached! Meaning when you access one, it is stored forever without any changes (deletions or updates) being applied to it.

For example: When you access the rooms property of the House class and use it for a longer time and in the meantime one of them gets deleted. The library will be unable to correctly delete it, since it's now stored by the user themselves. Therefore watch out for the proper existance!

In the next releases a property exists() will be added to validate the existance of objects to not possibly use an outdated one!

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
LazyHouse Represents a Hiven House which can contain rooms and entities (Lazy)
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
LazyUser Represents the standard Hiven User (Lazy)
UserTyping Represents a Hiven User typing in a room

openhivenpy.types.attachment.Attachment

Represents a Hiven Message Attachment containing a file

Attributes

filename: str property readonly

Name of the file

media_url: str property readonly

Media-url to access the file

raw: dict property readonly

The raw data dictionary received over the Swarm

Methods

__init__(self, data, client) special

Represents a Hiven Message Attachment containing a file

Parameters:

Name Type Description Default
data dict

Data that should be used to create the object

required
client HivenClient

The HivenClient

required
Source code in openhivenpy\types\attachment.py
@log_type_exception('Attachment')
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
    """
    super().__init__()
    self._filename = data.get('filename')
    self._media_url = data.get('media_url')
    self._raw = data.get('raw')
    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.

Parameters:

Name Type Description Default
data dict

Data that should be validated and used to form the object

required

Returns:

Type Description
dict

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

Attributes

author: Optional[User] property readonly

Author object of the Context Class

author_id: Optional[str] property readonly

ID of the author

house: Optional[House] property readonly

House object of the Context Class

house_id: Optional[str] property readonly

ID of the room

room: Optional[TextRoom] property readonly

Room object of the Context Class

room_id: Optional[str] property readonly

ID of the room

timestamp: Optional[datetime.datetime] property readonly

Time-stamp of the message - when the command was received

Methods

__init__(self, data, client) special

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

Parameters:

Name Type Description Default
data dict

Data that should be used to create the object

required
client HivenClient

The HivenClient

required
Source code in openhivenpy\types\context.py
@log_type_exception('Context')
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
    """
    super().__init__()
    self._room = data.get('room')
    self._room_id = data.get('room_id')
    self._author = data.get('author')
    self._author_id = data.get('author_id')
    self._house = data.get('house')
    self._house_id = data.get('house_id')
    self._timestamp = data.get('timestamp')
    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!

Parameters:

Name Type Description Default
data dict

Data that should be validated and used to form the object

required

Returns:

Type Description
dict

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.

This can represent an either customised embed or fetched embed from a website

Attributes

description: Optional[str] property readonly

The description of the embed, if it has one

image: Optional[str] property readonly

The URL to the image of the embed

title: Optional[str] property readonly

The title of the embed

type: Optional[int] property readonly

The type of the Embed

url: Optional[str] property readonly

The URL of the embed, if it's a web embed

Methods

__init__(self, data, client) special

Represents an embed message object either customised or from a website

Parameters:

Name Type Description Default
data dict

Data that should be used to create the object

required
client HivenClient

The HivenClient

required
Source code in openhivenpy\types\embed.py
@log_type_exception('Embed')
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
    """
    super().__init__()
    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')
    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.

Parameters:

Name Type Description Default
data dict

Data that should be validated and used to form the object

required

Returns:

Type Description
dict

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 object of the entity

house_id: Optional[str] property readonly

ID of the House parent of the Entity

id: Optional[str] property readonly

ID of the entity

name: Optional[str] property readonly

Name of the entity

position: Optional[int] property readonly

Position on the sidebar of the Room

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

Type of the entity

Methods

__init__(self, data, client) special

Represents a Hiven Entity inside a House which can contain Rooms

Parameters:

Name Type Description Default
data dict

Data that should be used to create the object

required
client HivenClient

The HivenClient

required
Source code in openhivenpy\types\entity.py
@log_type_exception('Entity')
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
    """
    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')
    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!

Parameters:

Name Type Description Default
data dict

Data that should be validated and used to form the object

required

Returns:

Type Description
dict

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.

If updated while the object exists, the data might differentiate, due to the object not being updated unlike the cache.

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.

    If updated while the object exists, the data might differentiate, due
    to the object not being updated unlike the cache.
    """
    return self._client.find_entity(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
@log_type_exception('Feed')
def __init__(self, data: dict, client: HivenClient):
    super().__init__()

__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)

Important

The class LazyHouse is inherited into the class House, meaning all properties of the LazyHouse class are also available in the standard House class

openhivenpy.types.house.House

Represents a Hiven House which can contain rooms and entities

Attributes

banner: Optional[str] property readonly

The banner of the House

client_member: Optional[Member] property readonly

The logged-in client as the member object

default_permissions: Optional[int] property readonly

Returns the default permissions for this House

entities: Optional[List[Entity]] property readonly

A list of the entities in this House

members: Optional[List[Member]] property readonly

A list of members in this house

owner: Optional[Member] property readonly

Owner Object of this House

roles: Optional[list] property readonly

A list of the roles in this House

users: Optional[List[Member]] property readonly

A list of members in this house. Alias for members

Methods

__init__(self, data, client) special

Source code in openhivenpy\types\house.py
@log_type_exception('House')
def __init__(self, data: dict, client: HivenClient):
    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
    super().__init__(data, client)

create_entity(self, name) async

Creates a entity in the house with the specified name.

Parameters:

Name Type Description Default
name str

The name of the new entity

required

Returns:

Type Description
Optional[Entity]

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()
        )
        raise e

create_invite(self, max_uses) async

Creates an invite for the current house.

Parameters:

Name Type Description Default
max_uses int

Maximal uses for the invite code

required

Returns:

Type Description
Optional[Invite]

The invite url if successful.

Exceptions:

Type Description
HTTPError

If any HTTP error is raised while executing

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.
    :raise HTTPError: If any HTTP error is raised while executing
    """
    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()
        )
        raise e

create_room(self, name, parent_entity_id=None) async

Creates a Room in the house with the specified name.

Returns:

Type Description
Optional[TextRoom]

A Room Instance for the Hiven Room that was created if successful

Exceptions:

Type Description
HTTPError

If any HTTP error is raised while executing

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
    :raise HTTPError: If any HTTP error is raised while executing
    """
    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()
        )
        raise e

delete(self) async

Deletes the house if permissions are sufficient!

Exceptions:

Type Description
HTTPError

If any HTTP error is raised while executing

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

    :raise HTTPError: If any HTTP error is raised while executing
    """
    try:
        await self._client.http.delete(f"/houses/{self.id}")

    except Exception as e:
        utils.log_traceback(
            brief=f"Failed to delete House {repr(self)}",
            exc_info=sys.exc_info()
        )
        raise e

edit(self, **kwargs) async

Changes the houses data on Hiven.

Available options: name, icon(base64)

Exceptions:

Type Description
HTTPError

If any HTTP error is raised while executing

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

    Available options: name, icon(base64)

    :raise HTTPError: If any HTTP error is raised while executing
    """
    try:
        for key, data in kwargs.items():
            if key in ['name']:
                await self._client.http.patch(
                    endpoint=f"/houses/{self.id}", json={key: data}
                )
            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()
        )
        raise e

find_entity(self, entity_id)

Fetches the raw data of a entity

Parameters:

Name Type Description Default
entity_id str

The id of the entity which should be fetched

required

Returns:

Type Description
Optional[dict]

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.find_entity(entity_id)

find_member(self, member_id)

Fetches the raw data of a member

Parameters:

Name Type Description Default
member_id str

The id of the Member which should be fetched

required

Returns:

Type Description
Optional[dict]

The dictionary of the member 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 dictionary of the member if it was found
    """
    return self._client.find_house_member(member_id, self.id)

find_room(self, room_id)

Fetches the raw data of a room

Parameters:

Name Type Description Default
room_id str

The id of the room which should be fetched

required

Returns:

Type Description
Optional[dict]

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.find_room(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!

Parameters:

Name Type Description Default
data dict

Data that should be validated and used to form the object

required

Returns:

Type Description
dict

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

Returns:

Type Description
Optional[Entity]

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
    """
    return self._client.get_entity(entity_id)

get_member(self, member_id)

Fetches a member from the cache based on the id

Parameters:

Name Type Description Default
member_id str

The id of the Member which should be fetched

required

Returns:

Type Description
Optional[Member]

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

    :param member_id: The id of the Member which should be fetched
    :return: The Member Instance if it exists else returns None
    """
    return self._client.get_house_member(member_id, self.id)

get_room(self, room_id)

Fetches a room from the cache based on the id

Returns:

Type Description
Optional[TextRoom]

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
    """
    return self._client.get_room(room_id)

json_validator(data)

leave(self) async

Leaves the house

Exceptions:

Type Description
HTTPError

If any HTTP error is raised while executing

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

    :raise HTTPError: If any HTTP error is raised while executing
    """
    try:
        await self._client.http.delete(
            endpoint=f"/users/@me/houses/{self.id}"
        )

    except Exception as e:
        utils.log_traceback(
            brief=f"Failed to leave {repr(self)}:",
            exc_info=sys.exc_info()
        )
        raise e

openhivenpy.types.house.LazyHouse

Represents a Hiven House which can contain rooms and entities

Note! This class is a lazy class and does not have every available data!

Consider fetching for more data the regular house object with HivenClient.get_house()

Attributes

icon: Optional[str] property readonly

URL to the ICON of this house. None if it doesn't exist

id: Optional[str] property readonly

Id of the House

name: Optional[str] property readonly

Name of the House

owner_id: Optional[int] property readonly

Owner user-id of this House

rooms: Optional[list] property readonly

List of all rooms in the house

type: Optional[int] property readonly

Type of the House

Methods

__init__(self, data, client) special

Represents a Hiven House which can contain rooms and entities

Parameters:

Name Type Description Default
data dict

Data that should be used to create the object

required
client HivenClient

The HivenClient

required
Source code in openhivenpy\types\house.py
@log_type_exception('LazyHouse')
def __init__(self, data: dict, client: HivenClient):
    """
    Represents a Hiven House which can contain rooms and entities

    :param data: Data that should be used to create the object
    :param client: The HivenClient
    """
    super().__init__()
    self._id = data.get('id')
    self._name = data.get('name')
    self._icon = data.get('icon')
    self._owner_id = data.get('owner_id')
    self._owner = data.get('owner')
    self._rooms = data.get('rooms')
    self._type = data.get('type')
    self._client = client

__repr__(self) special

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

__str__(self) special

Source code in openhivenpy\types\house.py
def __str__(self):
    return self.name

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! Only exceptions are member objects which are unique in every house

Parameters:

Name Type Description Default
data dict

Data that should be validated and used to form the object

required

Returns:

Type Description
dict

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!
    Only exceptions are member objects which are unique in every house

    :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)
    if not data.get('owner_id') and data.get('owner'):
        owner = data.pop('owner')
        if type(owner) is dict:
            owner_id = owner.get('id')
        elif isinstance(owner, DataClassObject):
            owner_id = getattr(owner, 'id', None)
        else:
            owner_id = None

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

    if type(data.get('members')) is list:
        members = data['members']
        data['members'] = {}
        for member_ in members:
            id_ = member_['user_id'] if member_.get('user_id') \
                else member_.get('user', {}).get('id')
            data['members'][id_] = utils.update_and_return(
                member_, user=id_  # replacing the object with an id ref
            )

    if type(data.get('roles')) is list:
        roles = data['roles']
        data['roles'] = {}
        for role in roles:
            id_ = role.get('id')
            data['roles'][id_] = role

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

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

    data['owner'] = data['owner_id']
    return data

get_cached_data(self)

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

If updated while the object exists, the data might differentiate, due to the object not being updated unlike the cache.

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

    If updated while the object exists, the data might differentiate, due
    to the object not being updated unlike the cache.
    """
    return self._client.find_house(self.id)

json_validator(data)

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

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
@log_type_exception('Invite')
def __init__(self, data: dict, client: HivenClient):
    super().__init__()
    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')
    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!

Parameters:

Name Type Description Default
data dict

Data that should be validated and used to form the object

required

Returns:

Type Description
dict

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

Parent House object instance of this class

house_id: Optional[str] property readonly

Returns the ID of the parent House

id: Optional[str] property readonly

User-ID of the member. Alias for user_id

joined_at: Optional[str] property readonly

Joined at date (unix-timestamp probably)

joined_house_at: Optional[str] property readonly

Joined at date (unix-timestamp probably). Alias for joined_at

roles: Optional[List[dict]] property readonly

Returns the roles of the Member

user_id: Optional[str] property readonly

User-ID of the member

Methods

__init__(self, data, client) special

Source code in openhivenpy\types\member.py
@log_type_exception('Member')
def __init__(self, data: dict, client: HivenClient):
    super().__init__(data.get('user'), client)
    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')

__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!

Parameters:

Name Type Description Default
data dict

Data that should be validated and used to form the object

required

Returns:

Type Description
dict

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.

Exceptions:

Type Description
HTTPError

If any HTTP error is raised while executing

Forbidden

If the client does not have the permissions to execute this command

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

    :raise HTTPError: If any HTTP error is raised while executing
    :raises Forbidden: If the client does not have the permissions to
     execute this command
    """
    try:
        endpoint = f"/{self._house_id}/members/{self._user_id}"
        await self._client.http.delete(endpoint)

    except (HTTPForbiddenError, HTTPFailedRequestError) as e:
        utils.log_traceback(
            brief=f"Failed to kick the member due to an exception "
                  "occurring:",
            exc_info=sys.exc_info()
        )
        raise e

openhivenpy.types.mention.Mention

Represents an mention for a user in Hiven

Attributes

author: Optional[User] property readonly

The author of the message containing the mention

author_id: Optional[str] property readonly

timestamp: Optional[datetime.datetime] property readonly

Returns the timestamp when the mention was made

user: Optional[User] property readonly

Returns the User mentioned

user_id: Optional[str] property readonly

The id of the user mentioned

Methods

__init__(self, data, client) special

Source code in openhivenpy\types\mention.py
@log_type_exception('Mention')
def __init__(self, data: dict, client: HivenClient):
    super().__init__()
    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')
    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!

Parameters:

Name Type Description Default
data dict

Data that should be validated and used to form the object

required

Returns:

Type Description
dict

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

Attributes

house_id: Optional[str] property readonly

ID of the original house (None if it does not exist)

message_id: Optional[str] property readonly

ID of the original message

room_id: Optional[str] property readonly

ID of the original room (can be private)

Methods

__init__(self, data, client) special

Source code in openhivenpy\types\message.py
@log_type_exception('DeletedMessage')
def __init__(self, data: dict, client: HivenClient):
    super().__init__()
    self._message_id = data.get('message_id')
    self._house_id = data.get('house_id')
    self._room_id = data.get('room_id')
    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.

Parameters:

Name Type Description Default
data dict

Data that should be validated and used to form the object

required

Returns:

Type Description
dict

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

Attributes

attachment: Optional[Attachment] property readonly

Returns the Attachment of the message, if it has one

author: Optional[User] property readonly

Returns the Author parent object instance

author_id: Optional[str] property readonly

ID of the parent Author

bucket: Optional[int] property readonly

Returns the bucket of the message

content: Optional[str] property readonly

Returns the string content of the message

device_id: Optional[str] property readonly

Returns the device id of the author of the message

edited_at: Optional[str] property readonly

Returns the date the message was edited (unix-timestamp)

embed: Embed property readonly

Returns the Embed of the message, if it has one

exploding: Optional[bool] property readonly

Returns whether the message is exploding

exploding_age: Optional[int] property readonly

Returns the exploding age of the message

house: Optional[House] property readonly

Returns the House parent object, if the message was sent inside a House

house_id: Optional[str] property readonly

Returns the id of the House parent object, if the message was sent inside a House

id: Optional[str] property readonly

ID of the message

is_house_message: bool property readonly

Returns whether the message was sent inside a House

mentions: Optional[List[Mention]] property readonly

Returns the mentions of the message

recipient_ids: Optional[List[str]] property readonly

A list of all recipients in the room - unique for the private rooms

room: Optional[TextRoom] property readonly

Returns the Room parent object the message was sent in

room_id: Optional[str] property readonly

Returns the id of the Room parent object

timestamp: Optional[datetime.datetime] property readonly

Returns the date the message was created (unix-timestamp)

type: Optional[int] property readonly

Returns the type of the message

Methods

__init__(self, data, client) special

Source code in openhivenpy\types\message.py
@log_type_exception('Message')
def __init__(self, data: dict, client: HivenClient):
    super().__init__()
    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')
    # I believe, 0 = normal message, 1 = system.
    self._type = data.get('type')
    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')
    self._recipient_ids = data.get('recipient_ids')
    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.

Parameters:

Name Type Description Default
delay float

Delay until deleting the message as read (in seconds)

None

Exceptions:

Type Description
HTTPError

If any HTTP error is raised while executing

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

    :param delay: Delay until deleting the message as read (in seconds)
    :raise HTTPError: If any HTTP error is raised while executing
    """
    try:
        if delay is not None:
            await asyncio.sleep(delay=delay)

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

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

edit(self, content) async

Edits a message on Hiven

Exceptions:

Type Description
HTTPError

If any HTTP error is raised while executing

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

    :raise HTTPError: If any HTTP error is raised while executing
    """
    try:
        await self._client.http.patch(
            endpoint=f"/rooms/{self.room_id}/messages/{self.id}",
            json={'content': content}
        )

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

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!

Parameters:

Name Type Description Default
data dict

Data that should be validated and used to form the object

required

Returns:

Type Description
dict

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.

Parameters:

Name Type Description Default
delay float

Delay until marking the message as read (in seconds)

None

Exceptions:

Type Description
HTTPError

If any HTTP error is raised while executing

Source code in openhivenpy\types\message.py
async def mark_as_read(self, delay: float = None) -> None:
    """
    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)
    :raise HTTPError: If any HTTP error is raised while executing
    """
    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"
        )

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

openhivenpy.types.private_room.PrivateRoom

Represents a private chat room with only one user

Attributes

client_user: Optional[User] property readonly

Returns the client_user of this class

description: Optional[str] property readonly

Return the description of the PrivateRoom

emoji: Optional[str] property readonly

The emoji of the PrivateRoom, if it has one

id: Optional[str] property readonly

Returns the id of the PrivateRoom

last_message_id: Optional[str] property readonly

The id of the last sent message

name: Optional[str] property readonly

Name of the PrivateRoom

recipient: Optional[User] property readonly

Returns the recipient object instance

recipient_id: Optional[str] property readonly

The ID of the recipient

type: Optional[int] property readonly

The type of the PrivateRoom

Methods

__init__(self, data, client) special

Source code in openhivenpy\types\private_room.py
@log_type_exception('PrivateRoom')
def __init__(self, data: dict, client: HivenClient):
    super().__init__()
    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

__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!

Parameters:

Name Type Description Default
data dict

Data that should be validated and used to form the object

required

Returns:

Type Description
dict

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.

If updated while the object exists, the data might differentiate, due to the object not being updated unlike the cache.

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.

    If updated while the object exists, the data might differentiate, due
    to the object not being updated unlike the cache.
    """
    return self._client.find_private_room(self.id)

json_validator(data)

send(self, content, delay=None) async

Sends a message in the private room.

Parameters:

Name Type Description Default
content str

Content of the message

required
delay float

Delay until sending the message (in seconds)

None

Returns:

Type Description
Optional[Message]

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.
    """
    raise NotImplementedError(
        "This is not implemented yet for Private Rooms"
    )

start_call(self, delay=None) async

Starts a call with the user in the private room

Not implemented

Parameters:

Name Type Description Default
delay float

Delay until calling (in seconds)

None
Source code in openhivenpy\types\private_room.py
async def start_call(self, delay: float = None) -> bool:
    """
    Starts a call with the user in the private room

    *Not implemented*

    :param delay: Delay until calling (in seconds)
    """
    raise NotImplementedError(
        "This is not implemented yet for Private Rooms"
    )

openhivenpy.types.private_room.PrivateGroupRoom

Represents a private group chat room with multiple users

Attributes

client_user: Optional[User] property readonly

Returns the Client User inside this PrivateGroupRoom

description: Optional[int] property readonly

Returns the description of the PrivateGroupRoom

emoji: Optional[str] property readonly

Returns the emoji of this PrivateGroupRoom if it exists

id: Optional[str] property readonly

Returns the id of the PrivateGroupRoom

last_message_id: Optional[str] property readonly

Returns the id of the last message inside the PrivateGroupRoom

name: Optional[str] property readonly

Returns the name of the PrivateGroupRoom

recipients: Optional[List[User]] property readonly

Returns a list of all recipients

type: Optional[int] property readonly

Returns the type of this PrivateGroupRoom

Methods

__init__(self, data, client) special

Source code in openhivenpy\types\private_room.py
@log_type_exception('PrivateGroupRoom')
def __init__(self, data: dict, client: HivenClient):
    super().__init__()
    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
    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!

Parameters:

Name Type Description Default
data dict

Data that should be validated and used to form the object

required

Returns:

Type Description
dict

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']}"

    rep = data.get('recipients')
    id_list: List[str] = []
    if type(rep) is list:
        for user in rep:
            if type(user) is dict:
                id_list += str(user.get('id', None))
            elif isinstance(user, DataClassObject):
                id_list += str(getattr(user, 'id', None))
            else:
                raise InvalidPassedDataError(
                    "The passed recipient is not in the correct "
                    "format!",
                    data=data
                )
    else:
        raise InvalidPassedDataError(
            "The passed recipients are not in the correct format!",
            data=data
        )
    data['recipients'] = id_list
    return data

get_cached_data(self)

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

If updated while the object exists, the data might differentiate, due to the object not being updated unlike the cache.

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.

    If updated while the object exists, the data might differentiate, due
    to the object not being updated unlike the cache.
    """
    return self._client.find_private_group_room(self.id)

json_validator(data)

send(self, content, delay=None) async

Sends a message in the private room.

Not implemented

Parameters:

Name Type Description Default
content str

Content of the message

required
delay float

Seconds to wait until sending the message (in seconds)

None

Returns:

Type Description
Optional[Message]

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.

    *Not implemented*

    :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
    """
    raise NotImplementedError(
        "This is not implemented yet for Private Rooms"
    )

start_call(self, delay=None) async

Starts a call with the user in the private room

Not implemented

Parameters:

Name Type Description Default
delay float

Delay until calling (in seconds)

None

Exceptions:

Type Description
HTTPError

If any HTTP error is raised while executing

Source code in openhivenpy\types\private_room.py
async def start_call(self, delay: float = None) -> bool:
    """
    Starts a call with the user in the private room

    *Not implemented*

    :param delay: Delay until calling (in seconds)
    :raise HTTPError: If any HTTP error is raised while executing
    """
    raise NotImplementedError(
        "This is not implemented yet for Private Rooms"
    )

openhivenpy.types.relationship.Relationship

Represents a user-relationship with another user or bot


Possible Type of the Relationship: 0 - No Relationship

    1 - Outgoing Friend Request

    2 - Incoming Friend Request

    3 - Friend

    4 - Restricted User

    5 - Blocked User

Attributes

id: Optional[str] property readonly

Alias for user_id. Stored using the target user id in the cache

type: Optional[int] property readonly

Possible Type of the relationship: 0 - No Relationship

1 - Outgoing Friend Request

2 - Incoming Friend Request

3 - Friend

4 - Restricted User

5 - Blocked User

user: Optional[User] property readonly

Target User Object

user_id: Optional[str] property readonly

ID of the target user

Methods

__init__(self, data, client) special

Source code in openhivenpy\types\relationship.py
@log_type_exception('Relationship')
def __init__(self, data: dict, client: HivenClient):
    super().__init__()
    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')
    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!

Parameters:

Name Type Description Default
data dict

Data that should be validated and used to form the object

required

Returns:

Type Description
dict

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.

If updated while the object exists, the data might differentiate, due to the object not being updated unlike the cache.

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.

    If updated while the object exists, the data might differentiate, due
    to the object not being updated unlike the cache.
    """
    return self._client.find_relationship(self.user_id)

json_validator(data)

openhivenpy.types.textroom.TextRoom

Represents a Hiven Room inside a House


Possible Types: 0 - Text

    1 - Portal

Attributes

description: Optional[str] property readonly

The description of the Room

emoji: Optional[str] property readonly

The assigned emoji of the room

house: Optional[House] property readonly

The parent house object

house_id: Optional[str] property readonly

The ID of the parent house

id: Optional[str] property readonly

ID of the Room

name: Optional[str] property readonly

Name of the Room

position: Optional[int] property readonly

Position on the sidebar of the Room

type: Optional[int] property readonly

Type of the Room (always 0 for TextRoom)

Methods

__init__(self, data, client) special

Source code in openhivenpy\types\textroom.py
@log_type_exception('TextRoom')
def __init__(self, data: dict, client: HivenClient):
    super().__init__()
    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')
    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

Exceptions:

Type Description
HTTPError

If any HTTP error is raised while executing

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

    Available options: emoji, name, description

    :raise HTTPError: If any HTTP error is raised while executing
    """
    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)}
                )
            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()
        )
        raise e

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.

Parameters:

Name Type Description Default
data dict

Data that should be validated and used to form the object

required

Returns:

Type Description
dict

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.

If updated while the object exists, the data might differentiate, due to the object not being updated unlike the cache.

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.

    If updated while the object exists, the data might differentiate, due
    to the object not being updated unlike the cache.
    """
    return self._client.find_room(self.id)

get_recent_messages(self) async

Gets the recent messages from the current room

Returns:

Type Description
Optional[List[Message]]

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

Exceptions:

Type Description
HTTPError

If any HTTP error is raised while executing

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.
    :raise HTTPError: If any HTTP error is raised while executing
    """
    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()
        )
        raise e

json_validator(data)

send(self, content, delay=None) async

Sends a message in the current room.

Parameters:

Name Type Description Default
content str

Content of the message

required
delay float

Seconds to wait until sending the message (in seconds)

None

Returns:

Type Description
Optional[Message]

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()
        )
        raise e

start_typing(self) async

Adds the client to the list of users typing

Exceptions:

Type Description
HTTPError

If any HTTP error is raised while executing

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

    :raise HTTPError: If any HTTP error is raised while executing
    """
    try:
        await self._client.http.post(f"/rooms/{self.id}/typing")

    except Exception as e:
        utils.log_traceback(
            brief=f"Failed to create invite for house {repr(self)}:",
            exc_info=sys.exc_info()
        )
        raise e

Important

The class LazyUser is inherited into the class User, meaning all properties of the LazyUser class are also available in the standard User class

openhivenpy.types.user.User

Represents the regular extended Hiven User

Attributes

blocked: Optional[bool] property readonly

Returns whether the user is blocked

email: Optional[str] property readonly

The e-mail of the user. Client-limited

location: Optional[str] property readonly

Set location of the user

mfa_enabled: Optional[bool] property readonly

Returns whether mfa is enabled

presence: Optional[str] property readonly

Current presence of the User

website: Optional[str] property readonly

Set website of the user

Methods

__init__(self, data, client) special

Source code in openhivenpy\types\user.py
@log_type_exception('User')
def __init__(self, data: dict, client: HivenClient):
    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')

__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.

Parameters:

Name Type Description Default
data dict

Data that should be validated and used to form the object

required

Returns:

Type Description
dict

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

json_validator(data)

openhivenpy.types.user.LazyUser

Represents the standard Hiven User

Note! This class is a lazy class and does not have every available data!

Consider fetching for more data the regular user object with HivenClient.get_user()

Attributes

account: Optional[str] property readonly

Returns the account id/string. Currently client-limited

application: Optional[bool] property readonly

Returns the application string passed. Currently client-limited

bio: Optional[str] property readonly

Bio of the user

bot: Optional[bool] property readonly

Returns true when the user is a bot

email_verified: Optional[bool] property readonly

Returns True if the email is verified

flags: Optional[Union[int, str]] property readonly

User flags represented as an numeric value/str

header: Optional[str] property readonly

The header of the user as a link

icon: Optional[str] property readonly

The icon of the user as a link

id: Optional[str] property readonly

Unique string id of the user

name: Optional[str] property readonly

Name of the user

user_flags: Optional[Union[int, str]] property readonly

Alias for flags

username: Optional[str] property readonly

Username of the user

Methods

__init__(self, data, client) special

Source code in openhivenpy\types\user.py
@log_type_exception('LazyUser')
def __init__(self, data: dict, client: HivenClient):
    super().__init__()
    self._username = data.get('username')
    self._name = data.get('name')
    self._bio = data.get('bio')
    self._id = data.get('id')
    self._email_verified = data.get('email_verified')
    # ToDo: Discord.py-esque way of user flags
    self._flags = data.get('flags')
    self._icon = data.get('icon')
    self._header = data.get('header')
    self._bot = data.get('bot', False)
    self._client = client

__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 '<LazyUser {}>'.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.

Parameters:

Name Type Description Default
data dict

Data that should be validated and used to form the object

required

Returns:

Type Description
dict

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 = cls.validate(data)
    return data

get_cached_data(self)

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

If updated while the object exists, the data might differentiate, due to the object not being updated unlike the cache.

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.

    If updated while the object exists, the data might differentiate, due
    to the object not being updated unlike the cache.
    """
    return self._client.find_user(self.id)

json_validator(data)

openhivenpy.types.usertyping.UserTyping

Represents a Hiven User typing in a room

Attributes

author: Optional[User] property readonly

Author object of the User-Typing Class

author_id: Optional[str] property readonly

ID of the parent Author object of the Context Class

house: Optional[House] property readonly

House object of the Context Class

house_id: Optional[str] property readonly

ID of the parent House object of the Context Class

is_house_typing: bool property readonly

Returns whether the typing is inside a house

room: Optional[TextRoom] property readonly

Room object of the Context Class

room_id: Optional[str] property readonly

ID of the parent Room object of the Context Class

timestamp: Optional[datetime.datetime] property readonly

Time-stamp of the User-Typing (unix)

__init__(self, data, client) special

Source code in openhivenpy\types\usertyping.py
@log_type_exception('UserTyping')
def __init__(self, data: dict, client: HivenClient):
    super().__init__()
    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')
    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-09-12