shridarpatil / frappe_whatsapp

WhatsApp cloud integration for frappe
https://www.youtube.com/watch?v=nq5Kcc5e1oc
Other
150 stars 137 forks source link

Sent messages in Whatsapp Message Log list #71

Open Ulter52 opened 2 months ago

Ulter52 commented 2 months ago

I am trying to add 'Send Whatsapp message' option/button to sales invoice, payment receipt and others to send that doc pdf as a service message. My code is able to send pdf but it is not showing or getting into the Whatsapp Message log. Please help me to get the sent message in the log. Here's my code.


import json
import frappe
from frappe.integrations.utils import make_post_request
from frappe import _
from frappe.utils import get_url

def get_settings() -> dict:
    """Get WhatsApp settings"""
    settings = frappe.get_doc("WhatsApp Settings", "WhatsApp Settings")
    return settings

def generate_payload(recipient: str, doctype: str, docname: str, print_format: str) -> str:
    """Generate WhatsApp message payload"""
    link = get_pdf_link(doctype, docname, print_format)
    payload = json.dumps({
        "messaging_product": "whatsapp",
        "recipient_type": "individual",
        "to": recipient,
        "type": "document",
        "document": {
            "link": link,
            "caption": docname
        }
    })
    return payload

def make_request(settings: dict, payload: str) -> dict:
    """Make POST request to WhatsApp API"""
    headers = {
        "authorization": f"Bearer {settings.get_password('token')}",
        "content-type": "application/json",
    }
    response = make_post_request(
        f"{settings.url}/{settings.version}/{settings.phone_id}/messages",
        headers=headers,
        data=payload,
    )
    return response

def log_message(response: dict, recipient: str, doctype: str, docname: str) -> None:
    """Log WhatsApp message"""
    message_id = response["messages"][0]["id"]
    frappe.get_doc({
        "doctype": "WhatsApp Message",
        "type": "Outgoing",
        "message": str(response),
        "to": recipient,
        "message_type": "Manual",
        "message_id": message_id,
        "content_type": "document"
    }).save(ignore_permissions=True)

def handle_error(error: Exception) -> None:
    """Handle error and log notification"""
    response = frappe.flags.integration_request.json()['error']
    error_message = response.get('Error', response.get("message"))
    frappe.msgprint(
        f"Failed to trigger whatsapp message: {error_message}",
        indicator="red",
        alert=True
    )

@frappe.whitelist()
def send_whatsapp_message(recipient: str, doctype: str, docname: str, print_format: str) -> dict:
    """Send WhatsApp message"""
    settings = get_settings()
    payload = generate_payload(recipient, doctype, docname, print_format)
    try:
        response = make_request(settings, payload)
        log_message(response, recipient, doctype, docname)
        return response
    except Exception as e:
        handle_error(e)

@frappe.whitelist()
def get_pdf_link(doctype: str, docname: str, print_format: str) -> str:
    """
    Generate a PDF link for a document.

    :param doctype: The document type (e.g., "Sales Invoice")
    :param docname: The document name (e.g., "SINV-001")
    :param print_format: The print format (e.g., "Standard")
    :return: The PDF link as a string
    """
    doc = frappe.get_doc(doctype, docname)
    if not doc:
        frappe.throw(_("Document not found: {doctype} - {docname}").format(doctype=doctype, docname=docname))

    print_settings = frappe.get_doc("Print Format", print_format)
    if not print_settings:
        frappe.throw(_("Print format not found: {print_format}").format(print_format=print_format))

    pdf_link = "/api/method/frappe.utils.print_format.download_pdf?"
    pdf_link += "doctype={doctype}&name={docname}&format={print_format}&no_letterhead=0".format(
        doctype=doctype, docname=docname, print_format=print_format
    )

    key = doc.get_document_share_key()
    pdf_link += "&key={key}".format(key=key)

    return get_url(pdf_link)
vineyrawat commented 1 month ago

Hi @Ulter52, I think you don't have to call any sort of API, you just have to create a WhatsApp Message document with message_type manual and content_type document, the application will automatically send the SMS and you'll also have a log/Whatsapp message record.