""" AUTHOR: Bhushan C Thakkar DATE: Monday, 20th Jan., 2025. OBJECTIVE: To give a structure to how Nimbus's API will respond when we try to send messages. REFERENCES: N/A DOWNLOADS: N/A """ # ***************************************************************************************************************** # ***** **** # *** IMPORT *** # ***** **** # ***************************************************************************************************************** # To make sibling directories accessible for imports: import sys sys.path.append(".") sys.path.append("..") # For system-level activities: import os import io # For making data behaviour_models: from pydantic import BaseModel, Field, field_validator, PastDatetime, AwareDatetime from typing import Optional, Literal, Union, Any, List # My utils: from utils_v2.string import regex from utils_v2.date_time import date_time # To work with MongoDB: from bson.objectid import ObjectId # To work with date and time: import datetime # ***************************************************************************************************************** # ***** **** # *** MACROS / ONE-TIME INIT *** # ***** **** # ***************************************************************************************************************** # --- Nothing Yet # ***************************************************************************************************************** # ***** **** # *** VARIABLES *** # ***** **** # ***************************************************************************************************************** # --- Nothing Yet # ***************************************************************************************************************** # ***** **** # *** FUNCTIONS *** # ***** **** # ***************************************************************************************************************** class NimbusWhatsappSendMessageResponse(BaseModel): ts: AwareDatetime = Field( description = "The time (UTC) at which this message was sent by the sender.", frozen = True, default_factory = lambda: date_time.get_current_utc_date_time(as_string = False) ) success: bool = Field( description = "Whether, or not, the request was successful.", frozen = True, default = False ) recipientNo: List[str] = Field( description = "One or more target nos. to send the WhatsApp message to.", frozen = True ) message: str | None = Field( description = "The actual message to send to the recipient(s).", frozen = True, default = None ) pdfUrl: str | None = Field( description = "A PDF file to send with your message.", frozen = True, default = None ) image0Url: str | None = Field( description = "An image file to send with your message.", frozen = True, default = None ) image1Url: str | None = Field( description = "An image file to send with your message.", frozen = True, default = None ) scheduleTs: AwareDatetime | None = Field( description = "The time (UTC) at which the message needs to be sent. Null for immediate delivery.", frozen = True, default = None ) httpCode: str | int | None = Field( description = "The HTTP code of the API call.", frozen = True, default = None ) status: str | None = Field( description = "To indicate success or failure.", frozen = True, default = None ) statusCode: str | int | None = Field( description = "The response code as defined by Nimbus.", frozen = True, default = None ) apiMessage: str = Field( description = "A message about any error, or a general acknowledgement message.", frozen = True, default = None ) requestId: str | int | None = Field( description = "How Nimbus identifies your message.", frozen = True, default = None ) messageCount: int | None = Field( description = "The no. of messages sent.", frozen = True, default = 0 ) messageCost: float | int | None = Field( description = "The cost (in nimbus' 'credits') of messages sent.", frozen = True, default = None ) balance: int | float | None = Field( description = "The balance remaining in the account.", frozen = True, default = None ) # ┏┓ ┏• # ┃ ┏┓┏┓╋┓┏┓ # ┗┛┗┛┛┗┛┗┗┫ # ┛ class Config: extra = "allow" # ┓┏ ┓• ┓ • # ┃┃┏┓┃┓┏┫┏┓╋┓┏┓┏┓ # ┗┛┗┻┗┗┗┻┗┻┗┗┗┛┛┗ @field_validator("ts", "scheduleTs", mode = "before") def parse_date_time(cls, value): return date_time.parse_date_time(input_value = value, timezone = date_time.TIMEZONE_UTC) @field_validator("recipientNo", mode = "before") def validate_recipients(cls, value): if isinstance(value, str): value = [value] return value # ┏┓ ┏┓ # ┃ ┓┏┏╋┏┓┏┳┓ ┣ ┓┏┏┓┏┏ # ┗┛┗┻┛┗┗┛┛┗┗ ┻ ┗┻┛┗┗┛ def api_input_json(self) -> dict: # Start with the bare minimum: api_input = { "mobile": ",".join(self.recipientNo), "msg": self.message or " " } # Add the optional media elements: if self.pdfUrl: api_input["pdf"] = self.pdfUrl if self.image0Url: api_input["img1"] = self.image0Url if self.image1Url: api_input["img2"] = self.image1Url # Add the scheduled delivery time: if self.scheduleTs: api_input["scheduleon"] = date_time.to_timezone( datetime_object = self.scheduleTs, timezone = date_time.TIMEZONE_IST ).strftime("%Y%m%d%H%M") # Done here: return api_input def from_api_response( self, http_code: int, response_json: dict = None ) -> "NimbusWhatsappSendMessageResponse": # Ensure that we are working with a dictionary: response_json = response_json or {} # Create and return the model: return NimbusWhatsappSendMessageResponse( ts = self.ts, recipientNo = self.recipientNo, message = self.message, pdfUrl = self.pdfUrl, image0Url = self.image0Url, image1Url = self.image1Url, scheduleTs = self.scheduleTs, success = True if response_json.get("statuscode") == 200 or response_json.get("status").strip().lower() == "success" else False, httpCode = http_code, status = response_json.get("status"), statusCode = response_json.get("statuscode"), apiMessage = response_json.get("msg"), requestId = response_json.get("requestId"), messageCount = response_json.get("msgcount"), messageCost = response_json.get("msgcost"), balance = response_json.get("balance") ) # ***************************************************************************************************************** # ***** **** # *** MAIN PROGRAM *** # ***** **** # ***************************************************************************************************************** if __name__ == "__main__": sample_response_json = { "status": "success", "msg": "submitted successfully", "statuscode": 200, "requestid": "ES5OmOpIPaVSmT", "msgcount": "1", "msgcost": 1, "balance": "0.1" } send_result = NimbusWhatsappSendMessageResponse( recipientNo = ["9870391155"], message = "Hello, Bhopli!" ) send_result = send_result.from_api_response( http_code = 200, response_json = sample_response_json ) print(send_result)