whatsapp_bot.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. from flask import Flask, request
  2. from twilio.twiml.messaging_response import MessagingResponse
  3. from embedchain import App
  4. app = Flask(__name__)
  5. chat_bot = App()
  6. @app.route("/chat", methods=["POST"])
  7. def chat():
  8. incoming_message = request.values.get("Body", "").lower()
  9. response = handle_message(incoming_message)
  10. twilio_response = MessagingResponse()
  11. twilio_response.message(response)
  12. return str(twilio_response)
  13. def handle_message(message):
  14. if message.startswith("add "):
  15. response = add_sources(message)
  16. else:
  17. response = query(message)
  18. return response
  19. def add_sources(message):
  20. message_parts = message.split(" ", 2)
  21. if len(message_parts) == 3:
  22. data_type = message_parts[1]
  23. url_or_text = message_parts[2]
  24. try:
  25. chat_bot.add(data_type, url_or_text)
  26. response = f"Added {data_type}: {url_or_text}"
  27. except Exception as e:
  28. response = f"Failed to add {data_type}: {url_or_text}.\nError: {str(e)}"
  29. else:
  30. response = "Invalid 'add' command format.\nUse: add <data_type> <url_or_text>"
  31. return response
  32. def query(message):
  33. try:
  34. response = chat_bot.chat(message)
  35. except Exception:
  36. response = "An error occurred. Please try again!"
  37. return response
  38. if __name__ == "__main__":
  39. app.run(host="0.0.0.0", port=5000, debug=False)