From 2f69c5c1030625bc2359ed19e18cfb7213029ad4 Mon Sep 17 00:00:00 2001 From: Nick Ninov Date: Thu, 13 Aug 2026 08:22:31 +0300 Subject: [PATCH 1/7] bot: Contact block / unblock Related to: - https://github.com/status-im/status-python-sdk/issues/36 - https://github.com/status-im/status-python-sdk/issues/35 --- docs/account.md | 71 +++++++++++++++++++++++++++++++++++++++++++ status_sdk/account.py | 23 ++++++++++++++ 2 files changed, 94 insertions(+) diff --git a/docs/account.md b/docs/account.md index 34fe038..3ffa154 100644 --- a/docs/account.md +++ b/docs/account.md @@ -774,6 +774,77 @@ removed = account.remove_contact(contact["public_key"]) print(f"Removed: {removed}") ``` +#### `block_contact(public_key)` + +Block a user, the same as **Block user** in Status App. Once blocked, the Status Backend stops surfacing that user's messages and contact requests to the account. + +Just like [`add_contact`](./account.md#add_contactpublic_key-display_namenone), the contact can be identified in three different ways: + +| Format | Example | Key in [`contacts`](./account.md#contacts) | +|-------|--------|-----------------| +| **Public key** | `0x04ebcad...` | `public_key` | +| **Chat key** (compressed key) | `zQ3shYSHp7...` | `compressed_key` | +| **Account URL** | `https://status.app/u/...` | `url` | + +| Name | Type | Required | Description | +|-----|-----|-----|-------------| +| `public_key` | `str` | Yes | The contact's Status **public key** (`0x...`), **chat key** (`zQ...`) or **account URL** (`https://...`). The value is normalised with [`get_public_key`](./account.md#get_public_keyvalue) before the call. | + + +```python +from status_sdk import Account + +account = Account() +params = { + "name": "status-app-bot", + "password": "SNTPUMP" +} +account.login(**params) + +contact = list(account.contacts.values())[0] +account.block_contact(contact["public_key"]) +``` + +Block a user from a chat key: + +```python +from status_sdk import Account + +account = Account() +params = { + "name": "status-app-bot", + "password": "SNTPUMP" +} +account.login(**params) + +account.block_contact("zQ3shYSHp7...") +``` + +#### `unblock_contact(public_key)` + +Unblock a previously [blocked](./account.md#block_contactpublic_key) user, the same as **Unblock user** in Status App. Their messages and contact requests reach the account again. The value is accepted in the same three formats as [`block_contact`](./account.md#block_contactpublic_key) and normalised with [`get_public_key`](./account.md#get_public_keyvalue). + +| Name | Type | Required | Description | +|-----|-----|-----|-------------| +| `public_key` | `str` | Yes | The contact's Status **public key** (`0x...`), **chat key** (`zQ...`) or **account URL** (`https://...`). | + + +```python +from status_sdk import Account + +account = Account() +params = { + "name": "status-app-bot", + "password": "SNTPUMP" +} +account.login(**params) + +account.unblock_contact("0x04ebcad...") + +# Unblocking alone does not make them a contact again +account.add_contact("0x04ebcad...", display_name="status-enjoyer") +``` + #### `get_public_key(value)` Normalise any of the three account identifiers into a **public key** (`0x...`). This normalisation is used internally by the library as well, so methods that accept a contact identifier work the same regardless of which format is passed. diff --git a/status_sdk/account.py b/status_sdk/account.py index 7658686..f3de2b1 100644 --- a/status_sdk/account.py +++ b/status_sdk/account.py @@ -886,6 +886,9 @@ def add_contact(self, public_key: str, display_name: Optional[str] = None): if public_key == self.info["public_key"]: return self + if display_name: + self.__validate_display_name(display_name) + if not display_name: contacts = self.contacts display_name = contacts.get(public_key, {}).get("display_name") @@ -927,6 +930,26 @@ def remove_contact(self, public_key: str) -> bool: self._call_rpc("messaging", "removeContact", params) return True + def block_contact(self, public_key: str): + """ + Block a contact. + + Parameters: + - `public_key` - the contact's public key / chat key / URL + """ + public_key = self.get_public_key(public_key) + self._call_rpc("messaging", "blockContact", [public_key]) + + def unblock_contact(self, public_key: str): + """ + Unblock a contact. + + Parameters: + - `public_key` - the contact's public key / chat key / URL + """ + public_key = self.get_public_key(public_key) + self._call_rpc("messaging", "unblockContact", [public_key]) + def get_public_key(self, value: str) -> str: """ Extract the public key from the URL / Chat key. From e1b20d330c283b683b796cd69abbb602cadd28e9 Mon Sep 17 00:00:00 2001 From: Nick Ninov Date: Thu, 13 Aug 2026 19:16:08 +0300 Subject: [PATCH 2/7] bot: Permanently Delete Messages - Related to https://github.com/status-im/status-python-sdk/issues/37 --- status_sdk/account.py | 51 ++++++++++++++++++++++++++++++++++++++----- 1 file changed, 46 insertions(+), 5 deletions(-) diff --git a/status_sdk/account.py b/status_sdk/account.py index f3de2b1..06801ca 100644 --- a/status_sdk/account.py +++ b/status_sdk/account.py @@ -786,11 +786,27 @@ def delete_message(self, id: str) -> bool: - if `True` then the message was deleted. If `False` then the message was not deleted due to permissions. """ self.info - response = self._call_rpc("messaging", "deleteMessageAndSend", [id]) - error: dict = response.get("error", {}) - if error: - self.logger.warning(f"Could not delete Message {id}... {error.get('message')}") - return not bool(error) + + exists , is_owner = self.__search_message(id) + if not exists: + return False + + rpc_methods = [ + "deleteMessageAndSend" if is_owner else None, + "deleteMessage" + ] + errors = [] + for rpc_method in rpc_methods: + if not rpc_method: + continue + response = self._call_rpc("messaging", rpc_method, [id]) + error: dict = response.get("error", {}) + if error: + self.logger.warning(f"[{rpc_method}] Could not delete Message {id}... {error.get('message')}") + + errors.append(bool(error)) + + return not any(errors) if errors else False def listen_contact_requests(self) -> Generator: """ @@ -1737,3 +1753,28 @@ def __validate_display_name(self, name: str): if not re.fullmatch(r"[A-Za-z0-9 _-]+", name): raise exceptions.InvalidDisplayNameError("Display name can contain only A-Z, 0-9, hyphens (-), underscores (_) and spaces.") + + def __search_message(self, id: str) -> tuple[bool, bool]: + """ + Look up a message by its ID. Useful for permission checks + before acting on a message. + + Parameters: + - `id` - the `id` of the message + + Output: + - `exists` - `True` if the message exists + - `is_owner` - `True` if the current account has sent the message + """ + response = self._call_rpc("messaging", "messageByMessageID", [id]) + is_owner = False + exists = False + + error = response.get("error") + if not error: + result: dict = response["result"] + is_owner = result["from"] == self.info["public_key"] + exists = True + + return exists, is_owner + From 95e969dd54833d988c82cdce9dd540439a93bd43 Mon Sep 17 00:00:00 2001 From: Nick Ninov Date: Thu, 13 Aug 2026 21:13:56 +0300 Subject: [PATCH 3/7] account: Mapping refactoring --- status_sdk/account.py | 38 ++++++++++++++++++++------------------ 1 file changed, 20 insertions(+), 18 deletions(-) diff --git a/status_sdk/account.py b/status_sdk/account.py index 06801ca..95dd49f 100644 --- a/status_sdk/account.py +++ b/status_sdk/account.py @@ -22,27 +22,27 @@ class Account: 2: "sent", # Request sent from the bot 3: "received", # Request sent from another account 4: "dismissed" # Request cancelled + }, + "status": { + "auto": 1, + "dnd": 2, + "on": 3, + "off": 4 + }, + "prefix": { + "messaging": "wakuext", + "urls": "sharedurls", + "wallets": "wallet", + "account": "accounts", + "identity": "multiaccounts", + "settings": "settings" } } - __prefix_mapping = { - "messaging": "wakuext", - "urls": "sharedurls", - "wallets": "wallet", - "account": "accounts", - "identity": "multiaccounts", - "settings": "settings" - } __keccak256_selectors = { "transfer": "a9059cbb" # keccak256("transfer(address,uint256)")[:4] } __ETH_ADDRESS = "0x0000000000000000000000000000000000000000" __KECCAK256_ERROR = "failed to open database: failed to set `journal_mode` pragma: file is not a database" - __status_types = { - "auto": 1, - "dnd": 2, - "on": 3, - "off": 4 - } __INSTALLATION_NAME = "python-sdk" def __init__(self, domain: str = "localhost", backend_port: int = 8080, media_port: int = 9000, is_secure: bool = False, backup_folder: Optional[str] = None, volume_folder: Optional[str] = None): """ @@ -618,9 +618,10 @@ def status(self) -> str: @status.setter def status(self, new_status: str): - selected = self.__status_types.get(new_status.lower()) + status_types: dict = self.__mappings["status"] + selected = status_types.get(new_status.lower()) if not selected: - raise exceptions.InvalidUserStatusError(f"Selected status '{selected}' is invalid... Available options: {' / '.join(self.__status_types.keys())}") + raise exceptions.InvalidUserStatusError(f"Selected status '{selected}' is invalid... Available options: {' / '.join(status_types.keys())}") self.__status = new_status.lower() self._call_rpc("messaging", "setUserStatus", [selected, ""]) @@ -1654,9 +1655,10 @@ def _call_rpc(self, prefix: str, method_name: str, params: Optional[Union[list, # Quick initialization check - RPC calls # can be made only after the user has logged in self.info - name = self.__prefix_mapping.get(prefix) + prefix_mapping: dict = self.__mappings["prefix"] + name = prefix_mapping.get(prefix) if not name: - raise exceptions.BackendError(f"Name {name} does not exist... Available options: {list(self.__prefix_mapping.keys())}") + raise exceptions.BackendError(f"Name {name} does not exist... Available options: {list(prefix_mapping.keys())}") if name == "wallet" and not self.__is_wallet_set: raise exceptions.WalletNotConfiguredError() From e13ca0ccf49e12504e4e6c416e99e7978c5a001e Mon Sep 17 00:00:00 2001 From: Nick Ninov Date: Fri, 14 Aug 2026 09:00:10 +0300 Subject: [PATCH 4/7] bot: Auto login - Related to https://github.com/status-im/status-python-sdk/issues/38 --- docs/account.md | 1 - status_sdk/account.py | 120 +++++++++++++++++++++++++++------------ status_sdk/exceptions.py | 4 ++ 3 files changed, 88 insertions(+), 37 deletions(-) diff --git a/docs/account.md b/docs/account.md index 3ffa154..fd27ba0 100644 --- a/docs/account.md +++ b/docs/account.md @@ -1406,7 +1406,6 @@ Provides information about the currently logged-in account. If `login()` has not | `display_name` | `str` | Display name of the account. | | `password` | `str` | Password used to encrypt the account locally. | | `wallet_address` | `str` | Ethereum wallet address associated with the account. | -| `ens` | `dict` | The account's [ENS](https://status.app/help/profile/transfer-your-ens-name-to-status) details. Contains `preferred_name` (`str` or `None`) - the ENS name the account has chosen to display - and `usernames` (`list[dict]`) - every ENS username registered to the account. Both are empty / `None` when no ENS name is set. | | `installation_id` | `str` | Id of **this** device's installation. Pass it to another device's [`sync`](./account.md#syncinstallation_id-namenone) to pair the two. `None` if the backend did not return one. | | `logged_in_timestamp` | `datetime.datetime` | Timestamp when the account successfully logged in. | diff --git a/status_sdk/account.py b/status_sdk/account.py index 95dd49f..a943f7f 100644 --- a/status_sdk/account.py +++ b/status_sdk/account.py @@ -120,8 +120,6 @@ def __init__(self, domain: str = "localhost", backend_port: int = 8080, media_po self.__signal = Signal(self.__urls["socket"]["signals"]) # Initialize profile self.available_accounts - # In case if there is a hanging logged in session - self.logout() def login(self, password: str, key_uid: Optional[str] = None, name: Optional[str] = None, mnemonic: Optional[str] = None, infura_token: Optional[str] = None, alchemy_token: Optional[str] = None, coingecko_api_key: Optional[str] = None): """ @@ -130,9 +128,9 @@ def login(self, password: str, key_uid: Optional[str] = None, name: Optional[str Parameters: - `password` - your Status password - - `key_uid` - your key unique identifier. If not provided `display_name` will be used to fetch it. This means that each `display_name` can be linked to one `key_uid` + - `key_uid` - your key unique identifier. If not provided `name` will be used to fetch it. This means that each `display_name` can be linked to one `key_uid` - `name` - your Status display name or ENS. Use `name` and `password` parameter combination if you have a 1 to 1 mapping (ENS has a unique `key_uid`) - - `mnemonic` - the mnemonic when creating an account. Use this field with `password` and `display_name` to recover an account + - `mnemonic` - the mnemonic when creating an account. Use this field with `password` and `name` to recover an account - `infura_token` - https://www.infura.io/ RPC token to allow Status Backend to use a wallet - `alchemy_token` - https://alchemy.com/ RPC token to allow Status Backend to use a wallet - `coingecko_api_key` - https://www.coingecko.com/ API key to allow Status Backend to use a wallet @@ -189,8 +187,6 @@ def login(self, password: str, key_uid: Optional[str] = None, name: Optional[str params["mnemonic"] = mnemonic self.logger.info(f"Restoring account for given mnemonics") - self.logout() - # Wallet usage is broken down into 3 components: # - transactions # - prices @@ -211,6 +207,15 @@ def login(self, password: str, key_uid: Optional[str] = None, name: Optional[str if alchemy_token and coingecko_api_key and infura_token: self.__is_wallet_set = True + if url_key == "login": + self.__info = self.__get_account_details(password, key_uid, mnemonic) + + if self.__info: + self.logger.info("Account already logged in!") + return self + + self.logout() + url = self.__urls["http"][url_key] params.update({ "logEnabled": True, @@ -221,9 +226,7 @@ def login(self, password: str, key_uid: Optional[str] = None, name: Optional[str signal_event = self.__signal.get("node.login") # Password must be hashed if the `data` folder has been copied over from another Status instance (`status-im/status-go` or Status App) if signal_event["is_error"] and signal_event["error_message"] == self.__KECCAK256_ERROR: - h = keccak.new(digest_bits=256) - h.update(params["password"].encode()) - params["password"] = "0x" + h.hexdigest().lower() + params["password"] = self.__hash_password(params["password"]) response = requests.post(url, json=params) signal_event = self.__signal.get("node.login") @@ -232,28 +235,10 @@ def login(self, password: str, key_uid: Optional[str] = None, name: Optional[str self.logger.info("Successfully logged in!") event: dict = signal_event["event"]["settings"] - ens_info: list[dict] = signal_event["event"].get("ensUsernames", []) - self.__info = { - "public_key": event["public-key"], - "url": None, - "emojis": event["emojiHash"], - "key_uid": event["key-uid"], - "compressed_key": event["compressedKey"], - "mnemonic": event.get("mnemonic", mnemonic), - "display_name": event["display-name"], - "bio": event.get("bio", ""), - "password": password, - "wallet_address": event["dapps-address"], - "ens": { - "preferred_name": event.get("preferred-name"), - "usernames": ens_info - }, - "installation_id": None, - "logged_in_timestamp": datetime.datetime.now() - } - self.__info["url"] = self._call_rpc("urls", "shareUserURLWithData", [event["public-key"]]).get("result") - result = self._call_rpc("settings", "getSettings").get("result") or {} - self.__info["installation_id"] = result.get("installation-id") + if not key_uid: + key_uid = event["key-uid"] + + self.__info = self.__get_account_details(password, key_uid, mnemonic) # Messenger can be activated only when logged in self.__start_messenger() if is_recovery: @@ -1598,11 +1583,6 @@ def __del__(self): Handles automatic logout when calling `del` and after running `python` """ - try: - self.logout() - except Exception: - pass - try: self.__signal.close(None) except Exception: @@ -1780,3 +1760,71 @@ def __search_message(self, id: str) -> tuple[bool, bool]: return exists, is_owner + def __hash_password(self, password: str) -> str: + """ + Hash a password the way Status App does before it reaches Status Backend. + + NOTE: Accounts created through Status App store the hash rather than the + password itself, so a `data` folder copied from it only accepts this form. + + Parameters: + - `password` - your Status password + + Output: + - the keccak256 hash of the password + """ + h = keccak.new(digest_bits=256) + h.update(password.encode()) + return "0x" + h.hexdigest().lower() + + def __get_account_details(self, password: str, key_uid: str, mnemonic: Optional[str] = None) -> dict: + """ + Check if the current account is already logged in or not + + Parameters: + - `password` - your Status password + - `key_uid` - your key unique identifier. If not provided `display_name` will be used to fetch it. This means that each `display_name` can be linked to one `key_uid` + - `mnemonic` - the mnemonic when creating an account. Use this field with `password` and `name` to recover an account + + Output: + - data for `self.__info` + """ + self.__info = {None} + response = self._call_rpc("settings", "getSettings") + self.__info = {} + + # No logged in session + if response.get("error"): + return {} + + event: dict = response["result"] + # Another account is logged in + if key_uid != event["key-uid"]: + return {} + + self.__info = {None} + correct_password = self._call_rpc("account", "verifyPassword", [password]).get("result") or False + if not correct_password: + # Accounts coming from Status App / `status-im/status-go` store the hashed password + correct_password = self._call_rpc("account", "verifyPassword", [self.__hash_password(password)]).get("result") or False + + if not correct_password: + self.__info = {} + raise exceptions.InvalidPasswordError(f"The password for account '{key_uid}' is incorrect...") + + info = { + "public_key": event["public-key"], + "url": self._call_rpc("urls", "shareUserURLWithData", [event["public-key"]]).get("result"), + "emojis": event["emojiHash"], + "key_uid": event["key-uid"], + "compressed_key": event["compressedKey"], + "mnemonic": event.get("mnemonic", mnemonic), + "display_name": event["display-name"], + "bio": event.get("bio", ""), + "password": password, + "wallet_address": event["dapps-address"], + "installation_id": event["installation-id"], + "logged_in_timestamp": datetime.datetime.now() + } + self.__info = {} + return info diff --git a/status_sdk/exceptions.py b/status_sdk/exceptions.py index 4e12bc8..2bd0487 100644 --- a/status_sdk/exceptions.py +++ b/status_sdk/exceptions.py @@ -7,6 +7,10 @@ class NotLoggedInError(Exception): def __init__(self): super().__init__("Make sure you are logged in to your Status account with login() first...") +class InvalidPasswordError(Exception): + def __init__(self, msg: Optional[str] = None): + super().__init__(msg or "The provided password is incorrect for this account...") + class WalletNotConfiguredError(Exception): def __init__(self, msg: Optional[str] = None): super().__init__(msg or "Cannot use this wallet method without setting `infura_token`, `alchemy_token` and `coingecko_api_key` when calling `login`.") From 86796bf95c59e1a003753c09e8e81f83ec719d38 Mon Sep 17 00:00:00 2001 From: Nick Ninov Date: Fri, 14 Aug 2026 12:43:33 +0300 Subject: [PATCH 5/7] license: Add MPL 2.0 --- LICENSE.md | 355 ++++++++++++++++++++++++++++++++++++++++++++++++++++ LICENSE.txt | 21 ---- 2 files changed, 355 insertions(+), 21 deletions(-) create mode 100644 LICENSE.md delete mode 100644 LICENSE.txt diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..cd44203 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,355 @@ +Mozilla Public License Version 2.0 +================================== + +### 1. Definitions + +**1.1. “Contributor”** + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +**1.2. “Contributor Version”** + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +**1.3. “Contribution”** + means Covered Software of a particular Contributor. + +**1.4. “Covered Software”** + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +**1.5. “Incompatible With Secondary Licenses”** + means + +* **(a)** that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or +* **(b)** that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +**1.6. “Executable Form”** + means any form of the work other than Source Code Form. + +**1.7. “Larger Work”** + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +**1.8. “License”** + means this document. + +**1.9. “Licensable”** + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +**1.10. “Modifications”** + means any of the following: + +* **(a)** any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or +* **(b)** any new file in Source Code Form that contains any Covered + Software. + +**1.11. “Patent Claims” of a Contributor** + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +**1.12. “Secondary License”** + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +**1.13. “Source Code Form”** + means the form of the work preferred for making modifications. + +**1.14. “You” (or “Your”)** + means an individual or a legal entity exercising rights under this + License. For legal entities, “You” includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, “control” means **(a)** the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or **(b)** ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + + +### 2. License Grants and Conditions + +#### 2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +* **(a)** under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and +* **(b)** under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +#### 2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +#### 2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +* **(a)** for any code that a Contributor has removed from Covered Software; + or +* **(b)** for infringements caused by: **(i)** Your and any other third party's + modifications of Covered Software, or **(ii)** the combination of its + Contributions with other software (except as part of its Contributor + Version); or +* **(c)** under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +#### 2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +#### 2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +#### 2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +#### 2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + + +### 3. Responsibilities + +#### 3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +#### 3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +* **(a)** such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +* **(b)** You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +#### 3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +#### 3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +#### 3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + + +### 4. Inability to Comply Due to Statute or Regulation + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: **(a)** comply with +the terms of this License to the maximum extent possible; and **(b)** +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + + +### 5. Termination + +**5.1.** The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated **(a)** provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and **(b)** on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +**5.2.** If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +**5.3.** In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + + +### 6. Disclaimer of Warranty + +> Covered Software is provided under this License on an “as is” +> basis, without warranty of any kind, either expressed, implied, or +> statutory, including, without limitation, warranties that the +> Covered Software is free of defects, merchantable, fit for a +> particular purpose or non-infringing. The entire risk as to the +> quality and performance of the Covered Software is with You. +> Should any Covered Software prove defective in any respect, You +> (not any Contributor) assume the cost of any necessary servicing, +> repair, or correction. This disclaimer of warranty constitutes an +> essential part of this License. No use of any Covered Software is +> authorized under this License except under this disclaimer. + +### 7. Limitation of Liability + +> Under no circumstances and under no legal theory, whether tort +> (including negligence), contract, or otherwise, shall any +> Contributor, or anyone who distributes Covered Software as +> permitted above, be liable to You for any direct, indirect, +> special, incidental, or consequential damages of any character +> including, without limitation, damages for lost profits, loss of +> goodwill, work stoppage, computer failure or malfunction, or any +> and all other commercial damages or losses, even if such party +> shall have been informed of the possibility of such damages. This +> limitation of liability shall not apply to liability for death or +> personal injury resulting from such party's negligence to the +> extent applicable law prohibits such limitation. Some +> jurisdictions do not allow the exclusion or limitation of +> incidental or consequential damages, so this exclusion and +> limitation may not apply to You. + + +### 8. Litigation + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + + +### 9. Miscellaneous + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + + +### 10. Versions of the License + +#### 10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +#### 10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +#### 10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +#### 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +## Exhibit A - Source Code Form License Notice + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +## Exhibit B - “Incompatible With Secondary Licenses” Notice + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/LICENSE.txt b/LICENSE.txt deleted file mode 100644 index 3d8cccb..0000000 --- a/LICENSE.txt +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2026 Status Research & Development GmbH - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. From c526e9c8427df8abd4e72ca2f00ec18af4df94fb Mon Sep 17 00:00:00 2001 From: Nick Ninov Date: Sat, 15 Aug 2026 00:36:07 +0300 Subject: [PATCH 6/7] messaging: Date formatting New supported formats: - `datetime.date` - `pd.Timestamp` - `str` --- docs/account.md | 18 ++++++++++++-- docs/community.md | 6 +++-- docs/group-chat.md | 6 +++-- status_sdk/account.py | 44 ++++++++++++++++++++++++++++++--- status_sdk/community/channel.py | 9 ++++--- status_sdk/exceptions.py | 3 +++ status_sdk/group_chat.py | 7 +++--- 7 files changed, 77 insertions(+), 16 deletions(-) diff --git a/docs/account.md b/docs/account.md index fd27ba0..cd4dc2b 100644 --- a/docs/account.md +++ b/docs/account.md @@ -526,8 +526,8 @@ Messages can be fetched from: | Name | Type | Required | Description | |-----|-----|-----|-------------| | `chat_id` | `str` | Yes | Identifier of the chat. All available chat IDs can be obtained from the [`chats`](./account.md#chats) property. | -| `start_timestamp` | `datetime.datetime` | No | The earliest timestamp to include. Messages older than this value will stop the fetch process. | -| `end_timestamp` | `datetime.datetime` | No | The latest timestamp to include. Messages newer than this value will be skipped. | +| `start_timestamp` | `str`
`datetime.date`
`datetime.datetime`
`pandas.Timestamp` | No | The earliest timestamp to include. Messages older than this value will stop the fetch process. | +| `end_timestamp` | `str`
`datetime.date`
`datetime.datetime`
`pandas.Timestamp` | No | The latest timestamp to include. Messages newer than this value will be skipped. | Returns `list[dict]` containing message objects. Timestamp fields returned by the backend are automatically converted into `datetime.datetime` objects. @@ -555,6 +555,20 @@ for message in messages: **Note**: If there are missing messages in a chat that might be because the node (Status Backend) has not received them yet. They may appear later. +**Timestamps** + +Both timestamps also accept a plain `str`, so a range can be written out without building a `datetime.datetime` first. The **time is optional** and can be given with any precision - the missing parts default to zero, meaning that `2026-08-11` is read as `2026-08-11 00:00:00`. A `datetime.date` carries no time at all and is moved to midnight the same way. + +| Format | Example | +|-----|-----| +| `YYYY-MM-DD HH:MM:SS.ffffff` | `2026-08-11 22:57:51.134000` | +| `YYYY-MM-DD HH:MM:SS` | `2026-08-11 22:57:51` | +| `YYYY-MM-DD HH:MM` | `2026-08-11 22:57` | +| `YYYY-MM-DD HH` | `2026-08-11 22` | +| `YYYY-MM-DD` | `2026-08-11` | + +Both `T` and a space are accepted as the date / time separator, so `2026-08-11T22:57:51` and `2026-08-11 22:57:51` are the same timestamp. + #### `delete_message(id)` Delete one of your **own** messages from a chat. The deletion is propagated to the other members of the chat, so the message disappears for everybody - the same as deleting a message in Status App. diff --git a/docs/community.md b/docs/community.md index 9a1a6a9..85192a6 100644 --- a/docs/community.md +++ b/docs/community.md @@ -1245,8 +1245,10 @@ Retrieve messages from the channel within an optional time range. Messages are r | Name | Type | Required | Description | |-----|-----|-----|-------------| -| `start_timestamp` | `datetime.datetime` | No | The earliest timestamp to include. Messages older than this stop the fetch. | -| `end_timestamp` | `datetime.datetime` | No | The latest timestamp to include. Messages newer than this are skipped. | +| `start_timestamp` | `str`
`datetime.date`
`datetime.datetime`
`pandas.Timestamp` | No | The earliest timestamp to include. Messages older than this stop the fetch. | +| `end_timestamp` | `str`
`datetime.date`
`datetime.datetime`
`pandas.Timestamp` | No | The latest timestamp to include. Messages newer than this are skipped. | + +Both timestamps accept the same values as [`get_messages`](./account.md#get_messageschat_id-start_timestampnone-end_timestampnone) on `Account`, so a range can be written as a plain `str` - for example `2026-08-11 22:57:51.134000`, `2026-08-11 22:57` or `2026-08-11`. Returns `list[dict]` of message objects. This delegates to [`get_messages`](./account.md#get_messageschat_id-start_timestampnone-end_timestampnone) on `Account`. diff --git a/docs/group-chat.md b/docs/group-chat.md index e717785..2496a9f 100644 --- a/docs/group-chat.md +++ b/docs/group-chat.md @@ -292,8 +292,10 @@ Retrieve messages from the group chat within an optional time range. Messages ar | Name | Type | Required | Description | |-----|-----|-----|-------------| -| `start_timestamp` | `datetime.datetime` | No | The earliest timestamp to include. Messages older than this value will stop the fetch process. | -| `end_timestamp` | `datetime.datetime` | No | The latest timestamp to include. Messages newer than this value will be skipped. | +| `start_timestamp` | `str`
`datetime.date`
`datetime.datetime`
`pandas.Timestamp` | No | The earliest timestamp to include. Messages older than this value will stop the fetch process. | +| `end_timestamp` | `str`
`datetime.date`
`datetime.datetime`
`pandas.Timestamp` | No | The latest timestamp to include. Messages newer than this value will be skipped. | + +Both timestamps accept the same values as [`get_messages`](./account.md#get_messageschat_id-start_timestampnone-end_timestampnone) on `Account`, so a range can be written as a plain `str` - for example `2026-08-11 22:57:51.134000`, `2026-08-11 22:57` or `2026-08-11`. Returns `list[dict]` containing message objects. Timestamp fields returned by the backend are automatically converted into `datetime.datetime` objects. diff --git a/status_sdk/account.py b/status_sdk/account.py index a943f7f..f1aa627 100644 --- a/status_sdk/account.py +++ b/status_sdk/account.py @@ -813,7 +813,7 @@ def listen_messages(self) -> Generator: if "chats" in event or "messages" in event: yield message - def get_messages(self, chat_id: str, start_timestamp: Optional[datetime.datetime] = None, end_timestamp: Optional[datetime.datetime] = None) -> list[dict]: + def get_messages(self, chat_id: str, start_timestamp: Optional[Union[str, datetime.datetime, datetime.date, pd.Timestamp]] = None, end_timestamp: Optional[Union[str, datetime.datetime, datetime.date, pd.Timestamp]] = None) -> list[dict]: """ Get all of the messages in the given start and end timestamps. Messages are returned in descending order (newest to oldest). @@ -821,12 +821,14 @@ def get_messages(self, chat_id: str, start_timestamp: Optional[datetime.datetime Parameters: - `chat_id` - the chat ID can be found in `self.chats` - - `start_timestamp` - the start timestamp for message extraction. If not provided all early messages will be fetched. - - `end_timestamp` - the end timestamp for message extraction. If not provided all latest messages will be fetched. + - `start_timestamp` - the start timestamp for message extraction. If not provided all early messages will be fetched. Can be a `datetime.datetime` or a string like `2026-08-11 22:57:51.134000` / `2026-08-11 22:57` / `2026-08-11` + - `end_timestamp` - the end timestamp for message extraction. If not provided all latest messages will be fetched. Can be a `datetime.datetime` or a string like `2026-08-11 22:57:51.134000` / `2026-08-11 22:57` / `2026-08-11` Output: - All messages within the given range """ + start_timestamp = self.__to_datetime(start_timestamp) + end_timestamp = self.__to_datetime(end_timestamp) # NOTE: Order of params matters when making the RCP call params = { "chat_id": chat_id, @@ -1707,6 +1709,42 @@ def __camel_to_snake(self, name: str) -> str: s2 = re.sub(r'([a-z0-9])([A-Z])', r'\1_\2', s1) return s2.lower() + def __to_datetime(self, timestamp: Union[str, datetime.datetime, datetime.date, pd.Timestamp, None]) -> Optional[datetime.datetime]: + """ + Convert a timestamp `str` / `datetime.date` into a `datetime.datetime`. + + Parameters: + - `timestamp` - the timestamp, e.g. `2026-08-11 22:57:51.134000`, `2026-08-11 22:57`, `2026-08-11` or `datetime.date`. A `datetime.datetime` / `None` is returned as it is + + Output: + - the `datetime.datetime` of the `timestamp` + """ + if timestamp is None or isinstance(timestamp, datetime.datetime): + return timestamp + + if isinstance(timestamp, datetime.date): + return datetime.datetime(timestamp.year, timestamp.month, timestamp.day) + + if isinstance(timestamp, pd.Timestamp): + timestamp = str(timestamp) + + if not isinstance(timestamp, str): + raise exceptions.InvalidTimestampError(f"Expected a `str` or a `datetime.datetime`, got `{type(timestamp).__name__}`...") + + # Accepted timestamp formats, tried from the most to the least precise + formats = [ + "%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M", "%Y-%m-%d %H", "%Y-%m-%d" + ] + value = timestamp.strip().replace("T", " ") + for current_format in formats: + try: + return datetime.datetime.strptime(value, current_format) + except ValueError: + continue + + raise exceptions.InvalidTimestampError(f"`{timestamp}` is not a valid timestamp. Supported formats: {', '.join(formats)}") + def __validate_display_name(self, name: str): """ Validate the display name based on Status App rules. diff --git a/status_sdk/community/channel.py b/status_sdk/community/channel.py index 28757ff..1736783 100644 --- a/status_sdk/community/channel.py +++ b/status_sdk/community/channel.py @@ -1,6 +1,7 @@ from ..account import Account from .. import exceptions -from typing import Optional +from typing import Union, Optional +import pandas as pd import re, datetime, random, unicodedata class Channel: @@ -214,15 +215,15 @@ def send_image(self, file_path: str, message: Optional[str] = None, reply_to_mes return self.__account.send_image(self.id, file_path, message, reply_to_message_id) - def get_messages(self, start_timestamp: Optional[datetime.datetime] = None, end_timestamp: Optional[datetime.datetime] = None) -> list[dict]: + def get_messages(self, start_timestamp: Optional[Union[str, datetime.datetime, datetime.date, pd.Timestamp]] = None, end_timestamp: Optional[Union[str, datetime.datetime, datetime.date, pd.Timestamp]] = None) -> list[dict]: """ Get all of the messages in the given start and end timestamps. Messages are returned in descending order (newest to oldest). Messages can be fetched for removed contacts as well. Parameters: - - `start_timestamp` - the start timestamp for message extraction. If not provided all early messages will be fetched. - - `end_timestamp` - the end timestamp for message extraction. If not provided all latest messages will be fetched. + - `start_timestamp` - the start timestamp for message extraction. If not provided all early messages will be fetched. Can be a `datetime.datetime` or a string like `2026-08-11 22:57:51.134000` / `2026-08-11 22:57` / `2026-08-11` + - `end_timestamp` - the end timestamp for message extraction. If not provided all latest messages will be fetched. Can be a `datetime.datetime` or a string like `2026-08-11 22:57:51.134000` / `2026-08-11 22:57` / `2026-08-11` Output: - All messages within the given range diff --git a/status_sdk/exceptions.py b/status_sdk/exceptions.py index 2bd0487..28c496a 100644 --- a/status_sdk/exceptions.py +++ b/status_sdk/exceptions.py @@ -125,3 +125,6 @@ class SignalError(Exception): class InvalidPathError(Exception): pass + +class InvalidTimestampError(ValueError): + pass diff --git a/status_sdk/group_chat.py b/status_sdk/group_chat.py index 3e8583a..0f76c98 100644 --- a/status_sdk/group_chat.py +++ b/status_sdk/group_chat.py @@ -1,6 +1,7 @@ from .account import Account from . import exceptions from typing import Union, Optional +import pandas as pd import re, datetime class GroupChat: @@ -84,15 +85,15 @@ def send_image(self, file_path: str, message: Optional[str] = None, reply_to_mes return self.__account.send_image(self.id, file_path, message, reply_to_message_id) - def get_messages(self, start_timestamp: Optional[datetime.datetime] = None, end_timestamp: Optional[datetime.datetime] = None) -> list[dict]: + def get_messages(self, start_timestamp: Optional[Union[str, datetime.datetime, datetime.date, pd.Timestamp]] = None, end_timestamp: Optional[Union[str, datetime.datetime, datetime.date, pd.Timestamp]] = None) -> list[dict]: """ Get all of the messages in the given start and end timestamps. Messages are returned in descending order (newest to oldest). Messages can be fetched for removed contacts as well. Parameters: - - `start_timestamp` - the start timestamp for message extraction. If not provided all early messages will be fetched. - - `end_timestamp` - the end timestamp for message extraction. If not provided all latest messages will be fetched. + - `start_timestamp` - the start timestamp for message extraction. If not provided all early messages will be fetched. Can be a `datetime.datetime` or a string like `2026-08-11 22:57:51.134000` / `2026-08-11 22:57` / `2026-08-11` + - `end_timestamp` - the end timestamp for message extraction. If not provided all latest messages will be fetched. Can be a `datetime.datetime` or a string like `2026-08-11 22:57:51.134000` / `2026-08-11 22:57` / `2026-08-11` Output: - All messages within the given range From b14de3bcab0b7253c2a6c3e975b721dd9d1bc023 Mon Sep 17 00:00:00 2001 From: Nick Ninov Date: Mon, 17 Aug 2026 11:43:40 +0300 Subject: [PATCH 7/7] bug: status-bot implementation --- pyproject.toml | 2 +- status_sdk/account.py | 16 ++++------------ status_sdk/logger.py | 6 +++--- 3 files changed, 8 insertions(+), 16 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 2cc6d3b..f27fdc6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "status-sdk" -version = "1.1.1" +version = "1.1.2" description = "Private chat. Communities. Multi-chain wallet. Browser. dApps all in one app, powered by SNT." readme = "README.md" requires-python = ">=3.11" diff --git a/status_sdk/account.py b/status_sdk/account.py index f1aa627..3ccd869 100644 --- a/status_sdk/account.py +++ b/status_sdk/account.py @@ -1731,19 +1731,11 @@ def __to_datetime(self, timestamp: Union[str, datetime.datetime, datetime.date, if not isinstance(timestamp, str): raise exceptions.InvalidTimestampError(f"Expected a `str` or a `datetime.datetime`, got `{type(timestamp).__name__}`...") - # Accepted timestamp formats, tried from the most to the least precise - formats = [ - "%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%d %H:%M:%S", - "%Y-%m-%d %H:%M", "%Y-%m-%d %H", "%Y-%m-%d" - ] - value = timestamp.strip().replace("T", " ") - for current_format in formats: - try: - return datetime.datetime.strptime(value, current_format) - except ValueError: - continue + try: + return datetime.datetime.fromisoformat(timestamp) + except: + raise exceptions.InvalidTimestampError(f"`{timestamp}` is not a valid timestamp... Please make sure the input is in ISO 8601 format (https://www.iso.org/iso-8601-date-and-time-format.html).") - raise exceptions.InvalidTimestampError(f"`{timestamp}` is not a valid timestamp. Supported formats: {', '.join(formats)}") def __validate_display_name(self, name: str): """ diff --git a/status_sdk/logger.py b/status_sdk/logger.py index 850b254..5ebc7d0 100644 --- a/status_sdk/logger.py +++ b/status_sdk/logger.py @@ -4,12 +4,12 @@ class Logger: instance: Optional[logging.Logger] = None - def __new__(cls) -> logging.Logger: + def __new__(cls, name: str = "status-bot") -> logging.Logger: if cls.instance: - return cls.instance + return logging.getLogger(name) - cls.instance = logging.getLogger("status-bot") + cls.instance = logging.getLogger(name) cls.instance.setLevel(logging.INFO) cls.instance.propagate = False