예제 #1
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"
예제 #2
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
예제 #3
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
예제 #4
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
예제 #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 sendSMS(self, recipient, message):
        'Sends a SMS to the given recipient with the given message.'

        self.__checkAuthToken()
        api_instance_Messaging = Telstra_Messaging.MessagingApi(
            Telstra_Messaging.ApiClient(self.configuration))
        payload = Telstra_Messaging.SendSMSRequest(recipient, message)
        try:
            api_response = api_instance_Messaging.send_sms(payload)
            pprint(api_response)
        except ApiException as e:
            print("Exception when calling MessagingApi->send_sms: %s\n" % e)
예제 #8
0
    def authenticate_client(self):
        api_instance = Telstra_Messaging.AuthenticationApi(
            Telstra_Messaging.ApiClient(self.configuration))

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

        except ApiException as e:
            print(
                "Exception when calling AuthenticationApi->auth_token: %s\n" %
                e)
예제 #9
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)
예제 #10
0
    def send_sms(self, msg_to, msg_body):
        api_instance = Telstra_Messaging.MessagingApi(
            Telstra_Messaging.ApiClient(self.configuration))
        send_sms_request = Telstra_Messaging.SendSMSRequest(to=msg_to,
                                                            body=msg_body)

        try:
            # Send SMS
            api_response = api_instance.send_sms(send_sms_request)
            # pprint(api_response)
            return True

        except ApiException as e:
            print("Exception when calling MessagingApi->send_sms: %s\n" % e)
예제 #11
0
    def provision_client(self):
        api_instance = Telstra_Messaging.ProvisioningApi(
            Telstra_Messaging.ApiClient(self.configuration))
        provision_number_request = Telstra_Messaging.ProvisionNumberRequest()

        try:
            # Create Subscription
            api_response = api_instance.create_subscription(
                provision_number_request)
            api_response = api_instance.get_subscription()

        except ApiException as e:
            print(
                "Exception when calling ProvisioningApi->create_subscription: %s\n"
                % e)
예제 #12
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
예제 #13
0
    def send_sms(self, to, content, reference, sender=None):
        telstra_api = telstra.MessagingApi(self._client)
        notify_url = f"{self.notify_host}/notifications/sms/telstra/{reference}" if self.notify_host else None

        payload = telstra.SendSMSRequest(to=to,
                                         body=content,
                                         _from=sender if sender else None,
                                         notify_url=notify_url)

        # Avoid circular imports by importing this file later.
        from app.models import (
            NOTIFICATION_SENDING,
            NOTIFICATION_PERMANENT_FAILURE,
        )

        try:
            resp = telstra_api.send_sms(payload)
            message = resp.messages[0]
            self.logger.info(
                f"Telstra send SMS request for {reference} succeeded: {message.message_id}"
            )

            return message.message_id, NOTIFICATION_SENDING
        except telstra.rest.ApiException as e:
            try:
                messages = json.loads(e.body)["messages"]

                if e.status == 400 and len(messages) > 0 and messages[0][
                        "code"] == "TO-MSISDN-NOT-VALID" and messages[0][
                            "deliveryStatus"] == "DeliveryImpossible":
                    self.logger.info(
                        f"Telstra send SMS request for {reference} failed with API exception, status: {e.status}, reason: {e.reason}, message code: {messages[0]['code']}, message delivery status: {messages[0]['deliveryStatus']}"
                    )

                    return None, NOTIFICATION_PERMANENT_FAILURE
            except ValueError:
                pass

            self.logger.error(
                f"Telstra send SMS request for {reference} failed with API exception"
            )
            raise e
        except Exception as e:
            self.logger.error(
                f"Telstra send SMS request for {reference} failed")
            raise e
예제 #14
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))
예제 #15
0
    def deleteSubscription(self):
        'Deletes the subscription, ie releases the mobile number in use.'

        self.__checkAuthToken()
        body = Telstra_Messaging.DeleteNumberRequest()
        try:
            self.provisionInstance.delete_subscription(body)
        except ApiException as e:
            print(
                "Exception when calling ProvisioningApi->delete_subscription: %s\n"
                % e)
예제 #16
0
    def createSubscription(self, length=None):
        'Creates a subscription with the Telstra API, ie gets a mobile number to use. length defines the number of days to create the subscription for, no value will default to API default.'

        self.__checkAuthToken()
        body = Telstra_Messaging.ProvisionNumberRequest(length)
        try:
            api_response = self.provisionInstance.create_subscription(body)
            pprint(api_response)
        except ApiException as e:
            print(
                "Exception when calling ProvisioningApi->create_subscription: %s\n"
                % e)
예제 #17
0
파일: telstra.py 프로젝트: malimu/notify
    def send_sms(self, to, content, reference, sender=None):
        telstra_api = telstra.MessagingApi(self._client)
        notify_host = self._callback_notify_url_host
        notify_url = f"{notify_host}/notifications/sms/telstra/{reference}" if notify_host else None

        payload = telstra.SendSMSRequest(to=to,
                                         body=content,
                                         _from=sender if sender else None,
                                         notify_url=notify_url)

        try:
            resp = telstra_api.send_sms(payload)
            message = resp.messages[0]
            self.logger.info(
                f"Telstra send SMS request for {reference} succeeded: {message.message_id}"
            )

        except Exception as e:
            self.logger.error(
                f"Telstra send SMS request for {reference} failed")
            raise e
예제 #18
0
    def send_sms(self, to, content, reference, sender=None):
        conf = self.auth()

        api_instance = Telstra_Messaging.MessagingApi(Telstra_Messaging.ApiClient(conf))
        payload = Telstra_Messaging.SendSMSRequest(
            to=to,
            body=content,
            notify_url="{}/notifications/sms/telstra/{}".format(self._callback_notify_url_host, reference)
        )

        start_time = monotonic()
        try:
            resp = api_instance.send_sms(payload)
            message = resp.messages[0]
            self.logger.info("Telstra send SMS request for {} succeeded: {}".format(reference, message.message_id))
        except Exception as e:
            self.logger.error("Telstra send SMS request for {} failed".format(reference))
            raise e
        finally:
            elapsed_time = monotonic() - start_time
            self.logger.info("Telstra send SMS request for {} finished in {}".format(reference, elapsed_time))
예제 #19
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))
예제 #20
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
예제 #21
0
 def __init__(self):
     self.configuration = Telstra_Messaging.Configuration()
     self.configuration.access_token = credentials.ACCESS_TOKEN
예제 #22
0
from __future__ import print_function
import time
import Telstra_Messaging
from Telstra_Messaging.rest import ApiException
from pprint import pprint

# Defining host is optional and default to https://tapi.telstra.com/v2
api_instance = Telstra_Messaging.AuthenticationApi(
    Telstra_Messaging.ApiClient())
client_id = 'Mr0NZxs2KsXcbqXJOgX1PRMtP4zkkgwG'  # str |
client_secret = 'qy7JjW8g98397oAM'  # str |
grant_type = 'client_credentials'  # str |  (default to 'client_credentials')
scope = 'scope_example'  # str | NSMS (optional)

try:
    # Generate OAuth2 token
    api_response = api_instance.auth_token(client_id,
                                           client_secret,
                                           grant_type,
                                           scope=scope)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling AuthenticationApi->auth_token: %s\n" % e)
예제 #23
0
파일: telstra.py 프로젝트: malimu/notify
 def get_message_status(self, message_id):
     telstra_api = telstra.MessagingApi(self._client)
     return telstra_api.get_sms_status(message_id=message_id)
예제 #24
0
파일: telstra.py 프로젝트: malimu/notify
 def provision_subscription(self):
     # maximum subscription is 5 years, 1825 days
     telstra_api = telstra.ProvisioningApi(self._client)
     req = telstra.ProvisionNumberRequest(active_days=1825)
     telstra_api.create_subscription(req)
예제 #25
0
파일: telstra.py 프로젝트: malimu/notify
 def _client(self):
     return telstra.ApiClient(self.auth)