Unable to send WhatsApp messages using FastAPI and requests in Python
I am working on a project using FastAPI to handle incoming WhatsApp messages and respond to them. I've set up the webhook, and I can successfully receive messages. However, I'm encountering issues when trying to send a response back to the user using the WhatsApp Business API.
Here is the relevant part of my code:
from fastapi import FastAPI, Request, HTTPException, Query from fastapi.responses import JSONResponse from pydantic import BaseModel import requests app = FastAPI() VERIFY_TOKEN = "tourism" class WhatsAppEvent(BaseModel): message: dict WHATSAPP_API_ENDPOINT = "https://graph.facebook.com/v18.0/***(Entered my phone number ID)/messages" WHATSAPP_API_TOKEN = "***(Entered my API access token)" @app.post("/") async def handle_post_request(request: Request): # Process the incoming POST request here data = await request.json() print("Received POST request data:", data) # Send a response return {"status": "success", "message": "POST request received"} @app.get("/") def verify(request: Request): mode = request.query_params.get('hub.mode') challenge = request.query_params.get('hub.challenge') token = request.query_params.get('hub.verify_token') if mode and token: if mode == 'subscribe' and token == VERIFY_TOKEN: print("WEBHOOK_VERIFIED") return JSONResponse(content=int(challenge), status_code=200) else: raise HTTPException(status_code=403, detail="Verification failed") return {"code": 200, 'message': 'test'} @app.post("/incoming-message") def receive_message(event: WhatsAppEvent): try: user_message = event.message['text'] sender_id = event.message['sender']['id'] bot_response = f'You said: {user_message}' #sending an echo message # Prepare response for WhatsApp response_data = { 'recipient': {'id': sender_id}, 'message': {'text': bot_response} } send_whatsapp_message(sender_id, bot_response) return JSONResponse(content=response_data, status_code=200) except Exception as e: raise HTTPException(status_code=500, detail=f"Error processing message: {str(e)}") def send_whatsapp_message(recipient_id, message_body): headers = { 'Authorization': f'Bearer {WHATSAPP_API_TOKEN}', 'Content-Type': 'application/json' } data = { 'phone': recipient_id, 'message': { 'text': message_body } } try: response = requests.post(WHATSAPP_API_ENDPOINT, headers=headers, json=data) response.raise_for_status() # Raises HTTPError for bad responses print("WhatsApp API response:", response.text) # Add this line for debugging return response.json() # If you want to return the API response data except requests.exceptions.HTTPError as errh: print("HTTP Error:", errh) raise HTTPException(status_code=response.status_code, detail=f"HTTP Error: {errh}") except requests.exceptions.RequestException as err: print("Request Error:", err) raise HTTPException(status_code=response.status_code, detail=f"Request Error: {err}") if __name__ == "__main__": import uvicorn uvicorn.run(app, reload=False, host="0.0.0.0", port=8000)
I have verified that the webhook is working (WEBHOOK_VERIFIED is printed in the console), and I can see the incoming messages in the logs. However, the send_whatsapp_message function does not seem to be sending messages successfully.
The response from the WhatsApp API is as follows:
WEBHOOK_VERIFIED INFO: 2a03:2880:23ff:5::face:b00c:0 - "GET /?hub.mode=subscribe&hub.challenge=1310749767&hub.verify_token=tourism HTTP/1.1" 200 OK Received POST request data: {'object': 'whatsapp_business_account', 'entry': [{'id': '**(My ID)', 'changes': [{'value': {'messaging_product': 'whatsapp', 'metadata': {'display_phone_number': '**(My number)', 'phone_number_id': '**(My Phone number ID)'}, 'contacts': [{'profile': {'name': 'Rishikesh Dasari'}, 'wa_id': '**(recipient Number)'}], 'messages': [{'from': '**(recipient Number)', 'id': 'wamid.HBgMOTE5MzkwMzYwMjYyFQIAEhgWM0VCMEMyRUU3MzQ4Q0VCNjFGQUIzRgA=', 'timestamp': '1705643757', 'text': {'body': 'hello'}, 'type': 'text'}]}, 'field': 'messages'}]}]} INFO: 2a03:2880:20ff:b::face:b00c:0 - "POST / HTTP/1.1" 200 OK
I have double-checked the WhatsApp API endpoint, token, and the structure of the request, but I'm still unable to send messages. I suspect there might be an issue with my send_whatsapp_message
function.
Can someone please review the code and provide insights on what might be causing the problem? Additionally, if there's a better way to handle sending WhatsApp messages in FastAPI, I'm open to suggestions.