Twilio转录回调

时间:2017-09-04 23:23:33

标签: mongodb asynchronous callback twilio ibm-watson

我正在尝试创建一个Twilio应用程序,它可以拨打电话,让它们由Voicebase转录,然后将它们作为JSON回调发送回来并存储在pyMongo数据库中。但是,当我使用ngrok进行测试时,没有任何内容打印到控制台以显示它正在工作。我在下面提供了app.py的代码:

import os
import re
from flask import Flask, jsonify, request, Response
from faker import Factory
from twilio.jwt.client import ClientCapabilityToken
from twilio.twiml.voice_response import VoiceResponse, Dial
from twilio.rest import Client
from twilio.twiml.voice_response import Record, VoiceResponse
from twilio.twiml.voice_response import Dial, Number, VoiceResponse
from twilio import twiml
import json
import os
import requests, time
from pymongo import MongoClient
import pymongo

app = Flask(__name__)
fake = Factory.create()
alphanumeric_only = re.compile('[\W_]+')
phone_pattern = re.compile(r"^[\d\+\-\(\) ]+$")

@app.route('/')
def index():
    return app.send_static_file('index.html')

@app.route('/token', methods=['GET'])
def token():
    # get credentials for environment variables
    account_sid = os.environ['TWILIO_ACCOUNT_SID']
    auth_token = os.environ['TWILIO_AUTH_TOKEN']
    application_sid = os.environ['TWILIO_TWIML_APP_SID']
    # Generate a random user name
    identity = alphanumeric_only.sub('', fake.user_name())

    # Create a Capability Token
    capability = ClientCapabilityToken(account_sid, auth_token)
    capability.allow_client_outgoing(application_sid)
    capability.allow_client_incoming(identity)
    token = capability.to_jwt()

    # Return token info as JSON
    return jsonify(identity=identity, token=token.decode('utf-8'))


@app.route("/voice", methods=['POST'])
def voice():
    resp = VoiceResponse()
    add_ons = json.loads(request.values['AddOns'])
    if "To" in request.form and request.form["To"] != '':
        dial = Dial(
            caller_id=os.environ['TWILIO_CALLER_ID'],
            record='record-from-answer-dual',
            recording_status_callback=['website_url']
        )
        # wrap the phone number or client name in the appropriate TwiML verb
        # by checking if the number given has only digits and format symbols
        if phone_pattern.match(request.form["To"]):
            dial.number(request.form["To"])
        else:
            dial.client(request.form["To"])
        resp.append(dial)
    else:
        resp.say("Thanks for calling!")

    return Response(str(resp), mimetype='text/xml')

@app.route("/callback", methods=['POST', 'PUT'])
def callback():
    print('activated')
    add_ons = json.loads(request.values['AddOns'])

    # If the Watson Speech to Text add-on found nothing, return immediately
    payload_url = add_ons["results"]["voicebase_transcription"]["payload"][0]["url"]

    account_sid = os.environ.get('TWILIO_ACCOUNT_SID')
    auth_token = os.environ.get('TWILIO_AUTH_TOKEN')
    resp = requests.get(payload_url, auth=(account_sid, auth_token)).json()
    print('working')
    results = resp['results'][0]['results']
    transcripts = map(lambda res: res['alternatives'][0]['transcript'], results)
    print(transcripts)
    client = MongoClient()
    posts = db.posts
    post_data = {
        'results': results,
        'content': transcripts
    }
    result = posts.insert_one(post_data)
    print('One post: {0}'.format(result.inserted_id))
    return ''.join(transcripts)
if __name__ == '__main__':
    app.run(debug=True)

0 个答案:

没有答案