Files
api_utils_converse_v2/models/message/chat/send.py
T
2025-06-12 13:46:29 +05:30

266 lines
8.9 KiB
Python

"""
AUTHOR:
Khushal P Soonderji
DATE:
Tuesday, 21st Jan., 2025.
OBJECTIVE:
To provide a structure to receive API calls to send chat messages from various third-party clients. At the time
of creating this file we are starting with Nimbus IT's unofficial WhatsApp services. We intend to add Telegram's
official APIs soon after.
REFERENCES:
N/A
DOWNLOADS:
N/A
"""
# *****************************************************************************************************************
# ***** ****
# *** IMPORT ***
# ***** ****
# *****************************************************************************************************************
# To make sibling directories accessible for imports:
import sys
sys.path.append(".")
sys.path.append("..")
# For making data behaviour_models:
from pydantic import BaseModel, Field, field_validator, AwareDatetime, PastDatetime
from typing import Optional, Literal, Union, List, Any
# My utils:
from utils_v2.string import regex
from utils_v2.date_time import date_time
# Models:
from models.core.message import CoreMessageModel
from utils_v2.sms.models.sms_message import SentSMSMessageModel
# To work with date and time:
import datetime
# To work with MongoDB:
from bson.objectid import ObjectId
# *****************************************************************************************************************
# ***** ****
# *** MACROS / ONE-TIME INIT ***
# ***** ****
# *****************************************************************************************************************
# RegEx Patterns:
REGEX_SESSION_TOKEN = r"^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$"
# *****************************************************************************************************************
# ***** ****
# *** VARIABLES ***
# ***** ****
# *****************************************************************************************************************
# --- Nothing Yet
# *****************************************************************************************************************
# ***** ****
# *** FUNCTIONS ***
# ***** ****
# *****************************************************************************************************************
class NimbusWhatsAppMessage(BaseModel):
recipientNo: str = Field(
description = "The phone no. of the target recipient(s)",
# pattern = r"\+?\d{0,3}\s*\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}",
frozen = True
)
message: str | None = Field(
description = "The actual text that you want to send.",
# min_length = 1,
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
)
# ---- ADDED BY OMKAR 2025-05-13 ----
waGroupId: str = Field(
description="The Whatsapp group ID. of the target recipient(s) group",
frozen=True
)
waGroupName: str | None = Field(
description="The actual group name.",
frozen=True,
default=None
)
# ┏┓ ┏•
# ┃ ┏┓┏┓╋┓┏┓
# ┗┛┗┛┛┗┛┗┗┫
# ┛
class Config:
extra = "forbid"
# ┓┏ ┓• ┓ •
# ┃┃┏┓┃┓┏┫┏┓╋┓┏┓┏┓
# ┗┛┗┻┗┗┗┻┗┻┗┗┗┛┛┗
@field_validator("scheduleTs", mode = "before")
def to_datetime(cls, value):
if not isinstance(value, datetime.datetime):
value = date_time.parse_date_time(
input_value = value,
date_formats = [
"%Y%m%d",
"%Y-%m-%d",
"%Y-%m-%d %H:%M:%S",
"%Y-%m-%d %H:%M:%S%z",
"%Y-%m-%dT%H:%M:%S",
"%Y-%m-%dT%H:%M:%S%z"
]
)
if value:
value = date_time.as_if_timezone(value, date_time.TIMEZONE_UTC)
value = date_time.to_timezone(value, date_time.TIMEZONE_IST)
return value
@field_validator("recipientNo", mode = "before")
def validate_contact_nos(cls, value):
value = regex.replace(text = str(value), pattern = r"[^\d]", substitute_text = "")
if len(value) > 10: value = regex.replace(text = str(value), pattern = r"^(91)", substitute_text = "")
value = regex.find_first(text = str(value), pattern = r"^[\d]{10}")
return value
# ---------------------------------------------------------------------------------------------------------------------
class ChatSendOneResult(BaseModel):
success: bool = Field(
description = "Whether, or not, the chat message was successfully sent.",
default = False
)
message: str | None = Field(
description = "A brief message to summarize the result of the process.",
default = None
)
chatMessage: CoreMessageModel = Field(
description = "The actual data of the chat message.",
default = None
)
# ┏┓ ┏•
# ┃ ┏┓┏┓╋┓┏┓
# ┗┛┗┛┛┗┛┗┗┫
# ┛
class Config:
extra = "forbid"
# ---------------------------------------------------------------------------------------------------------------------
class ChatSendManyResults(BaseModel):
totalCount: int = Field(
description = "The total no. of messages that were attempted.",
default = 0
)
successCount: int = Field(
description = "The no. of chat messages that were successfully sent.",
default = 0
)
failureCount: int = Field(
description = "The no. of chat messages that were NOT sent.",
default = 0
)
message: str = Field(
description = "A brief message to summarize the results of the process.",
default = None
)
chatMessages: List[CoreMessageModel] = Field(
description = "The actual data of the chat messages.",
default = []
)
# ┏┓ ┏•
# ┃ ┏┓┏┓╋┓┏┓
# ┗┛┗┛┛┗┛┗┗┫
# ┛
class Config:
extra = "forbid"
# *****************************************************************************************************************
# ***** ****
# *** MAIN PROGRAM ***
# ***** ****
# *****************************************************************************************************************
if __name__ == "__main__":
from utils_v2.string import json
my_request = SMSSendRequestData(
tokenId = "670f580d7cda4ebc1adc3444",
message = NimbusSMSIndiaMessage(
recipientNo = "+.9.1 ---> 93261 3642fgnn193261",
text = "Hello, Nimbus!",
templateId = "12345678"
)
)
print("NIMBUS SMS API MODEL:", json.to_string(my_request.model_dump(), default = str))