예제 #1
0
def get_token():
    access_token = r.get(TELSTRA_SMS_ACCESS_TOKEN)
    if access_token:
        return access_token

    configuration = Telstra_Messaging.Configuration()
    api_instance = Telstra_Messaging.AuthenticationApi(
        Telstra_Messaging.ApiClient(configuration))
    client_id = settings.TELSTRA_CLIENT_KEY
    client_secret = settings.TELSTRA_CLIENT_SECRET
    grant_type = 'client_credentials'

    try:
        # Generate OAuth2 token
        api_response = api_instance.auth_token(client_id, client_secret,
                                               grant_type)
        access_token = api_response.access_token
        expires_in = int(api_response.expires_in
                         ) if api_response.expires_in.isdigit() else 3599
        r.setex(TELSTRA_SMS_ACCESS_TOKEN, expires_in, access_token)
        return access_token
    except ApiException as e:
        log.error(
            "Exception when calling AuthenticationApi->auth_token: %s\n" % e)
        return None
예제 #2
0
def register_free_trial_bnum():
    configuration = Telstra_Messaging.Configuration()
    configuration.access_token = get_token()
    api_client = Telstra_Messaging.ApiClient(configuration)

    url = 'https://tapi.telstra.com/v2/messages/freetrial/bnum'
    headers = {'Accept': 'application/json',
               'Content-Type': 'application/json',
               'User-Agent': 'OpenAPI-Generator/1.0.7/python',
               'Authorization': 'Bearer JzW3OGXwQMhlXXsRNosuVbG7QHLR'}
    body = {"bnum": [
        "+61413725868",
    ]}
    response = api_client.rest_client.POST(url,
                                           query_params=[],
                                           headers=headers,
                                           post_params=[],
                                           _preload_content=True,
                                           _request_timeout=None,
                                           body=body)

    data = json.loads(response.data)
    status = response.status
    headers = response.getheaders()
    return data
예제 #3
0
def generate_text(number, message):
    # create an instance of the API class
    api_instance = Telstra_Messaging.AuthenticationApi()
    client_id = "Agl2rsjQ0fbLC1xqPGDNve2Oianci7wK"  # str |
    client_secret = "eWJoCzsYcTk2ITRl"  # str |
    grant_type = 'client_credentials'  # str |  (default to client_credentials)

    try:
        # Generate OAuth2 token
        api_response = api_instance.auth_token(client_id, client_secret,
                                               grant_type)
        access_token = api_response.__getattribute__('access_token')

        configuration = Telstra_Messaging.Configuration()
        configuration.access_token = access_token

        api_instance = Telstra_Messaging.MessagingApi(
            Telstra_Messaging.ApiClient(configuration))
        payload = {"to": number, "validity": "60", "body": message}

        try:
            # Send SMS
            api_response = api_instance.send_sms(payload)
        except ApiException as e:
            print("Exception when calling MessagingApi->send_sms: %s\n" % e)

    except ApiException as e:
        print("Exception when calling AuthenticationApi->auth_token: %s\n" % e)

    return "text sent"
예제 #4
0
def get_token():
    global TELSTRA_ACCESS_TOKEN, TELSTRA_ACCESS_TOKEN_EXPIRY
    access_token = TELSTRA_ACCESS_TOKEN if TELSTRA_ACCESS_TOKEN_EXPIRY > datetime.now(
    ) else None
    if access_token:
        return access_token

    configuration = Telstra_Messaging.Configuration()
    api_instance = Telstra_Messaging.AuthenticationApi(
        Telstra_Messaging.ApiClient(configuration))
    client_id = configs.TELSTRA_CLIENT_KEY
    client_secret = configs.TELSTRA_CLIENT_SECRET
    grant_type = 'client_credentials'

    try:
        # Generate OAuth2 token
        api_response = api_instance.auth_token(client_id, client_secret,
                                               grant_type)
        access_token = api_response.access_token
        expires_in = int(api_response.expires_in
                         ) if api_response.expires_in.isdigit() else 3599
        TELSTRA_ACCESS_TOKEN = access_token
        TELSTRA_ACCESS_TOKEN_EXPIRY = datetime.now() + timedelta(
            seconds=expires_in)
        return access_token
    except ApiException as e:
        log.error(
            "Exception when calling AuthenticationApi->auth_token: %s\n" % e)
        return None
예제 #5
0
def send_au_sms(to, body, app_name=None):
    counter = r.get(TELSTRA_SMS_MONTHLY_COUNTER) or 0
    counter = int(counter)
    if not counter < TELSTRA_MONTHLY_FREE_LIMIT:
        log.info('[SMS] Telstra SMS reach 1000 free limitation.')
        return False, 'Telstra SMS reach 1000 free limitation.'

    to = validate_au_mobile(to)
    if not to:
        return False, 'INVALID_PHONE_NUMBER'

    body = str(body)
    if not body:
        return False, 'EMPTY_CONTENT'

    # Configure OAuth2 access token for authorization: auth
    configuration = Telstra_Messaging.Configuration()
    configuration.access_token = get_token()
    from_number = get_from_number()

    # api_instance = Telstra_Messaging.ProvisioningApi(Telstra_Messaging.ApiClient(configuration))
    # provision_number_request = Telstra_Messaging.ProvisionNumberRequest()  # ProvisionNumberRequest | A JSON payload containing the required attributes
    api_instance = Telstra_Messaging.MessagingApi(
        Telstra_Messaging.ApiClient(configuration))
    send_sms_request = Telstra_Messaging.SendSMSRequest(to, body, from_number)

    try:
        # {'country': [{u'AUS': 1}],
        #  'message_type': 'SMS',
        #  'messages': [{'delivery_status': 'MessageWaiting',
        #                'message_id': 'd872ad3b000801660000000000462650037a0801-1261413725868',
        #                'message_status_url': 'https://tapi.telstra.com/v2/messages/sms/d872ad3b000801660000000000462650037a0801-1261413725868/status',
        #                'to': '+61413725868'}],
        #  'number_segments': 1}
        api_response = api_instance.send_sms(send_sms_request)
        success = api_response.messages[0].delivery_status == 'MessageWaiting'
        if connection.schema_name.startswith(Tenant.SCHEMA_NAME_PREFIX):
            sms = Sms(app_name=app_name,
                      send_to=to,
                      content=body,
                      success=success,
                      template_code=api_response.messages[0].delivery_status,
                      remark=api_response.messages[0].message_status_url,
                      biz_id=api_response.messages[0].delivery_status)
            sms.save()

        if success:
            counter = r.get(TELSTRA_SMS_MONTHLY_COUNTER) or 0
            counter = int(counter)
            counter += 1
            r.set(TELSTRA_SMS_MONTHLY_COUNTER, counter)
            if counter == TELSTRA_MONTHLY_FREE_LIMIT - 1:
                send_to_admin('[Warning] Telstra sms meet monthly limitation.')
                r.set(TELSTRA_SMS_MONTHLY_COUNTER, counter + 1)

            return True, 'MessageWaiting'
    except ApiException as e:
        log.error("Exception when calling MessagingApi->send_sms: %s\n" % e)
        return False, str(e)
예제 #6
0
    def auth(self):
        grant_type = 'client_credentials'
        api_instance = telstra.AuthenticationApi()

        resp = api_instance.auth_token(self._client_id, self._client_secret, grant_type)
        conf = telstra.Configuration()
        conf.access_token = resp.access_token
        return conf
예제 #7
0
def send_au_sms(mobile_number, message, from_app=None):
    counter = redis_counter.get_telstra_monthly_counter()
    counter = int(counter)
    if not counter < TELSTRA_MONTHLY_FREE_LIMIT:
        logger.info('[SMS] Telstra SMS reach 1000 free limitation.')
        return False, 'Telstra SMS reach 1000 free limitation.'

    mobile_number = validate_au_mobile(mobile_number)
    if not mobile_number:
        return False, 'INVALID_PHONE_NUMBER'

    message = str(message)
    if not message:
        return False, 'EMPTY_CONTENT'

    # Configure OAuth2 access token for authorization: auth
    configuration = Telstra_Messaging.Configuration()
    configuration.access_token = get_token()
    from_number = _get_from_number()

    # api_instance = Telstra_Messaging.ProvisioningApi(Telstra_Messaging.ApiClient(configuration))
    # provision_number_request = Telstra_Messaging.ProvisionNumberRequest()  # ProvisionNumberRequest | A JSON payload containing the required attributes
    api_instance = Telstra_Messaging.MessagingApi(
        Telstra_Messaging.ApiClient(configuration))
    send_sms_request = Telstra_Messaging.SendSMSRequest(
        mobile_number, message, from_number)

    try:
        # {'country': [{u'AUS': 1}],
        #  'message_type': 'SMS',
        #  'messages': [{'delivery_status': 'MessageWaiting',
        #                'message_id': 'd872ad3b000801660000000000462650037a0801-1261413725868',
        #                'message_status_url': 'https://tapi.telstra.com/v2/messages/sms/d872ad3b000801660000000000462650037a0801-1261413725868/status',
        #                'to': '+61413725868'}],
        #  'number_segments': 1}
        api_response = api_instance.send_sms(send_sms_request)
        success = api_response.messages[0].delivery_status == 'MessageWaiting'

        if success:
            counter = redis_counter.get_telstra_monthly_counter()
            counter = int(counter)
            counter += 1
            redis_counter.set_telstra_monthly_counter(counter)
            if counter == TELSTRA_MONTHLY_FREE_LIMIT - 1:
                send_to_admin('[Warning] Telstra sms meet monthly limitation.')
                redis_counter.set_telstra_monthly_counter(counter + 1)

            return True, 'MessageWaiting'
    except ApiException as e:
        logger.error("Exception when calling MessagingApi->send_sms: %s\n" % e)
        return False, str(e)
예제 #8
0
def get_from_number():
    destination_address = r.get(TELSTRA_SMS_DESTINATION_ADDRESS)
    if destination_address:
        return destination_address

    configuration = Telstra_Messaging.Configuration()
    configuration.access_token = get_token()
    api_instance = Telstra_Messaging.ProvisioningApi(Telstra_Messaging.ApiClient(configuration))
    provision_number_request = Telstra_Messaging.ProvisionNumberRequest()  # ProvisionNumberRequest | A JSON payload containing the required attributes
    api_response = api_instance.create_subscription(provision_number_request)
    destination_address = api_response.destination_address
    expiry_timestamp = int(api_response.expiry_date / 1000)
    expires_in = expiry_timestamp - int(time.mktime(datetime.datetime.now().timetuple()))
    r.setex(TELSTRA_SMS_DESTINATION_ADDRESS, expires_in, destination_address)
    return destination_address
예제 #9
0
    def generateAuthToken(self):
        'Uses the Telstra messaging API client credientals to get an OAuth 2.0 token.'

        api_instance_Auth = Telstra_Messaging.AuthenticationApi()
        try:
            self.authToken = api_instance_Auth.auth_token(
                self.client_id, self.client_secret, self.grant_type)
            self.authTokenExpiry = datetime.now() + timedelta(seconds=3598)
            pprint(self.authToken)
        except ApiException as e:
            print(
                "Exception when calling AuthenticationApi->auth_token: %s\n" %
                e)

        self.configuration = Telstra_Messaging.Configuration()
        self.configuration.access_token = self.authToken.access_token
        self.provisionInstance = Telstra_Messaging.ProvisioningApi(
            Telstra_Messaging.ApiClient(self.configuration))
예제 #10
0
    def auth(self):
        grant_type = 'client_credentials'

        api_instance = Telstra_Messaging.AuthenticationApi()

        start_time = monotonic()
        try:
            resp = api_instance.auth_token(self._client_id, self._client_secret, grant_type)

            self.logger.info("Telstra auth request succeeded")

            conf = Telstra_Messaging.Configuration()
            conf.access_token = resp.access_token

            return conf
        except Exception as e:
            self.logger.error("Telstra auth request failed")
            raise e
        finally:
            elapsed_time = monotonic() - start_time
            self.logger.info("Telstra auth request finished in {}".format(elapsed_time))
예제 #11
0
def get_from_number():
    global TELSTRA_DESTINATION_ADDRESS, TELSTRA_DESTINATION_ADDRESS_EXPIRY
    destination_address = TELSTRA_DESTINATION_ADDRESS if TELSTRA_DESTINATION_ADDRESS_EXPIRY > datetime.now(
    ) else None
    if destination_address:
        return destination_address

    configuration = Telstra_Messaging.Configuration()
    configuration.access_token = get_token()
    api_instance = Telstra_Messaging.ProvisioningApi(
        Telstra_Messaging.ApiClient(configuration))
    provision_number_request = Telstra_Messaging.ProvisionNumberRequest(
    )  # ProvisionNumberRequest | A JSON payload containing the required attributes
    api_response = api_instance.create_subscription(provision_number_request)
    destination_address = api_response.destination_address
    expiry_timestamp = int(api_response.expiry_date / 1000)
    expires_in = expiry_timestamp - int(time.mktime(
        datetime.now().timetuple()))
    TELSTRA_DESTINATION_ADDRESS = destination_address
    TELSTRA_DESTINATION_ADDRESS_EXPIRY = datetime.now() + timedelta(
        seconds=expires_in)
    return destination_address
예제 #12
0
 def __init__(self):
     self.configuration = Telstra_Messaging.Configuration()
     self.configuration.access_token = credentials.ACCESS_TOKEN