我正在实现一个智能对讲机,该对讲机实际上执行以下两项操作:
1)用语音消息回复访客: “嗨,我正在与您联系租户。如果是邮件,请说“交付”。否则,请保持在线。” 然后,它开始收集语音输入,如果满足条件,它将打开门并说:“我已经为您打开了门,请随时将包裹留在里面。”
2)在后台,它应该拨打租户(me),并且在我接听电话后,它应该停止执行任何代码。
除了后台调用,我已经实现了所有内容。似乎Twilio的api不支持并发任务。公元前启动Dial()
时,它将停止所有其他操作。
这是我的代码,带有适当的注释:
import os
import re
from flask import Flask, send_file, url_for, request, Blueprint, Response, abort
from twilio.twiml.voice_response import Gather, VoiceResponse, Dial
INTERCOM_BLUEPRINT = Blueprint('intercom', __name__, url_prefix='/intercom')
INTERCOM_APP = Flask(__name__)
ALLOWED_KEYWORDS = [r'liver', r'mail', r'usps', r'ups', r'fedex']
ALLOWED_REGEX = "({})".format(")|(".join(ALLOWED_KEYWORDS))
OPEN_DOOR_DTMF_COMMAND = '6'
# Util methods
def twiml(response):
response = Response(str(response))
response.headers['Content-Type'] = 'text/xml'
return response
def failback():
response = VoiceResponse()
response.redirect(
url_for('intercom.voice', _external=True, _scheme='https'))
return twiml(response)
# Play recordings
@INTERCOM_BLUEPRINT.route('/recording')
def recording():
type = request.args.get('values')
if type == "welcome":
return send_file(os.environ["INTERCOM_RECORDING_WELCOME"])
elif type == "opened":
return send_file(os.environ["INTERCOM_RECORDING_OPENED"])
else:
abort(404)
# Speech recognition callback
@INTERCOM_BLUEPRINT.route('/speech-response', methods=['POST'])
def speech_response():
speech_response = request.form.get(
'SpeechResult') or request.form.get('UnstableSpeechResult')
if expecting_delivery_today() and
speech_response is not None and
re.search(ALLOWED_REGEX, speech_response.lower()):
intercom_opened_url = url_for(
'intercom.recording', values='opened', _external=True, _scheme='https')
response = VoiceResponse()
response.play(intercom_opened_url, digits = OPEN_DOOR_DTMF_COMMAND)
response.hangup()
return twiml(response)
return failback()
# Entry method
@INTERCOM_BLUEPRINT.route("/voice", methods=['GET', 'POST'])
def voice():
speech_reponse_url = url_for(
'intercom.speech_response', _external=True, _scheme='https')
intercom_welcome_url = url_for(
'intercom.recording', values='welcome', _external=True, _scheme='https')
response = VoiceResponse()
with response.gather(action=speech_reponse_url, input='speech', speechTimeout='1') as gather:
gather.play(intercom_welcome_url)
""" The code below should be happening
on the background while the app is
gathering and analyzing input from the visitor
dial = Dial()
dial.dial(os.environ["TENANT_PHONE_NUMBER"])
response.append(dial)
"""
return twiml(response)
if __name__ == "__main__":
INTERCOM_APP.register_blueprint(INTERCOM_BLUEPRINT)
INTERCOM_APP.run(host='0.0.0.0', port=9092, debug=True)