def dial_outbound():
    try:
        event = request.args.get('Event')
        call_uuid = request.args.get('DialBLegUUID')
        if event == "DialAnswer":
            auth_id = "Your AUTH_ID"
            auth_token = "Your AUTH_TOKEN"
            p = plivo.RestAPI(auth_id, auth_token)
            record_params = {
                'call_uuid': call_uuid,
                'callback_url':
                "https://morning-ocean-4669.herokuapp.com/recording_callback/",
                'callback_method': "GET"
            }
            response = p.record(record_params)
            print str(response)
            play_params = {
                'call_uuid': call_uuid,
                'urls': "https://s3.amazonaws.com/plivocloud/Trumpet.mp3"
            }
            response = p.play(play_params)
            print str(response)
            return Response(response, mimetype='text/plain')
        else:
            print "Invalid"
            return Response("INVALID", mimetype='text/plain')
    except Exception as e:
        print '\n'.join(traceback.format_exc().splitlines())
Exemple #2
0
def message_back():
    if request.method == 'POST':
        print request.form
        from_num = request.form.get('From')
        from_parameters = request.form.get('Text')
        from_parameters = from_parameters.strip().split()
        print from_parameters

        person = {}
        person['phone_num'] = long(from_num)
        person['country_code'] = from_parameters[0]
        person['pregancy_stage'] = int(from_parameters[1])
        person['has_smartphone'] = False
        person['language'] = 'english'
        person['responsiveness'] = 5

        add_person(person)

        subscriber_msg = "You are now subscribed to the feed"
        message_params = {
            'src': plivo_number,
            'dst': from_num,
            'text': subscriber_msg,
        }
        p = plivo.RestAPI(PLIVO_AUTH_ID, PLIVO_AUTH_TOKEN)
        res = p.send_message(message_params)
        return str(res)
Exemple #3
0
def validate_message(id):
    '''fire the validation and thus fire the calls'''
    print "Validating: ", id

    db = create_engine(SQLALCHEMY_DATABASE_URI)
    metadata = MetaData(db)
    entries = Table('entries', metadata, autoload=True)
    esel = entries.select()

    data = esel.execute(request_id=id).first()

    print "Got data:", data['from_number']

    params = {
        'from': 1000,
        'to': data['from_number'],
        'answer_url': URL + '/verify/' + id
    }

    print "Params are: ", params

    # Do plivo magic
    p = plivo.RestAPI(data['auth_id'], data['auth_token'])
    resp = p.make_call(params)
    print "Fired: ", resp
Exemple #4
0
    def send(self, channel, msg, text):
        # url used for logs and exceptions
        url = 'https://api.plivo.com/v1/Account/%s/Message/' % channel.config[Channel.CONFIG_PLIVO_AUTH_ID]

        client = plivo.RestAPI(channel.config[Channel.CONFIG_PLIVO_AUTH_ID], channel.config[Channel.CONFIG_PLIVO_AUTH_TOKEN])
        status_url = "https://" + settings.TEMBA_HOST + "%s" % reverse('handlers.plivo_handler',
                                                                       args=['status', channel.uuid])

        payload = {'src': channel.address.lstrip('+'),
                   'dst': msg.urn_path.lstrip('+'),
                   'text': text,
                   'url': status_url,
                   'method': 'POST'}

        event = HttpEvent('POST', url, json.dumps(payload))

        start = time.time()

        try:
            # TODO: Grab real request and response here
            plivo_response_status, plivo_response = client.send_message(params=payload)
            event.status_code = plivo_response_status
            event.response_body = plivo_response

        except Exception as e:  # pragma: no cover
            raise SendException(six.text_type(e), event=event, start=start)

        if plivo_response_status != 200 and plivo_response_status != 201 and plivo_response_status != 202:
            raise SendException("Got non-200 response [%d] from API" % plivo_response_status,
                                event=event, start=start)

        external_id = plivo_response['message_uuid'][0]
        Channel.success(channel, msg, WIRED, start, event=event, external_id=external_id)
Exemple #5
0
def answer(token):
    plivo_client = plivo.RestAPI(plivo_settings['auth_id'], plivo_settings['auth_token'])
    req = json.loads(request.data)
    logging.debug(req)

    name = req['pusher']['name']
    repo = req['repository']['name']
    commit_msg = req['head_commit']['message']
    try:
        userrepo = UserRepo.query.filter_by(token = token).first()
        logging.debug(userrepo)
        if userrepo is None:
            logging.debug('Invalid token')
            return 'Invalid token: %s' % token

        if userrepo.repo_name != repo:
            logging.debug('Invalid hook')
            return 'Invalid hook: %r' % req

        app.message= '%s pushed a commit to %s, %s' % (name, repo, commit_msg)

        params = {
            'to': str(userrepo.user.mobile),
            'from': str(userrepo.user.mobile),
            'answer_url': 'http://%s/answer/plivo/' % request.headers['HOST'],
        }
        (status_code, response) = plivo_client.make_call(params)
        logging.debug(response)
    except Exception as e:
        logging.debug(str(e))
    return str('this should not be reachable')
Exemple #6
0
def conf_callback():
    if request.method == 'GET':
        conf_name = request.args.get('ConferenceName')
        event = request.args.get('Event')
    elif request.method == 'POST':
        conf_name = request.form.get('ConferenceName')
        event = request.form.get('Event')
    response = make_response('OK')
    response.headers['Content-type'] = 'text/plain'
    print "Conference Name : %s " % (conf_name)

    # The recording starts when the user enters the conference room
    
    if event == "ConferenceEnter":
        auth_id = "Your AUTH_ID"
        auth_token = "Your AUTH_TOKEN"
        p = plivo.RestAPI(auth_id, auth_token)

        params = {
            'conference_name' : conf_name
        }

        response = p.record_conference(params)
        print str(response)
        return str(response)
    else:
        print "invalid"
        return Response("INVALID", mimetype='text/plain')
Exemple #7
0
def connect_plivo(info):
    auth_id = "MANJI1ZGQYOWQ3NTU4MW"
    auth_token = "NmU2YThiMmZiM2FlNDM1MDFkMTQ2NTAyMDJmNDdh"

    p = plivo.RestAPI(auth_id, auth_token)

    params = {
        'to':
        '12566655017',  # The phone numer to which the call will be placed // Arsh: 16784670532
        'from':
        '11111111111',  # The phone number to be used as the caller id

        # answer_url is the URL invoked by Plivo when the outbound call is answered
        # and contains instructions telling Plivo what to do with the call
        'answer_url':
        "https://text-to-plivo-speech.herokuapp.com/text-to-speech/" + info,
        'answer_method':
        "GET",  # The method used to call the answer_url

        # Example for asynchronous request
        # callback_url is the URL to which the API response is sent.
        #'callback_url' => "http://myvoiceapp.com/callback/",
        #'callback_method' => "GET" # The method used to notify the callback_url.
    }

    # Make an outbound call and print the response
    response = p.make_call(params)
    print str(response)
    return str(response)
Exemple #8
0
	def send_phone_code(request, id):
		if request.method == 'GET':
			if request.user.account.id != int(id):
				raise PermissionDenied

			account = get_object_or_404(Account, pk=id)
			code = random.randint(1000, 9999)

			if account.phone_verified == 1:
				raise ValidationError(detail={'error': 'This email is already verified'})

			sms_content = '''Thanks for using Vinna app.
			Please verify your phone number.
			Verification code: %d''' % code
			
			plivo_instance = plivo.RestAPI(settings.PLIVO_AUTH_ID, settings.PLIVO_TOKEN)
			
			account = get_object_or_404(Account, pk=id)

			params = {
			    'src': settings.VERIFICATION_SENDER_PHONE,
			    'dst' : account.country.phone_country_code + account.phone,
			    'text' : sms_content,
			    'method' : 'POST'
			}

			response = plivo_instance.send_message(params)

			if response[0] != 202:
				raise ValidationError(detail={'error': response[1]})

			account.phone_verified = code
			account.save()

			return Response({'detail': 'Code updated'}, status=status.HTTP_200_OK)
Exemple #9
0
class SMS(ndb.Expando):

    auth_id = "MAMTKWZGMYZDIWNJI3ZD"
    auth_token = "MjUwNzUzYjc2MGNjMjNmMDdmNGY3YmEyMTA4YTE3"
    smsURL = "https://api.plivo.com/v1/Account/MAMTKWZGMYZDIWNJI3ZD/Message/"

    p = plivo.RestAPI(auth_id, auth_token)

    params = {
        'src': '27790471558', # Sender's phone number with country code
        'dst' : '27790471559', # Receiver's phone Number with country code
        'text' : u"Hello, this is plivo talking to you hello master?", # Your SMS Text Message - English
        'url' : "https://api.plivo.com/v1/Account/MAMTKWZGMYZDIWNJI3ZD/Message/", # The URL to which with the status of the message is sent
        'method' : 'POST' # The method used to call the url
    }

    def sendSMS(self,dst,text):
        try:
            destination = str(dst)
            message = str(text)
            message = message.strip()
            if destination.isdigit() and (len(destination) >= 10) and not(message == None):

                context = {'src': '27790471559', 'dst': destination , 'text': message, 'url': self.smsURL,'method':'post'}
                response = self.p.send_message(context)
                return response
            else:
                return None
        except:
            return None
Exemple #10
0
def send_sms(phone_number, message):
    """
    Send an SMS message to a given phone number
    
    Args:
        phone_number: E.164 format phone number to send message to without the
            leading + sign
        message: SMS text body
        
    Returns:
        None
    """
    if (phone_number is not None) and (message is not None):
        # phone number shouldn't have a + sign per plivo docs
        phone_number = ''.join(c for c in phone_number if c.isalnum())

        plivoAPI = plivo.RestAPI(settings.PLIVO_AUTH_ID,
                                 settings.PLIVO_AUTH_TOKEN)
        params = {
            'src': settings.PLIVO_NUMBER,
            'dst': phone_number,
            'text': message,
            'type': 'sms'
        }
        if settings.PLIVO_DEBUG:
            # Dont bother wasting credits when just testing out
            print params
        else:
            plivoAPI.send_message(params)
Exemple #11
0
def trigger_send(num_list, message):
    """
    Queues the messages.
    Returns the success/fail status.
    """
    auth_id = config.PLIVO_ID
    auth_token = config.PLIVO_KEY

    p = plivo.RestAPI(auth_id, auth_token)

    params = {
        'src': config.PLIVO_SRC,  # Sender's phone number with country code
        'dst': _parse_list(
            num_list
        ),  # Receivers' phone numbers with country code. The numbers are separated by "<" delimiter.
        'text': message  # Your SMS Text Message
    }

    # response = p.send_message(params)

    if response[0] >= 200 and response[0] <= 299:
        # 2XX Message.  Probably ok.
        return True
    else:
        print(response)
        return False
Exemple #12
0
 def getAccDetails(self):
     try:
         p = plivo.RestAPI(self.auth_id, self.auth_token)
         accDets = plivo.Account()
         print("Account Details:{}".format(accDets))
     except plivo.PlivoError as e:
         print(e)
Exemple #13
0
	def find_phone(request):
		if request.method == 'POST':
			if not 'phone' in request.data:
				raise ValidationError(detail={'error': 'Phone number is required'})

			phone = request.data['phone']

			account = None
			try:
				account = get_object_or_404(Account, phone=phone)
			except:
				pass

			if account:
				return Response(account.first_name, status=status.HTTP_200_OK)
			else:
				code = random.randint(1000, 9999)

				sms_content = 'Vinna code: ' + str(code)
				plivo_instance = plivo.RestAPI(settings.PLIVO_AUTH_ID, settings.PLIVO_TOKEN)
				
				params = {
				    'src': settings.VERIFICATION_SENDER_PHONE,
				    'dst' : '1' + phone,
				    'text' : sms_content,
				    'method' : 'POST'
				}
				response = plivo_instance.send_message(params)

				raise ValidationError(detail={code})
Exemple #14
0
def run_live():
    port = '8000'

    print("Running ngrok ...")
    ngrok = pexpect.spawn('ngrok', ['http', port])
    ngrok.expect(r'Forwarding\s+(http://.*?\.ngrok\.io)')

    print("Configuring plivo application ...")
    message_url = urljoin(
        ngrok.match.group(1).decode('ascii'), reverse('receive_sms'))
    sms_client = plivo.RestAPI(settings.PLIVO_AUTH_ID,
                               settings.PLIVO_AUTH_TOKEN)
    response_code, response_info = sms_client.modify_application({
        'app_id':
        settings.PLIVO_APPLICATION_ID,
        'message_url':
        message_url
    })
    if response_code == 202:
        print("Plivo message endpoint changed to %s" % message_url)
    else:
        print("Unable to set Plivo message endpoint: %s" %
              response_info['message'])
        return

    try:
        local("python manage.py runserver 0.0.0.0:%s" % port)
    finally:
        ngrok.close()
Exemple #15
0
def send_message_plivo(phone, body):
    api = plivo.RestAPI(settings.PLIVO_AUTH_ID, settings.PLIVO_AUTH_TOKEN)
    plivo_message = api.Message.send(src=settings.PLIVO_PHONE,
                                     dst=str(phone.phone),
                                     text=body,
                                     url=settings.PLIVO_WEBHOOK_URL)

    from .models import Message
    message = Message(phone=phone, gateway=Message.PLIVO)

    if plivo_message.status_code != 202:
        logger.exception('Failed to send Plivo message.',
                         extra={
                             'phone': phone,
                             'body': body,
                             'plivo_message.status_code':
                             plivo_message.status_code,
                             'plivo_message.json_data': plivo_message.json_data
                         })

        message.status = Message.FAILED
        message.error = (
            'Status code {status_code}, JSON data: \n{json_data}'.format(
                status_code=plivo_message.status_code,
                json_data=plivo_message.json_data))
        message.save()
        return message

    # Split messages are not supported.
    message.remote_uuid = plivo_message.json_data['message_uuid'][0]
    message.save()
    return message
Exemple #16
0
 def getResponse(self):
     # Message Detail Record i.e. MDR has several attributes
     p = plivo.RestAPI(self.auth_id, self.auth_token)  # ??
     try:
         xml_response = plivo.XML.Response()  # missing argument
         print("Response:{}".format(xml_response))
     except plivo.PlivoError as e:
         print(e)
Exemple #17
0
 def process_control(self, data):
     algobroker.Broker.process_control(self, data)
     if data.get('cmd', None) == "auth":
         self.auth_id = data['PLIVO_AUTH_ID']
         self.auth_token = data['PLIVO_AUTH_TOKEN']
         self.api = plivo.RestAPI(self.auth_id, self.auth_token)
         self.src_number = data['src_number']
         self.dst_number = data['dst_number']
Exemple #18
0
    def claim_number(self, user, phone_number, country, role):

        auth_id = self.request.session.get(Channel.CONFIG_PLIVO_AUTH_ID, None)
        auth_token = self.request.session.get(Channel.CONFIG_PLIVO_AUTH_TOKEN, None)

        org = user.get_org()

        plivo_uuid = generate_uuid()
        app_name = "%s/%s" % (settings.TEMBA_HOST.lower(), plivo_uuid)

        client = plivo.RestAPI(auth_id, auth_token)

        message_url = "https://" + settings.TEMBA_HOST + "%s" % reverse('handlers.plivo_handler', args=['receive', plivo_uuid])
        answer_url = "https://" + settings.AWS_BUCKET_DOMAIN + "/plivo_voice_unavailable.xml"

        plivo_response_status, plivo_response = client.create_application(params=dict(app_name=app_name,
                                                                                      answer_url=answer_url,
                                                                                      message_url=message_url))

        if plivo_response_status in [201, 200, 202]:
            plivo_app_id = plivo_response['app_id']
        else:  # pragma: no cover
            plivo_app_id = None

        plivo_config = {Channel.CONFIG_PLIVO_AUTH_ID: auth_id,
                        Channel.CONFIG_PLIVO_AUTH_TOKEN: auth_token,
                        Channel.CONFIG_PLIVO_APP_ID: plivo_app_id}

        plivo_number = phone_number.strip('+ ').replace(' ', '')

        plivo_response_status, plivo_response = client.get_number(params=dict(number=plivo_number))

        if plivo_response_status != 200:
            plivo_response_status, plivo_response = client.buy_phone_number(params=dict(number=plivo_number))

            if plivo_response_status != 201:  # pragma: no cover
                raise Exception(_("There was a problem claiming that number, please check the balance on your account."))

            plivo_response_status, plivo_response = client.get_number(params=dict(number=plivo_number))

        if plivo_response_status == 200:
            plivo_response_status, plivo_response = client.modify_number(params=dict(number=plivo_number,
                                                                                     app_id=plivo_app_id))
            if plivo_response_status != 202:  # pragma: no cover
                raise Exception(_("There was a problem updating that number, please try again."))

        phone_number = '+' + plivo_number
        phone = phonenumbers.format_number(phonenumbers.parse(phone_number, None),
                                           phonenumbers.PhoneNumberFormat.NATIONAL)

        channel = Channel.create(org, user, country, 'PL', name=phone, address=phone_number,
                                 config=plivo_config, uuid=plivo_uuid)

        analytics.track(user.username, 'temba.channel_claim_plivo', dict(number=phone_number))

        return channel
Exemple #19
0
def send_sms(to, text):
    client = plivo.RestAPI(PLIVO_AUTH_ID, PLIVO_AUTH_TOKEN)
    params = {
        'src': SMS_SOURCE_NUMBER,
        'text': text,
    }
    for number in to:
        params['dst'] = number
        message = client.send_message(params)
    return True
Exemple #20
0
def send_sms(to_number, text):
    cc = phone_country(to_number)

    src = {'US': '17077776191', 'CA': '13433441234'}.get(cc, '17077776191')

    p = plivo.RestAPI(current_app.config['PLIVO_AUTH_ID'],
                      current_app.config['PLIVO_AUTH_TOKEN'])
    params = {'src': src, 'dst': str(to_number), 'text': text}
    res = p.send_message(params)
    return '', 200
Exemple #21
0
def alarm(number):
    p = plivo.RestAPI(auth_id, auth_token)
    params = {
        'to': number,
        'from': '16623829952',
        'answer_url': "http://molson194.tk/answer.xml",
        'answer_method': "GET"
    }
    response = p.make_call(params)
    print str(response)
Exemple #22
0
 def send(self, to, msg, src=None):
     try:
         if not src:
             src = self.src
         client = plivo.RestAPI(self.auth_id, self.auth_token)
         message = client.Message.send(src=src, dst=to, text=msg[:160])
         return message
     except:
         pass
     return False
Exemple #23
0
    def plivomisscall(self, source, destination):
        self.call_params['from'] = source
        self.call_params['answer_method'] = 'POST'
        self.call_params['answer_url'] = self.answer_url
        self.call_params['to'] = destination
        self.call_params['hangup_on_ring'] = PlivoInfo.plivo_hang_onring

        triger_call = plivo.RestAPI(self.auth_id, self.auth_token)
        call_result = triger_call.make_call(self.call_params)
        print call_result
Exemple #24
0
 def comMsg(self):
     p = plivo.RestAPI(self.auth_id, self.auth_token)
     try:
         response = p.Message.create(
             src='+13238318440',
             dst='+13252210570',
             text='Test Message',
         )
         print(response)
     except plivo.PlivoError as e:
         print(e)
Exemple #25
0
def outcall():
    p=plivo.RestAPI(auth_id, auth_token)
    call_params={
            'to':'ph',
            'from':'xxxxxxxxxx',
            'answer_url':'https://www.dropbox.com/s/n76obusmwo64ttr/hangup.xml'
            }
    response = p.make_call(call_params)
   # if response['message']!='call fired':
    #    return 'call not made'
   # else:
    return 'call in progress'
Exemple #26
0
    def get_valid_client(self):
        auth_id = self.request.session.get(Channel.CONFIG_PLIVO_AUTH_ID, None)
        auth_token = self.request.session.get(Channel.CONFIG_PLIVO_AUTH_TOKEN, None)

        try:
            client = plivo.RestAPI(auth_id, auth_token)
            validation_response = client.get_account()
            if validation_response[0] != 200:
                client = None
        except plivo.PlivoError:  # pragma: needs cover
            client = None

        return client
Exemple #27
0
def send_sms(text, phone_number):
    try:
        p = plivo.RestAPI('MAMZRJZMMWM2RLNTG2MD',
                          'ZWZlZTA2YTZkZjEzNmJjZmFmYjQyYTc3NGY0NDU4')
        params = {
            'src': 'TOLL-ME',
            'dst': '+91' + str(phone_number),
            'text': "Your OTP for Verification is: " + text
        }
        #print(params)
        p.send_message(params)
    except plivo.exceptions.PlivoRestError as e:
        print(e)
Exemple #28
0
def call(number, message):
    auth_id = config['AUTH_ID']
    auth_token = config['AUTH_TOKEN']
    p = plivo.RestAPI(auth_id, auth_token)

    params = {
        'from': '1212121212',
        'to': number,
        'answer_url': config['BASE_URL'] + '/answer?message=' + message,
        'answer_method': "GET",
    }
    response = p.make_call(params)
    return response
Exemple #29
0
def send_plivo_message(to_number, body):
    p = plivo.RestAPI('MAZWU5ZWVKNMU4MZG1N2',
                      'YWMzMzk5NmIzNzc2MTAyZDI4ZTIwYzYzMWZhOTM0')
    flag = content_tiny_url(body)
    params = {
        'src': '+919686798312',  # Caller Id
        'dst': to_number,  # User Number to Call
        'text': flag,
        'type': "sms",
    }

    response = p.send_message(params)
    return response
def send_text(dict_of_recipients, auth_id, token):
    """Sends text messages, logging when the text was not sent."""

    p = plivo.RestAPI(auth_id, token)

    for name, number in dict_of_recipients.items():
        print("sending text to {}".format(name))
        params = {
            'src': plivo_number,
            'dst' : number,
            'text' : "Hi {}, just a reminder that you have water changes this week that you have either not done or not signed off on. Thanks!".format(name),
            'method' : 'POST'
        }
        response = p.send_message(params)