繁体   English   中英

Twilio / Django未收到响应短信

[英]Twilio/Django not receiving response SMS

我想输入一个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))

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

您是否考虑过将django-twilio软件包用于Django? 使用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。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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