1

我想给一个 twilio 号码发短信,然后向用户提出一系列问题。如果这是他们第一次发短信,则应该创建一个新的“来电者”。如果他们以前玩过,我想查找“last_question”,我们问他们并问他们适当的问题。我下面的代码没有产生 SMS 响应和 Twilio 错误“HTTP 检索失败”。

在 models.py 我有

class Caller(models.Model):
    body = models.CharField(max_length=200)
    from_number = models.CharField(max_length=20)
    last_question = models.CharField(max_length=2, default="0")

    def __unicode__(self):
        return self.body

在views.py

def hello_there(request):
    body = request.REQUEST.get('Body', None)
    from_number = request.REQUEST.get('From', None)
    try:
        caller = Caller.objects.get(from_number = from_number)
    except Caller.DoesNotExist:
        caller = None
    if caller:
        if caller.last_question == "0":
            if body == "Password":
                message = "Welcome to the game. What is 3 + 4?"
                caller.last_question = "1"
            else:
                message = "What is the password?"
        else:
            message = "you broke me"
    else:
        new_caller = Caller(body=body, from_number=from_number, last_question="0")
        new_caller.save()
        message = "New user created"
    resp = twilio.twiml.Reponse()
    resp.sms(message)
    return HttpResponse(str(resp))
4

1 回答 1

1

Twilio 员工在这里 - 问题可能是因为您没有csrf_exempt围绕此视图提供装饰器。Django 将触发安全错误,因为它正在接收HTTP POST来自 twilio.com 的请求。Django 不会接受任何HTTP POST没有 csrf 令牌的请求,除非你让它豁免。

你有没有想过为 Django 使用django-twilio包?使用 twilio 开发时,它会让您的生活更轻松。这是使用 django-twilio 的视图:

from django_twilio.decorators import twilio_view

@twilio_view
def hello_there(request):
    body = request.REQUEST.get('Body', None)
    from_number = request.REQUEST.get('From', None)
    try:
        caller = Caller.objects.get(from_number=from_number)
    except Caller.DoesNotExist:
        caller = None
    if caller:
        if caller.last_question == "0":
            if body == "Password":
                message = "Welcome to the game. What is 3 + 4?"
                caller.last_question = "1"
            else:
                message = "What is the password?"
        else:
            message = "you broke me"
    else:
        new_caller = Caller(body=body, from_number=from_number, last_question="0")
        new_caller.save()
        message = "New user created"
    resp = twilio.twiml.Reponse()
    resp.sms(message)
return resp

装饰师将twilio_view提供 csrf 豁免,并确保您的所有请求都是真实的并且来自 twilio.com。

查看安装说明以开始使用。

于 2014-02-17T19:24:31.067 回答