Skip to content
This repository has been archived by the owner on Apr 29, 2022. It is now read-only.

Commit

Permalink
Removed deprecated presence class, updated tracebacks and updated the…
Browse files Browse the repository at this point in the history
… version to v0.1.3.2
  • Loading branch information
Nicolas-Klatzer committed Apr 9, 2021
1 parent bbe27e1 commit 1530e9d
Show file tree
Hide file tree
Showing 26 changed files with 87 additions and 137 deletions.
2 changes: 1 addition & 1 deletion MANIFEST.in
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
global-include requirements.txt
include openhivenpy/*.env
exclude doc-examples
global-exclude *__pycache__*/
graft openhivenpy
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# ![OpenHiven.py](https://images.nxybi.me/da4e88d64f12.png) <br> OpenHiven.py
## The OpenSource Python API Wrapper for Hiven!

[![Package Version](https://img.shields.io/badge/package%20version-v0.1.3.1-purple?logo=python)](https://github.com/Nicolas-Klatzer/openhiven.py)
[![Package Version](https://img.shields.io/badge/package%20version-v0.1.3.2-purple?logo=python)](https://github.com/Nicolas-Klatzer/openhiven.py)
[![Python Version](https://img.shields.io/badge/python->=3.7-blue?logo=python)](https://python.org)
![Build](https://img.shields.io/github/workflow/status/Nicolas-Klatzer/openhiven.py/CodeQL?logo=github)
[![Latest Commit](https://img.shields.io/github/last-commit/Nicolas-Klatzer/openhiven.py?logo=github&color=violet)](https://github.com/Nicolas-Klatzer/openhiven.py/commits/mainy)
Expand Down
2 changes: 1 addition & 1 deletion openhivenpy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
__title__ = "openhiven.py"
__author__ = "Nicolas Klatzer"
__license__ = "MIT"
__version__ = "0.1.3.1"
__version__ = "0.1.3.2"
__copyright__ = "Nicolas Klatzer"

import logging
Expand Down
12 changes: 5 additions & 7 deletions openhivenpy/client/hivenclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ class HivenClient(EventHandler):
"""
Main Class for connecting to Hiven and interacting with the API.
"""

def __init__(
self,
token: str,
Expand Down Expand Up @@ -183,8 +184,7 @@ async def connect(self,
utils.log_traceback(msg="[HIVENCLIENT] Traceback:",
suffix=f"Failed to establish or keep the connection alive: \n"
f"{sys.exc_info()[0].__name__}: {e}!")
raise errs.SessionCreateError("Failed to establish HivenClient session! >"
f"{sys.exc_info()[0].__name__}: {e}")
raise errs.SessionCreateError("Failed to establish HivenClient session!") from e

def run(self,
*,
Expand Down Expand Up @@ -222,8 +222,7 @@ def run(self,
msg="[HIVENCLIENT] Traceback:",
suffix="Failed to establish or keep the connection alive: \n"
f"{sys.exc_info()[0].__name__}: {e}!")
raise errs.SessionCreateError("Failed to establish HivenClient session! >"
f"{sys.exc_info()[0].__name__}: {e}")
raise errs.SessionCreateError("Failed to establish HivenClient session!") from e

async def destroy(self, reason: str = "", *, exec_loop=True) -> bool:
"""
Expand All @@ -248,7 +247,7 @@ async def destroy(self, reason: str = "", *, exec_loop=True) -> bool:
suffix=f"Failed to close client session and websocket to Hiven: \n"
f"{sys.exc_info()[0].__name__}: {e}")
raise errs.ClosingError(f"Failed to close client session and websocket to Hiven! > "
f"{sys.exc_info()[0].__name__}: {e}")
f"{sys.exc_info()[0].__name__}: {e}")

async def close(self, reason: str = "", *, close_exec_loop=True) -> bool:
"""
Expand All @@ -274,8 +273,7 @@ async def close(self, reason: str = "", *, close_exec_loop=True) -> bool:
utils.log_traceback(msg="[HIVENCLIENT] Traceback:",
suffix=f"Failed to close client session and websocket to Hiven: \n"
f"{sys.exc_info()[0].__name__}: {e}")
raise errs.ClosingError(f"Failed to close client session and websocket to Hiven! > "
f"{sys.exc_info()[0].__name__}: {e}")
raise errs.ClosingError(f"Failed to close client session and websocket to Hiven") from e

@property
def client_type(self) -> str:
Expand Down
50 changes: 25 additions & 25 deletions openhivenpy/exception.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@

class HivenError(Exception):
"""
Base Exception in the openhivenpy library!
Base Exception in the openhivenpy library
All other exceptions inherit from this base class
"""
Expand All @@ -73,13 +73,13 @@ def __call__(self):


class HivenConnectionError(HivenError):
""" The connection to Hiven failed to be kept alive or started! """
exc_msg = "The connection to Hiven failed to be kept alive or started!"
""" The connection to Hiven failed to be kept alive or started """
exc_msg = "The connection to Hiven failed to be kept alive or started"


class HTTPForbiddenError(HivenError):
""" The client was forbidden to perform a Request """
exc_msg = "The client was forbidden to execute a certain task or function!"
exc_msg = "The client was forbidden to execute a certain task or function"


class InitializationError(HivenError):
Expand All @@ -88,36 +88,36 @@ class InitializationError(HivenError):


class InvalidPassedDataError(InitializationError):
""" Failed to utilise data as wanted due to missing or unexpected data! """
""" Failed to utilise data as wanted due to missing or unexpected data """
def __init__(self, *args, data):
if args:
arg = "".join([str(arg) for arg in args])
else:
arg = "The initializer failed to validate and utilise the data likely due to wrong data passed!"
arg = "The initializer failed to validate and utilise the data likely due to wrong data passed"

if data:
arg += f"\n Data: {data}"
super().__init__(arg)


class ClientTypeError(HivenError):
""" Invalid client type was passed resulting in a failed initialisation! """
exc_msg = "Invalid client type was passed resulting in a failed initialization!"
""" Invalid client type was passed resulting in a failed initialisation """
exc_msg = "Invalid client type was passed resulting in a failed initialization"


class InvalidTokenError(HivenError):
""" Invalid Token was passed! """
exc_msg = "Invalid Token was passed!"
""" Invalid Token was passed """
exc_msg = "Invalid Token was passed"


class HivenGatewayError(HivenConnectionError):
""" General Exception in the Gateway and Connection to Hiven! """
exc_msg = "Encountered and Exception in the Hiven Gateway!"
""" General Exception in the Gateway and Connection to Hiven """
exc_msg = "Encountered and Exception in the Hiven Gateway"


class HTTPError(HivenGatewayError):
""" Base Exception for exceptions in the HTTP and overall requesting """
exc_msg = "Failed to perform request! Code: {}! See HTTP logs!"
exc_msg = "Failed to perform request Code: {} See HTTP logs"

def __init__(self, *args, code="Unknown"):
if args:
Expand All @@ -133,40 +133,40 @@ class HTTPFailedRequestError(HTTPError):

class HTTPResponseError(HTTPError):
""" Response was in wrong format or expected data was not received """
exc_msg = "Failed to handle Response and utilise data! Code: {}! See HTTP logs!"
exc_msg = "Failed to handle Response and utilise data Code: {} See HTTP logs"


class HTTPReceivedNoDataError(HTTPError):
"""
Received a response without the required data field or
received a 204(No Content) in a request that expected data.
"""
exc_msg = "Response does not contain the expected Data! Code: {}! See HTTP logs!"
exc_msg = "Response does not contain the expected Data Code: {} See HTTP logs"


class SessionCreateError(HivenError):
""" Failed to create Session! """
exc_msg = "Failed to create Session!"
""" Failed to create Session """
exc_msg = "Failed to create Session"


class ClosingError(HivenGatewayError):
""" The client is unable to close the connection to Hiven! """
exc_msg = "Failed to close Connection!"
""" The client is unable to close the connection to Hiven """
exc_msg = "Failed to close Connection"


class WebSocketMessageError(HivenGatewayError):
""" An Exception occurred while handling a message/response from Hiven """
exc_msg = "Failed to handle WebSocket Message!"
exc_msg = "Failed to handle WebSocket Message"


class NoneClientType(Warning):
""" A None Type was passed in the Initialization! """
exc_msg = ("A None ClientType was passed! This can indicate faulty usage of the Client and could lead to errors"
"while running!")
""" A None Type was passed in the Initialization """
exc_msg = ("A None ClientType was passed This can indicate faulty usage of the Client and could lead to errors"
"while running")

# Command Exceptions #


class CommandError(HivenError):
""" General Exception while executing a command function on Hiven! """
exc_msg = "An Exception occurred while executing a command on Hiven!"
""" General Exception while executing a command function on Hiven """
exc_msg = "An Exception occurred while executing a command on Hiven"
20 changes: 7 additions & 13 deletions openhivenpy/gateway/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,9 +203,7 @@ async def stop(self) -> None:
suffix="Failed to stop or keep alive execution_loop: \n"
f"{sys.exc_info()[0].__name__}: {e}")
raise errs.ClosingError("Failed to stop or keep alive execution_loop!"
f"> {sys.exc_info()[0].__name__}: {e}")
finally:
return
f"> {sys.exc_info()[0].__name__}: {e}") from e

def add_to_loop(self, func: typing.Awaitable = None):
"""
Expand Down Expand Up @@ -408,21 +406,17 @@ async def connect(self, event_loop: asyncio.AbstractEventLoop) -> None:
raise errs.HivenConnectionError("[CONNECTION] Failed to get connected Client data!")

except Exception as e:
utils.log_traceback(msg="[CONNECTION] Traceback:",
suffix="Failed to establish the connection to Hiven: \n"
f"{sys.exc_info()[0].__name__}: {e}")
raise errs.HivenConnectionError("Failed to establish the connection to Hiven! "
f"> {sys.exc_info()[0].__name__}: {e}")
raise errs.HivenConnectionError("Failed to establish the connection to Hiven") from e
except KeyboardInterrupt:
raise KeyboardInterrupt
raise

finally:
else:
self._connection_status = "CLOSED"
logger.info("[CONNECTION] The Client-Session has been closed! Use connect() or run() to reconnect!")
return

# Kills the connection as well as the event loop
async def destroy(self, reason: str = None, exec_loop=True, block_restart: bool = False) -> None:
async def destroy(self, reason: str = None, exec_loop=True) -> None:
"""
Kills the event loop and the running tasks!
Expand Down Expand Up @@ -458,7 +452,7 @@ async def destroy(self, reason: str = None, exec_loop=True, block_restart: bool
suffix=f"Closing the connection to Hiven failed: \n"
f"{sys.exc_info()[0].__name__}: {e}")
raise errs.ClosingError("Closing the connection to Hiven failed!"
f"> {sys.exc_info()[0].__name__}: {e}")
f"> {sys.exc_info()[0].__name__}: {e}") from e

async def close(self, reason: str = None, close_exec_loop=True, block_restart: bool = False) -> None:
"""
Expand Down Expand Up @@ -498,7 +492,7 @@ async def close(self, reason: str = None, close_exec_loop=True, block_restart: b
suffix=f"Closing the connection to Hiven failed: \n"
f"{sys.exc_info()[0].__name__}: {e}")
raise errs.ClosingError("Closing the connection to Hiven failed! "
f"> {sys.exc_info()[0].__name__}: {e}")
f"> {sys.exc_info()[0].__name__}: {e}") from e

# Restarts the connection if it errored or crashed
async def handler_restart_websocket(self):
Expand Down
4 changes: 2 additions & 2 deletions openhivenpy/gateway/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ async def on_connection_queued_start(session, trace_config_ctx, params):
f"> {sys.exc_info()[0].__name__}: {e}")
self._ready = False
await self.session.close()
raise errs.SessionCreateError(f"Failed to create HTTP-Session! > {sys.exc_info()[0].__name__}: {e}")
raise errs.SessionCreateError(f"Failed to create HTTP-Session! > {sys.exc_info()[0].__name__}: {e}") from e

async def close(self) -> bool:
"""
Expand Down Expand Up @@ -246,7 +246,7 @@ async def http_request(_endpoint: str,
except Exception as _e:
utils.log_traceback(msg="[HTTP] Traceback:",
suffix=f"HTTP '{_method.upper()}' failed with endpoint: {_endpoint}: \n"
f"{sys.exc_info()[0].__name__}, {str(_e)}")
f"{sys.exc_info()[0].__name__}, {_e}")

else:
logger.error(f"[HTTP] << The HTTPClient was not ready when trying to perform request with "
Expand Down
12 changes: 6 additions & 6 deletions openhivenpy/gateway/ws.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,9 +221,11 @@ async def ws_connection():
# Closing
close = getattr(self, "close", None)
if callable(close):
await close(close_exec_loop=True,
reason="WebSocket encountered an error!",
block_restart=not self._restart)
await close(
close_exec_loop=True,
reason="WebSocket encountered an error!",
block_restart=not self._restart
)

return

Expand Down Expand Up @@ -781,9 +783,7 @@ async def presence_update_handler(self, data: dict):
"""
try:
user = await types.User.from_dict(data, self.http)
presence = types.Presence(data, user, self.http)

# TODO! Update user presence!
presence = user.presence

await self.event_handler.dispatch_on_presence_update(presence, user)

Expand Down
1 change: 0 additions & 1 deletion openhivenpy/types/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
from .hiven_client import *
from .usertyping import *
from .attatchment import *
from .presence import *
from .feed import *
from .entity import *
from .invite import *
Expand Down
4 changes: 2 additions & 2 deletions openhivenpy/types/attatchment.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,14 +65,14 @@ async def from_dict(cls, data: dict, http, **kwargs):

except ValidationError as e:
utils.log_validation_traceback(cls, e)
raise errs.InvalidPassedDataError(f"Failed to perform validation in '{cls.__name__}'",data=data)
raise errs.InvalidPassedDataError(f"Failed to perform validation in '{cls.__name__}'", data=data) from e

except Exception as e:
utils.log_traceback(msg=f"Traceback in '{cls.__name__}' Validation:",
suffix=f"Failed to initialise {cls.__name__} due to exception:\n"
f"{sys.exc_info()[0].__name__}: {e}!")
raise errs.InitializationError(f"Failed to initialise {cls.__name__} due to exception:\n"
f"{sys.exc_info()[0].__name__}: {e}!")
f"{sys.exc_info()[0].__name__}: {e}!") from e
else:
# Adding the http attribute for API interaction
instance._http = http
Expand Down
4 changes: 2 additions & 2 deletions openhivenpy/types/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,14 @@ async def from_dict(cls, data: dict, http, **kwargs):

except ValidationError as e:
utils.log_validation_traceback(cls, e)
raise errs.InvalidPassedDataError(f"Failed to perform validation in '{cls.__name__}'",data=data)
raise errs.InvalidPassedDataError(f"Failed to perform validation in '{cls.__name__}'", data=data) from e

except Exception as e:
utils.log_traceback(msg=f"Traceback in '{cls.__name__}' Validation:",
suffix=f"Failed to initialise {cls.__name__} due to exception:\n"
f"{sys.exc_info()[0].__name__}: {e}!")
raise errs.InitializationError(f"Failed to initialise {cls.__name__} due to exception:\n"
f"{sys.exc_info()[0].__name__}: {e}!")
f"{sys.exc_info()[0].__name__}: {e}!") from e
else:
# Adding the http attribute for API interaction
instance._http = http
Expand Down
4 changes: 2 additions & 2 deletions openhivenpy/types/embed.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,14 +68,14 @@ async def from_dict(cls, data: dict, http, **kwargs):

except ValidationError as e:
utils.log_validation_traceback(cls, e)
raise errs.InvalidPassedDataError(f"Failed to perform validation in '{cls.__name__}'",data=data)
raise errs.InvalidPassedDataError(f"Failed to perform validation in '{cls.__name__}'", data=data) from e

except Exception as e:
utils.log_traceback(msg=f"Traceback in '{cls.__name__}' Validation:",
suffix=f"Failed to initialise {cls.__name__} due to exception:\n"
f"{sys.exc_info()[0].__name__}: {e}!")
raise errs.InitializationError(f"Failed to initialise {cls.__name__} due to exception:\n"
f"{sys.exc_info()[0].__name__}: {e}!")
f"{sys.exc_info()[0].__name__}: {e}!") from e
else:
# Adding the http attribute for API interaction
instance._http = http
Expand Down
4 changes: 2 additions & 2 deletions openhivenpy/types/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,14 +81,14 @@ async def from_dict(cls, data: dict, http, house, **kwargs):

except ValidationError as e:
utils.log_validation_traceback(cls, e)
raise errs.InvalidPassedDataError(f"Failed to perform validation in '{cls.__name__}'",data=data)
raise errs.InvalidPassedDataError(f"Failed to perform validation in '{cls.__name__}'", data=data) from e

except Exception as e:
utils.log_traceback(msg=f"Traceback in '{cls.__name__}' Validation:",
suffix=f"Failed to initialise {cls.__name__} due to exception:\n"
f"{sys.exc_info()[0].__name__}: {e}!")
raise errs.InitializationError(f"Failed to initialise {cls.__name__} due to exception:\n"
f"{sys.exc_info()[0].__name__}: {e}!")
f"{sys.exc_info()[0].__name__}: {e}!") from e
else:
# Adding the http attribute for API interaction
instance._http = http
Expand Down
3 changes: 1 addition & 2 deletions openhivenpy/types/hiven_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
from . import user
from . import relationship
from . import private_room
from . import presence
from .. import utils
from .. import exception as errs

Expand Down Expand Up @@ -194,7 +193,7 @@ def website(self) -> str:
return getattr(self.user, 'website', None)

@property
def presence(self) -> presence.Presence:
def presence(self) -> str:
return getattr(self.user, 'presence', None)

@property
Expand Down
Loading

0 comments on commit 1530e9d

Please sign in to comment.