예제 #1
0
    def setup_number(self, number, inbound_sms_url=None,
                     inbound_voice_host=None):
        """Sets up a number with Nexmo.

        TODO(matt): get some clarity on what this method does..

        Args:
            number: the number to setup
            inbound_sms_url: the callback to hit for inbound SMS
            inbound_voice_host: the callback to hit for inbound voice
        """
        # Use provider defaults if values not specified in the method call.
        if not inbound_sms_url:
            inbound_sms_url = self.inbound_sms_url
        if not inbound_voice_host:
            inbound_voice_host = self.inbound_voice_host

        voice_callback_value = '%s@%s' % (number, inbound_voice_host)
        request = {
            'password': self.password,
            'username': self.username,
            'type': 'update',
            'country': self.country,
            'msisdn': number,
            'moHttpUrl': urllib.quote_plus(inbound_sms_url),
            'voiceCallbackType': 'sip',
            'voiceCallbackValue': urllib.quote_plus(voice_callback_value)
        }
        res = NexmoMessage(request).send_request()
        print 'setting up number %s' % number
        return res['code'] == 200
예제 #2
0
    def _register_sms(self, n):
        # validate phone number syntax
        if not n or len(n.strip()) == 0:
            log.debug("number empty - %s" % n)
            return c2s.RegistrationResponse.STATUS_INVALID_USERNAME

        phone = phone_num = n.strip()
        # exclude the initial plus to verify the digits
        if (phone[0] == '+'):
            phone_num = phone[1:]

        # not all digits...
        if not phone_num.isdigit():
            log.debug("number is not all-digits - %s" % phone_num)
            return c2s.RegistrationResponse.STATUS_INVALID_USERNAME

        # replace double-zero with plus
        if phone[0:2] == '00':
            phone = '+' + phone[2:]

        # insert validation record
        # TODO do not use directly - let the storage module do it
        valdb = database.validations(self.broker.db)
        userid = utils.sha1(phone)

        # throttling :P
        if valdb.get_code(userid, True):
            return c2s.RegistrationResponse.STATUS_THROTTLING

        userid += utils.rand_str(8, utils.CHARSBOX_AZN_UPPERCASE)
        ret = valdb.update(userid)
        if ret[0] > 0:
            # send SMS
            code = ret[1]
            sms_from = self.config['registration']['from']

            if self.config['registration']['android_emu']:
                # android emulation
                import os
                os.system('adb emu sms send %s %s' % (sms_from, code))
            else:
                # send sms
                from nexmomessage import NexmoMessage
                msg = {
                    'reqtype': 'json',
                    'username': self.config['registration']['nx.username'],
                    'password': self.config['registration']['nx.password'],
                    'from': sms_from,
                    'to': phone
                }
                sms = NexmoMessage(msg)
                # FIXME send just the code for now
                sms.set_text_info(code)
                js = sms.send_request()
                log.debug("sms sent [response=%s]" % js)

            return c2s.RegistrationResponse.STATUS_CONTINUE
        else:
            return c2s.RegistrationResponse.STATUS_ERROR
예제 #3
0
파일: sms.py 프로젝트: wmv/cli-sms
	def fire(recipient, text):

		return NexmoMessage(
			{
				'reqtype': 'json',
				'api_key': SMS.CREDENTIALS['nexmo']['api_key'],
				'api_secret': SMS.CREDENTIALS['nexmo']['api_secret'],
				'from': getpass.getuser(),
				'to': recipient,
				'text': text
			}
		).send_request()
예제 #4
0
 def cancel_number(self, number):
     """Release a number back to Nexmo."""
     req = {
         'username': self.username,
         'password': self.password,
         'type': 'cancel',
         'country': self.country,
         'msisdn': number
     }
     res = NexmoMessage(req).send_request()
     print 'releasing number %s' % number
     return res['code'] == 200
예제 #5
0
 def buy_number(self, number):
     """Buy a number from Nexmo."""
     req = {
         'password': self.password,
         'username': self.username,
         'type': 'buy',
         'country': self.country,
         'msisdn': number
     }
     res = NexmoMessage(req).send_request()
     print 'buying number %s' % number
     return res['code'] == 200
예제 #6
0
    def get_existing_numbers(self, ignore_country=True):
        """Gets all numbers purchased by this user

        TODO(matt): better comments on this one.
        """
        total = None
        size = 100
        index = 1
        seen = 0
        # First request finds out how many there are.
        req = {
            'password': self.password,
            'username': self.username,
            'type': 'numbers',
            'size': size
        }
        res = NexmoMessage(req).send_request()
        nums = []
        for r in res['numbers']:
            seen += 1
            if (ignore_country or r['country'] == self.country):
                nums.append(r['msisdn'])
        total = int(res['count'])

        while seen < total:
            index += 1
            req = {
                'password': self.password,
                'username': self.username,
                'type': 'numbers',
                'size': size,
                'index': index
            }
            res = NexmoMessage(req).send_request()
            for r in res['numbers']:
                seen += 1
                if (ignore_country or r['country'] == self.country):
                    nums.append(r['msisdn'])

        return nums
예제 #7
0
 def search_numbers(self, features="SMS,VOICE"):
     """Search for available numbers from Nexmo in self.country."""
     req = {
         'password': self.password,
         'username': self.username,
         'type': 'search',
         'country': self.country,
         'features': features
     }
     res = NexmoMessage(req).send_request()
     if 'numbers' not in res or len(res['numbers']) == 0:
         raise ValueError("No numbers available.")
     # May need to filter based on some desired properties, like mobile.
     return random.choice(res['numbers'])['msisdn']
예제 #8
0
 def send_sms(self, number, code):
     msg = {
         'reqtype': 'json',
         'username': self.config['nx.username'],
         'password': self.config['nx.password'],
         'from': self.config['from'],
         'to': number,
     }
     sms = NexmoMessage(msg)
     # FIXME send just the code for now
     sms.set_text_info(code)
     response = sms.send_request()
     log.debug("sms sent [response=%s]" % response)
     return (response and int(response['message-count']) == 1
             and int(response['messages'][0]['status']) == 0)
예제 #9
0
 def get_number_info(self, number, count=10):
     """Get info on a number."""
     req = {
         'password': self.password,
         'username': self.username,
         'type': 'numbers',
         'pattern': number,
         'size': count
     }
     res = NexmoMessage(req).send_request()
     # TODO(matt): not sure I understand what's happening below..  It's hard
     #             to figure out without knowing the Nexmo response.  Seems
     #             to be duplicating 'r' into 'nums'.  Maybe it's making it
     #             possible to lookup by number?
     nums = {}
     for r in res['numbers']:
         nums[r['msisdn']] = r
     return nums
예제 #10
0
def main():

    r = "json"
    u = "changeme"
    p = "changeme"
    f = "marcuz"
    t = "39**********"
    m = "fool the reader àèìòù !!!"

    msg = {'reqtype': r, 'api_secret': p, 'from': f, 'to': t, 'api_key': u}
    tts = copy.deepcopy(msg)

    # account balance
    req = {'api_secret': p, 'api_key': u, 'type': 'balance'}
    print("request details: %s") % NexmoMessage(req).get_details()
    print NexmoMessage(req).send_request()

    print

    # my numbers
    req = {'api_secret': p, 'api_key': u, 'type': 'numbers'}
    print("request details: %s") % NexmoMessage(req).get_details()
    print NexmoMessage(req).send_request()

    print

    # pricing for country 'NL'
    req['type'] = 'pricing'
    req['country'] = 'NL'
    print("request details: %s") % NexmoMessage(req).get_details()
    print NexmoMessage(req).send_request()

    # text message
    msg['text'] = m
    sms1 = NexmoMessage(msg)
    print("SMS details: %s") % sms1.get_details()
    m += " ktnxbye"
    sms1.set_text_info(m)
    print("SMS details: %s") % sms1.get_details()
    print sms1.send_request()

    tts['text'] = "Welcome to Nexmo T T S service."
    tts1 = NexmoTTS(tts)
    print("TTS Details: %s") % (tts1.get_details())
    print tts1.send_request()
예제 #11
0
    def send(self, to, from_, body, to_country=None, from_country=None):
        """Send an SMS to Nexmo.

        Returns:
           True if the message was accepted, False otherwise.
        """
        # The Nexmo client can't send an empty string, so instead send a space.
        if len(body) == 0:
            body = ' '

        msg = {
            'username': self.username,
            'password': self.password,
            'reqtype': 'json',
            'from': from_,
            'to': to
        }
        sms = NexmoMessage(msg)
        sms.set_text_info(body)
        res = sms.send_request()
        return (res['message-count'] == '1' and
                res['messages'][0]['status'] == '0')
예제 #12
0
def main():

    r = "json"
    u = "changeme"
    p = "changeme"
    f = "marcuz"
    t = "+39**********"
    m = "fool the reader àèìòù !!!"
    bb = "0011223344556677"
    bu = "06050415811581"

    msg = {'reqtype': r, 'api_secret': p, 'from': f, 'to': t, 'api_key': u}

    # account balance
    req = {'api_secret': p, 'api_key': u, 'type': 'balance'}
    print("request details: %s") % NexmoMessage(req).get_details()
    print NexmoMessage(req).send_request()

    print

    # my numbers
    req = {'api_secret': p, 'api_key': u, 'type': 'numbers'}
    print("request details: %s") % NexmoMessage(req).get_details()
    print NexmoMessage(req).send_request()

    print

    # pricing for country 'NL'
    req['type'] = 'pricing'
    req['country'] = 'NL'
    print("request details: %s") % NexmoMessage(req).get_details()
    print NexmoMessage(req).send_request()

    # text message
    msg['text'] = m
    sms1 = NexmoMessage(msg)
    print("SMS details: %s") % sms1.get_details()
    m += " ktnxbye"
    sms1.set_text_info(m)
    print("SMS details: %s") % sms1.get_details()
    print sms1.send_request()
예제 #13
0
 def send_report(self):
     if (self.pattern.send_sms and self.pattern.nexmo_api_key
             and self.pattern.nexmo_secret_key
             and self.pattern.sms_from_number
             and self.pattern.sms_report_numbers):
         context = {'feedback': self, 'site': Site.objects.get_current()}
         body = render_to_string('spicy.feedback/sms/report.txt', context)
         for number in self.pattern.sms_report_numbers.splitlines():
             if not number.strip():
                 continue
             text = body[:140].encode('utf-8')
             msg = {
                 'reqtype': 'json',
                 'api_key': self.pattern.nexmo_api_key,
                 'api_secret': self.pattern.nexmo_secret_key,
                 'from': self.pattern.sms_from_number,
                 'to': number,
                 'text': text
             }
             sms = NexmoMessage(msg)
             sms.set_text_info(msg['text'])
             sms.sms['type'] = 'unicode'
             sms.send_request()
예제 #14
0
def send_sms(number, message, msg_type="text"):
    if config.DEBUG_SMS:
        print("SMS DEBUG:\n%s\nfrom: %s\n===========" % (message, number))
        return

    msg = {
        'reqtype': 'json',
        'api_key': config.NEXMO_API_KEY,
        'api_secret': config.NEXMO_API_SECRET,
        'from': config.NEXMO_PHONE_NO,
        'to': number,
        'text': message,
        'type': msg_type
    }
    sms = NexmoMessage(msg)
    sms.set_text_info(msg['text'])
    response = sms.send_request()
    if not response:
        logger.error("[NEXMO] Failed to send response: %s [to] %s" %
                     (message, number))
        print "Failed to send response"

    if config.LOG_MESSAGES:
        mlogger.log_message(number, message, mlogger.MessageDirection.OUTBOUND)
예제 #15
0
from nexmomessage import NexmoMessage

API_KEY = '67ac5f35'
API_SECRET = '420b4115'
DESTINATION_NUMBER = '16302071793'

YOUR_NUMBER = '14844409627'
msg = {
    'reqtype': 'json',
    'api_key': API_KEY,
    'api_secret': API_SECRET,
    'from': YOUR_NUMBER,
    'to': DESTINATION_NUMBER,
    'text': 'marshall'
}

sms = NexmoMessage(msg)
sms.set_text_info(msg['text'])
res = sms.send_request()
if res:
    print res
    print 'response'
else:
    print res
예제 #16
0
import sys
from nexmomessage import NexmoMessage

# Process command line, show usage information if not valid number of arguments

if len(sys.argv) < 3:
    print "Usage: %s <number> <message>" % sys.argv[0]
    sys.exit(1)
else:
    sendto = sys.argv[1]
    restofline = sys.argv[2:]

message = ''

if type(restofline) in [list, tuple, set]:
    for argument in restofline:
        message += ' ' + argument

message = message.strip()

nexmomsg = {
    'reqtype': nexmoreqtype,
    'password': nexmopass,
    'from': nexmosendnumber,
    'to': sendto,
    'username': nexmouser,
    'text': message
}
sms1 = NexmoMessage(nexmomsg)
sms1.set_text_info(message)