0

I'm using twilio api for receiving and sending whatsapp messages using the python and flask framework.The problem is when I'm sending the message it stores the content inside a variable which is declare inside a function and I wanted the variable value outside the function but it returns only the response for the message. My goal is to get the value of the incoming message, run some code on the basis of that value and again respond the user with a whatsapp message.

I've already tried declaring global attribute and tried nested functions to callback the variable's value and also declaring new variable to same value of getting (orignal_variable inside the function)msg = request.form.get('Body') and message = request.form.get('Body')(outside the function) but it gives RuntimeError: Working outside of request context.

app = Flask(__name__)

@app.route("/sms", methods=['POST'])
def sms_reply():
    msg = request.form.get('Body')
    resp = MessagingResponse()
    resp.message("Hello")
    return str(resp)

I was expecting to run some more code on the basis of the value of the incoming whatsapp message.

1 Answers1

0

In case you want to return the message including a messaging response you need to create a more complex type that contains both these values and then return that object instead.

from flask import jsonify
app = Flask(__name__)

class SmsReplyResult:
  def __init__(self, msg, other_data):
    self.msg = msg
    self.other_data = other_data

@app.route("/sms", methods=['POST'])
def sms_reply():
    msg = request.form.get('Body')
    result = SmsReplyResult(msg, "hello")
    return jsonify(result)

This example assumes the caller is expecting json as a response

Elertan
  • 377
  • 3
  • 8