Exception handling for resync system time and api check
tengocj opened this issue · 2 comments
Hello ser, I was wondering if you can please change the exception handling for the resync system time and api key error
so one can just use normal try except block-handling for opening a new websocket connection. Right now when I am trying to except this Exception
nothing is happening rather it's always getting logged and instead of modifying the library i'd be very happy if you can change that in the next pr. ty
Hi. You can solve this issue pretty easy without any changes in the package. Moreover, you have two options:
- Provide custom message handling callback. For that you need to pass
callback_function
parameter toWebSocket
like so:
ws = WebSocket(
channel_type="private",
api_key='api_key',
api_secret='api_secret',
callback_function=callback_function,
)
- Easier one - inherit from the
WebSocket
, and override the method, that handles the auth message:
from pybit.unified_trading import WebSocket
from pybit._websocket_stream import logger
class MyWebSocket(WebSocket):
def _process_auth_message(self, message):
if message.get("success") is True:
logger.debug(f"Authorization for {self.ws_name} successful.")
self.auth = True
# If we get unsuccessful auth, notify user.
elif message.get("success") is False or message.get("type") == "error":
# Here replace exception raising with your own error handling(reconnection).
raise Exception(
f"Authorization for {self.ws_name} failed. Please check your "
f"API keys and resync your system time. Raw error: {message}"
)
ws = MyWebSocket(
channel_type="private",
api_key='api_key',
api_secret='api_secret',
)
The second way is easier because you override only the auth message handling. For the first option you'll have to handle all the messages(you still can use the package methods, and replace only the auth message handling part, anyways, it requires to write more code than the 2 option).
P.S. Keep in mind that the code above is not tested.
Appreciate that, didn't have time to go through full docs. Thank you very much for the fast reply!