2017-06-21 41 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