### Download and Install Plugin from Message Document Source: https://zwylib-docs.vercel.app/utilities This function facilitates the download and installation of a plugin. It expects the plugin file to be available as a document within a message object. If the download is not immediate, it handles retries and queuing. It utilizes the `PluginsController` for installation and provides logging for progress and errors. ```python logger = zwylib.build_log("MyPlugin") zwylib.download_and_install_plugin(message, "example_plugin") # Logs download/install progress and shows error bulletin if installation fails ``` -------------------------------- ### zwylib.download_and_install_plugin Source: https://zwylib-docs.vercel.app/utilities Downloads a plugin file from a message's document and installs it, with retry logic for downloads. ```APIDOC ## `zwylib.download_and_install_plugin` ### Description Downloads a plugin file from a message’s document and installs it using the `PluginsController`. If the file is not yet downloaded, it queues the download and retries. ### Arguments * `msg` (`Any`): Message object containing the plugin file as a document in `msg.media`. * `plugin_id` (`str`): Identifier of the plugin to install. * `max_tries` (`int`, default `10`): Must not be set manually. Maximum tries of plugin downloading. * `is_queued` (`bool`, default `False`): Must not be set manually. Indicates whether the function is called as part of a queued retry. * `current_try` (`int`, default `0`): Must not be set manually. Current plugin download try. ### Example ```python logger = zwylib.build_log("MyPlugin") zwylib.download_and_install_plugin(message, "example_plugin") # Logs download/install progress and shows error bulletin if installation fails ``` ``` -------------------------------- ### zwylib.is_zwylib_version_sufficient Source: https://zwylib-docs.vercel.app/utilities Checks if the installed Zwylib version meets a minimum required version. ```APIDOC ## `zwylib.is_zwylib_version_sufficient` ### Description Checks if the installed Zwylib version meets a minimum required version. ### Arguments * `required_version` (`str`): The minimum required version string (e.g., "1.2.3"). ### Returns * `bool`: `True` if the installed version is sufficient, `False` otherwise. ### Example ```python if zwylib.is_zwylib_version_sufficient("2.0.0"): print("Zwylib version is up to date.") else: print("Please update Zwylib to version 2.0.0 or higher.") ``` ``` -------------------------------- ### Import ZwyLib Library in Python Source: https://zwylib-docs.vercel.app/index This snippet demonstrates how to import the ZwyLib library in a Python project. It includes error handling for cases where the library is not installed, ensuring the plugin cannot run without its essential dependency. ```python try: import zwylib # import the library except (ImportError, ModuleNotFoundError): # zwylib not found — its tools cannot be used. raise an error raise Exception("Cannot run without ZwyLib. Please install it.") class MyPlugin(BasePlugin): ... ``` -------------------------------- ### Register Command with Optional Argument and Default Value (Python) Source: https://zwylib-docs.vercel.app/commands Illustrates registering a command with an optional argument that has a default value (`None` in this case). This provides a fallback when the argument is omitted, simplifying command usage and reducing potential errors related to missing parameters. Similar to the previous example, argument count validation applies. ```python from typing import Optional def register_commands(): dispatcher = zwylib.command_manager.get_dispatcher(...) @dispatcher.register_command("test") def test_command(params: Any, account: int, option: Optional[str] = None) -> HookResult: params.message = f"Option: {option}" return HookResult(strategy=HookStrategy.MODIFY_FINAL, params=params) ``` -------------------------------- ### Get Command Dispatcher - Python Source: https://zwylib-docs.vercel.app/commands Creates or retrieves a Dispatcher instance for a given plugin ID. You can specify a custom prefix and command priority. The Dispatcher is used to register commands for a specific plugin. ```python CommandManager.get_dispatcher( plugin_id: str, prefix="default", # defaults to "." commands_priority=-1 ) -> Dispatcher # Example usage: zwylib.command_manager.get_dispatcher("MyPluginID", "!", 10) ``` -------------------------------- ### Retrieve Plugin Instance by ID Source: https://zwylib-docs.vercel.app/utilities The `get_plugin` function retrieves a specific plugin instance managed by the `PluginsController` using its unique identifier. It returns the plugin object if found, otherwise returns `None`. This is essential for accessing and interacting with installed plugins. ```python plugin = zwylib.get_plugin("example_plugin") if plugin: print(f"Found plugin: {plugin}") else: print("Plugin not found") ``` -------------------------------- ### Deregister Command (Python) Source: https://zwylib-docs.vercel.app/commands Provides an example of how to manually remove a registered command from a dispatcher. This is useful for dynamic command management. Calling `unregister_command` also removes any associated subcommands. ```python dispatcher = zwylib.command_manager.get_dispatcher(__id__) dispatcher.unregister_command("my_command") ``` -------------------------------- ### Get Message Details Source: https://zwylib-docs.vercel.app/requests Retrieves a specific message from a chat or user by reloading it from the server. It retries fetching the message if it's not immediately available. ```APIDOC ## POST /websites/zwylib-docs_vercel_app/get_message ### Description Asynchronously reloads a specific message from the server and retrieves it from local storage, passing it to the callback. Retries up to `get_msg_tries_limit` times if the message is not yet available. ### Method POST ### Endpoint /websites/zwylib-docs_vercel_app/get_message ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **peer_id** (int) - Required - ID of the peer (chat or user) containing the message. - **message_id** (int) - Required - ID of the message to retrieve. - **callback** (Optional[function]) - Optional - Function called with the message or None when retrieved. - **get_msg_tries_limit** (int) - Optional - Maximum number of retry attempts (default: 10). - **wait_time_seconds** (int) - Optional - Delay between retry attempts in seconds (default: 1). ### Request Example ```json { "peer_id": -12345, "message_id": 67890, "callback": "message_callback", "get_msg_tries_limit": 10, "wait_time_seconds": 1 } ``` ### Response #### Success Response (200) - **message** (object | null) - The retrieved message object or null if not found. #### Response Example ```json { "message": { "id": 67890, "message": "Hello, world!" } } ``` ``` -------------------------------- ### Get Chat Participant Information Source: https://zwylib-docs.vercel.app/requests Fetches detailed information about a specific participant within a chat. The retrieved information is passed to a provided callback function. ```APIDOC ## POST /websites/zwylib-docs_vercel_app/get_chat_participant ### Description Fetches information about a specific participant in a chat and passes the result to the provided callback. Accepts additional parameters matching the TL schema. ### Method POST ### Endpoint /websites/zwylib-docs_vercel_app/get_chat_participant ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **chat_id** (int) - Required - ID of the chat to fetch the participant from. - **target_peer_id** (int) - Required - ID of the participant to fetch. - **callback** (function) - Required - Function called with the participant information or error. - **kwargs** - Optional - Additional parameters matching the TL schema. ### Request Example ```json { "chat_id": -12345, "target_peer_id": 123456, "callback": "participant_callback" } ``` ### Response #### Success Response (200) - **participant_info** (object | null) - Information about the participant or null if not found. #### Response Example ```json { "participant_info": { "user_id": 123456, "username": "example_user" } } ``` ``` -------------------------------- ### Get Chat Participant Information Source: https://zwylib-docs.vercel.app/requests Retrieves details about a specific participant within a chat. This function requires the chat ID and the target participant's peer ID, along with a callback function to handle the results or any errors. Extra parameters matching the TL schema are supported. ```python def participant_callback(updates, error): if error: print(f"Error: {error}") else: print("Participant info retrieved") zwylib.Requests.get_chat_participant(chat_id=-12345, target_peer_id=123456, callback=participant_callback) ``` -------------------------------- ### Registering Commands with Arguments Source: https://zwylib-docs.vercel.app/commands Demonstrates how to register commands with required, variadic, and optional arguments, including type handling and expected outcomes. ```APIDOC ## POST /register/command ### Description Register a new command with the command dispatcher, supporting various argument types including required, variadic, and optional parameters. ### Method POST ### Endpoint `/register/command` ### Parameters #### Request Body - **command_name** (string) - Required - The name of the command to register. - **function_definition** (string) - Required - The Python function definition for the command. - **argument_types** (object) - Optional - Specifies the expected types for command arguments. - **param_name** (string) - Required - The type of the argument (e.g., 'int', 'str', 'Optional[str]', 'Union[str, int]'). ### Request Example ```json { "command_name": "numbers", "function_definition": "def numbers_command(params: Any, account: int, first: int, *args: int) -> HookResult:\n params.message = f\"First: {first}, additional numbers: {args}\"\n return HookResult(strategy=HookStrategy.MODIFY_FINAL, params=params)", "argument_types": { "first": "int", "args": "int" } } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message of successful registration. #### Response Example ```json { "message": "Command 'numbers' registered successfully." } ``` ``` -------------------------------- ### Register a Basic Command with ZwyLib Source: https://zwylib-docs.vercel.app/commands Demonstrates how to register a simple command using `zwylib.command_manager.get_dispatcher` and the `@dispatcher.register_command` decorator. It requires `params` and `account` and must return `HookResult`. Errors like `MissingRequiredArguments` or `InvalidTypeError` can occur. ```python # ... metadata and zwylib import ... def register_commands(): prefix = "!" # command prefix for your plugin commands_priority = 10 # your commands' execution priority over others # commands are registered through a dispatcher dispatcher = zwylib.command_manager.get_dispatcher(__id__, prefix, commands_priority) # register the "!test" command @dispatcher.register_command("test") def test_command(params: Any, account: int) -> HookResult: # https://plugins.exteragram.app/docs/plugin-class#message-sending-hook params.message = "Command '!test' executed successfully!" return HookResult(strategy=HookStrategy.MODIFY_FINAL, params=params) class MyPlugin(BasePlugin): def on_plugin_load(self): # register commands when the plugin loads register_commands() def on_plugin_unload(self): # on unload, deregister commands to avoid issues with plugin updates/validation zwylib.command_manager.remove_dispatcher(__id__) ... # rest of plugin logic ``` -------------------------------- ### Register Command with Optional Argument (Python) Source: https://zwylib-docs.vercel.app/commands Shows how to register a command with an optional argument. If the argument is not provided, it defaults to `None`. This allows for flexible command usage, but requires careful handling of missing values. Errors occur if too few or too many arguments are provided. ```python from typing import Optional def register_commands(): dispatcher = zwylib.command_manager.get_dispatcher(...) @dispatcher.register_command("test") def test_command(params: Any, account: int, option: Optional[str]) -> HookResult: params.message = f"Option: {option}" return HookResult(strategy=HookStrategy.MODIFY_FINAL, params=params) ``` -------------------------------- ### Register Command with Only Variadic Arguments (Python) Source: https://zwylib-docs.vercel.app/commands Demonstrates registering a command that only accepts variadic arguments using `*args`. This is useful for commands that need to process an arbitrary number of inputs. The arguments are captured as a tuple. Supported types for arguments include strings and integers. ```python from typing import Union def register_commands(): dispatcher = zwylib.command_manager.get_dispatcher(...) @dispatcher.register_command("echo") def echo_command(params: Any, account: int, *args: Union[str, int]) -> HookResult: params.message = f"Echo: {list(args)}" return HookResult(strategy=HookStrategy.MODIFY_FINAL, params=params) ``` -------------------------------- ### Register Command with Required and Variadic Arguments (Python) Source: https://zwylib-docs.vercel.app/commands Demonstrates registering a command that accepts required arguments and a variable number of additional arguments. The `*args` captures any subsequent arguments passed to the command. An `InvalidTypeError` is raised if argument types are not supported. ```python from typing import Union def register_commands(): dispatcher = zwylib.command_manager.get_dispatcher(...) @dispatcher.register_command("numbers") def numbers_command(params: Any, account: int, first: int, *args: int) -> HookResult: params.message = f"First: {first}, additional numbers: {args}" return HookResult(strategy=HookStrategy.MODIFY_FINAL, params=params) ``` -------------------------------- ### Dispatcher Methods API Source: https://zwylib-docs.vercel.app/commands APIs for interacting with the Dispatcher object, including setting prefixes and registering commands. ```APIDOC ## PUT /zwylib/dispatcher/set_prefix ### Description Sets the prefix for all commands registered via this dispatcher. The prefix saves between exteraGram sessions. ### Method PUT ### Endpoint /zwylib/dispatcher/set_prefix ### Parameters #### Query Parameters - **dispatcher_id** (str) - Required - Identifier for the dispatcher instance. - **prefix** (str) - Required - New command prefix. ### Request Example ```json { "dispatcher_id": "", "prefix": "/" } ``` ### Response #### Success Response (200) - **message** (str) - Confirmation message. #### Response Example ```json { "message": "Prefix updated successfully." } ``` --- ## POST /zwylib/dispatcher/register_command ### Description Decorator to register a command. Arguments `params` and `account` are required. The return type must be `HookResult`. ### Method POST ### Endpoint /zwylib/dispatcher/register_command ### Parameters #### Query Parameters - **dispatcher_id** (str) - Required - Identifier for the dispatcher instance. - **name** (str) - Required - Command name. Cannot be empty or contain spaces. ### Request Body #### **Function Definition** - **function_code** (str) - Required - The Python code for the command function, including the decorator. ### Request Example ```python # Assume dispatcher_id is obtained from get_dispatcher # dispatcher = zwylib.command_manager.get_dispatcher("MyPluginID") { "dispatcher_id": "", "name": "hello", "function_code": "@dispatcher.register_command(\"hello\")\ndef test_command(params: Any, account: int) -> HookResult:\n params.message = \"Hi!\"\n return HookResult(strategy=HookStrategy.MODIFY, params=params)" } ``` ### Response #### Success Response (200) - **message** (str) - Confirmation message. #### Response Example ```json { "message": "Command registered successfully." } ``` #### Error Response (400) - **error** (str) - Description of the error (e.g., MissingRequiredArguments, InvalidTypeError). #### Error Example ```json { "error": "MissingRequiredArguments: params or account are missing." } ``` ``` -------------------------------- ### Dispatcher Management API Source: https://zwylib-docs.vercel.app/commands APIs for creating and removing command dispatchers for plugins. ```APIDOC ## POST /zwylib/command_manager/get_dispatcher ### Description Creates (if necessary) and returns a `Dispatcher` instance for the given `plugin_id`. This dispatcher is responsible for registering commands under the current plugin ID. ### Method POST ### Endpoint /zwylib/command_manager/get_dispatcher ### Parameters #### Query Parameters - **plugin_id** (str) - Required - Your plugin's unique ID. - **prefix** (str) - Optional - Prefix for all commands of this plugin. Defaults to ".". - **commands_priority** (int) - Optional - Execution priority. Defaults to -1. ### Request Example ```json { "plugin_id": "MyPluginID", "prefix": "!", "commands_priority": 10 } ``` ### Response #### Success Response (200) - **dispatcher** (Dispatcher) - The Dispatcher instance. #### Response Example ```json { "dispatcher": "" } ``` --- ## DELETE /zwylib/command_manager/remove_dispatcher ### Description Removes the dispatcher associated with the given plugin. ### Method DELETE ### Endpoint /zwylib/command_manager/remove_dispatcher ### Parameters #### Query Parameters - **plugin_id** (str) - Required - ID of the plugin whose dispatcher is being removed. ### Request Example ```json { "plugin_id": "__id__" } ``` ### Response #### Success Response (200) - **message** (str) - Confirmation message. #### Response Example ```json { "message": "Dispatcher removed successfully." } ``` ``` -------------------------------- ### zwylib.copy_to_clipboard Source: https://zwylib-docs.vercel.app/utilities Copies the provided text to the clipboard and optionally displays a success bulletin. ```APIDOC ## `zwylib.copy_to_clipboard` ### Description Copies the provided text to the clipboard and displays a “Copied to clipboard” bulletin if successful and a `BulletinHelper` is provided. ### Arguments * `bulletin_helper` (`Optional[[BulletinHelper](https://plugins.exteragram.app/docs/bulletin-helper)]`): Instance of a bulletin helper to show the success message. If `None`, no bulletin is shown. * `text_to_copy` (`str`): Text to copy to the clipboard. ### Returns * `None`: Does not return a value. ### Example ```python bulletins = zwylib.build_bulletin_helper("MyPlugin") zwylib.copy_to_clipboard(bulletins, "example text") # Copies "example text" to clipboard and shows a bulletin ``` ``` -------------------------------- ### zwylib.get_plugin Source: https://zwylib-docs.vercel.app/utilities Retrieves a plugin instance by its unique identifier from the `PluginsController`. ```APIDOC ## `zwylib.get_plugin` ### Description Retrieves a plugin instance from the `PluginsController` by its identifier. ### Arguments * `plugin_id` (`str`): Identifier of the plugin to retrieve. ### Returns * `Optional[Plugin]`: The plugin instance if found, or `None` if no plugin matches the `plugin_id`. ### Example ```python plugin = zwylib.get_plugin("example_plugin") if plugin: print(f"Found plugin: {plugin}") else: print("Plugin not found") ``` ``` -------------------------------- ### Display Info Bulletin with Copy Button using InnerBulletinHelper Source: https://zwylib-docs.vercel.app/logging-and-notifications Displays an info-style message prefixed by the plugin name and includes a button to copy provided text to the clipboard. This combines informational display with quick data sharing. ```python bulletins = zwylib.build_bulletin_helper("MyPlugin") bulletins.show_info_with_copy("Info message", "info text") # Expected display: MyPlugin: Info message (with a copy button) ``` -------------------------------- ### Create InnerBulletinHelper Instance with ZwyLib Source: https://zwylib-docs.vercel.app/logging-and-notifications A factory function that instantiates `InnerBulletinHelper`. It allows for an optional prefix, typically the plugin name, to be prepended to all messages displayed through the helper. This ensures notifications are contextually relevant to the plugin generating them. ```python import zwylib bulletins = zwylib.build_bulletin_helper("MyPlugin") bulletins.show_info("Something happened") # Expected display: MyPlugin: Something happened ``` -------------------------------- ### Check ZwyLib Version Sufficiency - Python Source: https://zwylib-docs.vercel.app/utilities Checks if the current ZwyLib version meets a specified minimum requirement. Optionally displays a bulletin to the user if the version is insufficient, with a link to update. Takes the plugin name, required version, and a flag for showing bulletins as input. Returns a boolean indicating sufficiency. ```python import zwylib zwylib.is_zwylib_version_sufficient("MyPlugin", "1.2.0") ``` -------------------------------- ### Registering Error Handlers Source: https://zwylib-docs.vercel.app/commands Shows how to attach a specific error handler to a registered command to manage exceptions during its execution. ```APIDOC ## POST /command/{command_name}/error_handler ### Description Register a dedicated error handler for a specific command. This handler will be invoked if any exception occurs during the execution of the command. ### Method POST ### Endpoint `/command/{command_name}/error_handler` ### Parameters #### Path Parameters - **command_name** (string) - Required - The name of the command to attach the error handler to. #### Request Body - **error_handler_definition** (string) - Required - The Python function definition for the error handler. It must accept `params`, `account`, and `error` as arguments. ### Request Example ```json { "error_handler_definition": "def number_command_error_handler(params: Any, account: int, error: Exception) -> HookResult:\n params.message = f\"An error occurred in 'number': {error}\"\n return HookResult(strategy=HookStrategy.MODIFY_FINAL, params=params)" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message of successful error handler registration. #### Response Example ```json { "message": "Error handler registered for command 'number'." } ``` ``` -------------------------------- ### Register Nested Subcommands with ZwyLib Source: https://zwylib-docs.vercel.app/commands Shows how to register nested subcommands by chaining the `@subcommand` decorator on existing command functions. This allows for hierarchical command structures, like `!test sub new`. ```python # ... metadata and zwylib import ... def register_commands(): dispatcher = zwylib.command_manager.get_dispatcher(__id__, "!") # called as "!test" @dispatcher.register_command("test") def test_command(params: Any, account: int) -> HookResult: ... # called as "!test sub" @test_command.subcommand("sub") def test_subcommand(params: Any, account: int) -> HookResult: params.message = "Command '!test sub' executed successfully!" return HookResult(strategy=HookStrategy.MODIFY_FINAL, params=params) # called as "!test sub new" @test_subcommand.subcommand("new") def test_sub_new_command(params: Any, account: int) -> HookResult: params.message = "Command '!test sub new' executed successfully!" return HookResult(strategy=HookStrategy.MODIFY_FINAL, params=params) ``` -------------------------------- ### Build Logger Instance with ZwyLib Source: https://zwylib-docs.vercel.app/logging-and-notifications Creates a `logging.Logger` instance with a specified prefix and logging level. It automatically includes the plugin name and caller function name in log messages. This is useful for structured and consistent logging across different plugins. ```python import logging import zwylib logger = zwylib.build_log("MyPluginLogger") class MyPlugin(BasePlugin): def on_plugin_unload(self): logger.error("Execution failed", "code 42") # Expected log format: [MyPluginLogger] [on_plugin_unload] Execution failed code 42 ``` -------------------------------- ### zwylib.format_exc Source: https://zwylib-docs.vercel.app/utilities Formats the current exception into a readable string, including traceback information. ```APIDOC ## `zwylib.format_exc` ### Description Formats the current exception into a readable string, including traceback information. ### Returns * `str`: A string representation of the current exception and its traceback. ### Example ```python try: 1 / 0 except: error_string = zwylib.format_exc() print(error_string) ``` ``` -------------------------------- ### zwylib.SingletonMeta Source: https://zwylib-docs.vercel.app/utilities Metaclass for implementing the singleton pattern. Ensures that a class has only one instance. ```APIDOC ## `zwylib.SingletonMeta` ### Description Metaclass implementing the singleton pattern. Use it as the metaclass for any class that must have only one instance. ### Example ```python class MyManager(metaclass=SingletonMeta): ... a = MyManager() b = MyManager() assert a is b # True ``` ``` -------------------------------- ### zwylib.format_exc_from Source: https://zwylib-docs.vercel.app/utilities Formats a given exception into a readable string, including traceback information from a specific point. ```APIDOC ## `zwylib.format_exc_from` ### Description Formats a given exception into a readable string, including traceback information from a specific point. ### Arguments * `exc` (`BaseException`): The exception to format. * `frame` (`FrameType`): The frame from which to start formatting the traceback. ### Returns * `str`: A string representation of the exception and its traceback from the specified frame. ### Example ```python import traceback try: 1 / 0 except Exception as e: tb = traceback.extract_tb(e.__traceback__) formatted_error = zwylib.format_exc_from(e, tb[-1].frame) print(formatted_error) ``` ``` -------------------------------- ### Implement Singleton Pattern with SingletonMeta Source: https://zwylib-docs.vercel.app/utilities The SingletonMeta metaclass enforces the singleton pattern, ensuring that a class has only one instance. This is useful for managing global states or resources where a single point of control is required. The metaclass intercepts class creation to manage instance uniqueness. No external dependencies are required. ```python class SingletonMeta(type): pass class MyManager(metaclass=SingletonMeta): ... a = MyManager() b = MyManager() assert a is b # True ``` -------------------------------- ### ZWYLIB CacheFile for Binary Data Source: https://zwylib-docs.vercel.app/cachefiles The CacheFile class manages cache files for binary data. It supports initialization with a filename, automatic reading on creation, and optional zlib compression for reading and writing. Content is stored as bytes or None. Methods include read, write, wipe, and delete. ```python class CacheFile: def __init__(self, filename: str, read_on_init=True, compress=False): # ... implementation details ... pass def read(self) -> None: # ... implementation details ... pass def write(self) -> None: # ... implementation details ... pass def wipe(self) -> None: # ... implementation details ... pass def delete(self) -> None: # ... implementation details ... pass content: Optional[bytes] ``` ```python from zwylib import CacheFile cache = CacheFile("mycache.bin", compress=True) cache.content = b"some binary data" cache.write() ``` -------------------------------- ### Show Success Bulletin with Copy Functionality Source: https://zwylib-docs.vercel.app/logging-and-notifications Displays a success-style bulletin that includes a copy button for additional text. ```APIDOC ## POST /bulletins/success/copy ### Description Displays a success-style bulletin with a copy button. ### Method POST ### Endpoint /bulletins/success/copy ### Parameters #### Request Body - **message** (string) - Required - The message to display in the bulletin. - **copy_text** (string) - Required - The text to be copied to the clipboard when the button is clicked. ### Request Example ```json { "message": "Success!", "copy_text": "success details" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Show Info Bulletin with Post Redirect Source: https://zwylib-docs.vercel.app/logging-and-notifications Displays an info-style bulletin with a button that redirects the user to a specific post within a chat. ```APIDOC ## POST /bulletins/info/redirect/post ### Description Displays an info-style bulletin with a post-redirect button. ### Method POST ### Endpoint /bulletins/info/redirect/post ### Parameters #### Request Body - **message** (string) - Required - The message to display in the bulletin. - **button_text** (string) - Required - The text displayed on the redirect button. - **peer_id** (integer) - Required - The ID of the chat to redirect to. - **message_id** (integer) - Required - The ID of the message (post) to redirect to. ### Request Example ```json { "message": "Info message", "button_text": "View", "peer_id": -12345, "message_id": 67890 } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Display Success Bulletin with Copy Functionality Source: https://zwylib-docs.vercel.app/logging-and-notifications Displays a success-style bulletin. It features a confirmation message and a button to copy specific text to the clipboard. This is ideal for confirming operations or providing success-related information that users might need to copy. ```Python def show_success_with_copy(message: str, copy_text: str) -> None: """ Displays a success-style bulletin with a copy button. Arguments * `message` (str): The message to display. * `copy_text` (str): Text to be copied to the clipboard. """ pass # Implementation details omitted for brevity ``` -------------------------------- ### Show Success Bulletin with Post Redirect Source: https://zwylib-docs.vercel.app/logging-and-notifications Displays a success-style bulletin with a button that redirects the user to a specific post within a chat. ```APIDOC ## POST /bulletins/success/redirect/post ### Description Displays a success-style bulletin with a post-redirect button. ### Method POST ### Endpoint /bulletins/success/redirect/post ### Parameters #### Request Body - **message** (string) - Required - The message to display in the bulletin. - **button_text** (string) - Required - The text displayed on the redirect button. - **peer_id** (integer) - Required - The ID of the chat to redirect to. - **message_id** (integer) - Required - The ID of the message (post) to redirect to. ### Request Example ```json { "message": "Success!", "button_text": "View post", "peer_id": -12345, "message_id": 67890 } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Display Bulletin with Copy Button using InnerBulletinHelper Source: https://zwylib-docs.vercel.app/logging-and-notifications Displays a message along with a button that allows the user to copy specified text to the clipboard. It requires a message, the text to copy, and an icon resource ID. ```python bulletins = zwylib.build_bulletin_helper("MyPlugin") bulletins.show_with_copy("Copy this text", "example text", R.raw.info) # Expected display: MyPlugin: Copy this text (with a copy button) ``` -------------------------------- ### zwylib.Callback1 Source: https://zwylib-docs.vercel.app/utilities Wrapper class to pass Python functions to Java code via Chaquopy, emulating Java's `Utilities.Callback` interface. ```APIDOC ## `zwylib.Callback1` ### Description Wrapper class allowing a Python function to be passed into Java code via Chaquopy, emulating the `Utilities.Callback` Java interface. ### Constructor Arguments * `fn` (`Callable[[Any], None]`): A Python function that accepts a single argument and returns nothing. Called from Java via `.run(...)`. ### Methods #### `run` ```python Callback1.run(arg: Any) -> None ``` Called from Java, forwards the provided argument to the Python function. Exceptions are logged internally and not raised. ### Example ```python def my_python_callback(value): print(f"Received from Java: {value}") callback = zwylib.Callback1(my_python_callback) some_java_object.setCallback(callback) ``` ``` -------------------------------- ### Display Success Bulletin with InnerBulletinHelper Source: https://zwylib-docs.vercel.app/logging-and-notifications Displays a success message prefixed by the plugin name, optionally with a fragment. This confirms the successful completion of an operation to the user. ```python bulletins = zwylib.build_bulletin_helper("MyPlugin") bulletins.show_success("Data saved successfully") # Expected display: MyPlugin: Data saved successfully ``` -------------------------------- ### Register Command using Decorator - Python Source: https://zwylib-docs.vercel.app/commands Registers a command function using a decorator. The command requires specific arguments (`params` and `account`) and must return a `HookResult`. This method is part of the Dispatcher class. ```python @dispatcher.register_command(name: str) def test_command(params: Any, account: int) -> HookResult: params.message = "Hi!" return HookResult(strategy=HookStrategy.MODIFY, params=params) # Example usage: @dispatcher.register_command("hello") def test_command(params: Any, account: int) -> HookResult: params.message = "Hi!" return HookResult(strategy=HookStrategy.MODIFY, params=params) ``` -------------------------------- ### Show Bulletin with Post Redirect Source: https://zwylib-docs.vercel.app/logging-and-notifications Displays a bulletin with a button that redirects the user to a specific post within a chat. ```APIDOC ## POST /bulletins/redirect/post ### Description Displays a bulletin with a button that redirects to a specific post in a chat. ### Method POST ### Endpoint /bulletins/redirect/post ### Parameters #### Request Body - **message** (string) - Required - The message to display in the bulletin. - **button_text** (string) - Required - The text displayed on the redirect button. - **peer_id** (integer) - Required - The ID of the chat to redirect to. - **message_id** (integer) - Required - The ID of the message (post) to redirect to. - **icon_res_id** (integer) - Optional - Resource ID for the bulletin icon. Defaults to 0. ### Request Example ```json { "message": "View post", "button_text": "Go to post", "peer_id": -12345, "message_id": 67890, "icon_res_id": 0 } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Copy Text to Clipboard with Clipboard Notification Source: https://zwylib-docs.vercel.app/utilities The `copy_to_clipboard` function copies specified text to the system clipboard. Optionally, it can display a confirmation message using a `BulletinHelper` instance. This function is useful for providing user feedback after a copy action. ```python bulletins = zwylib.build_bulletin_helper("MyPlugin") zwylib.copy_to_clipboard(bulletins, "example text") # Copies "example text" to clipboard and shows a bulletin ``` -------------------------------- ### Display Info Bulletin with Post Redirect Source: https://zwylib-docs.vercel.app/logging-and-notifications Presents an informational bulletin with a button for redirecting to a specific post. This function is designed for informative messages that link to relevant content. It requires the message content, button label, and the target chat and message identifiers. ```Python def show_info_with_post_redirect(message: str, button_text: str, peer_id: int, message_id: int) -> None: """ Displays an info-style bulletin with a post-redirect button. Arguments * `message` (str): The message to display. * `button_text` (str): Text for the redirect button. * `peer_id` (int): ID of the chat to redirect to. * `message_id` (int): ID of the message to redirect to. """ pass # Implementation details omitted for brevity ``` -------------------------------- ### Display Info Bulletin with InnerBulletinHelper Source: https://zwylib-docs.vercel.app/logging-and-notifications Displays an informational message prefixed by the plugin name. It can optionally include a fragment for additional context. This method is part of the `InnerBulletinHelper` class for user-friendly notifications. ```python bulletins = zwylib.build_bulletin_helper("MyPlugin") bulletins.show_info("Operation completed") # Expected display: MyPlugin: Operation completed ``` -------------------------------- ### Display Bulletin with Post Redirect Button Source: https://zwylib-docs.vercel.app/logging-and-notifications Renders a bulletin containing a message and a button that, when clicked, redirects the user to a specific post within a chat. It allows customization of the button text and specifies the target chat and message IDs. An optional icon resource ID can also be provided. ```Python def show_with_post_redirect(message: str, button_text: str, peer_id: int, message_id: int, icon_res_id: int = 0) -> None: """ Displays a bulletin with a button that redirects to a specific post in a chat. Arguments * `message` (str): The message to display. * `button_text` (str): Text for the redirect button. * `peer_id` (int): ID of the chat to redirect to. * `message_id` (int): ID of the message to redirect to. * `icon_res_id` (int, default 0): Resource ID for the bulletin icon. """ pass # Implementation details omitted for brevity ``` -------------------------------- ### Show Error Bulletin with Post Redirect Source: https://zwylib-docs.vercel.app/logging-and-notifications Displays an error-style bulletin with a button that redirects the user to a specific post within a chat. ```APIDOC ## POST /bulletins/error/redirect/post ### Description Displays an error-style bulletin with a post-redirect button. ### Method POST ### Endpoint /bulletins/error/redirect/post ### Parameters #### Request Body - **message** (string) - Required - The message to display in the bulletin. - **button_text** (string) - Required - The text displayed on the redirect button. - **peer_id** (integer) - Required - The ID of the chat to redirect to. - **message_id** (integer) - Required - The ID of the message (post) to redirect to. ### Request Example ```json { "message": "Error occurred", "button_text": "View details", "peer_id": -12345, "message_id": 67890 } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Display Success Bulletin with Post Redirect Source: https://zwylib-docs.vercel.app/logging-and-notifications Displays a success-style bulletin featuring a button that redirects to a specified post. This function is intended for confirmations or notifications of successful actions, providing a direct link to related content. It requires the success message, button label, and the target chat and message IDs. ```Python def show_success_with_post_redirect(message: str, button_text: str, peer_id: int, message_id: int) -> None: """ Displays a success-style bulletin with a post-redirect button. Arguments * `message` (str): The message to display. * `button_text` (str): Text for the redirect button. * `peer_id` (int): ID of the chat to redirect to. * `message_id` (int): ID of the message to redirect to. """ pass # Implementation details omitted for brevity ``` -------------------------------- ### Bridge Python Functions to Java Callbacks with Callback1 Source: https://zwylib-docs.vercel.app/utilities Callback1 is a wrapper class designed to pass Python functions to Java code through Chaquopy, simulating Java's `Utilities.Callback` interface. It takes a Python function as an argument, which is then executed when the `run` method is called from Java. Exceptions during the Python function execution are logged internally and not re-raised. ```python def my_python_callback(value): print(f"Received from Java: {value}") callback = zwylib.Callback1(my_python_callback) some_java_object.setCallback(callback) ``` -------------------------------- ### Format Current Exception Traceback - Python Source: https://zwylib-docs.vercel.app/utilities Formats the current exception traceback as a string, similar to Python's built-in traceback.format_exc(). Returns a string containing the formatted traceback, stripped of leading/trailing whitespace. No specific inputs are required beyond an active exception context. ```python import zwylib try: 1 / 0 except ZeroDivisionError: error_trace = zwylib.format_exc() print(error_trace) # Prints the formatted traceback ``` -------------------------------- ### Show Error Bulletin with Copy Functionality Source: https://zwylib-docs.vercel.app/logging-and-notifications Displays an error-style bulletin that includes a copy button for additional text. ```APIDOC ## POST /bulletins/error/copy ### Description Displays an error-style bulletin with a copy button. ### Method POST ### Endpoint /bulletins/error/copy ### Parameters #### Request Body - **message** (string) - Required - The message to display in the bulletin. - **copy_text** (string) - Required - The text to be copied to the clipboard when the button is clicked. ### Request Example ```json { "message": "Error occurred", "copy_text": "error details" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### zwylib.format_exc_only Source: https://zwylib-docs.vercel.app/utilities Formats only the exception message into a readable string, without traceback information. ```APIDOC ## `zwylib.format_exc_only` ### Description Formats only the exception message into a readable string, without traceback information. ### Arguments * `exc` (`BaseException`): The exception to format. ### Returns * `str`: A string representation of the exception message. ### Example ```python try: 1 / 0 except Exception as e: error_message = zwylib.format_exc_only(e) print(error_message) ``` ``` -------------------------------- ### Format Specific Exception Traceback - Python Source: https://zwylib-docs.vercel.app/utilities Formats the traceback of a specific exception object as a string. Takes an Exception object as input and returns a string representation of its traceback, excluding leading/trailing whitespace. Useful for handling exceptions caught within a try-except block. ```python import zwylib try: 1 / 0 except ZeroDivisionError as e: error_trace = zwylib.format_exc_from(e) print(error_trace) # Prints the formatted traceback ``` -------------------------------- ### Display Error Bulletin with Post Redirect Source: https://zwylib-docs.vercel.app/logging-and-notifications Shows an error-style bulletin that includes a button to redirect the user to a specific post. This is useful for error messages that require users to navigate to a particular location for more details or resolution. It requires the error message, button text, and target post identifiers. ```Python def show_error_with_post_redirect(message: str, button_text: str, peer_id: int, message_id: int) -> None: """ Displays an error-style bulletin with a post-redirect button. Arguments * `message` (str): The message to display. * `button_text` (str): Text for the redirect button. * `peer_id` (int): ID of the chat to redirect to. * `message_id` (int): ID of the message to redirect to. """ pass # Implementation details omitted for brevity ``` -------------------------------- ### Register Error Handler for Command (Python) Source: https://zwylib-docs.vercel.app/commands Shows how to register a custom error handler for a specific command using the `@register_error_handler` decorator. This handler intercepts exceptions raised during the command's execution, allowing for custom error messages to be sent to the user. The handler must accept `params`, `account`, and `error` as arguments. ```python def register_commands(): dispatcher = zwylib.command_manager.get_dispatcher(...) @dispatcher.register_command("number") def number_command(params: Any, account: int, number: int) -> HookResult: params.message = f"number: {type(number)}" return HookResult(strategy=HookStrategy.MODIFY_FINAL, params=params) @number_command.register_error_handler def number_command_error_handler(params: Any, account: int, error: Exception) -> HookResult: params.message = f"An error occurred in 'number': {error}" return HookResult(strategy=HookStrategy.MODIFY_FINAL, params=params) ``` -------------------------------- ### Display Error Bulletin with InnerBulletinHelper Source: https://zwylib-docs.vercel.app/logging-and-notifications Displays an error message prefixed by the plugin name. It supports an optional fragment for more context. This is used to clearly indicate failures or issues to the user. ```python bulletins = zwylib.build_bulletin_helper("MyPlugin") bulletins.show_error("Failed to load data") # Expected display: MyPlugin: Failed to load data ``` -------------------------------- ### zwylib.Requests.search_messages Source: https://zwylib-docs.vercel.app/requests Asynchronously searches for messages in a peer based on specified criteria and passes the result to the provided callback. Additional parameters (e.g., `q`, `offset_id`, `add_offset`, `max_id`, `min_id`, `min_date`, `max_date`, `limit`) should be passed as keyword arguments matching the TL schema. ```APIDOC ## POST /zwylib/Requests/search_messages ### Description Asynchronously searches for messages in a peer based on specified criteria and passes the result to the provided callback. ### Method POST ### Endpoint /zwylib/Requests/search_messages ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **peer_id** (int) - Required - ID of the peer to search in. - **callback** (function) - Optional - Function called with the list of messages (or `None`) and an error (or `None`). - **from_id** (int) - Optional - ID of the sender to filter messages by. - **top_msg_id** (int) - Optional - ID of the top message for topic-based search. - **saved_peer_id** (int) - Optional - ID of the saved messages peer. - **saved_reaction** (TLRPC.Reaction) - Optional - Reaction to filter messages by. - **filter** (TLRPC.TL_inputMessagesFilter) - Optional - Filter for message types. - **delay** (int) - Optional - Delay in seconds before sending the request. - **kwargs** (dict) - Optional - Additional parameters matching the TL schema (e.g., `q`, `offset_id`, `add_offset`, `max_id`, `min_id`, `min_date`, `max_date`, `limit`). ### Request Example ```json { "peer_id": -12345, "q": "hello", "limit": 50 } ``` ### Response #### Success Response (200) This method does not return a value directly, results are handled by the callback function. #### Response Example ```json { "status": "success" } ``` ```