def get_nexmo_client():
    """Return an instance of Nexmo client library"""
    api_key = os.environ.get("NEXMO_API_KEY")
    api_secret = os.environ.get("NEXMO_API_SECRET")
    app_id = os.environ.get("NEXMO_APP_ID")
    private_key = os.environ.get("NEXMO_PRIVATE_KEY_VOICE_APP")

    client = nexmo.Client(key=api_key,
                          secret=api_secret,
                          application_id=app_id,
                          private_key=private_key)
    return client
Example #2
0
def calls():
    print('you are at the calls endpoint good job')
    client = nexmo.Client(application_id=NEXMO_APPLICATION_ID, private_key=NEXMO_PRIVATE_KEY)

    response = client.create_call({
        'to': [{'type': 'phone', 'number': number_to_call}],
        'from': {'type': 'phone', 'number': number_to_call},
        'answer_url': ['http://cb9df9b5.ngrok.io/answer']
    })

    session['uuid'] = response['uuid']
    return redirect(url_for('answer'))
Example #3
0
def sendSMS(emergencyType, assistanceType, IncidentLocation, department):
    numberDic = {'SCDF': '6593548076'}
    client = nexmo.Client(key='9369c004', secret='k0BkH393kDW2mPZz')
    client.send_message({
        'from':
        'Nexmo',
        'to':
        numberDic[department],
        'text':
        '<<Emergency Assistance Needed for ' + emergencyType +
        '>>\n\nIncident Location: ' + IncidentLocation +
        '\n\nType of Assistance:' + assistanceType + '\n',
    })
Example #4
0
def test_check_signature(dummy_data):
    params = {
        'a': '1',
        'b': '2',
        'timestamp': '1461605396',
        'sig': '6af838ef94998832dbfc29020b564830'
    }

    client = nexmo.Client(key=dummy_data.api_key,
                          secret=dummy_data.api_secret,
                          signature_secret='secret')

    assert client.check_signature(params)
Example #5
0
def SendSms(sender, to, text):
    client = nexmo.Client(
        key='863ebd62', secret='grwxupG0M9yPJfcP'
    )  # credencias do serviço nexmo - consultadas em Vonage API Dashboard
    indicativo = '351'  # indicativo do país
    Mobilenr = to  # número do destinatário
    to = indicativo + Mobilenr

    client.send_message({
        'from': sender,
        'to': to,
        'text': text,
    })
Example #6
0
def sendSMS(message):
    phoneNo = formSMS['phoneNumber']
    client = nexmo.Client()

    try:
        client.send_message({
            'from': 'Niwater',
            'to': phoneNo,
            'text': message,
        })
        logging.info('SMS was successfuly sent.')
    except Exception as e:
        logging.info('Sending SMS failed. ' + str(e))
Example #7
0
def send_text(number, message):
    client = nexmo.Client(key=NEXMO_API_KEY, secret=NEXMO_API_SECRET)
    response = client.send_message({
        'from': BOWER_PHONE_NUMBER,
        'to': number,
        'text': message
    })
    response = response['messages'][0]
    print(response)
    if response['status'] == '0':
        return (True, "")
    else:
        return (False, response['error-text'])
Example #8
0
def nexmocall(postdata):
    try:
        PRIVATE_KEY = open("private.key", 'r').read()
        client = nexmo.Client(application_id="APP ID", key=nexmo_key,
                                          secret=nexmo_secret, private_key=PRIVATE_KEY)
        response = client.create_call({
                    "to": [{"type": "phone", "number": "{0}".format(postdata["number"])}],
                    "from": {"type": "phone", 'number': "123456789"},
                    "answer_url": ["http://NCCO-STORE".format(postdata["client"])]
                    })
        return response
    except:
        return 3
Example #9
0
def rentSMS():
    client = nexmo.Client(key=nexmo_api_key, secret=nexmo_api_secret)
    options = json.loads(
        client.get_available_numbers("US", {"features": "SMS"}))
    v_num = options.get('numbers')[0].get('msisdn')
    response = json.loads(client.buy_number({
        "country": "US",
        "msisdn": v_num
    }))
    if response.get('error-code') == '200':
        return v_num
    print("Could not purchase number. Something went wrong.")
    return '123'
Example #10
0
def test_check_signature(dummy_data):
    params = {
        "a": "1",
        "b": "2",
        "timestamp": "1461605396",
        "sig": "6af838ef94998832dbfc29020b564830",
    }

    client = nexmo.Client(key=dummy_data.api_key,
                          secret=dummy_data.api_secret,
                          signature_secret="secret")

    assert client.check_signature(params)
Example #11
0
    def on_subscription_data(self, pdu):
        for service1 in pdu['messages']:
            client = nexmo.Client(key='', secret='')
            response = client.send_message({'from': '', 'to': '', 'text': 'Emergency services are on the way'})

            response = response['messages'][0]

            if response['status'] == '0':
              print 'Sent message', response['message-id']

              print 'Remaining balance is', response['remaining-balance']
            else:
              print 'Error:', response['error-text']
Example #12
0
def sendMessage(sendTo, name):
    c = nexmo.Client(key='4179aed7', secret='B6ED8JS3Kap5bIsI')
    c.send_message({
        'from':
        'Nexmo',
        'to':
        str(sendTo),
        'text':
        '%s missed the bus on (%d/%d/%d.)' %
        (name, curr.month, curr.day, curr.year)
    })
    print("\t[ Current Balance -->", c.get_balance(), "]")
    print("\t<-- Alert message sent to [ ", name, "] parents!!!!! -->\n\n")
Example #13
0
def sendSMS(emergencyType, assistanceType, IncidentLocation, department):
    numberDic = {'SCDF': '6594498046'}
    client = nexmo.Client(key='e68c16e1', secret='9uRWmU1uguyz2Kle')
    client.send_message({
        'from':
        'Nexmo',
        'to':
        numberDic[department],
        'text':
        '<<Emergency Assistance Needed for ' + emergencyType +
        '>>\n\nIncident Location: ' + IncidentLocation +
        '\n\nType of Assistance:' + assistanceType + '\n',
    })
Example #14
0
    def test_check_signature(self):
        params = {
            'a': '1',
            'b': '2',
            'timestamp': '1461605396',
            'sig': '6af838ef94998832dbfc29020b564830'
        }

        self.client = nexmo.Client(key=self.api_key,
                                   secret=self.api_secret,
                                   signature_secret='secret')

        self.assertTrue(self.client.check_signature(params))
Example #15
0
def sms_to_us(phone_num, msg):
    client = nexmo.Client(key=NEXMO_API_KEY, secret=NEXMO_API_SECRET)
    response = client.send_message({
        'from': '12015471485',
        'to': phone_num,
        'text': msg
    })

    response = response['messages'][0]
    if response['status'] == '0':
        utils.logger.debug('Send sms success. Remaining balance is %s',
                           response['remaining-balance'])
    else:
        utils.logger.debug(response['error-text'])
Example #16
0
 def __init__(
     self,
     client=None,
     application_id=None,
     private_key=None,
 ):
     try:
         # Client is protected
         self._client = client
         if self._client is None:
             self._client = nexmo.Client(application_id=application_id,
                                         private_key=private_key)
     except Exception as e:
         print('Error: {error_message}'.format(error_message=str(e)))
Example #17
0
    def on_event(self, event, payload):
        if event != "PrintDone":
            return

        if not self._settings.get(['enabled']):
            return

        filename = os.path.basename(payload["file"])

        import datetime
        import octoprint.util
        elapsed_time = octoprint.util.get_formatted_timedelta(
            datetime.timedelta(seconds=payload["time"]))

        tags = {'filename': filename, 'elapsed_time': elapsed_time}
        message = self._settings.get(["message_format", "body"]).format(**tags)
        secret = self._settings.get(["secret"])
        api_key = self._settings.get(["api_key"])
        phone_number = self._settings.get(["phone_number"])
        senderID = self._settings.get(["senderID"])
        message_class = 1
        client = nexmo.Client(key=api_key, secret=secret)

        if self._settings.get(["flashsms"]):
            message_class = 0

        response = client.send_message({
            'from': senderID,
            'to': phone_number,
            'text': message,
            'message-class': message_class
        })

        try:
            response = response['messages'][0]

            if response['status'] == '0':
                # log message id
                self._logger.info(response['message-id'])
            else:
                # log nexmo error if any
                self._logger.info(response['error-text'])

        except Exception as e:
            # report problem sending sms
            self._logger.exception("SMS notification error: %s" % (str(e)))
        else:
            # report notification was sent
            self._logger.info("Print notification sent to %s" %
                              (self._settings.get(['phone_number'])))
def transfer(callid):
    payload = {
        "action": "transfer",
           "destination": {
             "type": "ncco",
             "url": ["http://{}/transfer?dest={}".format(HOSTNAME, MYNUMBER)]
        }
    }
    url = "https://api.nexmo.com/v1/calls/{}".format(callid)
    client = nexmo.Client(application_id=APP_ID, private_key=PRIVATE_KEY, key='dummy', secret='dummy')
    headers =  client._Client__headers()
    headers['Content-Type'] = 'application/json'
    response = requests.put(url, headers=headers, data=json.dumps(payload))
    return response
    def post(self, request, *args, **kwargs):
        data = json.loads(request.body)

        # We only want to record completed calls in this instance
        if data['status'] == 'completed':
            campaign = Campaign.active.for_number(data['to'])

            if campaign:
                mix = Mixpanel(settings.MIXPANEL_TOKEN)
                client = nexmo.Client(
                    key=settings.NEXMO_API_KEY,
                    secret=settings.NEXMO_API_SECRET
                )

                # Track people data
                insight = client.get_advanced_number_insight(number=data['from'])

                mix.people_set(
                    insight['international_format_number'],
                    {
                        '$phone': '+' + insight.get('international_format_number'),
                        '$first_name': insight.get('first_name'),
                        '$last_name': insight.get('last_name'),
                        'Country': insight.get('country_name'),
                        'Country Code': insight.get('country_code_iso3'),
                        'Valid Number': insight.get('valid_number'),
                        'Reachable': insight.get('reachable'),
                        'Ported': insight.get('ported'),
                        'Roaming': insight.get('roaming').get('status'),
                        'Carrier Name': insight.get('current_carrier').get('name'),
                        'Network Type': insight.get('current_carrier').get('network_type'),
                        'Network Country': insight.get('current_carrier').get('country'),
                    }
                )

                # Track call data
                mix.track(
                    insight['international_format_number'],
                    'inbound call',
                    {
                        'Campaign ID': campaign.pk,
                        'Campaign Name': campaign.name,
                        'Duration': data.get('duration'),
                        'Start Time': data.get('start_time'),
                        'End Time': data.get('end_time'),
                        'Price': data.get('price')
                    }
                )

        return HttpResponse()
def send_message(sender, text):
    client = nexmo.Client(key=NEXMO_API_KEY, secret=NEXMO_API_SECRET)
    response = client.send_message({
        'from': sender,
        'to': NEXMO_TEST_PHONE,
        'text': text
    })
    response = response['messages'][0]

    if response['status'] == '0':
        print 'Sent message', response['message-id']
        print 'Remaining balance is', response['remaining-balance']
    else:
        print 'Error:', response['error-text']
    def handle(self, *args, **options):
        """
        We send out scheduled emails on three cases:
        1. One week before birthday to friends.
        2. One day before birthday to friends.
        3. On the birthday to the person.
        """
        # register SMS client
        self.sms_client = nexmo.Client(key=NEXMO_CLIENT_KEY,
                                       secret=NEXMO_CLIENT_SECRET)

        self.handle_invites()
        self.handle_reminders()
        self.handle_on_birthday()
def get_nexmo_client():
    """Return an instance of Nexmo client library"""
    app_id = os.environ.get("NEXMO_APP_ID")
    private_key = os.environ.get("NEXMO_PRIVATE_KEY_VOICE_APP")

    if not app_id:
        click.echo("Missing NEXMO_APP_ID environment variable.")
        sys.exit(-1)
    if not private_key:
        click.echo("Missing NEXMO_PRIVATE_KEY_VOICE_APP environment variable.")
        sys.exit(-1)

    client = nexmo.Client(application_id=app_id, private_key=private_key)
    return client
Example #23
0
def send_code(phone):
    client = nexmo.Client(key='9e6881d8', secret='EfmTX6rrUe64X3RE')
    seeds = string.digits
    random_str = random.choices(seeds, k=4)
    code = "".join(random_str)

    res_send_code = client.send_message({
        'from': 'admin_vue',
        'to': f'86{phone}',
        'text': f'admin_vue 验证码:{code}',
    })
    # send_state = res_send_code.get("messages")[0].get("status")
    print(res_send_code)
    return code
Example #24
0
    def __init__(self, sender, api_key, api_secret, fromaddr, smtp_pwd,
                 smtp_server, smtp_port):
        super(Notify, self).__init__()
        self.nexmo = nexmo.Client(key=api_key, secret=api_secret)
        self.api_key = api_key
        self.api_secret = api_secret
        self.sender = sender

        self.fromaddr = fromaddr
        self.smtp_pwd = smtp_pwd
        self.smtp_server = smtp_server
        self.smtp_port = smtp_port

        self.clients = list()
def message(i):
    client = nexmo.Client(key='5ef03909', secret='omiBgsZg5cljMQoT')
    if (i == 1):
        client.send_message({
            'from': '18622296358',
            'to': '165044xx9401',
            'text': 'X7-3 Drive missing',
        })
    elif (i == 2):
        client.send_message({
            'from': '18622296358',
            'to': '16504xx9401',
            'text': 'X7-3 Drive Link speed ..',
        })
Example #26
0
    def submit(self):
        data = self.cleaned_data
        phone_number = data['phone_number']

        url_param = {
            'message': data['message'],
            'voice': data['voice'],
        }
        answer_url = '{url}/?{params}'.format(
            url=self.request.build_absolute_uri(reverse('outgoing_call')),
            params=parse.urlencode(url_param))

        # print(answer_url)
        # this for txt
        # client = nexmo.Client(key=NexmoConfig.api_key, secret=NexmoConfig.api_secret)

        # this require voice api, therefore need new JWT auth (need app + private key)
        client = nexmo.Client(key=NexmoConfig.api_key,
                              secret=NexmoConfig.api_secret,
                              application_id=NexmoConfig.application_id,
                              private_key=NexmoConfig.private_key)

        # sms_result = client.send_message({'from': NexmoConfig.from_phone, 'to': phone_number, 'text': data['message']})
        # print(sms_result)

        call_params = {
            'from': {
                'type': 'phone',
                'number': NexmoConfig.from_phone
            },
            'to': [{
                'type': 'phone',
                'number': phone_number
            }],
            'answer_url': [answer_url],
            'answer_method': 'POST',  # default 'GET'
            # 'machine_detection': 'hangup',        # default
            'length_timer': 60,  # hangup after 5min, default 7200min => 2h
            'ringing_timer': 30,  # wait 60s while ringing, default 60s
        }
        # self.p(call_params, 'Call Params')
        result = client.create_call(call_params)
        # self.p(result, 'Call Result')

        result = client.get_application(
            application_id=NexmoConfig.application_id)
        # self.p(result)

        return 'Voice sent!'
Example #27
0
def verify(request):
    id = request.session['user_id']
    user = CustomerUser.objects.get(id=id)

    stl = SimTheoLoai.objects.all()
    sns = SimNamSinh.objects.all()
    nm = NhaMang.objects.all()
    stg = SimTheoGia.objects.all()
    hd = HoaDon.objects.order_by('-NgayDatHang')[0:5]

    # Sắp xếp danh mục sim theo giá theo title
    stg_dsx = sorted(stg, key=operator.attrgetter('title'))

    Data = {
        "hd": hd,
        "stl": stl,
        "sns": sns,
        "nm": nm,
        "stg": stg_dsx,
    }

    if request.method == 'POST':
        if request.POST.get("verify") == 'sdt':
            key = 'd3541bdb'
            secret = '9Tn3HaqVhJX1pVKW'
            sdt = "+84{}".format(user.SDT)
            client = nexmo.Client(key=key, secret=secret)

            response = client.start_verification(number=sdt,
                                                 brand="SimSoDucLoc",
                                                 code_length="4")
            request.session['request_id'] = response["request_id"]
            return redirect('user:xacthucsdt')
        else:
            current_site = get_current_site(request)
            mail_subject = 'Kích hoạt tài khoản của bạn.'
            message = render_to_string(
                'simso/page-user/activeemail.html', {
                    'user': user,
                    'domain': current_site.domain,
                    'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                    'token': account_activation_token.make_token(user),
                })
            to_email = user.email
            email = EmailMessage(mail_subject, message, to=[to_email])
            email.send()
            return render(request, 'simso/page-user/success.html', Data)

    return render(request, 'simso/page-user/verify.html', Data)
Example #28
0
    def __init__(self):
        # Load secret config (API Key, phone numbers)
        try:
            self.conf = env_config_from_json(conf_file)
        except Exception as e:
            logger.exception('Init sms conf failed')
            raise

        # Create Nexmo instance
        try:
            self.provider = nexmo.Client(key=self.conf['NEXMO_API_KEY'],
                                         secret=self.conf['NEXMO_API_SECRET'])
        except Exception as e:
            logger.exception('Init Nexmo failed')
            raise
Example #29
0
def send_message(sender, reciever, message):

    client = nexmo.Client(key=settings.KEY, secret=settings.SECRET)
    string = str(message)
    response = client.send_message({
        'from': sender,
        'to': reciever,
        'text': string
    })
    response = response['messages'][0]

    if response['status'] == '0':
        return "SENT"
    else:
        return "ERROR"
Example #30
0
    def setUp(self):
        self.api_key = 'nexmo-api-key'
        self.api_secret = 'nexmo-api-secret'
        self.application_id = 'nexmo-application-id'
        self.private_key = open('test/private_key.txt').read()
        self.public_key = open('test/public_key.txt').read()
        self.user_agent = 'nexmo-python/{0}/{1}'.format(
            nexmo.__version__, platform.python_version())
        self.client = nexmo.Client(key=self.api_key,
                                   secret=self.api_secret,
                                   application_id=self.application_id,
                                   private_key=self.private_key)

        if not hasattr(self, 'assertRaisesRegex'):
            self.assertRaisesRegex = self.assertRaisesRegexp