zafiaonline.transport.websocket package

Submodules

zafiaonline.transport.websocket.config module

WebSocket server configuration loader.

This module provides the Config class for loading WebSocket server connection settings from a YAML file. The configuration includes server address, port, and connection type, with sensible defaults if values are missing.

Typical usage example:

config = Config() print(config.address, config.port, config.connect_type)

class zafiaonline.transport.websocket.config.Config(path='ws_config.yaml')[source]

Bases: object

Loads WebSocket server configuration from a YAML file.

Reads settings from a YAML configuration file and assigns them to instance attributes. If any values are missing, sensible defaults are used.

Parameters:

path (str)

address

WebSocket server hostname or IP. Defaults to “dottap.com”.

Type:

str

port

WebSocket server port. Defaults to 7091.

Type:

int

connect_type

WebSocket protocol (“ws” or “wss”). Defaults to “wss”.

Type:

str

zafiaonline.transport.websocket.websocket_handler module

WebSocketHandler module.

Provides a high-level wrapper around a WebSocket client connection with automatic reconnection, background message listening, and lifecycle management. This class is designed to integrate with the zafiaonline framework and handle unstable network conditions gracefully.

Typical usage example:

from zafiaonline.transport.websocket.websocket_handler import WebSocketHandler from zafiaonline.transport.websocket.websocket_module import Websocket

ws = Websocket(client) handler = WebSocketHandler(ws) await handler._connect() await handler._post_connect_setup()

class zafiaonline.transport.websocket.websocket_handler.WebSocketHandler(socket)[source]

Bases: object

Manages the lifecycle of a WebSocket client connection.

Handles connection setup, graceful disconnection, reconnection with exponential backoff, and background listening for incoming messages. Designed for robust operation in unreliable network environments.

Parameters:

socket (Websocket)

alive

Indicates whether the connection is currently active.

Type:

bool

ws

The active WebSocket connection instance.

Type:

websockets.WebSocketClientProtocol | None

uri

The WebSocket server URI to connect to.

Type:

str

ws_lock

Lock used to protect concurrent access to the WebSocket.

Type:

asyncio.Lock

listener_task

Background task that listens for incoming messages.

Type:

asyncio.Task | None

websocket

The WebSocket wrapper that manages low-level connection logic.

Type:

Any

data_queue

Queue for storing received messages.

Type:

asyncio.Queue

socket

Optional reference to the parent client or controller.

Type:

Websocket

zafiaonline.transport.websocket.websocket_module module

WebSocket support for real-time client-server communication.

This module provides an asynchronous WebSocket client with support for authentication, message handling, error management, and lifecycle control. It is designed as part of the zafiaonline framework to enable robust real-time communication between client and server.

Typical usage example:

from zafiaonline.main import Client from zafiaonline.transport.websocket.websocket import Websocket

client = Client(…) ws = Websocket(client) await ws.create_connection() await ws.send_server({“ty”: “sin”}) data = await ws.get_data(“sin”) await ws.disconnect()

class zafiaonline.transport.websocket.websocket_module.Websocket(client)[source]

Bases: WebSocketHandler

Manages a WebSocket connection with support for authentication, message handling, and graceful shutdown.

Parameters:

client (Client)

client

Reference to the main client instance, used for syncing data.

Type:

Client

user_id

Identifier of the authenticated user, synced from the client.

Type:

str | None

token

Authentication token, synced from the client.

Type:

str | None

update_auth_data()[source]

Updates user_id and token from the client instance.

Copies authentication data from the associated client, if available.

Returns:

None

Return type:

None

await create_connection()[source]

Establishes a WebSocket connection if not already connected.

Raises:
  • websockets.exceptions.ConnectionClosed – If the WebSocket connection is closed unexpectedly.

  • websockets.exceptions.InvalidStatus – If the server responds with an invalid status code.

  • Exception – If an unexpected error occurs during connection initialization.

Return type:

None

await disconnect()[source]

Gracefully closes the WebSocket connection.

Raises:
  • websockets.exceptions.ConnectionClosed – If the connection was already closed.

  • Exception – If an unexpected error occurs while closing the connection.

Return type:

None

await send_server(data, remove_token_from_object=False)[source]

Sends a JSON-encoded payload to the WebSocket server.

Parameters:
  • data (dict) – The data payload to send over the WebSocket.

  • remove_token_from_object (bool) – If True, omits authentication details (‘token’ and ‘user_id’) from the outgoing message.

Raises:
  • json.JSONDecodeError – If serialization fails.

  • AttributeError – If the WebSocket instance is unexpectedly missing.

  • websockets.ConnectionClosed – If the WebSocket is closed during send.

Returns:

None

Return type:

None

await listen()[source]

Waits for and returns a single decoded JSON message from the WebSocket queue.

Returns:

The decoded JSON message.

Return type:

dict[str, Any]

Raises:
  • KeyboardInterrupt – If execution is interrupted manually.

  • asyncio.CancelledError – If the listener stops because self.alive is False.

  • json.JSONDecodeError – If a JSON decoding error escapes internal handling.

  • Exception – If an unexpected error occurs during processing.

await get_data(mafia_type)[source]

Waits for and returns a WebSocket event matching the expected mafia type.

Parameters:
  • mafia_type (str) – The expected event type to match. Only messages with this type,

  • "empty" (PacketDataKeys.ERROR_OCCUR)

  • type (or an error)

Returns:

A dictionary with the matching message data.

Return type:

dict[str, Any]

Raises:
  • RuntimeError – If an unexpected event is received (e.g., GAME_STARTED).

  • BanError – If a USER_BLOCKED event is received.

  • asyncio.CancelledError – If the get_data stops because self.alive is False.

  • asyncio.TimeoutError – If no valid data is received within 10 seconds.

  • KeyboardInterrupt – If execution is interrupted manually.

  • Exception – For all other unexpected exceptions.

await safe_get_data(key, retries=2, delay=2)[source]

Attempts to retrieve data associated with the given key, retrying on failure.

Parameters:
  • key (str) – The event type to request via get_data.

  • retries (int, optional) – Number of retry attempts. Defaults to 2.

  • delay (int, optional) – Delay between retries in seconds. Defaults to 2.

Returns:

The first non-None response returned by get_data.

Return type:

dict[str, Any]

Raises:

ValueError – If all attempts fail or return None.

Module contents

class zafiaonline.transport.websocket.Websocket(client)[source]

Bases: WebSocketHandler

Manages a WebSocket connection with support for authentication, message handling, and graceful shutdown.

Parameters:

client (Client)

client

Reference to the main client instance, used for syncing data.

Type:

Client

user_id

Identifier of the authenticated user, synced from the client.

Type:

str | None

token

Authentication token, synced from the client.

Type:

str | None

await create_connection()[source]

Establishes a WebSocket connection if not already connected.

Raises:
  • websockets.exceptions.ConnectionClosed – If the WebSocket connection is closed unexpectedly.

  • websockets.exceptions.InvalidStatus – If the server responds with an invalid status code.

  • Exception – If an unexpected error occurs during connection initialization.

Return type:

None

await disconnect()[source]

Gracefully closes the WebSocket connection.

Raises:
  • websockets.exceptions.ConnectionClosed – If the connection was already closed.

  • Exception – If an unexpected error occurs while closing the connection.

Return type:

None

await get_data(mafia_type)[source]

Waits for and returns a WebSocket event matching the expected mafia type.

Parameters:
  • mafia_type (str) – The expected event type to match. Only messages with this type,

  • "empty" (PacketDataKeys.ERROR_OCCUR)

  • type (or an error)

Returns:

A dictionary with the matching message data.

Return type:

dict[str, Any]

Raises:
  • RuntimeError – If an unexpected event is received (e.g., GAME_STARTED).

  • BanError – If a USER_BLOCKED event is received.

  • asyncio.CancelledError – If the get_data stops because self.alive is False.

  • asyncio.TimeoutError – If no valid data is received within 10 seconds.

  • KeyboardInterrupt – If execution is interrupted manually.

  • Exception – For all other unexpected exceptions.

await listen()[source]

Waits for and returns a single decoded JSON message from the WebSocket queue.

Returns:

The decoded JSON message.

Return type:

dict[str, Any]

Raises:
  • KeyboardInterrupt – If execution is interrupted manually.

  • asyncio.CancelledError – If the listener stops because self.alive is False.

  • json.JSONDecodeError – If a JSON decoding error escapes internal handling.

  • Exception – If an unexpected error occurs during processing.

await safe_get_data(key, retries=2, delay=2)[source]

Attempts to retrieve data associated with the given key, retrying on failure.

Parameters:
  • key (str) – The event type to request via get_data.

  • retries (int, optional) – Number of retry attempts. Defaults to 2.

  • delay (int, optional) – Delay between retries in seconds. Defaults to 2.

Returns:

The first non-None response returned by get_data.

Return type:

dict[str, Any]

Raises:

ValueError – If all attempts fail or return None.

await send_server(data, remove_token_from_object=False)[source]

Sends a JSON-encoded payload to the WebSocket server.

Parameters:
  • data (dict) – The data payload to send over the WebSocket.

  • remove_token_from_object (bool) – If True, omits authentication details (‘token’ and ‘user_id’) from the outgoing message.

Raises:
  • json.JSONDecodeError – If serialization fails.

  • AttributeError – If the WebSocket instance is unexpectedly missing.

  • websockets.ConnectionClosed – If the WebSocket is closed during send.

Returns:

None

Return type:

None

update_auth_data()[source]

Updates user_id and token from the client instance.

Copies authentication data from the associated client, if available.

Returns:

None

Return type:

None

class zafiaonline.transport.websocket.Config(path='ws_config.yaml')[source]

Bases: object

Loads WebSocket server configuration from a YAML file.

Reads settings from a YAML configuration file and assigns them to instance attributes. If any values are missing, sensible defaults are used.

Parameters:

path (str)

address

WebSocket server hostname or IP. Defaults to “dottap.com”.

Type:

str

port

WebSocket server port. Defaults to 7091.

Type:

int

connect_type

WebSocket protocol (“ws” or “wss”). Defaults to “wss”.

Type:

str