### Install Taqnyat Python Library Source: https://context7.com/taqnyat/python/llms.txt Install the library using pip or clone the source repository. ```bash pip install taqnyat ``` ```bash git clone https://github.com/taqnyat/python.git ``` -------------------------------- ### Install Taqnyat-Python via PIP Source: https://github.com/taqnyat/python/blob/main/README.md Install the Taqnyat-Python library using pip. This is the recommended method for adding the library to your Python environment. ```bash pip install taqnyat ``` -------------------------------- ### Get Taqnyat Account Balance Source: https://github.com/taqnyat/python/blob/main/README.md Initialize the Taqnyat client with a bearer token and fetch the account balance. Requires a valid bearer token for authentication. ```python from TaqnyatSms import Client bearer = "**************************0adc2b" taqnyt = Client(bearer) balance = taqnyt.balance() print(balance) ``` -------------------------------- ### Get Taqnyat Services Status Source: https://github.com/taqnyat/python/blob/main/README.md Initialize the Taqnyat client with a bearer token and retrieve the current service status. Ensure you have a valid bearer token. ```python from TaqnyatSms import Client bearer = "**************************0adc2b" taqnyt = Client(bearer) status = taqnyt.sendStatus() print(status) ``` -------------------------------- ### Get Taqnyat Account Senders Source: https://github.com/taqnyat/python/blob/main/README.md Initialize the Taqnyat client with a bearer token and retrieve a list of configured senders. A valid bearer token is necessary. ```python from TaqnyatSms import Client bearer = "**************************0adc2b" taqnyt = Client(bearer) senders = taqnyt.senders() print(senders) ``` -------------------------------- ### Client.balance Source: https://context7.com/taqnyat/python/llms.txt Fetches the current account balance and status via GET /account/balance. Returns a dict with balance details, useful for monitoring credit consumption and triggering top-up alerts. ```APIDOC ## Client.balance — Retrieve Account Balance ### Description Fetches the current account balance and status. ### Method GET ### Endpoint /account/balance ### Response #### Success Response (200) - **balance** (float) - The current account balance. - **currency** (string) - The currency of the balance (e.g., SAR). - **status** (string) - The status of the account (e.g., active). ### Request Example ```python from TaqnyatSms import Client client = Client("your_bearer_token_here") balance_info = client.balance() print(balance_info) ``` ### Response Example ```json { "balance": 250.75, "currency": "SAR", "status": "active" } ``` ``` -------------------------------- ### Handle Errors with Client Methods Source: https://context7.com/taqnyat/python/llms.txt All Client methods return a string error message for failures instead of raising exceptions. This example demonstrates how to check the return type to distinguish success (dict) from failure (string). ```python from TaqnyatSms import Client client = Client("your_bearer_token_here") def safe_send(client: Client, body: str, recipients: list, sender: str): result = client.sendMsg(body, recipients, sender) if isinstance(result, str): if result == "Add Authentication": print("Error: No bearer token provided.") elif result.startswith("HTTP Error"): print(f"API error: {result}") # e.g., "HTTP Error: 401 Client Error: Unauthorized - Body: ..." elif result.startswith("SSL Error"): print(f"SSL error: {result}") elif result.startswith("Request Error"): print(f"Network error: {result}") else: print(f"Unexpected response: {result}") elif isinstance(result, dict): print(f"Success: messageId={result.get('messageId')}, status={result.get('status')}") else: print(f"Unknown response format: {result}") safe_send(client, "Test message", ["966501234567"], "TestSender") ``` -------------------------------- ### Mocking requests.Session for Unit Tests Source: https://context7.com/taqnyat/python/llms.txt Inject a mock `requests.Session` to simulate API responses during unit testing. This setup is crucial for isolating tests and avoiding external network calls. ```python import unittest from unittest.mock import Mock from TaqnyatSms import Client def make_mock_session(json_payload): response = Mock() response.raise_for_status = Mock() response.json = Mock(return_value=json_payload) response.content = b"{}" session = Mock() session.headers = {} session.request = Mock(return_value=response) return session class MyAppSMSTests(unittest.TestCase): def test_send_otp_success(self): session = make_mock_session({"messageId": "123", "status": "queued"}) client = Client("test_token", session=session) result = client.sendMsg("Your OTP: 999888", ["966501234567"], "MyApp") self.assertEqual(result["status"], "queued") _, kwargs = session.request.call_args self.assertEqual(kwargs["json"Македония]["body"], "Your OTP: 999888") self.assertEqual(kwargs["json"Македония]["recipients"], ["966501234567"]) def test_missing_token_blocked(self): session = make_mock_session({}) client = Client("", session=session) result = client.sendMsg("Hello", ["966501234567"], "MyApp") self.assertEqual(result, "Add Authentication") session.request.assert_not_called() if __name__ == "__main__": unittest.main() ``` -------------------------------- ### Client.senders Source: https://context7.com/taqnyat/python/llms.txt Retrieves all approved sender names registered to the account via GET /v1/messages/senders. Sender names must be pre-approved by Taqnyat before use in outgoing messages. ```APIDOC ## Client.senders — List Approved Senders ### Description Retrieves all approved sender names registered to the account. ### Method GET ### Endpoint /v1/messages/senders ### Response #### Success Response (200) - **senders** (list of strings) - A list of approved sender names. ### Request Example ```python from TaqnyatSms import Client client = Client("your_bearer_token_here") senders = client.senders() print(senders) ``` ### Response Example ```json { "senders": ["MyBrand", "ClinicApp", "AlertSys"] } ``` ``` -------------------------------- ### Client.__init__ Source: https://context7.com/taqnyat/python/llms.txt Initializes the Taqnyat API client with authentication credentials and optional configuration settings. ```APIDOC ## Client.__init__ — Initialize the API Client Creates a new `Client` instance configured with a Bearer authentication token. Optionally accepts a custom base URL, request timeout, SSL verification setting, or a pre-built `requests.Session` for advanced use cases such as connection pooling or testing. ```python from TaqnyatSms import Client import requests # Basic initialization with just a bearer token client = Client("your_bearer_token_here") # Advanced initialization with custom options custom_session = requests.Session() custom_session.headers.update({"X-Custom-Header": "value"}) client = Client( auth="your_bearer_token_here", verify=True, # True uses certifi CA bundle; False disables SSL verification timeout=30, # Request timeout in seconds (default: 15) session=custom_session, base_url="https://api.taqnyat.sa", # Override for testing/staging ) # Missing auth is caught at call time, not initialization empty_client = Client("") result = empty_client.balance() print(result) # Output: "Add Authentication" ``` ``` -------------------------------- ### Initialize Taqnyat API Client Source: https://context7.com/taqnyat/python/llms.txt Create a `Client` instance with a bearer token. Custom options like base URL, timeout, and SSL verification can be configured. Missing authentication is handled at call time. ```python from TaqnyatSms import Client import requests # Basic initialization with just a bearer token client = Client("your_bearer_token_here") # Advanced initialization with custom options custom_session = requests.Session() custom_session.headers.update({"X-Custom-Header": "value"}) client = Client( auth="your_bearer_token_here", verify=True, # True uses certifi CA bundle; False disables SSL verification timeout=30, # Request timeout in seconds (default: 15) session=custom_session, base_url="https://api.taqnyat.sa", # Override for testing/staging ) # Missing auth is caught at call time, not initialization empty_client = Client("") result = empty_client.balance() print(result) # Output: "Add Authentication" ``` -------------------------------- ### Retrieve Account Balance with Client.balance Source: https://context7.com/taqnyat/python/llms.txt Fetches the current account balance and status. Useful for monitoring credit consumption and triggering top-up alerts. Ensure a valid bearer token is provided. ```python from TaqnyatSms import Client client = Client("your_bearer_token_here") balance_info = client.balance() print(balance_info) # Expected output: {"balance": 250.75, "currency": "SAR", "status": "active"} ``` ```python # Practical usage: alert when balance is low def check_balance_threshold(bearer_token: str, minimum: float) -> None: client = Client(bearer_token) result = client.balance() if isinstance(result, dict): current = result.get("balance", 0) print(f"Current balance: {current} {result.get('currency', '')}") if current < minimum: print(f"WARNING: Balance below {minimum}. Please top up.") else: print(f"Error fetching balance: {result}") check_balance_threshold("your_bearer_token_here", minimum=50.0) # Output: "Current balance: 250.75 SAR" # or: "WARNING: Balance below 50.0. Please top up." ``` -------------------------------- ### List Approved Senders with Client.senders Source: https://context7.com/taqnyat/python/llms.txt Retrieves all approved sender names registered to the account. Sender names must be pre-approved by Taqnyat before use. This function validates a sender name before sending a message. ```python from TaqnyatSms import Client client = Client("your_bearer_token_here") senders = client.senders() print(senders) # Expected output: {"senders": ["MyBrand", "ClinicApp", "AlertSys"]} ``` ```python # Validate a sender name before sending def send_if_sender_valid(bearer_token: str, sender: str, body: str, recipients: list) -> None: client = Client(bearer_token) result = client.senders() if isinstance(result, dict): approved = result.get("senders", []) if sender not in approved: print(f"Sender '{sender}' is not approved. Approved: {approved}") return response = client.sendMsg(body, recipients, sender) print(f"Sent: {response}") else: print(f"Could not retrieve senders: {result}") send_if_sender_valid( "your_bearer_token_here", sender="MyBrand", body="Hello from MyBrand!", recipients=["966501234567"], ) ``` -------------------------------- ### Send SMS using Taqnyat Source: https://github.com/taqnyat/python/blob/main/README.md Send an SMS message using the Taqnyat API. Requires a bearer token, message body, recipient list, and sender name. ```python # Sending a SMS using Taqnyat API and Python is easy as the following: from TaqnyatSms import Client bearer = "**************************0adc2b" body = "message Content" recipients = ["966********"] sender = "Sender Name" client = Client(bearer) message = client.sendMsg(body, recipients, sender) print(message) ``` -------------------------------- ### Client.sendStatus Source: https://context7.com/taqnyat/python/llms.txt Checks the operational status of the Taqnyat SMS gateway. ```APIDOC ## Client.sendStatus — Check Service Status Queries the Taqnyat system status endpoint (`GET /system/status`) to verify whether the SMS gateway is operational. Useful for health checks before sending bulk messages. ```python from TaqnyatSms import Client client = Client("your_bearer_token_here") status = client.sendStatus() print(status) # Expected output: {"status": "available", "message": "All systems operational"} # Example health check integration def is_service_available(bearer_token: str) -> bool: client = Client(bearer_token) result = client.sendStatus() if isinstance(result, dict): return result.get("status") == "available" return False if is_service_available("your_bearer_token_here"): print("Taqnyat gateway is up — safe to send messages.") else: print("Gateway unavailable, aborting send.") ``` ``` -------------------------------- ### Send Scheduled SMS using Taqnyat Source: https://github.com/taqnyat/python/blob/main/README.md Send a scheduled SMS message using the Taqnyat API. In addition to standard SMS parameters, specify a scheduled time in ISO 8601 format. ```python # Sending a scheduled SMS using Taqnyat API and Python is equally simple: from TaqnyatSms import Client bearer = "**************************0adc2b" body = "message Content" recipients = ["966********"] sender = "Sender Name" scheduled = "2020-09-30T14:26" taqnyt = Client(bearer) message = taqnyt.sendMsg(body, recipients, sender, scheduled=scheduled) print(message) ``` -------------------------------- ### Check Taqnyat Service Status Source: https://context7.com/taqnyat/python/llms.txt Query the SMS gateway status using `sendStatus`. Useful for health checks before sending messages. Returns a dictionary or an error string. ```python from TaqnyatSms import Client client = Client("your_bearer_token_here") status = client.sendStatus() print(status) # Expected output: {"status": "available", "message": "All systems operational"} # Example health check integration def is_service_available(bearer_token: str) -> bool: client = Client(bearer_token) result = client.sendStatus() if isinstance(result, dict): return result.get("status") == "available" return False if is_service_available("your_bearer_token_here"): print("Taqnyat gateway is up — safe to send messages.") else: print("Gateway unavailable, aborting send.") ``` -------------------------------- ### Send an SMS Message Source: https://context7.com/taqnyat/python/llms.txt Send an SMS to one or more recipients using the `sendMsg` method. Supports immediate or scheduled delivery. Handles errors by returning a string. ```python from TaqnyatSms import Client client = Client("your_bearer_token_here") # Send an immediate SMS to a single recipient result = client.sendMsg( body="Your OTP is 482910. Valid for 5 minutes.", recipients=["966501234567"], sender="MyAppName", ) print(result) # Expected output: {"messageId": "...", "status": "queued", "cost": 0.5, ...} # Send to multiple recipients at once result = client.sendMsg( body="Flash sale! 30% off all items today only.", recipients=["966501234567", "966509876543", "966551122334"], sender="MyBrand", ) print(result) # Expected output: {"messageId": "...", "status": "queued", "totalRecipients": 3, ...} # Send a scheduled SMS (ISO 8601 format) result = client.sendMsg( body="Reminder: Your appointment is tomorrow at 10:00 AM.", recipients=["966501234567"], sender="ClinicApp", scheduled="2024-06-15T09:00", ) print(result) # Expected output: {"messageId": "...", "status": "scheduled", "scheduledAt": "2024-06-15T09:00", ...} # Handle errors if isinstance(result, str) and result.startswith(("HTTP Error", "SSL Error", "Request Error")): print(f"Failed to send: {result}") ``` -------------------------------- ### Client.deleteMsg Source: https://context7.com/taqnyat/python/llms.txt Cancels and deletes a previously scheduled message via DELETE /v1/messages. Pass the `deleteKey` returned when the message was originally created to target a specific message. ```APIDOC ## Client.deleteMsg — Delete a Scheduled Message ### Description Cancels and deletes a previously scheduled message. ### Method DELETE ### Endpoint /v1/messages ### Parameters #### Query Parameters - **deleteKey** (string) - Optional - The unique key to identify the message to be deleted. If omitted, a delete request without a key is sent. ### Request Example ```python from TaqnyatSms import Client client = Client("your_bearer_token_here") # Schedule a message and capture the deleteKey scheduled_response = client.sendMsg( body="Reminder: Event starts at 7 PM.", recipients=["966501234567"], sender="EventApp", scheduled="2024-12-31T18:00" ) delete_key = scheduled_response.get("deleteKey") if isinstance(scheduled_response, dict) else None # Delete the scheduled message using its deleteKey if delete_key: result = client.deleteMsg(deleteKey=delete_key) print(result) # Delete without a specific key result = client.deleteMsg() print(result) ``` ### Response #### Success Response (200) - Response can be a string like "deleted" or a JSON object like `{"success": True}`. ``` -------------------------------- ### Delete Scheduled Message with Client.deleteMsg Source: https://context7.com/taqnyat/python/llms.txt Cancels and deletes a previously scheduled message. Requires the `deleteKey` obtained when the message was scheduled. Can also attempt deletion without a specific key. ```python from TaqnyatSms import Client client = Client("your_bearer_token_here") # First, schedule a message and capture the deleteKey scheduled_response = client.sendMsg( body="Reminder: Event starts at 7 PM.", recipients=["966501234567"], sender="EventApp", scheduled="2024-12-31T18:00", ) print(scheduled_response) # Expected output: {"messageId": "msg_abc123", "deleteKey": "del_xyz789", "status": "scheduled"} ``` ```python delete_key = scheduled_response.get("deleteKey") if isinstance(scheduled_response, dict) else None # Delete the scheduled message using its deleteKey if delete_key: result = client.deleteMsg(deleteKey=delete_key) print(result) # Expected output: "deleted" or {"success": True} ``` ```python # Delete without a specific key result = client.deleteMsg() print(result) ``` -------------------------------- ### Client.sendMsg Source: https://context7.com/taqnyat/python/llms.txt Sends an SMS message to one or more recipients. Supports immediate or scheduled delivery. ```APIDOC ## Client.sendMsg — Send an SMS Message Sends an SMS to one or more recipients via a POST request to `/v1/messages`. The `body` parameter holds the message text, `recipients` is a list of phone numbers in international format (e.g., `"966XXXXXXXXX"`), and `sender` is the approved sender name registered with Taqnyat. An optional `scheduled` parameter accepts an ISO 8601 datetime string to defer delivery. ```python from TaqnyatSms import Client client = Client("your_bearer_token_here") # Send an immediate SMS to a single recipient result = client.sendMsg( body="Your OTP is 482910. Valid for 5 minutes.", recipients=["966501234567"], sender="MyAppName", ) print(result) # Expected output: {"messageId": "...", "status": "queued", "cost": 0.5, ...} # Send to multiple recipients at once result = client.sendMsg( body="Flash sale! 30% off all items today only.", recipients=["966501234567", "966509876543", "966551122334"], sender="MyBrand", ) print(result) # Expected output: {"messageId": "...", "status": "queued", "totalRecipients": 3, ...} # Send a scheduled SMS (ISO 8601 format) result = client.sendMsg( body="Reminder: Your appointment is tomorrow at 10:00 AM.", recipients=["966501234567"], sender="ClinicApp", scheduled="2024-06-15T09:00", ) print(result) # Expected output: {"messageId": "...", "status": "scheduled", "scheduledAt": "2024-06-15T09:00", ...} # Handle errors if isinstance(result, str) and result.startswith(("HTTP Error", "SSL Error", "Request Error")): print(f"Failed to send: {result}") ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.