[python] api

Viewer

  1. import threading
  2. import time
  3.  
  4. import requests
  5. from flask import Flask, request, jsonify
  6. import boto3
  7. from twilio.rest import Client
  8.  
  9. app = Flask(__name__)
  10. sqs = boto3.resource("sqs")
  11.  
  12.  
  13. @app.route("/open", methods=['GET', 'POST'])
  14. def receive_message():
  15.     # Validate the incoming request with Twilio's API key
  16.     # if request.headers.get("Authorization") != "YOUR_TWILIO_API_KEY":
  17.     #     return "Unauthorized", 401
  18.  
  19.     # Extract the message and user number from the request
  20.     message = request.values.get('Body')  # Example, you'll need to extract the actual message from the request
  21.     user_number = request.values.get('From').split(':')[1]  # Example, you'll need to extract the actual user number from the request
  22.  
  23.     # Add the message to the "Receive SQS" queue
  24.     queue = sqs.get_queue_by_name(QueueName="receive_queue")
  25.     queue.send_message(MessageBody=f"{user_number}: {message}")
  26.  
  27.     return "", 200
  28.  
  29.  
  30. @app.route("/send", methods=["POST"])
  31. def send_message():
  32.     # Extract the message and user number from the request
  33.     user_number = request.json.get("user_number")
  34.     message = request.json.get("message")
  35.  
  36.     # Add the message to the "Send SQS" queue
  37.     queue = sqs.get_queue_by_name(QueueName="send_queue")
  38.     queue.send_message(MessageBody=f"{user_number}: {message}")
  39.  
  40.     return "", 200
  41.  
  42.  
  43. @app.route("/receive", methods=["POST"])
  44. def receive_response():
  45.     # Extract the user number from the request
  46.     user_number = request.json.get("user_number")
  47.  
  48.     # Check the "Receive SQS" queue for messages related to the user number
  49.     queue = sqs.get_queue_by_name(QueueName="receive_queue")
  50.     messages = []
  51.     for message in queue.receive_messages(MaxNumberOfMessages=10):
  52.         if user_number in message.body:
  53.             messages.append(message.body)
  54.             message.delete()
  55.  
  56.     return jsonify({"messages": messages})
  57.  
  58.  
  59. def process_send_queue():
  60.     while True:
  61.         # Get the "Send SQS" queue
  62.         queue = sqs.get_queue_by_name(QueueName="send_queue")
  63.  
  64.         # Get up to 10 messages from the queue
  65.         messages = queue.receive_messages(MaxNumberOfMessages=10)
  66.  
  67.         # Loop through each message
  68.         for message in messages:
  69.             # Extract the user number and message from the message body
  70.             user_number, message_txt = message.body.split(": ")
  71.  
  72.             # Send the message using Twilio
  73.             twilio_client.messages.create(
  74.                 to=f"whatsapp:{user_number}",
  75.                 from_="whatsapp:+14155238886",
  76.                 body=message_txt
  77.             )
  78.             print(f'Processed message: {message_txt} from {user_number}')
  79.  
  80.             # Delete the message from the queue
  81.             message.delete()
  82.  
  83.         # Sleep for a bit before checking the queue again
  84.         time.sleep(5)
  85.  
  86.  
  87. def process_receive_queue():
  88.     while True:
  89.         # Get the "Receive SQS" queue
  90.         queue = sqs.get_queue_by_name(QueueName="receive_queue")
  91.  
  92.         # Get up to 10 messages from the queue
  93.         messages = queue.receive_messages(MaxNumberOfMessages=10)
  94.  
  95.         # Loop through each message
  96.         for message in messages:
  97.             user_number, message_txt = message.body.split(": ")
  98.             # Check if the message contains "/start"
  99.             if "/start" in message_txt:
  100.                 # # Call the processing-service API
  101.                 requests.post("https://7360-2405-201-d006-e076-acb4-13d4-6cc9-1174.in.ngrok.io/start",
  102.                               json={"user_number": user_number})
  103.                 print(f'Started New conversation started with {user_number}')
  104.                 message.delete()
  105.                 continue
  106.  
  107.             # Delete the message from the queue
  108.             message.delete()
  109.  
  110.         # Sleep for a bit before checking the queue again
  111.         time.sleep(5)
  112.  
  113.  
  114. if __name__ == "__main__":
  115.     # Initialize the Twilio client
  116.     twilio_client = Client(
  117.         "ACCOUNT_KEY",
  118.         "ACCOUNT_ID"
  119.     )
  120.     # Start send and receive queue processing threads
  121.     send_thread = threading.Thread(target=process_send_queue)
  122.     send_thread.start()
  123.  
  124.     receive_thread = threading.Thread(target=process_receive_queue)
  125.     receive_thread.start()
  126.  
  127.     # Start the Flask app
  128.     app.run(port=5000, debug=True)
  129.  

Editor

You can edit this paste and save as new:


File Description
  • api
  • Paste Code
  • 03 Feb-2023
  • 4.26 Kb
You can Share it: