Webhook to receive twilio whatsapp messages

How to create webhooks in hf gradio app to receive user initiated Whatsapp user message via twilio through webhook as a http post.

can flask be used?

tried below code but it doesnt work:
import gradio as gr
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse

app = Flask(name)

@app.route(“/webhook”, methods=[“POST”])
def handle_webhook():
# Get the incoming message from Twilio
message = request.form[“Body”]

# Perform any desired processing or logic here

# Create a Twilio MessagingResponse object
response = MessagingResponse()

# Add your response message to the Twilio response
response.message("This is the response message.")

# Return the Twilio response
return str(response)

def process_message(message):
# Perform any desired processing or logic on the message
# and return the response
response = “This is the processed message.”
return response

iface = gr.Interface(fn=process_message,
inputs=“text”,
outputs=“text”,
title=“Twilio WhatsApp App”,
description=“Enter your message and press ‘Submit’.”,
allow_flagging=False)

iface.launch(server_name=“0.0.0.0”,
server_port=5000)
app.run()

hi @amitagh,
You have two options,

Mount your Gradio App withing FastAPI and design extra routes to receive post requests

Since we provide webhooks on our hub, we also provide a simple abstraction withing huggingface_hub, thus, you could take advantage of it for your Twillio app

Thanks @radames for the inputs.
Based on what u said i used below code snippet:


     # Gradio app in HF spaces
import gradio as gr

from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse

from huggingface_hub import webhook_endpoint, WebhookPayload
from huggingface_hub import WebhooksServer

    # Webhook handling.
@webhook_endpoint()
async def trig_webhk():
    print("Rcvd trig:")

    # Process incoming message and generate a response
    response_msg = "You sent: " 

    # Prepare Twilio response
    twilio_response = MessagingResponse()
    twilio_response.message(response_msg)

    return str(twilio_response)

def proc_msg():
    return "None"

    # Define the Gradio interface for the app
iface = gr.Interface(
    fn=proc_msg,  # Add your function to display the response message
    inputs=None,  # Add your input components
    outputs="text"  # Display the response message as text
)

app = WebhooksServer(ui=iface)
app.run(debug=True)

My Webhook function gets hit on HTTP post from Twilio.
But i am not able access POST content.

Ideally in a flask app i would get incoming msg using “incoming_msg = request.values.get(‘Body’, ‘’).lower()”
And respond with the Twilio response as i have in my code above.

How could i do that on Gradio webhooks?
Also if i am correct webhook activity doesnt show http post coming from Twilio, so i assume it doesnt trace external Webhook triggers.

you need the webhook payload argument

@webhook_endpoint()
async def trig_webhk(payload: WebhookPayload):
    # payload from Twillio?
    print("Rcvd trig:", payload)

    # Process incoming message and generate a response
    response_msg = "You sent: " 

    # Prepare Twilio response
    twilio_response = MessagingResponse()
    twilio_response.message(response_msg)

    return str(twilio_response)

I did try with trig_webhk(payload) but with that the trig_webhk didn’t used to get triggered on a http post message.
Only when the func def had no payload param it used to get triggered.
Did you try the function in your setup?

sorry, didn’t test your code, I noticed the missing payload parameter, since you’re using the webhook I’m cc @Wauplin for huggingface_hub integration

Hey there :wave: So the Webhook Server integration is firstly designed to receive webhooks from the Hugging Face Hub. In theory it can be used for twilio webhooks though I never tried and don’t know how it would work. What I can tell you is that Gradio is based on the FastAPI framework instead of Flask. To access the request payload, you can refer to this FastAPI guide. TL;DR: you can define a Pydantic model or parameters for the data structure you expect in the request payload and FastAPI will automatically parse it and inject the value to your function for type (based on type annotation). In the case mentioned by @radames, payload: WebhookPayload is tell FastAPI to parse the body as a WebhookPayload object which is specific to the Huggingface Hub Webhooks. For twilio webhooks you’ll have to define the data structure yourself. Looks like this twilio+fastapi guide can help you with that.

1 Like

great points @Wauplin , I wasn’t sure if we could use the WebhooksServer or not. Since it just simple FastAPI server under the hood I thought it could work. @amitagh can you please try to specify the payload accordingly to the data Twillio send to the hook?

Thank you. Will check it out.

1 Like