webhook_utils.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. import os
  2. import base64
  3. import asyncio
  4. import requests
  5. import httpx
  6. from PIL import Image
  7. from dotenv import load_dotenv
  8. from io import BytesIO
  9. load_dotenv()
  10. META_ACCESS_TOKEN = os.getenv("META_ACCESS_TOKEN")
  11. WHATSAPP_API_URL = os.getenv("WHATSAPP_API_URL")
  12. TOGETHER_API_KEY = os.getenv("TOGETHER_API_KEY")
  13. MEDIA_URL = "https://graph.facebook.com/v20.0/{media_id}"
  14. BASE_URL = os.getenv("BASE_URL")
  15. PHONE_NUMBER_ID = os.getenv("PHONE_NUMBER_ID")
  16. GROQ_API_KEY = os.getenv("GROQ_API_KEY")
  17. def send_message(to: str, text: str):
  18. if not text:
  19. print("Error: Message text is empty.")
  20. return
  21. payload = {
  22. "messaging_product": "whatsapp",
  23. "to": to,
  24. "type": "text",
  25. "text": {"body": text}
  26. }
  27. headers = {
  28. "Authorization": f"Bearer {META_ACCESS_TOKEN}",
  29. "Content-Type": "application/json"
  30. }
  31. response = requests.post(WHATSAPP_API_URL, headers=headers, json=payload)
  32. if response.status_code == 200:
  33. print("Message sent")
  34. else:
  35. print(f"Send failed: {response.text}")
  36. async def send_message_async(user_phone: str, message: str):
  37. loop = asyncio.get_running_loop()
  38. await loop.run_in_executor(None, send_message, user_phone, message)
  39. async def send_audio_message(to: str, file_path: str):
  40. url = f"https://graph.facebook.com/v20.0/{PHONE_NUMBER_ID}/media"
  41. with open(file_path, "rb") as f:
  42. files = { "file": ("reply.mp3", open(file_path, "rb"), "audio/mpeg")}
  43. params = {
  44. "messaging_product": "whatsapp",
  45. "type": "audio",
  46. "access_token": ACCESS_TOKEN
  47. }
  48. response = requests.post(url, params=params, files=files)
  49. if response.status_code == 200:
  50. media_id = response.json().get("id")
  51. payload = {
  52. "messaging_product": "whatsapp",
  53. "to": to,
  54. "type": "audio",
  55. "audio": {"id": media_id}
  56. }
  57. headers = {
  58. "Authorization": f"Bearer {ACCESS_TOKEN}",
  59. "Content-Type": "application/json"
  60. }
  61. requests.post(WHATSAPP_API_URL, headers=headers, json=payload)
  62. else:
  63. print("Audio upload failed:", response.text)
  64. async def llm_reply_to_text_v2(user_input: str, user_phone: str, media_id: str = None,kind: str = None):
  65. try:
  66. # print("inside this function")
  67. headers = {
  68. 'accept': 'application/json',
  69. 'Content-Type': 'application/json',
  70. }
  71. json_data = {
  72. 'user_input': user_input,
  73. 'media_id': media_id,
  74. 'kind': kind
  75. }
  76. async with httpx.AsyncClient() as client:
  77. response = await client.post("https://df00-171-60-176-142.ngrok-free.app/llm-response", json=json_data, headers=headers,timeout=60)
  78. response_data = response.json()
  79. # print(response_data)
  80. if response.status_code == 200 and response_data['error'] == None:
  81. message_content = response_data['response']
  82. if message_content:
  83. loop = asyncio.get_running_loop()
  84. await loop.run_in_executor(None, send_message, user_phone, message_content)
  85. else:
  86. print("Error: Empty message content from LLM API")
  87. await send_message_async(user_phone, "Received empty response from LLM API.")
  88. else:
  89. print("Error: Invalid LLM API response", response_data)
  90. await send_message_async(user_phone, "Failed to process image due to an internal server error.")
  91. except Exception as e:
  92. print("LLM error:", e)
  93. await send_message_async(user_phone, "Sorry, something went wrong while generating a response.")