【发布时间】:2019-11-15 15:49:00
【问题描述】:
我正在尝试为使用 Twilio API 及其 Python 包装器的相对简单的消息传递系统奠定基础。用户应该能够给关键字发短信并收到一串回复。
问题是,使用 Twilio 文档中建议的 HttpResponse() 包,当我遍历消息以将它们添加到响应链时,它们会在一个块中命中 Twilio,并发送服务以看似随机的顺序发送它们,这确实损害了块的可读性。
这是我在 Django 中运行以创建响应的循环的简化版本:
@csrf_exempt
def inbox(request)
if request.method == "POST":
# Interpret the keyword in the incoming message
data = request.POST
messageBody = data['Body'].lower()
# Check if it matches a valid keyword
targetTrigger = Keyword.objects.get(trigger_word=messageBody)
# Pull the appropriate responses
messageChain = Message.objects.filter(keyword_answers=targetTrigger)
# Create the messaging response
resp = MessagingResponse()
# Populate it with messages
for sms in messageChain:
resp.message(sms)
# Send them to Twilio
return HttpResponse(str(resp))
为了便于阅读,我忽略了尝试和错误捕获。就像我说的那样,这会以看似随机的顺序发送消息,较短的消息似乎更多地首先发送到我的 iPhone。并非总是如此,但足以让我需要重新考虑这种方法。
奇怪的是,文档中几乎没有关于在 SMS HttpResponse 中发送多条消息的内容,尽管我认为这是一个常见的用例。我正在考虑的替代方法是发回一个空白的 HttpResponse 以简单地向 Twilio 确认消息已成功接收,然后将其常规的一对一发送方法与我的 for 循环一起使用。这似乎效率有点低,但我需要消息发送顺序的准确性。
有什么建议吗? Twilio 开发人员传道者,我知道你们都在这里。
【问题讨论】:
标签: python django twilio twilio-api