示例#1
0
def patient_stats():
    global end_time
    p_id = request.args.get("id")
    outcome = request.args.get('result')
    client = Client(account_sid, auth_token)
    callrec = client.calls(call_id).fetch()
    end_time = callrec.end_time.strftime("%Y-%m-%d %H:%M:%S")
    service_imp.load_calledpatient_data(p_id, start_time, end_time, outcome)
    return "Sent stats!"
示例#2
0
def update():
    account_sid = os.environ['TWILIO_ACCOUNT_SID']
    auth_token = os.environ['AUTH_TOKEN']

    client = Client(account_sid, auth_token)

    call = client.calls(manager_sid).update(url="/whisper", method="POST")

    return ''
示例#3
0
def get_call(call_sid):
    """
    Wrapper for getting call information from Twilio API.
    """
    logger.info("Getting Call {}".format(call_sid))
    client = Client(account_access, account_secret)
    call = client.calls(call_sid)

    return call
示例#4
0
def call(request):

    # Your Account Sid and Auth Token from twilio.com/console

    account_sid = 'ACc74819c84a2b3b685476b29d1affba76'
    auth_token = 'f209d606239c309c0e31c2009dcfbe81'
    client = Client(account_sid, auth_token)
    call = client.calls.create(url='http://demo.twilio.com/docs/voice.xml',
                               to='+917303153300',
                               from_='+17342924458')

    while (client.calls(call.sid).fetch().status != "completed"):
        pass
    print(client.calls(call.sid).fetch().duration)
    duration = client.calls(call.sid).fetch().duration
    up = UserProfile.objects.get(user_detail=request.user)
    request.session['duration'] = duration
    return redirect('/callfinal/')
def twilio_route_call(asid, csid, url):

    account_sid = 'AC2330c6acc9cdac777b2f1dca56d69876'
    auth_token = 'd7cc39c73c50bdbf845907f2489598ed'
    client = Client(account_sid, auth_token)

    call = client.calls(csid) \
                .update(
                    method='POST',
                    url=url
                )
示例#6
0
def drop():

    participant = request.json['participant']
    # drop = request.json['drop']
    # conf_sid = request.json['conferenceSid']
    client = Client(current_user.twilio_account_sid,
                    current_user.twilio_auth_token)

    call = client.calls(participant) \
        .update(status="completed")

    return "Participant dropped!", 200
示例#7
0
def partialBackup():
    returnVal = ""
    temp_info = {
        "speech": request.form['UnstableSpeechResult'],
        "num": int(request.form['SequenceNumber'])
    }
    MAX_SEQUENCE.append(temp_info)
    if len(responses) == 0:
        print request.form['StableSpeechResult']
        if any(p in request.form['StableSpeechResult'] for p in punctuation):
            try:
                all_sentences = re.split('(?<=[.!?]) +',
                                         request.form['StableSpeechResult'])
                for val in all_sentences:
                    if any(p in str(val) for p in punctuation) == False:
                        all_sentences.remove(val)
                if len(all_sentences) > 0:
                    print("FOUND EARLY FIRST PART")
                    all_sentences = [
                        "ask citi bank " + x for x in all_sentences
                    ]
                    a = requests.post("http://127.0.0.1:8001/interact",
                                      data={"question": all_sentences})
                    print a.json()
                    for val in a.json()['response']:
                        if val in ALLOWED_RESPONSES:
                            responses.append(val)
                            print("AYYYYOOOO FOUND EARLY")
                            #resp = VoiceResponse()
                            #resp.append(val)
                            client = Client(account_sid, auth_token)
                            call = client.calls(
                                request.form['CallSid']).update(
                                    method='POST',
                                    url='http://telemetry.ngrok.io/completed')
                            return ""
                        else:
                            print("{} not in {}".format(
                                val, ALLOWED_RESPONSES))
                else:
                    print("Nah")
            except Exception as exp:
                print exp
    return returnVal
示例#8
0
    def post(self, request, format=None):
        data_received = request.data
        print "received:", data_received

        callStatus = data_received['CallStatus']
        callSid = data_received['CallSid']

        if callStatus == 'answered' or callStatus == 'in-progress':
            print "attempting to terminate call"

            client = TwClient(getattr(settings, "TW_ACCOUNT_SID", None),
                              getattr(settings, "TW_AUTH_TOKEN", None))

            call = client.calls(callSid) \
                .update(status="completed")

            print(call.direction)

        return Response(status=status.HTTP_200_OK)
示例#9
0
def call():
    global call_id, start_time
    number = request.args.get('phone')
    changenumber = number.replace("-", "")
    nn = '+1' + changenumber
    client = Client(account_sid, auth_token)
    call = client.calls.create(
        machine_detection='Enable',
        url='http://demo.twilio.com/docs/voice.xml',
        to=
        '+18586665289',  #placeholder number grab this from the number column in table
        from_='+13143107942'  #purchased twilio number
    )
    #sid = call()
    call_id = call.sid
    callrec = client.calls(call.sid).fetch()
    #print(callrec.duration)
    duration = callrec.duration
    if duration is None:
        duration = str(0)
    start_time = callrec.start_time.strftime("%Y-%m-%d %H:%M:%S")
    return "Called!"
示例#10
0
def record():

    wavUrl = session.pop('wavUrl')
    callSid = session.pop('callSid')
    r = requests.get(wavUrl)

    watsonUrl = 'https://stream.watson-j.jp/speech-to-text/api/v1/recognize?continuous=true&model=ja-JP_NarrowbandModel&word_confidence=true'
    username = os.environ["STT_USERNAME"]
    password = os.environ["STT_PASSWORD"]
    headers = {'Content-Type': 'audio/wav'}
    audio = r.content
    r2 = requests.post(watsonUrl,
                       data=audio,
                       headers=headers,
                       auth=(username, password))

    say = u"ごめんなさい、聞き取れませんでした。"
    if (r.status_code == 200):
        res = json.loads(r2.text)

        if (len(res['results']) != 0):
            for result in res['results']:
                for alternative in result['alternatives']:
                    transcript = alternative['transcript']
            say = transcript

    accountSid = os.environ["ACCOUNT_SID"]
    authToken = os.environ["AUTH_TOKEN"]
    client = Client(accountSid, authToken)

    call = client.calls(callSid).update(
        url="https://twimlserver.herokuapp.com/reply?say=" +
        urllib.quote(say.encode('utf-8')),
        method="GET")

    return call.to
# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import Client

# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)

feedback = client.calls("CAe03b7cd806070d1f32bdb7f1046a41c0") \
                 .feedback() \
                 .fetch()

print(feedback.date_created)
示例#12
0
def call_crashed_gpus():
    is_system_calling = redis_store.get("is_system_already_calling")
    if is_system_calling is None:
        redis_store.set("is_system_already_calling", 0)
    is_system_calling = bool(int(redis_store.get("is_system_already_calling")))
    num_of_crashed_gpus = redis_store.get("main_dashboard:num_of_crashed_gpus")
    if num_of_crashed_gpus is None:
        num_of_crashed_gpus = 0
    else:
        num_of_crashed_gpus = int(num_of_crashed_gpus)
    try:
        client_twilio = Client(str(Config.TWILIO_ACCOUNT_SID),
                               str(Config.TWILIO_AUTH_TOKEN))
        is_notified = False
        try_num = 1
        url_with_attack_response = "https://powmining.com/twilio_responses/crashed_gpus"
        if num_of_crashed_gpus > 0 and is_system_calling is False:
            while try_num <= 10 and bool(
                    int(redis_store.get("is_system_already_calling"))
            ) is False and is_notified is False:
                redis_store.set("is_system_already_calling", 1)
                save_simple_action(
                    "Attempt to notify about crashed gpus. \nTry № {} \nGPUs crashed {}"
                    .format(try_num, num_of_crashed_gpus))
                try_num += 1
                if Config.TWILIO_PHONE_NUMBER_1:
                    call_num_1 = client_twilio.calls.create(
                        to=str(Config.TWILIO_PHONE_NUMBER_1),
                        from_=str(Config.TWILIO_PHONE_NUMBER_SERVER),
                        url=url_with_attack_response)
                    time.sleep(40)
                    call_num_1 = client_twilio.calls(call_num_1.sid).fetch()
                    if not (call_num_1.status == "busy"
                            or call_num_1.status == "failed"):
                        call_num_1 = client_twilio.calls(
                            call_num_1.sid).update(status="completed")
                    call_num_1 = client_twilio.calls(call_num_1.sid).fetch()
                    save_simple_action(
                        "Call to {} ended with status {}".format(
                            call_num_1.to, call_num_1.status))
                    if call_num_1.status == "busy" or call_num_1.status == "completed" \
                            or call_num_1.status == "in-progress":
                        is_notified = True
                        save_simple_action(
                            "{} has been notified about crashed gpus.".format(
                                call_num_1.to))
                    else:
                        save_simple_action(
                            "Failed to notify {} about crashed gpus.".format(
                                call_num_1.to))

                if Config.TWILIO_PHONE_NUMBER_2 and not is_notified:
                    call_num_2 = client_twilio.calls.create(
                        to=str(Config.TWILIO_PHONE_NUMBER_2),
                        from_=str(Config.TWILIO_PHONE_NUMBER_SERVER),
                        url=url_with_attack_response)
                    time.sleep(40)
                    call_num_2 = client_twilio.calls(call_num_2.sid).fetch()
                    if not (call_num_2.status == "busy"
                            or call_num_2.status == "failed"):
                        call_num_2 = client_twilio.calls(
                            call_num_2.sid).update(status="completed")
                    call_num_2 = client_twilio.calls(call_num_2.sid).fetch()
                    save_simple_action(
                        "Call to {} ended with status {}".format(
                            call_num_2.to, call_num_2.status))
                    if call_num_2.status == "busy" or call_num_2.status == "completed" \
                            or call_num_2.status == "in-progress":
                        is_notified = True
                        save_simple_action(
                            "{} has been notified about crashed gpus.".format(
                                call_num_2.to))
                    else:
                        save_simple_action(
                            " Failed to notify {} about crashed gpus.".format(
                                call_num_2.to))

                if Config.TWILIO_PHONE_NUMBER_3 and not is_notified:
                    call_num_3 = client_twilio.calls.create(
                        to=str(Config.TWILIO_PHONE_NUMBER_3),
                        from_=str(Config.TWILIO_PHONE_NUMBER_SERVER),
                        url=url_with_attack_response)
                    time.sleep(40)
                    call_num_3 = client_twilio.calls(call_num_3.sid).fetch()
                    if not (call_num_3.status == "busy"
                            or call_num_3.status == "failed"):
                        call_num_3 = client_twilio.calls(
                            call_num_3.sid).update(status="completed")
                    call_num_3 = client_twilio.calls(call_num_3.sid).fetch()
                    save_simple_action(
                        "Call to {} ended with status {}".format(
                            call_num_3.to, call_num_3.status))
                    if call_num_3.status == "busy" or call_num_3.status == "completed" \
                            or call_num_3.status == "in-progress":
                        is_notified = True
                        save_simple_action(
                            "{} has been notified about crashed gpus.".format(
                                call_num_3.to))
                    else:
                        save_simple_action(
                            " Failed to notify {} about crashed gpus.".format(
                                call_num_3.to))

                if Config.TWILIO_PHONE_NUMBER_4 and not is_notified:
                    call_num_4 = client_twilio.calls.create(
                        to=str(Config.TWILIO_PHONE_NUMBER_4),
                        from_=str(Config.TWILIO_PHONE_NUMBER_SERVER),
                        url=url_with_attack_response)
                    time.sleep(40)
                    call_num_4 = client_twilio.calls(call_num_4.sid).fetch()
                    if not (call_num_4.status == 'busy'
                            or call_num_4.status == 'failed'):
                        call_num_4 = client_twilio.calls(
                            call_num_4.sid).update(status="completed")
                    call_num_4 = client_twilio.calls(call_num_4.sid).fetch()
                    save_simple_action(
                        "Call to {} ended with status {}".format(
                            call_num_4.to, call_num_4.status))
                    if call_num_4.status == "busy" or call_num_4.status == "completed" \
                            or call_num_4.status == "in-progress":
                        is_notified = True
                        save_simple_action(
                            "{} has been notified about crashed gpus.".format(
                                call_num_4.to))
                    else:
                        save_simple_action(
                            " Failed to notify {} about crashed gpus.".format(
                                call_num_4.to))

                if Config.TWILIO_PHONE_NUMBER_5 and not is_notified:
                    call_num_5 = client_twilio.calls.create(
                        to=str(Config.TWILIO_PHONE_NUMBER_5),
                        from_=str(Config.TWILIO_PHONE_NUMBER_SERVER),
                        url=url_with_attack_response)
                    time.sleep(40)
                    call_num_5 = client_twilio.calls(call_num_5.sid).fetch()
                    if not (call_num_5.status == "busy"
                            or call_num_5 == "failed"):
                        call_num_5 = client_twilio.calls(
                            call_num_5.sid).update(status="completed")
                    call_num_5 = client_twilio.calls(call_num_5.sid).fetch()
                    save_simple_action(
                        "Call to {} ended with status {}".format(
                            call_num_5.to, call_num_5.status))
                    if call_num_5.status == "busy" or call_num_5.status == "completed" \
                            or call_num_5.status == "in-progress":
                        is_notified = True
                        save_simple_action(
                            "{} has been notified about crashed gpus.".format(
                                call_num_5.to))
                    else:
                        save_simple_action(
                            " Failed to notify {} about crashed gpus.".format(
                                call_num_5.to))

                redis_store.set("is_system_already_calling", 0)
        else:
            print("No GPUs crashed.all OK.")
    except Exception as e:
        redis_store.set("is_system_already_calling", 0)
        print(e)
        print("Exception occurred while trying to notify about crashed gpus.")
        pass
示例#13
0
#write requests & responses from Twilio to log file, useful for debugging:
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s %(levelname)s %(message)s',
    filename='/usr/local/twilio/python3/sdkv6x/calls/logs/call_feedback.log',
    filemode='a')

# Your Account Sid and Auth Token from twilio.com/console & stored in Mac OS ~/.bash_profile in this example
account_sid = os.environ.get('$TWILIO_ACCOUNT_SID')
auth_token = os.environ.get('$TWILIO_AUTH_TOKEN')
client = Client(account_sid, auth_token)

# A list of call feedback parameters & their permissable values, comment out (#) those lines not required:

feedback = client.calls("CAxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") \
                 .feedback() \
                 .create(quality_score=2, #1-5, where 1=imperfect & 5=perfect
                         issue=['digits-not-captured'])

#print list of all call feedback properties to console, useful for learning info available you can work with?

print(feedback.account_sid)
print(feedback.date_created)
print(feedback.date_updated)
print(feedback.issues)
print(feedback.quality_score)
print(feedback.sid)

#create variable for this call
cdr = (feedback.issues)

#open *.log file with cdr var as filename...
# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import Client

# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)

call = client.calls("CAe1644a7eed5088b159577c5802d8be38").update(status="completed")

print(call.direction)
示例#15
0
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client

# Your Account Sid and Auth Token from twilio.com/console
account_sid = '"ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)

call = client.calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
             .update(url="https://example.com")

print(call.to)
示例#16
0
# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import Client
from time import sleep

# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = ""
auth_token = ""
client = Client(account_sid, auth_token)

call = client.calls.create(to="+447737088306",
                           from_="+441163260745",
                           machine_detection="Enable",
                           method="GET",
                           status_callback="https://requestb.in/1jigllq1",
                           url="http://twimlbin.com/59b6d602")

print(call.sid)
print(call.answered_by)
sleep(6)
call2 = client.calls(call.sid).fetch()
print(call2.to)
print(call2.answered_by)
示例#17
0
#write requests & responses from Twilio to log file, useful for debugging:
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s %(levelname)s %(message)s',
    filename='/usr/local/twilio/python3/sdkv6x/calls/logs/call_feedback.log',
    filemode='a')

# Your Account Sid and Auth Token from twilio.com/console & stored in Mac OS ~/.bash_profile in this example
account_sid = os.environ.get('$TWILIO_ACCOUNT_SID')
auth_token = os.environ.get('$TWILIO_AUTH_TOKEN')
client = Client(account_sid, auth_token)

# A list of call feedback parameters & their permissable values, comment out (#) those lines not required:

feedback = client.calls("CAxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") \
                 .feedback() \
                 .create(quality_score=1, #1-5, where 1=imperfect & 5=perfect
                         issue=['audio-latency'])

#print list of all call feedback properties to console, useful for learning info available you can work with?

print(feedback.account_sid)
print(feedback.date_created)
print(feedback.date_updated)
print(feedback.issues)
print(feedback.quality_score)
print(feedback.sid)

#create variable for this call
cdr = (feedback.issues)

#open *.log file with cdr var as filename...
示例#18
0
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client

# Your Account Sid and Auth Token from twilio.com/console
account_sid = '"ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)

client.calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete()
# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import Client

# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)

feedback = client.calls("CAe03b7cd806070d1f32bdb7f1046a41c0") \
                 .feedback() \
                 .create(quality_score=3,
                         issue=['imperfect-audio'])

print(feedback.date_created)
示例#20
0
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client

# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)

feedback = client.calls('CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
                 .feedback() \
                 .fetch()

print(feedback.date_created)
示例#21
0
class Twilio:
    """Twilio connector over TwilioClient.
	"""
    def __init__(self, settings):
        """
		:param settings: `Twilio Settings` doctype
		"""
        self.settings = settings
        self.account_sid = settings.account_sid
        self.application_sid = settings.twiml_sid
        self.api_key = settings.api_key
        self.api_secret = settings.get_password("api_secret")
        self.twilio_client = TwilioClient(self.account_sid,
                                          settings.get_password("auth_token"))

    @classmethod
    def connect(self):
        """Make a twilio connection.
		"""
        settings = frappe.get_doc("Twilio Settings")
        if not (settings and settings.enabled):
            return
        return Twilio(settings=settings)

    def get_phone_numbers(self):
        """Get account's twilio phone numbers.
		"""
        numbers = self.twilio_client.incoming_phone_numbers.list()
        return [n.phone_number for n in numbers]

    def generate_voice_access_token(self,
                                    from_number: str,
                                    identity_postfix=None,
                                    ttl=60 * 60):
        """Generates a token required to make voice calls from the browser.
		"""
        # identity is used by twilio to identify the user uniqueness at browser(or any endpoints).
        identity = from_number
        if identity_postfix:
            identity = '_'.join(
                [identity, self.safe_identity(identity_postfix)])

        # Create access token with credentials
        token = AccessToken(self.account_sid,
                            self.api_key,
                            self.api_secret,
                            identity=identity,
                            ttl=ttl)

        # Create a Voice grant and add to token
        voice_grant = VoiceGrant(
            outgoing_application_sid=self.application_sid,
            incoming_allow=True,  # Allow incoming calls
        )
        token.add_grant(voice_grant)
        return token.to_jwt()

    @classmethod
    def safe_identity(cls, identity: str):
        """Create a safe identity by replacing unsupported special charaters with '-'.
		Twilio Client JS fails to make a call connection if identity has special characters like @, [, / etc)
		https://www.twilio.com/docs/voice/client/errors (#31105)
		"""
        return re.sub(r'[^a-zA-Z0-9_.-]+', '-', identity).strip()

    def generate_twilio_dial_response(self, from_number: str, to_number: str):
        """Generates voice call instructions needed for twilio.
		"""
        url_path = "/api/method/twilio_integration.twilio_integration.api.update_recording_info"
        recording_status_callback = get_public_url(url_path)

        resp = VoiceResponse()
        dial = Dial(caller_id=from_number,
                    record=self.settings.record_calls,
                    recording_status_callback=recording_status_callback,
                    recording_status_callback_event='completed')
        dial.number(to_number)
        resp.append(dial)
        return resp

    def get_call_info(self, call_sid):
        return self.twilio_client.calls(call_sid).fetch()
# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import Client

# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)

call = client.calls("CAe1644a7eed5088b159577c5802d8be38") \
             .update(url="http://demo.twilio.com/docs/voice.xml",
                     method="POST")

print(call.to)
示例#23
0
def parse_events():
    account_sid = request.form['AccountSid']
    TWILIO_SYNC_SERVICE_SID = current_app.config['TWILIO_SYNC_SERVICE_SID']
    user = User.query.filter_by(twilio_account_sid=account_sid).first()
    pprint(user)
    pprint(user.sync_map_sid)
    TWILIO_SYNC_MAP_SID = user.sync_map_sid
    request_dict = {}
    request_dict = request.form.to_dict()
    pprint(request_dict)

    event = request_dict['StatusCallbackEvent']
    pprint(event)
    if 'CallSid' in request_dict:
        call_sid = request_dict['CallSid']
    else:
        call_sid = None
    conference_sid = request_dict['ConferenceSid']
    muted = False if 'Muted' not in request_dict or request_dict[
        'Muted'] == 'false' else True
    pprint(event)
    client = Client(current_app.config['TWILIO_ACCOUNT_SID'],
                    current_app.config['TWILIO_AUTH_TOKEN'])
    if event == 'participant-join':

        call = client.calls(call_sid).fetch()
        pprint(call)
        pprint("CALL DETAILS {}".format(call.from_formatted))
        participant_number = call.from_formatted if call.direction == "inbound" else call.to_formatted
        data = {
            "conferenceSid": conference_sid,
            "callSid": call_sid,
            "participantNumber": participant_number,
            "direction": call.direction,
            "muted": False,
            "speaking": False,
            "dropped": False
        }

        conference_id = UserConference.query.filter_by(
            call_sid=conference_sid).first()
        print(conference_id)
        if conference_id is None:
            user = User.query.filter_by(twilio_account_sid=account_sid).first()
            conference_data = UserConference(call_sid=conference_sid,
                                             name="The Marae",
                                             account_sid=account_sid)
            db.session.add(conference_data)
            db.session.commit()
            user.conferences.append(conference_data)
            conference_id = UserConference.query.filter_by(
                call_sid=conference_sid).first()
            user.send_sms(
                "Your conference has started! {} is already in The Marae {}".
                format(participant_number, url_for('main.index',
                                                   _external=True)))

        participant = Participant(number=data['participantNumber'],
                                  direction=data['direction'],
                                  call_sid=data['callSid'])
        db.session.add(participant)
        db.session.commit()
        conference_id.participants.append(participant)
        print("DATA >>> {}".format(data))

        map_item = client.sync.services(TWILIO_SYNC_SERVICE_SID) \
            .sync_maps(TWILIO_SYNC_MAP_SID) \
            .sync_map_items \
            .create(key=call_sid, data=data)

        print("MAP ITEM >>> {}".format(map_item))
        return "OK", 200
    elif event == 'participant-speech-start':
        print("{} >>> SPEAKING!".format(call_sid))

        current_data = client.sync.services(TWILIO_SYNC_SERVICE_SID) \
            .sync_maps(TWILIO_SYNC_MAP_SID) \
            .sync_map_items(call_sid) \
            .fetch()
        new_data = current_data.data
        new_data["speaking"] = True
        data = json.dumps(new_data)
        map_item = client.sync.services(TWILIO_SYNC_SERVICE_SID) \
            .sync_maps(TWILIO_SYNC_MAP_SID) \
            .sync_map_items(call_sid) \
            .update(data=str(data))
        return "OK", 200

    elif event == 'participant-speech-stop':
        print("{} >>> STOPPED SPEAKING!".format(call_sid))
        current_data = client.sync.services(TWILIO_SYNC_SERVICE_SID) \
            .sync_maps(TWILIO_SYNC_MAP_SID) \
            .sync_map_items(call_sid) \
            .fetch()
        new_data = current_data.data
        new_data["speaking"] = False
        data = json.dumps(new_data)
        map_item = client.sync.services(TWILIO_SYNC_SERVICE_SID) \
            .sync_maps(TWILIO_SYNC_MAP_SID) \
            .sync_map_items(call_sid) \
            .update(data=str(data))
        return "OK", 200

    elif event == 'participant-leave':
        print("{} >>> LEFT THE CONFERENCE!".format(call_sid))
        participant = Participant.query.filter_by(call_sid=call_sid).first()
        print("PARTICIPANT >>> ")
        print(participant)
        client = Client(user.twilio_account_sid, user.twilio_auth_token)
        call = client.calls(call_sid).fetch()
        print("DURATION >>> ")
        print(call.duration)
        participant.duration = call.duration
        db.session.add(participant)
        db.session.commit()
        current_data = client.sync.services(TWILIO_SYNC_SERVICE_SID) \
            .sync_maps(TWILIO_SYNC_MAP_SID) \
            .sync_map_items(call_sid) \
            .fetch()
        new_data = current_data.data
        new_data["speaking"] = False
        new_data["muted"] = False
        new_data["dropped"] = True
        data = json.dumps(new_data)
        map_item = client.sync.services(TWILIO_SYNC_SERVICE_SID) \
            .sync_maps(TWILIO_SYNC_MAP_SID) \
            .sync_map_items(call_sid) \
            .update(data=str(data))
        return "OK", 200
    elif event == 'conference-end':
        print("conference-end!")
        conference_data = UserConference.query.filter_by(
            call_sid=conference_sid).first()
        user = User.query.filter_by(twilio_account_sid=account_sid).first()
        client = Client(user.twilio_account_sid, user.twilio_auth_token)
        twilio_conference = client.conferences(conference_sid).fetch()
        conference_data.region = twilio_conference.region
        start_time = datetime.strptime(conference_data.date_created,
                                       '%Y-%m-%d %H:%M:%S.%f')
        conference_data.duration = round(
            (datetime.utcnow() - start_time).total_seconds())
        db.session.add(conference_data)
        db.session.commit()
        print(twilio_conference.region)
        delete_map_items()
        return "ITEMS DELETED", 200
    elif event == 'participant-mute':
        print("{} >>> MUTED!".format(call_sid))

        current_data = client.sync.services(TWILIO_SYNC_SERVICE_SID) \
            .sync_maps(TWILIO_SYNC_MAP_SID) \
            .sync_map_items(call_sid) \
            .fetch()
        new_data = current_data.data
        new_data["muted"] = True
        data = json.dumps(new_data)
        map_item = client.sync.services(TWILIO_SYNC_SERVICE_SID) \
            .sync_maps(TWILIO_SYNC_MAP_SID) \
            .sync_map_items(call_sid) \
            .update(data=str(data))
        return "OK", 200
    elif event == 'participant-unmute':
        print("{} >>> UNMUTED!".format(call_sid))

        current_data = client.sync.services(TWILIO_SYNC_SERVICE_SID) \
            .sync_maps(TWILIO_SYNC_MAP_SID) \
            .sync_map_items(call_sid) \
            .fetch()
        new_data = current_data.data
        new_data["muted"] = False
        data = json.dumps(new_data)
        map_item = client.sync.services(TWILIO_SYNC_SERVICE_SID) \
            .sync_maps(TWILIO_SYNC_MAP_SID) \
            .sync_map_items(call_sid) \
            .update(data=str(data))
        return "OK", 200
    else:
        print("EVENT >>> {}".format(event))
        return "OK", 200
示例#24
0
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client

# Your Account Sid and Auth Token from twilio.com/console
account_sid = '"ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)

feedback = client.calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
                 .feedback() \
                 .fetch()

print(feedback.date_created)
示例#25
0
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client


# Your Account Sid and Auth Token from twilio.com/console
# DANGER! This is insecure. See http://twil.io/secure
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)

recording = client.calls('CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
                  .recordings('REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
                  .update(status='stopped')

print(recording.call_sid)
def action(logger, number_to, number_from):
    account_sid = 'ACc86884f6d8841e6497873914ab28de99'
    auth_token = '950cc4c17493774642b1c4ef7243c9c2'
    client = Client(account_sid, auth_token)
    try:
        call = client.calls.create(
            machine_detection='Enable',
            method='GET',
            status_callback='http://123f25d0.ngrok.io/response',
            status_callback_event=[
                'initiated', 'answered', 'completed', 'no-answer', 'queued',
                'completed', 'ringing', 'failed', 'busy'
            ],
            status_callback_method='POST',
            url='http://123f25d0.ngrok.io/answer',
            to=number_to,
            from_=number_from)
    except Exception as ex:
        logger.end_log(ex.message)

    past = call.status
    while ValueError:
        try:
            call = client.calls(call.sid) \
                .update(
                      )
            if past != call.status:
                past = call.status
                if call.status == 'completed':
                    print(call.answered_by)
                    if call.answered_by == "human":
                        logger.end_log(
                            "The person you want to contacted answered the call"
                        )
                        break
                    elif call.answered_by == "unknown":
                        logger.end_log(
                            "The someone you want to contacted answered the message"
                        )
                        break
                    else:
                        logger.end_log(
                            "The person you want to contacted received the message"
                        )
                        break

                elif call.status == 'in-progress':
                    print(call.answered_by)
                    logger.write_log("The call has been answered")

                elif call.status == 'failed':
                    logger.end_log("The call has failed")
                    break

                elif call.status == 'ringing':
                    logger.write_log(
                        "The cellphone you want to call is ringing")

                elif call.status == 'queued':
                    logger.write_log("The call has been set")

        except ValueError:
            logger.error_log(ValueError.message)
            print(ValueError)
# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import Client

# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)

call = client.calls("CA42ed11f93dc08b952027ffbc406d0868").fetch()
print(call.to)
示例#28
0
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client

# Your Account Sid and Auth Token from twilio.com/console
# DANGER! This is insecure. See http://twil.io/secure
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)

call = client.calls('CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').fetch()

print(call.to)
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client

# Your Account Sid and Auth Token from twilio.com/console
# DANGER! This is insecure. See http://twil.io/secure
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)

recording = client.calls('CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
                  .recordings('REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
                  .update(pause_behavior='skip', status='paused')

print(recording.call_sid)
示例#30
0
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client

# Your Account Sid and Auth Token from twilio.com/console
# DANGER! This is insecure. See http://twil.io/secure
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)

call = client.calls('CAe1644a7eed5088b159577c5802d8be38') \
             .update(
                  method='POST',
                  url='http://demo.twilio.com/docs/voice.xml'
              )

print(call.to)
#write requests & responses from Twilio to log file, useful for debugging:
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s %(levelname)s %(message)s',
    filename='/usr/local/twilio/python3/sdkv6x/calls/logs/call_feedback.log',
    filemode='a')

# Your Account Sid and Auth Token from twilio.com/console & stored in Mac OS ~/.bash_profile in this example
account_sid = os.environ.get('$TWILIO_ACCOUNT_SID')
auth_token = os.environ.get('$TWILIO_AUTH_TOKEN')
client = Client(account_sid, auth_token)

# A list of call feedback parameters & their permissable values, comment out (#) those lines not required:

feedback = client.calls("CAxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") \
                 .feedback() \
                 .create(quality_score=3, #1-5, where 1=imperfect & 5=perfect
                         issue=['unsolicited-call'])

#print list of all call feedback properties to console, useful for learning info available you can work with?

print(feedback.account_sid)
print(feedback.date_created)
print(feedback.date_updated)
print(feedback.issues)
print(feedback.quality_score)
print(feedback.sid)

#create variable for this call
cdr = (feedback.issues)

#open *.log file with cdr var as filename...
示例#32
0
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client


# Your Account Sid and Auth Token from twilio.com/console
# DANGER! This is insecure. See http://twil.io/secure
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)

call = client.calls('CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
             .update(url='https://example.com')

print(call.to)