Ejemplo n.º 1
0
def generatePass(phoneNo):
    #def generatePass(phoneNo):
    genCode = random.randint(100000, 999999)
    # Specify your login credentials
    username = os.environ['AT_USERNAME']
    apikey = os.environ['AT_APIKEY']
    # Specify the receiving number
    to = phoneNo
    # Message to be sent
    message = "Your verification code is {}, valid for 30 minutes.".format(
        genCode)
    # Create a new instance of our awesome gateway class
    gateway = AfricasTalkingGateway(username, apikey)

    try:
        results = gateway.sendMessage(to, message)

        for recipient in results:
            # status is either "Success" or "error message"
            print('number = {}; status = {}; messageId = {}; cost = {}'.format(
                recipient['number'], recipient['status'],
                recipient['messageId'], recipient['cost']))
    except AfricasTalkingGatewayException as e:
        print('Encountered an error while sending: {}').format(str(e))

    return genCode
Ejemplo n.º 2
0
    def _processRequest(self, request):
        params = json.loads(request.content.read())
        log.msg('PaymentRequest::_processRequest: Received %s' % str(params))
        status = params["status"]
        phoneNumber = params["phoneNumber"]
        value = params["value"]

        request.setResponseCode(200)
        request.write("OK")

        if not request.finished:
            request.finish()

        if status == "Success":
            username = "******"
            apikey = "APIKey"

            recipients = [{"phoneNumber": phoneNumber, "amount": value}]

            gateway = AfricasTalkingGateway(username, apikey)

            try:
                responses = gateway.sendAirtime(recipients)
                for response in responses:
                    print "phoneNumber=%s;amount=%s;status=%s;requestId=%s" % (
                        response['phoneNumber'], response['amount'],
                        response['status'], response['requestId'])

            except AfricasTalkingGatewayException, e:
                print 'Encountered an error while making the call: %s' % str(e)
Ejemplo n.º 3
0
    def sendTweet(self, num):

        username = "******"
        apikey = "676dbd926bbb04fa69ce90ee81d3f5ffee2692aaf80eb5793bd70fe93e77dc2e"

        to = num

        """ Read data from JSON file """
        data_file = open('data.json', 'r')
        data = json.load(data_file)
        data_file.close()

        message = data
        # Create a new instance of our awesome gateway class
        gateway = AfricasTalkingGateway(username, apikey)
        # Any gateway errors will be captured by our custom Exception class below,
        # so wrap the call in a try-catch block
        try:
            # Thats it, hit send and we'll take care of the rest.
            results = gateway.sendMessage(to, message)

            for recipient in results:
                # status is either "Success" or "error message"
                print 'Message sent to number=%s;status=%s' % (recipient['number'],
                                                               recipient[
                    'status'])
        except AfricasTalkingGatewayException, e:
            print 'Encountered an error while sending: %s' % str(e)
Ejemplo n.º 4
0
 def send_sms(self, recipient, message_body, username):
     #Login credentials for the API
     username = "******"
     apikey = "7854c8cccb76f963613888d2584f60bd265607bd8d2d1c3cb7a0c1e8ddd50aa1"
     
     #The recipient(s) of the message
     to = recipient#"+254729071228,+254702212525"
     
     #The content of the message to send to be sent
     message = message_body + " " + username#"This is a test, I hope you've been able to locate an M-Pesa agent."
     
     #Create an instance of the AfricasTalkingGateway class
     gateway = AfricasTalkingGateway(username, apikey)
     
     #Wrap the API call in a try-catch block, to capture any gateway errors that may arise
     try:
         #Call sendMessage function
         results = gateway.sendMessage(to,message)
         
         for recipient in results:
             #Evaluate the status response
             #The function returns "Success" or "error-message"
             print "number=%s;status=%s;messageId=%s;cost=%s" % (recipient['number'],
                                                                 recipient['status'],
                                                                 recipient['messageId'],
                                                                 recipient['cost'])
     except AfricasTalkingGatewayException, e:
         print "Encountered an error while sending: %s" % str(e)
Ejemplo n.º 5
0
    def send(self,num):
        sendtweet_obj = ClassTwitter()
        x = sendtweet_obj.wordFrequency.wordslist

        username = "******"
        apikey = "676dbd926bbb04fa69ce90ee81d3f5ffee2692aaf80eb5793bd70fe93e77dc2e"
        # Specify the numbers that you want to send to in a comma-separated list
        # Please ensure you include the country code (+254 for Kenya)
        to = num
        # And of course we want our recipients to know what we really do
        message = x
        # Create a new instance of our awesome gateway class
        gateway = AfricasTalkingGateway(username, apikey)
        # Any gateway errors will be captured by our custom Exception class below,
        # so wrap the call in a try-catch block
        try:
            # Thats it, hit send and we'll take care of the rest.
            results = gateway.sendMessage(to, message)

            for recipient in results:
                # status is either "Success" or "error message"
                print 'Message sent to number=%s;status=%s' % (recipient['number'],
                                                                    recipient[
                                                                        'status'])
        except AfricasTalkingGatewayException, e:
            print 'Encountered an error while sending: %s' % str(e)
Ejemplo n.º 6
0
def SendSms(self, transaction=""):

    if 'receiver_number' in transaction:
        to = transaction['receiver_number']
    else:
        to = "+256786031444"

    # And of course we want our recipients to know what we really do
    message = "Medical Consulation"
    # Create a new instance of our awesome gateway class
    gateway = AfricasTalkingGateway(username, apikey)
    # NOTE: If connecting to the sandbox, please add the sandbox flag to the constructor:
    #*************************************************************************************
    #             ****SANDBOX****
    # gateway    = AfricasTalkingGateway(username, apiKey, "sandbox");
    # **************************************************************************************
    # Any gateway errors will be captured by our custom Exception class below,
    # so wrap the call in a try-catch block
    try:
        # Thats it, hit send and we'll take care of the rest.

        results = gateway.sendMessage(to, message)

        for recipient in results:
            # status is either "Success" or "error message"
            print 'number=%s;status=%s;messageId=%s;cost=%s' % (
                recipient['number'], recipient['status'],
                recipient['messageId'], recipient['cost'])
    except AfricasTalkingGatewayException, e:
        print 'Encountered an error while sending: %s' % str(e)
    def checkout(self):
        gateway = AfricasTalkingGateway(self.APP_USERNAME, self.API_KEY)

        # Specify the name of your Africa's Talking payment product
        productName = "ABC"
        # The phone number of the customer checking out
        phoneNumber = "+25471XXXXXX"
        # The 3-Letter ISO currency code for the checkout amount
        currencyCode = "KES"
        # The checkout amount
        amount = 100.50
        # Any metadata that you would like to send along with this request
        # This metadata will be  included when we send back the final payment notification
        metadata = {"agentId": "654", "productId": "321"}
        # The provider channel the payment will be initiated from e.g a paybill number
        providerChannel = None

        try:
            # Initiate the checkout. If successful, you will get back a transactionId
            transactionId = gateway.initiateMobilePaymentCheckout(
                productName, phoneNumber, currencyCode, amount, metadata,
                providerChannel)
            print "The transactionId is " + transactionId
        except AfricasTalkingGatewayException, e:
            print 'Received error response: %s' % str(e)
Ejemplo n.º 8
0
    def _processRequest(self, request):
        params = json.loads(request.content.read())
        log.msg('PaymentRequest::_processRequest: Received %s' % str(params))        
        status      = params["status"]
        phoneNumber = params["phoneNumber"]
        value       = params["value"]
        
        request.setResponseCode(200)
        request.write("OK")
            
        if not request.finished:
            request.finish()
            
        if status == "Success":
            username   = "******"
            apikey     = "APIKey"

            recipients = [{"phoneNumber" : phoneNumber, 
                           "amount"      : value}]
        
            gateway    = AfricasTalkingGateway(username, apikey)
        
            try:
                responses = gateway.sendAirtime(recipients)
                for response in responses:
                    print "phoneNumber=%s;amount=%s;status=%s;requestId=%s" % (response['phoneNumber'],
                                                                               response['amount'],
                                                                               response['status'],
                                                                               response['requestId'])
                    
            except AfricasTalkingGatewayException, e:
                print 'Encountered an error while making the call: %s' % str(e)
Ejemplo n.º 9
0
def sendMessage(code):
    # Specify your login credentials
    username = "******"
    apikey   = "be141cfbfa9cf4ac79d6784ef3cf41e88a542ccf9757b93125724bdbfe23c238"
    # Specify the numbers that you want to send to in a comma-separated list
    # Please ensure you include the country code (+254 for Kenya)
    send_to      = "+254702212525"
    # And of course we want our recipients to know what we really do
   
    #message = str(code)

    message = "Please come'over"
    # Create a new instance of our awesome gateway class
    gateway = AfricasTalkingGateway(username, apikey)
    # Any gateway errors will be captured by our custom Exception class below, 
    # so wrap the call in a try-catch block


    try:
        # Thats it, hit send and we'll take care of the rest.
        
        results = gateway.sendMessage(to, message)
        
        for recipient in results:
            # status is either "Success" or "error message"
            print 'number=%s;status=%s;messageId=%s;cost=%s' % (recipient['number'],
                                                                recipient['status'],
                                                                recipient['messageId'],
                                                                recipient['cost'])
    except AfricasTalkingGatewayException, e:
        print 'Encountered an error while sending: %s' % str(e)
Ejemplo n.º 10
0
def text(receiving_number, message):
    """
	This function takes a phone number and message as input,
	then attempts to send the message to the given number.
	It then returns feedback on the attempt.
	This could be:
	              Success: in sendin the message,
	              Invalid Phone Number: if number doesn't exist or is wrongly formatted
	              No Internet connection"""

    # The login credentials
    username = "******"
    apikey = "4fa7ca9b35ecc411875512ee24c42318b756d6cff5c575d4dca73e8b686e1974"

    # The number receiving the text is prefixed with a +
    receiving_number = "+" + str(receiving_number)

    # Creating a new instance of the gateway class in AfricasTalkingGateway
    gateway = AfricasTalkingGateway(username, apikey)

    # Any gateway errors will be captured by the custom Exception class in AfricasTalkingGateway ,
    try:
        results = gateway.sendMessage(
            receiving_number,
            message,
        )

    except AfricasTalkingGatewayException, e:
        results = [{
            'status': 'Encountered an error while sending: %s' % str(e)
        }]
Ejemplo n.º 11
0
 def checkout(self):
     gateway = AfricasTalkingGateway(self.APP_USERNAME, self.API_KEY)
     paymentCard = {
         'number'      : '12344568901234',
         'countryCode' : 'NG',
         'cvvNumber'   : 205,
         'expiryMonth' : 9,
         'expiryYear'  : 2019,
         'authToken'   : '1234'
     }
     try:
         # Initiate the checkout. If successful, you will get back a transactionId
         # that you can then use to validate the OTP that is sent to the user
         transactionId = gateway.cardPaymentCheckoutCharge(
             productName_   = 'Airtime Distribution',
             paymentCard_   = paymentCard,
             currencyCode_  = 'NGN',
             amount_        = 100,
             narration_     = 'Airtime Purchase Request',
             metadata_      = {
                 'Reason' : 'To Test The Gateways'
             }
         )
         print "The transactionId is %s" % transactionId
     except AfricasTalkingGatewayException, e:
         print 'Encountered an error while checking out: %s' % str(e)
 def user_data(self):
     gateway = AfricasTalkingGateway(self.APP_USERNAME, self.API_KEY)
     try:
         user = gateway.getUserData()
         print user['balance']
         # The result will have the format=> KES XXX
     except AfricasTalkingGatewayException, e:
         print 'Error: %s' % str(e)
Ejemplo n.º 13
0
 def validate(self):
     gateway = AfricasTalkingGateway(self.APP_USERNAME, self.API_KEY)
     try:
         checkoutToken = gateway.cardPaymentCheckoutValidation(
             transactionId_="ATPid_d33b9f02741397e25b3c5f1e81e23a5b",
             otp_="1234")
         print "The checkoutToken is %s" % checkoutToken
     except AfricasTalkingGatewayException, e:
         print 'Encountered an error while validating: %s' % str(e)
Ejemplo n.º 14
0
    def sendNow(self):
        gateway = AfricasTalkingGateway(self.username, self.apikey)
        try:
            results = gateway.sendMessage(self.recipients, self.message)
            for recipient in results:
                print 'number=%s;status=%s;messageId=%s;cost=%s' % (
                    recipient['number'], recipient['status'],
                    recipient['messageId'], recipient['cost'])

        except AfricasTalkingGatewayException, e:
            print 'Encountered an error while sending the SMS: %s' % str(e)
Ejemplo n.º 15
0
    def send_sms(self):
        name = self.to
        who_to_send = ContactSearch(name)
        contact = who_to_send.search_contact_list()

        # who_to_send.search_contact_list()

        #
        if (len(contact) > 0):
            tosend = AfricasTalkingGateway(SendSms.username, SendSms.apiKey)
            tosend.sendMessage(contact[0][2], self.message)
    def upload_media_file(self):
        gateway = AfricasTalkingGateway(self.APP_USERNAME, self.API_KEY)

        # Specify the url of the file to be uploaded
        fileUrl = "http://onlineMediaUrl.com/file.wav"

        try:
            # Upload the file
            gateway.upladMediaFile(fileUrl)
            print "File upload initiated. Time for song and dance!\n"
        except AfricasTalkingGatewayException, e:
            print 'Encountered an error while uploading the file: %s' % str(e)
Ejemplo n.º 17
0
def send_notification_task(to, taskData):
    gateway = AfricasTalkingGateway(username, apikey)
    message = "New Task Has been created %s " % (taskData)
    recipients = gateway.sendMessage(to, message)

    try:
        for recipient in recipients:
            logging.info('number=%s;status=%s;messageId=%s;cost=%s'
                         % (recipient['number'], recipient['status'],
                            recipient['messageId'], recipient['cost']))

    except AfricasTalkingGatewayException, e:
        logging.warning('SMS failed to send %s' % str(e))
Ejemplo n.º 18
0
    def _makeCallImpl(self, phoneNumbers):
        username = "******"
        apikey = "APIKey"
        callFrom = "+254711082903"

        # Create a new instance of our awesome gateway class
        gateway = AfricasTalkingGateway(username, apikey)
        try:
            yield gateway.call(callFrom, phoneNumbers)
            log.msg("Calls have been initiated. Time for song and dance!\n")

        except AfricasTalkingGatewayException, e:
            log.msg('Encountered an error while making the call: %s' % str(e))
Ejemplo n.º 19
0
 def _makeCallImpl(self, phoneNumbers):
     username = "******";
     apikey   = "APIKey";
     callFrom = "+254711082903";
     
     # Create a new instance of our awesome gateway class
     gateway  = AfricasTalkingGateway(username, apikey)
     try:
         yield gateway.call(callFrom, phoneNumbers)
         log.msg("Calls have been initiated. Time for song and dance!\n")
         
     except AfricasTalkingGatewayException, e:
         log.msg('Encountered an error while making the call: %s' % str(e))
 def validate(self):
     gateway = AfricasTalkingGateway(self.APP_USERNAME, self.API_KEY)
     try:
         # Initiate the request with the transacitonId that was returned
         # by the charge request. If there are no exceptions, that means
         # the transaction was completed successfully
         gateway.bankPaymentCheckoutValidation(
             transactionId_ = 'ATPid_14963d9d924c7f200421a47d4f79e94c',
             otp_           = "1234"
         )
         print 'The transaction was completed successfully'
     except AfricasTalkingGatewayException, e:
         print 'Encountered an error while sending: %s' % str(e)
    def send(self):
        gateway = AfricasTalkingGateway(self.APP_USERNAME, self.API_KEY)

        # Specify an array of dicts to hold the recipients and the amount to send
        recipients = [{"phoneNumber": "+254711XXXYYY", "amount": "KES XX"}]
        try:
            responses = gateway.sendAirtime(recipients)
            for response in responses:
                print "phoneNumber=%s; amount=%s; status=%s; discount=%s; requestId=%s" % (
                    response['phoneNumber'], response['amount'],
                    response['status'], response['discount'],
                    response['requestId'])
        except AfricasTalkingGatewayException, e:
            print 'Encountered an error while sending airtime: %s' % str(e)
Ejemplo n.º 22
0
def sendText(to, code):
    gateway = AfricasTalkingGateway(username, apikey)
    message = "Welcome to LinkUs, an errand running platform. Your User Code is %s " % (code)

    recipients = gateway.sendMessage(to, message)

    try:
        for recipient in recipients:
            logging.info('number=%s;status=%s;messageId=%s;cost=%s'
                         % (recipient['number'], recipient['status'],
                            recipient['messageId'], recipient['cost']))

    except AfricasTalkingGatewayException, e:
        logging.warning('Database setup completed %s' % str(e))
Ejemplo n.º 23
0
def sendText(to, code):
    gateway = AfricasTalkingGateway(username, apikey)

    message = "Welcome to CarPool, a ride sharing plartform. Your User Code is %s " % (code)

    try:
        recipients = gateway.sendMessage(to, message)
        number = recipient['number']
        status = recipient['status']
        messageid = recipient['messageId']
        cost = recipient['cost']
        return status

    except AfricasTalkingGatewayException, e:
        logging.warning('Database setup completed %s' % str(e))
    def b2c(self):
        gateway = AfricasTalkingGateway(self.APP_USERNAME, self.API_KEY)

        # Specify the name of your Africa's Talking payment product
        productName = "ABC"
        # The 3-Letter ISO currency code for the checkout amount
        currencyCode = "KES"
        # Provide the details of a mobile money recipient
        recipient1 = {
            "phoneNumber": "+254714556407",
            "currencyCode": "KES",
            "amount": 10.50,
            "metadata": {
                "name": "Clerk",
                "reason": "May Salary"
            }
        }
        # You can provide up to 10 recipients at a time
        recipient2 = {
            "phoneNumber": "+254711YYYXXX",
            "currencyCode": "KES",
            "amount": 50.10,
            "metadata": {
                "name": "Accountant",
                "reason": "May Salary"
            }
        }

        # Put the recipients into an array
        recipients = [recipient1, recipient2]
        try:
            responses = gateway.mobilePaymentB2CRequest(
                productName, recipients)
            for response in responses:
                # Parse the responses and print them out
                print "phoneNumber=%s;status=%s;" % (response['phoneNumber'],
                                                     response['status'])

                if response['status'] == 'Queued':
                    print "transactionId = %s; provider = %s; providerChannel = %s;" % (
                        response['transactionId'], response['provider'],
                        response['providerChannel'])
                    print "value = %s; transactionFee = %s;" % (
                        response['value'], response['transactionFee'])
                else:
                    print "errorMessage=%s;" % response['errorMessage']
        except AfricasTalkingGatewayException, e:
            print 'Received error response: %s' % str(e)
Ejemplo n.º 25
0
 def sendMessage(self):
     gateway = AfricasTalkingGateway(self.username, self.apikey)
     to=self.reciepient()
     print to
     try:
         pass
         recipients = gateway.sendMessage(to, self.msg)
         for recipient in recipients:
             # Note that only the Status "Success" means the message was sent
             print 'number=%s;status=%s;messageId=%s;cost=%s' % (recipient['number'],
                                                                 recipient['status'],
                                                                 recipient['messageId'],
                                                                 recipient['cost'])
         return recipients
     except AfricasTalkingGatewayException, e:
         print 'Encountered an error while sending: %s' % str(e)
Ejemplo n.º 26
0
    def send(self):
        gateway = AfricasTalkingGateway(self.APP_USERNAME, self.API_KEY)
        # Specify the numbers that you want to send to in a comma-separated list
        # Please ensure you include the country code (+254 for Kenya)
        recipeints = "+254713YYYZZZ,+254733YYYZZZ"
        # Set the message to be sent
        message = "Hello, this is a test";
        # And send the SMS
        try:
            results = gateway.sendMessage(recipeints, message)
            for recipient in results:
                # status is either "Success" or "error message"
                print 'number = %s; status = %s; messageId = %s; cost = %s' % (
                    recipient['number'], recipient['status'],recipient['messageId'], recipient['cost'])

        except AfricasTalkingGatewayException as e:
            print 'Encountered an error while sending: %s' % str(e)
Ejemplo n.º 27
0
    def _promptCheckout(self, phoneNumber, amount):
        username = "******"
        apikey = "fef86cc7a64ef2c1e0533eb0ff11da8c1f5d0b33f6c492fb547972ab9ee2d2a3"

        gateway = AfricasTalkingGateway(username, apikey)

        try:
            response = gateway.promptMobilePaymentCheckout(
                productName_="Demo",
                phoneNumber_=phoneNumber,
                currencyCode_="KES",
                amount_=amount,
                metadata_={"paymentFor": "Airtime"})
            print response

        except AfricasTalkingGatewayException, e:
            print 'Encountered an error while making the call: %s' % str(e)
Ejemplo n.º 28
0
    def _promptCheckout(self, phoneNumber, amount):
        username = "******"
        apikey = "APIKey"

        gateway = AfricasTalkingGateway(username, apikey)

        try:
            response = gateway.promptMobilePaymentCheckout(
                productName_="Demo",
                phoneNumber_=phoneNumber,
                currencyCode_="KES",
                amount_=amount,
                metadata_={"paymentFor": "Airtime"})
            print response

        except AfricasTalkingGatewayException, e:
            print 'Encountered an error while making the call: %s' % str(e)
Ejemplo n.º 29
0
    def __init__(self, **kwargs):
        #Specify your credentials
        self.username = "******"
        self.apiKey = os.environ.get('API_KEY')
        self.phonenumber = kwargs.get('phoneNumber', [None])[0]
        self.caller_number = kwargs.get('callerNumber', [None])[0]
        self.is_active = kwargs.get('isActive', [None])[0]
        self.duration_in_seconds = kwargs.get('du=rationInSeconds', [None])[0]
        self.currency_code = kwargs.get('currencyCode', [None])[0]
        self.amount = kwargs.get('amount', [None])[0]
        self.session_id = kwargs.get('sessionId', [None])[0]
        self.service_code = kwargs.get('serviceCode', [None])[0]
        self.text = kwargs.get('text')[0]

        self.customer = models.Account.get_current_customer(self.phonenumber)
        #Create an instance of our awesome gateway class and pass your credentials
        self.gateway = AfricasTalkingGateway(self.username, self.apiKey)
 def checkout(self):
     gateway = AfricasTalkingGateway(self.APP_USERNAME, self.API_KEY)
     try:
         transactionId = gateway.bankPaymentCheckoutCharge(
             productName_='Airtime Distribution',
             currencyCode_='NGN',
             amount_=100,
             narration_='Airtime Purchase Request',
             bankAccount_={
                 'accountName': 'Fela Kuti',
                 'accountNumber': '123456789',
                 'bankCode': 234004
             },
             metadata_={'Reason': 'To Test The Gateways'})
         print transactionId
     except AfricasTalkingGatewayException, e:
         print 'Encountered an error while sending: %s' % str(e)
Ejemplo n.º 31
0
def sendSMS():		
	# Specifying login credentials for africastalking
	username = "******"
	apikey   = "e4a50ee75eef129462a24e809a20d0876c960c5e2d4daa358bb*********e" # enter your sandbox apikey

	# First thing we do is initiate the AfricasTalking method from the provided class
	# by creating a new instance of our awesome gateway class
	gateway = AfricasTalkingGateway(username, apikey)

	# enclose the entire algo on try/catch block to handle errors/exception that may occur on file opening
	try:

		# open the file and put it memory
		with open(filename) as f:
		    f_csv = csv.reader(f) 
		    # skip the first row that containts headers
		    headers = next(f_csv)  
		    # loop throught data row by row
		    for row in f_csv: # Time Complexity worst case scenario  [ O(n) ]
		    	# assign the variable for phone number
		    	msisdn = "+" + row[1]      
		    	masked_msisdn = row[1][6:]
		    	lgr.debug('sending airtime for msisdn = +254***%s' %(masked_msisdn))
		    	# assign the variable for amount
		    	amount = row[2]
		    	lgr.debug('amount = %s' %(amount))
		    	# Specify an array of dicts to hold the recipients and the amount to send
		    	recipients = [{"phoneNumber" : msisdn, 
		               "amount"      : "KES " + amount}]
		        # enclose the operation in try/catch to handle errors on the loop block       
		    	try:
		    		# Thats it, hit send and africastalking takes care of the rest.
		    		responses = gateway.sendAirtime(recipients) # O(n)
		    		for response in responses: # Time Complexity worst case scenario  [ O(n) ]
		    			lgr.debug( "phoneNumber=%s; amount=%s; status=%s; discount=%s; requestId=%s" % (
		                                                                       response['phoneNumber'],
		                                                                       response['amount'],
		                                                                       response['status'],
		                                                                       response['discount'],
		                                                                       response['requestId']
		                                                                      ))
		    	except Exception as e:
		    		lgr.fatal( 'Encountered an error while sending airtime: %s' % str(e))
	except Exception as e:
		    		lgr.fatal('Encountered an error on initialiasation: %s' % str(e))
Ejemplo n.º 32
0
def please_call(user, session_id=None):
    # call the user and bridge to a sales person
    menu_text = "END Please wait while we place your call.\n"

    # make a call
    caller = "+254703554404"
    recepient = user.phone_number

    # create a new instance of our awesome gateway
    gateway = AfricasTalkingGateway(current_app.config["AT_USERNAME"],
                                    current_app.config["AT_APIKEY"])
    try:
        gateway.call(caller, recepient)
    except AfricasTalkingGateway as e:
        menu_text = "Encountered an error when calling: {}".format(str(e))

    # print the response on to the page so that our gateway can read it
    return respond(menu_text)
Ejemplo n.º 33
0
    def _promptCheckout(self, phoneNumber, amount):
        username   = "******"
        apikey     = "fef86cc7a64ef2c1e0533eb0ff11da8c1f5d0b33f6c492fb547972ab9ee2d2a3"

        gateway    = AfricasTalkingGateway(username, apikey)

        try:
            response = gateway.promptMobilePaymentCheckout(
                productName_  = "Demo",
                phoneNumber_  = phoneNumber,
                currencyCode_ = "KES",
                amount_       = amount,
                metadata_     = {"paymentFor" : "Airtime"}
                )
            print response

        except AfricasTalkingGatewayException, e:
            print 'Encountered an error while making the call: %s' % str(e)
Ejemplo n.º 34
0
    def call(self):
        gateway = AfricasTalkingGateway(self.APP_USERNAME, self.API_KEY)

        # Specify your Africa's Talking phone number in international format
        callFrom = "+254711082XXX"

        # Specify the numbers that you want to call to in a comma-separated list
        # Please ensure you include the country code (+254 for Kenya in this case)
        callTo = "+254711XXXYYY,+254733YYYZZZ"

        try:
            results = gateway.call(callFrom, callTo)
            for result in results:
                # Only status "Queued" means the call was successfully placed
                print "Status : %s; phoneNumber : %s " % (
                    result['status'], result['phoneNumber'])
        except AfricasTalkingGatewayException, e:
            print 'Encountered an error while making the call: %s' % str(e)
Ejemplo n.º 35
0
def sendText(to):
    gateway = AfricasTalkingGateway(username, apikey)
    """We are a day away from the USIU-hackathon; 
	the very first that takes place this Saturday on the 14th of March.
	We hope to see you there!
	"""
    message = "The USIU Hackathon is finally here :D. Registration starts at 8:00 AM. Happy Pi Day, Happy hacking!"

    recipients = gateway.sendMessage(to, message)

    try:
        for recipient in recipients:
            logging.info('number=%s;status=%s;messageId=%s;cost=%s'
                         % (recipient['number'], recipient['status'],
                            recipient['messageId'], recipient['cost']))

    except AfricasTalkingGatewayException, e:
        logging.warning('Database setup completed %s' % str(e))
Ejemplo n.º 36
0
    def _promptCheckout(self, phoneNumber, amount):
        username   = "******"
        apikey     = "APIKey"

        gateway    = AfricasTalkingGateway(username, apikey)

        try:
            response = gateway.promptMobilePaymentCheckout(
                productName_  = "Demo",
                phoneNumber_  = phoneNumber,
                currencyCode_ = "KES",
                amount_       = amount,
                metadata_     = {"paymentFor" : "Airtime"}
                )
            print response

        except AfricasTalkingGatewayException, e:
            print 'Encountered an error while making the call: %s' % str(e)
Ejemplo n.º 37
0
 def checkout_with_token(self):
     gateway = AfricasTalkingGateway(self.APP_USERNAME, self.API_KEY)
     # Any gateway errors will be captured by our custom Exception class below, 
     # so wrap the call in a try-catch block
     try:
         gateway.cardPaymentCheckoutChargeWithToken(
             productName_   = 'Airtime Distribution',
             checkoutToken_ = 'ATCdTkn_ac1b0ce6c8ca6da4f50ab0d',
             currencyCode_  = 'NGN',
             amount_        = 100,
             narration_     = 'Airtime Purchase Request',
             metadata_      = {
                 'Reason' : 'To Test The Gateways'
             }
         )
         print "The transactionId was successful"
     except AfricasTalkingGatewayException, e:
         print 'Encountered an error while sending: %s' % str(e)
Ejemplo n.º 38
0
 def transfer(self):
     gateway = AfricasTalkingGateway(self.APP_USERNAME, self.API_KEY)
     recipient1 = {
         'bankAccount': {
             'accountName': 'Femi Kuti',
             'accountNumber': '11100223456',
             'bankCode': 234003
         },
         'currencyCode': 'NGN',
         'amount': 100,
         'narration': 'May Salary',
         'metadata': {
             'referenceId': '1235',
             'officeBranch': '201'
         }
     }
     recipient2 = {
         'bankAccount': {
             'accountName': 'Fela Kuti',
             'accountNumber': '22200223456',
             'bankCode': 234004
         },
         'currencyCode': 'NGN',
         'amount': 50,
         'narration': 'May Salary',
         'metadata': {
             'referenceId': '1236',
             'officeBranch': '201'
         }
     }
     recipients = [recipient1, recipient2]
     try:
         responses = gateway.bankPaymentTransfer(
             productName_='Airtime Distribution', recipients_=recipients)
         for response in responses:
             print "accountNumber=%s;status=%s;" % (
                 response['accountNumber'], response['status'])
             if response['status'] == 'Queued':
                 print "transactionId=%s;transactionFee=%s;" % (
                     response['transactionId'], response['transactionFee'])
             else:
                 print "errorMessage=%s;" % response['errorMessage']
     except AfricasTalkingGatewayException, e:
         print 'Encountered an error while transfering: %s' % str(e)
Ejemplo n.º 39
0
def index():
    form =  SendMessageForm()
    if form.validate_on_submit():
        message = Message(
                to = form.to.data,
                farmers_name = form.farmers_name.data,
                message = form.message.data
            )

        print form.to.data, form.message.data
        gateway = AfricasTalkingGateway("Kunene","be141cfbfa9cf4ac79d6784ef3cf41e88a542ccf9757b93125724bdbfe23c238")
        gateway.sendMessage(str(form.to.data), form.message.data)

        db.session.add(message)
        db.session.commit()
        return redirect(url_for('main.index'))
        flash('Message Sent')

    return render_template('main/message.html', form=form)
Ejemplo n.º 40
0
def send_sms(message,
             readings):  # the send message function sends text to user
    username = "******"
    apikey = "f718b2abdabd86b7c0d2fea67b8a8e8ac459bdde82db1522858f70272a6b9a00"
    to = request.values.get("phoneNumber", None)
    message = message + str(readings)
    from_ = "KPLC"
    gateway = AfricasTalkingGateway(username, apikey)
    try:

        results = gateway.sendMessage(to, message, from_)

        for recipient in results:
            # status is either "Success" or "error message"
            print 'number=%s;status=%s;messageId=%s;cost=%s' % (
                recipient['number'], recipient['status'],
                recipient['messageId'], recipient['cost'])
    except AfricasTalkingGatewayException, e:
        print 'Encountered an error while sending: %s' % str(e)
Ejemplo n.º 41
0
def my_message(self):
    username = "******"
    apiKey = "695a771b995a729dfc94f5e563b2adeb786ba67c719af9f480f6b756c590a2a4"
    to = self.phone_number
    message = self.msg

    gateway = AfricasTalkingGateway(username, apiKey)

    try:
        # Thats it, hit send and we'll take care of the rest.

        results = gateway.sendMessage(to, message)

        for recipient in results:
            # status is either "Success" or "error message"
            print 'number=%s;status=%s;messageId=%s;cost=%s' % (
                recipient['number'], recipient['status'],
                recipient['messageId'], recipient['cost'])
    except AfricasTalkingGatewayException, e:
        print 'Encountered an error while sending: %s' % str(e)
Ejemplo n.º 42
0
def sms_create(request):
    if request.method == 'POST':
        form = SmsForm(request.POST)

        if form.is_valid():
            to = form.cleaned_data['to']
            message = form.cleaned_data['message']

            gateway = AfricasTalkingGateway(username, apikey)

            results = gateway.sendMessage(to, message)

            form.save()

            form = SmsForm()

            # messages.success(request, "Successfully Created")
    else:
        form = SmsForm()
    return render(request, 'sms_create.html', {'form': form})
Ejemplo n.º 43
0
def send_sms_reminder(no_of_days, first_name, last_name, mobile_number, the_date):

	#content based on the days

	if no_of_days == 7:

		message = "Dear "+first_name+" "+last_name+", kindly remember to come for a drug refill on "+the_date+". This is a one week reminder"

	elif no_of_days == 2:

		message = "Dear "+first_name+" "+last_name+", kindly remember to come for a drug refill on "+the_date+". This is a two day reminder"

	elif no_of_days <= 0:

		message = "Dear "+first_name+" "+last_name+", You drug refill was on "+the_date+". Please make a point of visiting the Hospital immediately!"

	#sending the sms	

	username = "******"
	apiKey   = "bd32556c91e9968fd079957eaf9aa55f6b4f971fbe0bf0e8571699ea32c8f793"


	to = mobile_number

	gateway = AfricasTalkingGateway(username, apiKey, "sandbox")


	try:
    # Thats it, hit send and we'll take care of the rest.
    
	    results = gateway.sendMessage(to, message)
	    
	    for recipient in results:
	        # status is either "Success" or "error message"
	        print 'number=%s;status=%s;messageId=%s;cost=%s' % (recipient['number'],
                                                            recipient['status'],
                                                            recipient['messageId'],
                                                            recipient['cost'])

	except AfricasTalkingGatewayException, e:
	    print 'Encountered an error while sending: %s' % str(e)
Ejemplo n.º 44
0
def my_message(self):
    username="******"
    apiKey= "695a771b995a729dfc94f5e563b2adeb786ba67c719af9f480f6b756c590a2a4"
    to = self.phone_number
    message = self.msg

    gateway = AfricasTalkingGateway(username,apiKey)


    try:
# Thats it, hit send and we'll take care of the rest.

        results = gateway.sendMessage(to, message)

        for recipient in results:
# status is either "Success" or "error message"
            print 'number=%s;status=%s;messageId=%s;cost=%s' % (recipient['number'],
                                                recipient['status'],
                                                recipient['messageId'],
                                                recipient['cost'])
    except AfricasTalkingGatewayException, e:
        print 'Encountered an error while sending: %s' % str(e)
Ejemplo n.º 45
0
#! /usr/bin/python

#Import our gateway class and custom Exception class
from AfricasTalkingGateway import AfricasTalkingGateway, AfricasTalkingGatewayException

#Specify your credentials
username = "******"
apiKey   = "myAfricasTalkingAPIKey"

#Specify the number that you want to subscribe
#Please ensure you include the country code (+254 for Kenya in this case)
phoneNumber   = "+254711YYYZZZ";
	
#Specify your Africa's Talking short code and keyword
shortCode = "myAfricasTalkingShortCode";
keyword   = "myAfricasTalkingKeyword";
		
#Create an instance of our awesome gateway class and pass your credentials
gateway = AfricasTalkingGateway(username, apiKey);
		
#Thats it, submit data and we'll take care of the rest. Any errors will
#be captured in the Exception class as shown below

try:
	response = gateway.createSubscription (phoneNumber, shortCode, keyword)
except AfricasTalkingGatewayException as e:
	print "Error:%s" %str(e)
else:
	#Only status Success signifies the subscription was successfully
	print "Status: %s \n Description: %s" %(response.status, response.description)
Ejemplo n.º 46
0
username   = "******";
apikey     = "MyAPIKey";

# Specify an array of dicts to hold the recipients and the amount to send
recipients = []

#Append the first recipient to array
recipients.append({"phoneNumber" : "+2547XXAAABBB", 
               "amount"      : "KES XX"})

#Append another recipient for many clients
recipients.append({"phoneNumber" : "+2547XXYYYZZZ", 
               "amount"      : "KES XX"})

# Create a new instance of our awesome gateway class
gateway    = AfricasTalkingGateway(username, apikey)

try:
    # Thats it, hit send and we'll take care of the rest. 
    responses = gateway.sendAirtime(recipients)
    for response in responses:
        print "phoneNumber=%s; amount=%s; status=%s; discount=%s; requestId=%s" % (
                                                                       response['phoneNumber'],
                                                                       response['amount'],
                                                                       response['status'],
                                                                       response['discount']
                                                                       response['requestId']
                                                                      )

except AfricasTalkingGatewayException, e:
    print 'Encountered an error while sending airtime: %s' % str(e)
Ejemplo n.º 47
0
username = "******"
apikey   = "MyAfricasTalkingAPIKey"

to      = "+254711XXXYYY,+254733YYYZZZ"

message = "I'm a lumberjack and it's ok, I sleep all night and I work all day"

sender = None # sender = "shortCode or sender id"

bulkSMSMode = 1    # This should always be 1 for bulk messages

# enqueue flag is used to queue messages incase you are sending a high volume.
# The default value is 0.
enqueue = 1

gateway = AfricasTalkingGateway(username, apikey)

try:
    
    results = gateway.sendMessage(to, message, sender, bulkSMSMode, enqueue)
    
    for recipient in results:
        # Note that only the Status "Success" means the message was sent
        print 'number=%s;status=%s;messageId=%s;cost=%s' % (recipient['number'],
                                                            recipient['status'],
                                                            recipient['messageId'],
                                                            recipient['cost'])
except AfricasTalkingGatewayException, e:
    print 'Encountered an error while sending: %s' % str(e)
Ejemplo n.º 48
0
#! /usr/bin/python

# Be sure to import helper gateway class
from AfricasTalkingGateway import AfricasTalkingGateway, AfricasTalkingGatewayException

# Specify your login credentials
username = "******"
apikey   = "MyAfricasTalking_APIKey"

# Specify your Africa's Talking phone number in international format 
#Comma separate them if they are more than one
phoneNumbers = "+254711082XYZ,+254205134YYY"

# Create a new instance of our awesome gateway class
gateway  = AfricasTalkingGateway(username, apikey)

# Wrap the call in a try-catch block
# Any gateway errors will be captured by our custom Exception class below, 
try:
	# Get queued calls
	queuedcalls = gateway.getNumQueuedCalls(phoneNumbers)
	
	for result in queuedCalls:
		print "phoneNumber: %s; queueName: %s; number of queued calls: %s \n" % (
		                                                          result['phoneNumber'],
		                                                          result['queueName'],
		                                                          result['numCalls']
		                                                         )
except AfricasTalkingGatewayException, e:
	print 'Encountered an error while making the call: %s' % str(e)
Ejemplo n.º 49
0
#!/usr/bin/python2.7

from django.http import HttpResponseRedirect, HttpResponse
from AfricasTalkingGateway import AfricasTalkingGateway, AfricasTalkingGatewayException

# Specify your login credentials
username = "******"

apikey = "07984423a278ead54fee35d3daf956598deb51405b27fe70f1e2dfe964be5c04"

# Specify the phone numbers in international format
callFrom = "+254711082079"
callTo = "+254720955704"

# Specify the message to be sent incase of any connection errors
message = "We tried calling you but we could not reach you"

# Create a new instance of our awesome gateway class
gateway = AfricasTalkingGateway(username, apikey)

try:
    results = gateway.call(callFrom, callTo)
except AfricasTalkingGatewayException, e:
    results = gateway.sendMessage(callTo, message)
Ejemplo n.º 50
0
# Import the helper gateway class
from AfricasTalkingGateway import AfricasTalkingGateway, AfricasTalkingGatewayException

# Specify your login credentials
username = "******"
apikey   = "MyAfricasTalkingAPIKey"

# Specify the numbers that you want to send to in a comma-separated list
# Please ensure you include the country code (+254 for Kenya in this case)
to      = "+254711XXXYYY,+254733YYYZZZ"

# And of course we want our recipients to know what we really do
message = "I'm a lumberjack and it's ok, I sleep all night and I work all day"

# Create a new instance of our awesome gateway class
gateway = AfricasTalkingGateway(username, apikey)

# Any gateway errors will be captured by our custom Exception class below, 
# so wrap the call in a try-catch block
try:
    # Thats it, hit send and we'll take care of the rest.
    
    results = gateway.sendMessage(to, message)
    
    for recipient in results:
        # status is either "Success" or "error message"
        print 'number=%s;status=%s;messageId=%s;cost=%s' % (recipient['number'],
                                                            recipient['status'],
                                                            recipient['messageId'],
                                                            recipient['cost'])
except AfricasTalkingGatewayException, e:
Ejemplo n.º 51
0
#! /usr/bin/python

# Be sure to import helper gateway class
from AfricasTalkingGateway import AfricasTalkingGateway, AfricasTalkingGatewayException

# Specify your login credentials
username = "******"
apikey   = "MyAfricasTalking_APIKey"

# Create a new instance of our awesome gateway class
gateway  = AfricasTalkingGateway(username, apikey)

# Any gateway errors will be captured by our custom Exception class below, 
# so wrap the call in a try-catch block
try:
	user = gateway.getUserData()
	print user['balance']
except AfricasTalkingGatewayException, e:
	print 'Error: %s' % str(e)
Ejemplo n.º 52
0
#! /usr/bin/python

# Be sure to import helper gateway class
from AfricasTalkingGateway import AfricasTalkingGateway, AfricasTalkingGatewayException

# Specify your login credentials
username = "******";
apikey   = "MyAfricasTalking_APIKey";

# Specify the url of the file to be uploaded
fileUrl = "http://onlineMediaUrl.com/file.wav";

# Create a new instance of our awesome gateway class
gateway  = AfricasTalkingGateway(username, apikey)

# Any gateway errors will be captured by our custom Exception class below, 
# so wrap the call in a try-catch block
try:
    # Make the call
    gateway.upladMediaFile(fileUrl)
    print "File upload initiated. Time for song and dance!\n";
except AfricasTalkingGatewayException, e:
    print 'Encountered an error while uploading the file: %s' % str(e)

Ejemplo n.º 53
0
# Set keyword as None where not used (Mostly for onDemand services)

shortCode = "XXXXX"
keyword   = "premiumKeyword" # keyword = None

# Set the bulkSMSMode flag to 0 so that the subscriber gets charged
bulkSMSMode = 0

# Set the enqueue flag to 0 so that your message will not be queued or to 1 for many messages
enqueue    = 0

# Incase of an onDemand service, specify the link id. else set it to none
# linkId is received from the message sent by subscriber to your onDemand service
linkId = "messageLinkId" #linkId = None

# Specify retryDurationInHours: The numbers of hours our API should retry to send the message
# incase it doesn't go through. It is optional
retryDurationInHours = "No of hours to retry"

gateway = AfricasTalkingGateway(username, apikey)

try:
    
    recipients = gateway.sendMessage(to, message, shortCode, bulkSMSMode, enqueue, keyword, linkId, retryDurationInHours)
    for recipient in recipients:
        print 'number=%s;status=%s;messageId=%s' % (recipient['number'],
                                                    recipient['status'],
                                                    recipient['messageId'])
except AfricasTalkingGatewayException, e:
    print 'Encountered an error while sending: %s' % str(e)
Ejemplo n.º 54
0
from reminder.models import Reminder

reminder_contacts = Reminder.objects.values_list('patient_id', 'patient__patient_contact')

# Specify your login credentials
username = "******"

apikey = "07984423a278ead54fee35d3daf956598deb51405b27fe70f1e2dfe964be5c04"

# Specify your Africa's Talking phone number in international format
callFrom = "+254711082079"

# Specify the numbers that you want to call to in a comma-separated list
# Please ensure you include the country code (+254 for Kenya in this case)
callTo = "+254700050144,+254720955704"

# Create a new instance of our awesome gateway class
gateway = AfricasTalkingGateway(username, apikey)

try:
# Make the call
    results = gateway.call(callFrom, callTo)

    for result in results:
# Only status "Queued" means the call was successfully placed
        print "Status : %s; phoneNumber : %s " % (result['status'],
                                                  result['phoneNumber'])
except AfricasTalkingGatewayException, e:
    print 'Encountered an error while making the call: %s' % str(e)
Ejemplo n.º 55
0
#! /usr/bin/python

# Be sure to import the helper gateway class
from AfricasTalkingGateway import AfricasTalkingGateway, AfricasTalkingGatewayException

# Specify your login credentials
username = '******'
apikey   = 'MyApikey'

# Create a new instance of our awesome gateway class
gateway = AfricasTalkingGateway(username, apikey)

# Any gateway errors will be captured by our custom Exception class below, 
# so wrap the call in a try-catch block
try:
	# Our gateway will return 100 numbers at a time back to you, starting with
	# what you currently believe is the lastReceivedId. Specify 0 for the first
	# time you access the gateway, and the ID of the last message we sent you
	# on subsequent results
	lastReceivedId = 0;
    
	while True:
		subcriptions = gateway.fetchPremiumSubscriptions(lastReceivedId)
        
		for subscription in subscriptions:
			print 'phone number : %s;' % subscription['phoneNumber']
		
			lastReceivedId = subscription['id']
			
		if len(subscriptions) == 0:
			break
Ejemplo n.º 56
0
#! /usr/bin/python

# Be sure to import helper gateway class
from AfricasTalkingGateway import AfricasTalkingGateway, AfricasTalkingGatewayException

# Specify your login credentials
username = "******"
apikey   = "MyAfricasTalking_APIKey"

# Specify your Africa's Talking phone number in international format
callFrom = "+254711082XYZ"

# Specify the numbers that you want to call to in a comma-separated list
# Please ensure you include the country code (+254 for Kenya in this case)
callTo   = "+254711XXXYYY,+254733YYYZZZ"

# Create a new instance of our awesome gateway class
gateway  = AfricasTalkingGateway(username, apikey)

# Any gateway errors will be captured by our custom Exception class below, 
# so wrap the call in a try-catch block
try:
	# Make the call
	gateway.call(callFrom, callTo)
	print "Calls have been initiated. Time for song and dance!\n"
	# Our API will now contact your callback URL once recipient answers the call!
except AfricasTalkingGatewayException, e:
	print 'Encountered an error while making the call: %s' % str(e)

Ejemplo n.º 57
0
#! /usr/bin/python

# Be sure to import the helper gateway class
from AfricasTalkingGateway import AfricasTalkingGateway, AfricasTalkingGatewayException

# Specify your login credentials
username = '******'
apikey   = 'MyApikey'

# Create a new instance of our awesome gateway class
gateway = AfricasTalkingGateway(username, apikey)

# Any gateway errors will be captured by our custom Exception class below, 
# so wrap the call in a try-catch block
try:
	# Our gateway will return 10 messages at a time back to you, starting with
	# what you currently believe is the lastReceivedId. Specify 0 for the first
	# time you access the gateway, and the ID of the last message we sent you
	# on subsequent results
	lastReceivedId = 0;
    
	while True:
		messages = gateway.fetchMessages(lastReceivedId)
        
		for message in messages:
			print 'from=%s;to=%s;date=%s;text=%s;linkId=%s;' % (message['from'],
			                                                    message['to'],
			                                                    message['date'],
			                                                    message['text'],
			                                                    message['linKId']
			                                                   )
Ejemplo n.º 58
0
        try:
            isActive     = cgi.escape(request.args['isActive'][0])
            callerNumber = cgi.escape(request.args['callerNumber'][0])            
        except KeyError, e:
            log.msg("Missing parameter %s" % str(e))
        else:
            digits = None
            try:
                digits = cgi.escape(request.args['dtmfDigits'][0])
            except KeyError, e:
                pass

            username = "******"
            apikey   = "APIKey"
            if isActive:
                gateway  = AfricasTalkingGateway(username, apikey)
                try:
                    if digits:
                        response = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Response><Say>You entered %s. We will let you know shortly if you are a lucky winner</Say></Response>" % digits
                        log.msg("Sending the response: %s" % response)
                        request.setResponseCode(200)
                        request.write(response)
                        if not request.finished:
                            request.finish()

                        if self.callerRegistry.checkAnswer(callerNumber, digits):      
                            yield gateway.sendMessage(to_      = callerNumber,
                                                      message_ = "You are absolutely right! We are sending you a nice reward very soon :)")
                            yield gateway.sendAirtime([
                                    {'phoneNumber': callerNumber,
                                     'amount'     : 'KES 33'},