zafiaonline.utils package¶
Submodules¶
zafiaonline.utils.exceptions module¶
Custom exception classes for Mafia Online client.
This module defines application-specific exceptions used throughout the Mafia Online WebSocket client codebase. These exceptions allow for precise handling of login failures, bans, and other client-side error conditions.
Typical usage example:
from zafiaonline.exceptions import LoginError, BanError
- if not user_logged_in:
raise LoginError(“Invalid credentials”)
- if server_response[“type”] == “USER_BLOCKED”:
raise BanError(client, server_response, auth)
- exception zafiaonline.utils.exceptions.ListenDataException(message='An error occurred while receiving data from the listener.')[source]¶
Bases:
ExceptionRaised when an error occurs while receiving data from the WebSocket listener.
This exception is typically used to indicate unexpected issues during the WebSocket message listening process, such as malformed data, timeouts, or disconnections that were not handled properly.
- Parameters:
message (str)
- Return type:
None
- exception zafiaonline.utils.exceptions.ListenExampleErrorException(message='An example listening error occurred.')[source]¶
Bases:
ExceptionRaised for specific test cases or example scenarios involving WebSocket listening errors.
This exception is useful for handling controlled test failures, debugging, or identifying particular patterns in received messages that need special handling.
- Parameters:
message (str)
- Return type:
None
- exception zafiaonline.utils.exceptions.BanError(client, data={}, auth=None)[source]¶
Bases:
ExceptionException raised when a user is banned by the server.
This error is triggered upon receiving a USER_BLOCKED event from the server, indicating the client is no longer allowed to interact due to a violation or other reason.
- Parameters:
client (Client)
data (dict)
auth (type | None)
- Return type:
None
- auth¶
Optional authentication object for fallback user data.
- Type:
Type | None
- message¶
Explanation of the ban including reason and remaining time.
- Type:
str
zafiaonline.utils.logging_config module¶
Logging configuration for the Mafia Online client.
Initializes and configures the global logger used throughout the Mafia Online client library. The logger outputs messages to stdout using a standard timestamped format.
Typical usage example:
from zafiaonline.logger import logger
logger.info(“Application started”) logger.error(“An error occurred”)
zafiaonline.utils.md5hash module¶
Utilities for MD5 hashing.
This module provides a static utility class Md5 that includes methods for computing MD5 hashes, with and without repeated salting.
Typical usage involves hashing sensitive strings such as passwords or tokens in a way compatible with the Mafia protocol (which requires a specific salt and number of iterations).
- class zafiaonline.utils.md5hash.Md5[source]¶
Bases:
objectUtility class for performing MD5-based hashing.
This class provides static functionality for computing raw and salted MD5 hashes. It is stateless and does not define any instance attributes.
- staticmethod md5_hash(string)[source]¶
Returns the MD5 hash of the given string.
- Parameters:
string (str) – The input string to hash.
- Returns:
The MD5 hash of the input string.
- Return type:
str
- staticmethod md5salt(string, salt='azxsw', iterations=5)[source]¶
Returns a string hashed multiple times with a salt.
- Parameters:
string (str) – The input string to hash.
salt (str, optional) – The salt to append before hashing. Defaults to “azxsw”.
iterations (int, optional) – Number of hash iterations. Defaults to 5.
- Returns:
The salted and repeatedly hashed string.
- Return type:
str
zafiaonline.utils.proxy_store module¶
Proxy store module.
This module provides the ProxyStore class for managing proxies in memory, as well as a global store instance that can be imported and used across the project.
Example
from zafiaonline.proxy_store import store store.add(”http://1.2.3.4:8080”) proxy = store.get_random_proxy()
- class zafiaonline.utils.proxy_store.ProxyStore[source]¶
Bases:
objectIn-memory storage for proxies.
This class provides methods to add, retrieve, and fetch random proxies. Proxies are stored only in memory and will be lost after program termination.
- add(proxy)[source]¶
Add a proxy to the store.
- Parameters:
proxy (str) – Proxy string (e.g., “http://1.2.3.4:8080”).
- Return type:
None
zafiaonline.utils.utils module¶
Copies non-callable attributes of a client object onto itself.
This module provides a utility function for copying all non-callable attributes from a client’s __dict__ back to the client instance.
Intended for use in dynamic or reflective systems where attribute resetting or propagation is necessary.
- class zafiaonline.utils.utils.Helpers[source]¶
Bases:
object- get_user_attributes(auth)[source]¶
Reassigns all non-callable attributes from a client’s __dict__ to itself.
- Parameters:
auth (AuthService) – The client object whose attributes will be reassigned.
- Returns:
None
- Return type:
None
- await send_and_get(send_func, get_func, request, response_key, extract_key=None, default=None)[source]¶
Send a request to the server and retrieve structured data.
- Parameters:
send_func (Callable) – Async function to send data to the server.
get_func (Callable) – Async function to retrieve data from the server.
request (dict) – The request payload to send.
response_key (str) – The key used to extract the response block.
extract_key (str | None, optional) – Specific key inside the response dict to return. If None, the whole dict is returned. Defaults to None.
default (Any, optional) – Default value if no valid response is found. Defaults to None.
- Returns:
The extracted value, the full dict, or the default if nothing is found.
- Return type:
Any
zafiaonline.utils.utils_for_send_messages module¶
Provides anti-ban protection and message tracking utilities for chat bots.
This module includes logic for handling sent messages, measuring time intervals between them, and applying rules to avoid triggering automated bans on platforms with rate-limiting or spam detection systems.
It includes the SentMessages class for storing and managing message history, as well as utility functions for validating message content, calculating average time deltas, and detecting suspicious behavior.
Typical usage example:
messages = SentMessages(enable_logging=True) messages.add_message(“hello world”) if antiban.is_ban_risk_message(messages):
print(“Slow down to avoid ban.”)
- class zafiaonline.utils.utils_for_send_messages.Message[source]¶
Bases:
TypedDictRepresents a single text message with a timestamp.
- message_time¶
The time when the message was created or sent.
- Type:
datetime
- text¶
The textual content of the message.
- Type:
str
- message_time: datetime¶
- text: str¶
- class zafiaonline.utils.utils_for_send_messages.SentMessages(enable_logging=False)[source]¶
Bases:
objectManages sent messages with optional logging.
- Parameters:
enable_logging (bool)
- enable_logging¶
Whether to store messages in the log list.
- Type:
bool
- add_message(message)[source]¶
Adds a message to the internal storage with a timestamp.
The message is added to messages, and if logging is enabled, also to logged_messages.
- Parameters:
message (str) – The message text to store.
- Return type:
None
- staticmethod get_time()[source]¶
Returns the current local date and time.
- Returns:
The current local datetime object.
- Return type:
datetime
- get_messages()[source]¶
Returns a list of all recorded messages.
- Returns:
A list of messages stored in the instance.
- Return type:
List[Message]
- clear_messages()[source]¶
Clears all stored messages.
This method removes all messages from the internal messages list.
- Return type:
None
- get_length_last_messages(max_len=6)[source]¶
Returns the number of last messages up to max_len.
- Parameters:
max_len (int, optional) – Maximum number of recent messages to consider. Defaults to 6.
- Returns:
Number of messages in the last max_len entries.
- Return type:
int
- Raises:
ValueError – If no messages are available.
- class zafiaonline.utils.utils_for_send_messages.Utils[source]¶
Bases:
object- staticmethod clean_content(content)[source]¶
Cleans and truncates a string to 200 characters, replacing multiple spaces with one.
- Parameters:
content (str) – The input text content.
- Returns:
The cleaned and truncated string.
- Return type:
str
- staticmethod validate_message_content(content)[source]¶
Checks if the message content is not empty or whitespace.
- Parameters:
content (str) – The message content to validate.
- Returns:
True if the message is not blank, False otherwise.
- Return type:
bool
- staticmethod get_time_of_messages(messages)[source]¶
Extracts the message_time field from a list of Message dictionaries.
- Parameters:
messages (List[Message]) – A list of messages, each with a ‘message_time’ key.
- Returns:
A list of datetime objects extracted from the messages.
- Return type:
List[datetime]
- Raises:
ValueError – If the input list is empty or any message lacks ‘message_time’.
- staticmethod get_current_time_of_messages(time_list)[source]¶
Calculates the elapsed time in seconds since each datetime in the list.
- Parameters:
time_list (List[datetime]) – A list of datetime objects.
- Returns:
A list of time differences (in seconds) between now and each datetime.
- Return type:
List[float]
Example
If time_list contains datetimes from 5 and 10 seconds ago, the returned list will be approximately [5.0, 10.0].
- auto_delete_first_message(handler)[source]¶
Automatically deletes or clears messages from the handler based on timing and count.
Deletes the first message if the number of recent messages is 10 or more. Clears all messages if the average time since recent messages exceeds 20 seconds and there are at least 3 recent messages.
- Parameters:
handler (SentMessages) – The message handler that stores and manages messages.
- Returns:
None
- Return type:
None
- get_average_time(handler, max_len=6)[source]¶
Calculates the average age (in seconds) of the most recent messages.
This function extracts timestamps from the last max_len messages stored in the handler, computes how much time has passed since each message was sent, and returns the average of these time differences.
- Parameters:
handler (SentMessages) – The message handler containing messages.
max_len (int, optional) – The number of most recent messages to consider. Defaults to 6.
- Returns:
The average time (in seconds) since the selected messages were sent.
- Return type:
float
- Raises:
ValueError – If the list of messages is empty or contains messages without valid timestamps.
- is_ban_risk_message(sent_messages_class)[source]¶
Determines whether recent messaging behavior poses a ban risk.
This method analyzes the frequency of sent messages and determines if the message rate is high enough to trigger anti-spam or anti-bot protection.
- Parameters:
sent_messages_class (SentMessages) – The message handler containing the list of sent messages.
- Returns:
True if the message rate suggests ban risk, False otherwise.
- Return type:
bool
Module contents¶
- class zafiaonline.utils.Md5[source]¶
Bases:
objectUtility class for performing MD5-based hashing.
This class provides static functionality for computing raw and salted MD5 hashes. It is stateless and does not define any instance attributes.
- staticmethod md5_hash(string)[source]¶
Returns the MD5 hash of the given string.
- Parameters:
string (str) – The input string to hash.
- Returns:
The MD5 hash of the input string.
- Return type:
str
- staticmethod md5salt(string, salt='azxsw', iterations=5)[source]¶
Returns a string hashed multiple times with a salt.
- Parameters:
string (str) – The input string to hash.
salt (str, optional) – The salt to append before hashing. Defaults to “azxsw”.
iterations (int, optional) – Number of hash iterations. Defaults to 5.
- Returns:
The salted and repeatedly hashed string.
- Return type:
str
- exception zafiaonline.utils.ListenDataException(message='An error occurred while receiving data from the listener.')[source]¶
Bases:
ExceptionRaised when an error occurs while receiving data from the WebSocket listener.
This exception is typically used to indicate unexpected issues during the WebSocket message listening process, such as malformed data, timeouts, or disconnections that were not handled properly.
- Parameters:
message (str)
- Return type:
None
- exception zafiaonline.utils.ListenExampleErrorException(message='An example listening error occurred.')[source]¶
Bases:
ExceptionRaised for specific test cases or example scenarios involving WebSocket listening errors.
This exception is useful for handling controlled test failures, debugging, or identifying particular patterns in received messages that need special handling.
- Parameters:
message (str)
- Return type:
None
- exception zafiaonline.utils.BanError(client, data={}, auth=None)[source]¶
Bases:
ExceptionException raised when a user is banned by the server.
This error is triggered upon receiving a USER_BLOCKED event from the server, indicating the client is no longer allowed to interact due to a violation or other reason.
- Parameters:
client (Client)
data (dict)
auth (type | None)
- Return type:
None
- auth¶
Optional authentication object for fallback user data.
- Type:
Type | None
- message¶
Explanation of the ban including reason and remaining time.
- Type:
str
- exception zafiaonline.utils.LoginError[source]¶
Bases:
ExceptionException raised when authentication with the server fails.
This can occur due to invalid credentials, network errors, or server-side issues during the login process.
- class zafiaonline.utils.Utils[source]¶
Bases:
object- auto_delete_first_message(handler)[source]¶
Automatically deletes or clears messages from the handler based on timing and count.
Deletes the first message if the number of recent messages is 10 or more. Clears all messages if the average time since recent messages exceeds 20 seconds and there are at least 3 recent messages.
- Parameters:
handler (SentMessages) – The message handler that stores and manages messages.
- Returns:
None
- Return type:
None
- staticmethod clean_content(content)[source]¶
Cleans and truncates a string to 200 characters, replacing multiple spaces with one.
- Parameters:
content (str) – The input text content.
- Returns:
The cleaned and truncated string.
- Return type:
str
- get_average_time(handler, max_len=6)[source]¶
Calculates the average age (in seconds) of the most recent messages.
This function extracts timestamps from the last max_len messages stored in the handler, computes how much time has passed since each message was sent, and returns the average of these time differences.
- Parameters:
handler (SentMessages) – The message handler containing messages.
max_len (int, optional) – The number of most recent messages to consider. Defaults to 6.
- Returns:
The average time (in seconds) since the selected messages were sent.
- Return type:
float
- Raises:
ValueError – If the list of messages is empty or contains messages without valid timestamps.
- staticmethod get_current_time_of_messages(time_list)[source]¶
Calculates the elapsed time in seconds since each datetime in the list.
- Parameters:
time_list (List[datetime]) – A list of datetime objects.
- Returns:
A list of time differences (in seconds) between now and each datetime.
- Return type:
List[float]
Example
If time_list contains datetimes from 5 and 10 seconds ago, the returned list will be approximately [5.0, 10.0].
- staticmethod get_time_of_messages(messages)[source]¶
Extracts the message_time field from a list of Message dictionaries.
- Parameters:
messages (List[Message]) – A list of messages, each with a ‘message_time’ key.
- Returns:
A list of datetime objects extracted from the messages.
- Return type:
List[datetime]
- Raises:
ValueError – If the input list is empty or any message lacks ‘message_time’.
- is_ban_risk_message(sent_messages_class)[source]¶
Determines whether recent messaging behavior poses a ban risk.
This method analyzes the frequency of sent messages and determines if the message rate is high enough to trigger anti-spam or anti-bot protection.
- Parameters:
sent_messages_class (SentMessages) – The message handler containing the list of sent messages.
- Returns:
True if the message rate suggests ban risk, False otherwise.
- Return type:
bool