CsG.
CsG.

Reputation: 86

Issue with Azure Flask Webhook Setup for WhatsApp API - Receiving and Managing Event Payloads

Hello fellow developers,

I hope you're all doing well. I am currently developing a project to create a WhatsApp bot using Python, a Flask server, and the WATI API. I am facing challenges when it comes to implementing a webhook server using Flask on Azure to receive event payloads from WATI.

Webhook Functionality:

The webhook is triggered whenever a user sends a message to the WhatsApp number associated with my bot. When this happens, a payload is received, which helps me extract the text content of the message. Based on the content of the message, my bot is supposed to perform various actions.

The Challenge:

In order to trigger the webhook in WATI, I need to provide an HTTPS link with an endpoint defined in my Python Flask route code. In the past, I attempted to use Railway, which automatically generated the URL, but I've had difficulty achieving the same result on Azure. I've made attempts to create both an Azure Function and a Web App, but neither seems to be able to receive the webhook requests from WATI.

Here is the link to the process for deploying on Railway: Webhook Setup

I'm reaching out to the community in the hope that someone with experience in building webhook servers on Azure could provide some guidance or insights. Your input would be immensely appreciated.

Below is the code generated when I created the function app via Visual Studio. Unfortunately, I'm unable to see any output in Azure'sLog Streams:

import azure.functions as func
import logging 
import json 
import WATI as wa
app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)


@app.route(route="HttpExample", methods=['POST']) 

def HttpExample(req: func.HttpRequest) -> func.HttpResponse: 
        logging.info('Python HTTP trigger function processed a request.')
    name = req.params.get('name')
    if not name:
        try:
            print("1")
            req_body = req.get_json()
        except ValueError:
            pass
     else:
        print("2")
        name = req_body.get('name')
    
    if name:
        print("1")
        return func.HttpResponse(f"Hello, {name}. This HTTP triggered function executed successfully.")
    else:
        return func.HttpResponse(
            "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
            status_code=200
        )

Upvotes: 0

Views: 245

Answers (1)

SiddheshDesai
SiddheshDesai

Reputation: 8215

When this happens, a payload is received, which helps me extract the text content of the message. Based on the content of the message, my bot is supposed to perform various actions.

You can use Azure Function Http Trigger code to extract the text content from the message with your custom logic like below:-

function_app.py:-

import azure.functions as func
import logging

app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)

@app.route(route="http_trigger")
def main(req: func.HttpRequest) -> func.HttpResponse:
    # Check if the request method is POST
    if req.method == 'POST':
        try:
            req_body = req.get_json()
            event_type = req_body.get("eventType")
            
            # Check if the eventType is "templateMessageSent"
            if event_type == "templateMessageSent":
                # Extract relevant data from the payload
                message_id = req_body.get("whatsappMessageId")
                template_name = req_body.get("templateName")
                text = req_body.get("text")
                wa_id = req_body.get("waId")
                
                # Perform actions based on the message content
                if text:
                    # Your logic to process the message content
                    # For example, you can send a response back to the user
                    response_message = f"Received a template message with ID: {message_id}, from {wa_id}. Template name: {template_name}, Message: {text}"
                    return func.HttpResponse(response_message, status_code=200)
                else:
                    return func.HttpResponse("Message content is missing.", status_code=400)
            else:
                return func.HttpResponse("Ignoring unknown event type.", status_code=200)  # You can change the status code as needed
        except ValueError:
            return func.HttpResponse("Invalid JSON payload.", status_code=400)
    else:
        return func.HttpResponse("Method not allowed", status_code=405)

Output:-

I am sending one sample json from this WATI Webhook sample message template here- Webhooks (wati.io) as a message in the request body of the POST request. After I send the POST request with the message body the Function is triggered. You can implement your logic instead of the json sample I am using to extract the content of Whatsapp message after its received.

Sample Json as request body taken from WATI webhooks sample:-

{
  "eventType": "templateMessageSent",
  "id": "xxxx538bf0845a0ba0",
  "whatsappMessageId": "abcdefghi_jklmnop",
  "templateId": "xxxxg8h9i10j",
  "templateName": "shipping_template",
  "created": "2022-10-13T07:20:11.3921095Z",
  "conversationId": "xxxg7h8i9j10",
  "ticketId": "xxx3p4q5r6s7t8u9v10",
  "text": "Hi! Your order is out for delivery",
  "operatorEmail": "[email protected]",
  "waId": "911234567890",
  "type": "template",
  "statusString": "SENT",
  "sourceType": "WEB"
}

Local :-

Copy this Http url in the Postman Http POST request:-

enter image description here

Postman:-

enter image description here

You can deploy this Function in the Function app and then add the below Function API URL in your WATI Dashboard > Webhooks > Add Webhook > Add a new Webhook > URL (Add Function URL) > Template Message Sent > Status Enabled > Trigger sample callback so it retrieves the message whenever it is received.

Create one Python Function app and deploy your code in the Function app like below, You can add the below URL in as a Webhook Url in your WATI Dashboard:-

enter image description here

If the URL is not visible after deployment, Copy the URL from Azure Portal and the same function app to add it in webhook:-

In Azure Portal:-

enter image description here

Clicked Test/Run Added the sample template message json in the body and received below response:-

enter image description here

enter image description here

In Postman:-

enter image description here

Similar reference with Twilio:-

easonlai/azure_function_python_sample_01: Azure Function (Python) sample to call API, comparing previously state and send alert message over WhatsApp via Twilio. (github.com)

Upvotes: 0

Related Questions