python - Twilio/Django 未收到回复短信

标签 python django twilio

我想给一个 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 员工 - 问题可能是因为您没有在此 View 周围提供 csrf_exempt 装饰器。 Django 将触发安全错误,因为它正在接收来自 twilio.com 的 HTTP POST 请求。 Django 将不会接受任何没有 csrf token 的 HTTP POST 请求,除非您将其豁免。

您是否考虑过使用 django-twilio Django 包?使用 twilio 进行开发将使您的生活变得更加轻松。这就是 django-twilio 的 View :

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。

查看 installation instructions开始吧。

关于python - Twilio/Django 未收到回复短信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18051604/

相关文章:

python - 如何使用PIL(pillow)绘制任何语言的文字?

python - 为什么这个 asyncio.Task 永远不会完成取消?

python - BOOTSTRAP//尽管添加了 cdn 链接和引用样式链接,但仍无法工作//PYTHON

javascript - Firestore 云功能 |基于时间字段的触发事件等于

java - 在 Twilio 发起的通话期间发送短信或调用其他人

python - 如何并行运行 Tensorboard

python - Django 自然键,两个值的组合?

javascript - 神秘的空值添加到我的数组的开头

python - 如何调试 Django 单元测试?

php - 如何接收发送到 twilio 号码的短信