[python] api
Viewer
*** This page was generated with the meta tag "noindex, nofollow". This happened because you selected this option before saving or the system detected it as spam. This means that this page will never get into the search engines and the search bot will not crawl it. There is nothing to worry about, you can still share it with anyone.
- import threading
- import time
- import requests
- from flask import Flask, request, jsonify
- import boto3
- from twilio.rest import Client
- app = Flask(__name__)
- sqs = boto3.resource("sqs")
- @app.route("/open", methods=['GET', 'POST'])
- def receive_message():
- # Validate the incoming request with Twilio's API key
- # if request.headers.get("Authorization") != "YOUR_TWILIO_API_KEY":
- # return "Unauthorized", 401
- # Extract the message and user number from the request
- message = request.values.get('Body') # Example, you'll need to extract the actual message from the request
- user_number = request.values.get('From').split(':')[1] # Example, you'll need to extract the actual user number from the request
- # Add the message to the "Receive SQS" queue
- queue = sqs.get_queue_by_name(QueueName="receive_queue")
- queue.send_message(MessageBody=f"{user_number}: {message}")
- return "", 200
- @app.route("/send", methods=["POST"])
- def send_message():
- # Extract the message and user number from the request
- user_number = request.json.get("user_number")
- message = request.json.get("message")
- # Add the message to the "Send SQS" queue
- queue = sqs.get_queue_by_name(QueueName="send_queue")
- queue.send_message(MessageBody=f"{user_number}: {message}")
- return "", 200
- @app.route("/receive", methods=["POST"])
- def receive_response():
- # Extract the user number from the request
- user_number = request.json.get("user_number")
- # Check the "Receive SQS" queue for messages related to the user number
- queue = sqs.get_queue_by_name(QueueName="receive_queue")
- messages = []
- for message in queue.receive_messages(MaxNumberOfMessages=10):
- if user_number in message.body:
- messages.append(message.body)
- message.delete()
- return jsonify({"messages": messages})
- def process_send_queue():
- while True:
- # Get the "Send SQS" queue
- queue = sqs.get_queue_by_name(QueueName="send_queue")
- # Get up to 10 messages from the queue
- messages = queue.receive_messages(MaxNumberOfMessages=10)
- # Loop through each message
- for message in messages:
- # Extract the user number and message from the message body
- user_number, message_txt = message.body.split(": ")
- # Send the message using Twilio
- twilio_client.messages.create(
- to=f"whatsapp:{user_number}",
- from_="whatsapp:+14155238886",
- body=message_txt
- )
- print(f'Processed message: {message_txt} from {user_number}')
- # Delete the message from the queue
- message.delete()
- # Sleep for a bit before checking the queue again
- time.sleep(5)
- def process_receive_queue():
- while True:
- # Get the "Receive SQS" queue
- queue = sqs.get_queue_by_name(QueueName="receive_queue")
- # Get up to 10 messages from the queue
- messages = queue.receive_messages(MaxNumberOfMessages=10)
- # Loop through each message
- for message in messages:
- user_number, message_txt = message.body.split(": ")
- # Check if the message contains "/start"
- if "/start" in message_txt:
- # # Call the processing-service API
- requests.post("https://7360-2405-201-d006-e076-acb4-13d4-6cc9-1174.in.ngrok.io/start",
- json={"user_number": user_number})
- print(f'Started New conversation started with {user_number}')
- message.delete()
- continue
- # Delete the message from the queue
- message.delete()
- # Sleep for a bit before checking the queue again
- time.sleep(5)
- if __name__ == "__main__":
- # Initialize the Twilio client
- twilio_client = Client(
- "ACCOUNT_KEY",
- "ACCOUNT_ID"
- )
- # Start send and receive queue processing threads
- send_thread = threading.Thread(target=process_send_queue)
- send_thread.start()
- receive_thread = threading.Thread(target=process_receive_queue)
- receive_thread.start()
- # Start the Flask app
- app.run(port=5000, debug=True)
Editor
You can edit this paste and save as new: