2017-06-21 42 views
0

我正在学习使用Python和Flask的Twilio。我希望能够拨打一些号码,给这个人2个选项,然后根据他们的选择,给他们播放一个语音留言,并给他发送一条短信和他们的答案。语音和消息响应在相同的响应

我已经写了一些代码:

from flask import Flask, request 
from TwilioPhoneCall import app 
from twilio.twiml.voice_response import VoiceResponse, Gather 
from twilio.twiml.messaging_response import MessagingResponse, Message 


@app.route("/", methods=['GET', 'POST']) 
def message(): 
    resp = VoiceResponse() 

    gather = Gather(num_digits=1, action='/gather') 
    gather.say('Hello there! Do you like apples?.'+ 
       ' type one for yes '+ 
       ' type two for no.') 
    resp.append(gather) 

    resp.redirect('/') 


    return str(resp) 

@app.route('/gather', methods=['GET', 'POST']) 
def gather(): 
    resp = VoiceResponse() 

    if 'Digits' in request.values: 
     choice = request.values['Digits'] 

     if choice == '1': 
      resp.say('Nice! Apples are very healthy!') 
      msg = Message(to='myphonenumber').body('He likes apples!') 
      resp.append(msg) 

      return str(resp) 

     elif choice == '2': 
      resp.say('Shame on you! Apples are very healthy!') 
      msg = Message(to='myphonenumber').body('He said no.') 
      resp.append(msg) 

      return str(resp) 

     else: 
      resp.say('Sorry, choose one or two.') 

    resp.redirect('/') 

    return str(resp) 

几乎每一件事情顺利进行:所有的语音留言和选择选项的工作。问题出在SMS消息上,从不发送。

我也试着添加一个MessagingResponse并返回这个和VoiceResponse,但我得到一个应用程序错误,我认为这是因为我有两个<response></response>标签,每个响应(语音和消息) 。

有没有办法做到这一点?

回答

0

Twilio开发者传道这里。

你离这里很近。您唯一犯的错误是您在响应传入消息时使用<Message>,并且<Sms>发送SMS消息作为语音呼叫的一部分。

所以,你gather路线应该使用resp.sms,像这样:

@app.route('/gather', methods=['GET', 'POST']) 
def gather(): 
    resp = VoiceResponse() 

    if 'Digits' in request.values: 
     choice = request.values['Digits'] 

     if choice == '1': 
      resp.say('Nice! Apples are very healthy!') 
      resp.sms('He likes apples!', to='myphonenumber') 
      return str(resp) 

     elif choice == '2': 
      resp.say('Shame on you! Apples are very healthy!') 
      resp.sms('He said no.', to='myphonenumber') 
      return str(resp) 

     else: 
      resp.say('Sorry, choose one or two.') 

    resp.redirect('/') 

    return str(resp) 

让我知道这是否有助于在所有。

+0

是的!那就是诀窍。感谢Phil和Twilio的良好工作表示祝贺。我真的很享受它的许多功能摆弄。 – gunslinger

+0

太棒了!希望你的摆弄顺利。如果您有任何其他问题,我会在这里! – philnash