简体   繁体   中英

how to send a message and wait for a reply in python, twilio in whatsapp

I want to take the details of a person on whatsapp and store it but it seems its not working as I want it to. It's not waiting for the user to input the first data before the second one is coming.

This is my models.py :

class student_Account(models.Model):
    name = models.CharField(max_length = 30)
    place_of_stay = models.CharField(max_length = 30)

    def __str__(self):
        return self.name

and this is my views.py :

@csrf_exempt
def sms(request):
    incoming_msg = request.POST.get('Body', '').lower()
    resp = MessagingResponse()
    msg = resp.message()
    msg1 = resp.message()

    if 'hi' in incoming_msg:
        reply = ("Hello and welcome to kkk banking system WhatsApp bot!\n\n"
                "What would you like to do\n"
                "1. Create an accout?\n"
                "2. Check your account balance\n")

        msg.body(reply)


    if incoming_msg == '1':
        reply = ("Enter your name")
        a = incoming_msg
        student.name = a
        reply = ("Enter your place of stay")
        b = incoming_msg
        student.place_of_stay = b
        msg.body(reply)
        student.save()
        reply = ("Your details has been saved!!.")
        msg.body(reply)

Every answer/response by your user via WhatsApp/SMS will be a new call to your sms method, ie you need to either A) split your logic to collect the data you need or B) let them enter it in one go.

Re A) : You could save the data in the session, a cache or your model to keep track whether the user has answered a question (eg identified by the user's phone number because this is submitted each time). You will need to find a way to identify the answers. Maybe with " Enter your place of stay " the user can only pick from a selected number of answers? Then you could do an if checking if the incoming_msg is one of those and otherwise it'll probably be an answer to the other question, eg pseudocode:

if incoming_msg == 'hi':
    # Show welcome message
    # return message
elif incoming_msg == '1':
    # Show first question
    # return message
elif incoming_msg in [<list of available places>]:
    # Retrieve current user from session/cache
    # Save place of stay
    # return message
else:
    # Save name
    # Update session/cache
    # Form second question
    # Return message

Re B) : You could let the user submit something like <name> <place of stay> in one go, eg Joseph My place of stay and then you split the answer in your business logic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM