def main(): # Initializing SDKs for Africas Talking and Open Weather Map username = "" # Account username api_key_at = "" # Africa's Talking API Key api_key_owm = "" # OWM Api Key africastalking.initialize(username, api_key_at) owm = pyowm.OWM(api_key_owm) date_format = 'iso' # Defining input arguments parser = argparse.ArgumentParser() parser.add_argument('location', help='City/Village name or nearest landmark') parser.add_argument('recipients', nargs='*', help='phone number(s) of recipient(s)') args = parser.parse_args() location = args.location recipients = args.recipients # Build functionality to set latest reported contact as sms recipient (currently user input) # recipient = str(export_report.get_latest_contact()) latitude, longitude = locations.get_coords(location) present_weather_info = get_present_weather_info(owm, latitude, longitude, location) forecast_weather_info = get_forecast_weather_info(owm, latitude, longitude, date_format, location) short_text, long_text = (generate_sms(present_weather_info, forecast_weather_info, location)) pest_report = "Hello from Wikilimo! \nA pest '" + \ str(export_report.get_latest_pest(export_report.sheet)) +\ "' has been recently reported nearby. Please take the necessary precautions." send_sms(short_text, recipients) send_sms(long_text, recipients) send_sms(pest_report, recipients)
def at(request): if request.method == 'POST': #get chargephone = request.POST.get('chargephone') amount = request.POST.get('amount') phone = request.POST.get('phone') #instatiate gateway api_key = "db76dc5eb626a86afb261dc1eb729a5bd6c4c1ea04b5cec23162ae36f24bf377" username = '******' africastalking.initialize(username=username, api_key=api_key) productName = "0zz" # The phone number of the customer checking out phoneNumber = chargephone # The 3-Letter ISO currency code for the checkout amount currencyCode = "UGX" metadata = {"agentId": "654", "productId": "321"} payment = africastalking.Payment res = payment.mobile_checkout(product_name=productName, phone_number=chargephone, currency_code=currencyCode, amount=amount, metadata=metadata) if (res.get('status') == 'PendingConfirmation'): pay(phone, amount) stats = Athist(amount=amount, status="sent", destination=phone, source=chargephone) stats.save() res = print(stats) return redirect('mm_history') else: print('No money') pass return redirect('mm_history')
def getShortcode(request): # Initialize SDK if request.method == 'POST': try: username = "******" # use 'sandbox' for development in the test environment api_key = "652230d338f11fd49333722a8acba0161942b5b3efb880caf2fb21958e4fdde4" # use your sandbox app API key for development in the test environment africastalking.initialize(username, api_key) random_code = get_random_string(length=6, allowed_chars='123456789') phonenumber = request.POST.get("phone_number") # appKey = request.data.get("appSignature") new_phone_number = f"{254}{phonenumber[-9:]}" # print(new_phone_number) short_code = ShortCode.objects.create( phone_number=phonenumber, short_code=random_code, ) # Initialize a service e.g. SMS sms = africastalking.SMS # Use the service synchronously response = sms.send("<#> Your MASHKYS code is:" + random_code, ["+" + new_phone_number], "MASHKYS") context = { 'results': 'success', 'response': "We have text you pin for setting your password, if an account exists with the phonenumber you entered You should receive an SMS shortly. If you don't receive an email, please make sure you've entered the phonenumber you registered with " } # sweetify.success(request, title='Success' 'Check your phone for a code we have sent to your and key it into the number pad below. ', button='ok') except: print('NO INTERNET') context = {'results': 'error', 'response': "No Internet "} return JsonResponse(context, safe=False)
def query_transactions(): logger.info("tasks.query_transactions: Starting Execution") africastalking_username = os.environ['AFRICASTALKING_USERNAME'] africastalking_api_key = os.environ['AFRICASTALKING_API_KEY'] # Initialize the SDK africastalking.initialize(africastalking_username, africastalking_api_key) payment = africastalking.Payment # Set the name of your Africa's Talking payment product africastalking_product_name = os.environ['AFRICASTALKING_PRODUCT_NAME'] filters = { "category": "MobileC2B", "status": "Success", } response = None # Fetch the product transactions try: response = payment.product_transactions(africastalking_product_name, filters) logger.info("tasks.query_transactions: Response: {}".format( response['responses'])) return response['responses'] except Exception as e: logger.error("tasks.query_transactions: Received error response:%s" % str(e))
def getShortCodeSMS(request): phonenumber = request.data.get("phone_number") if Buyer.objects.filter(phone_number = phonenumber).exists(): context = { 'response': 'Already Registered' } return Response(context, status=status.HTTP_400_BAD_REQUEST) else: # Initialize SDK username = "******" # use 'sandbox' for development in the test environment api_key = "652230d338f11fd49333722a8acba0161942b5b3efb880caf2fb21958e4fdde4" # use your sandbox app API key for development in the test environment africastalking.initialize(username, api_key) random_code = get_random_string(length=6, allowed_chars='123456789') appKey = request.data.get("appSignature") new_phone_number = f"{254}{phonenumber[-9:]}" # print(random_code) # Initialize a service e.g. SMS sms = africastalking.SMS # Use the service synchronously response = sms.send("<#> Your MASHKYS code is:" + random_code + ":\n " + appKey , ["+"+new_phone_number], "MASHKYS") print(response) short_code = ShortCode.objects.create( phone_number = phonenumber, short_code = random_code, ) context = { 'response': 'success' } return Response(context, status=status.HTTP_200_OK)
def form_valid(self, form): changemaker = form.cleaned_data['changemaker'] message = form.cleaned_data['message'] obj = form.save(commit=False) obj.user = self.request.user africastalking.initialize(username, api_key) sms = africastalking.SMS recipients = [] for item in changemaker: mobile = str(item) if mobile[0:2] == "07": mobile = mobile.replace("07", "+2547", 1) elif mobile[0] == "7": mobile = mobile.replace("7", "+2547", 1) elif mobile[0:4] == "2547": mobile = mobile.replace("2547", "+2547", 1) else: mobile = mobile recipients.append(mobile) sms.send(message, recipients) obj.save() return HttpResponseRedirect('/sms/')
def get_at_account_balance(): username = os.getenv("AT_USERNAME") api_key = os.getenv("AT_API_KEY") balance = 0 africastalking.initialize(username, api_key) try: # Fetch the application data application = africastalking.Application user_data = application.fetch_application_data() balance_string = user_data['UserData']['balance'] if balance_string: # split, balance format is KES XX balance_list = balance_string.split(' ') balance = float(balance_list[1]) except Exception as e: current_app.logger.error(e, exc_info=True) balance = 0 return balance
def mpesa_checkout(data): username = config('AF_USERNAME') api_key = config('AF_KEY') sandname = config('SAND_USERNAME') sandkey = config('SAND_KEY') africastalking.initialize(sandname, sandkey) # africastalking.initialize(username, api_key) payment = africastalking.Payment try: res = payment.mobile_checkout(product_name=data['pn'], phone_number=data['phn'], currency_code=data['cc'], amount=data['am'], metadata={ 'agentId': data['md']['ad'], 'productId': data['md']['pd'] }) print("The transactionId is " + str(res)) return res except africastalking.Service.AfricasTalkingException as e: print("Received error response: %s" % str(e))
def phone(request): if request.method == 'POST': number = request.POST['numbari'] request.session['phonenumber'] = number print(request.session['phonenumber']) #initialize the sdk username = "******" api_key = "24475cdb3f486f244e38a12b3aca908044f81e9f3f1fbf305b809abee0a86aeb" africastalking.initialize(username, api_key) #recipients number1 = ("+" + number) recipients = [number1] #message generatedCode = my_random_string(6) request.session['generatedCode'] = generatedCode message = generatedCode # For example, D9E50C #initialize the service, in our case, SMS sms = africastalking.SMS #USE THE SERVICE def on_finish(error, response): if error is not None: raise error print(response) sms.send(message, recipients, callback=on_finish) return redirect('otp') return render(request, 'tutorial/login.html')
def sms(request): print('smsing') phones = [] event = Event.objects.all() for x in event: if x.user.profile.phone_number: numbers = x.user.profile.phone_number message = x.notes print(numbers) phones.append(numbers) # Initialize SDK username = "******" # use 'sandbox' for development in the test environment api_key = "18696560f647f921b072950f4ef9e5c24a76e583ec26b6ceb4f2ef6d34403daa" # use your sandbox app API key for development in the test environment africastalking.initialize(username, api_key) # Initialize a service e.g. SMS sms = africastalking.SMS # Use the service synchronously response = sms.send(message, phones) print(response) # Or use it asynchronously def on_finish(error, response): if error is not None: raise error print(response) # # sms.send("Hello Message!", ["+2547xxxxxx"], callback=on_finish) return redirect('home')
def sendsms(self, name): apikey = "983a36a35b591a83c382ebe9a1a33e7ee3a5e0e98981e6f5d47da8e87f176798" username = "******" # sender_id = "mysenderid" africastalking.initialize(username, apikey) message_recipient = ['+254705066102'] sms = africastalking.SMS currentTime = int(time.strftime('%H')) if currentTime < 12: greeting = "Goodmorning " elif currentTime > 12: greeting = "Good afternoon " elif currentTime > 18: greeting = "Good evening " smsfooter = " welcome home" authname = name smsheader = greeting smspayload = smsheader + (authname) + smsfooter #text to speech conversion file = "test1.mp3" #initialize tts, create mp3 and play tts = gTTS(smspayload, 'en') tts.save(file) os.system("mpg321 " + file) smsresponse = sms.send(smspayload, message_recipient) logging.debug(smsresponse)
def __init__(self): self.username = "******" self.api_key = "d14da11eaa567f7055f712b2336bf97bb59051d22f1fd83be042adda56d07584" # Initialize the SDK africastalking.initialize(self.username, self.api_key) # Get the SMS service self.sms = africastalking.SMS
def send_airtime(): form = SendAirtime() africastalking.initialize(username, apikey) airtime = africastalking.Airtime application = africastalking.Application if form.validate_on_submit(): to = form.to.data saved_tel = to.alias value = form.airtime_value.data try: airtime.send(to, value, currency_code=app.config['AT_CURRENCY_CODE']) save_airtime = AirtimeSent(amount_sent=value, sent_to=saved_tel) db.session.add(save_airtime) db.session.commit() mail_date = current_date() res = application.fetch_application_data() my_balance = res['UserData']['balance'] flash(f'You have successfully send airtime worth KShs: {value} to {to}! Your balance is {my_balance}', 'success') airtime_mail(value, saved_tel, mail_date, my_balance) except Exception as e: flash(f'Airtime transfer failed: {e}', 'danger') return render_template('send_airtime.html', form=form)
def send_alert(nextofkin_number): # Initialize SDK username = config("AFRICASTALKING_USERNAME") api_key = config("AFRICASTALKING_SECRET_KEY") africastalking.initialize(username, api_key) # Initialize a service e.g. SMS sms = africastalking.SMS # Use the service synchronously # response = sms.send("Wassup broskii", ["+254719158559"]) # print(response) # Or use it asynchronously def on_finish(error, response): if error is not None: raise error print(response) getTime = datetime.datetime.now() currentTime = getTime.strftime("%H:%M") receiver = current_user["next_of_kin_name"] driver = current_user["first_name"] message = f"Hello there {receiver}, driver {driver} has been reported to be asleep at exactly {currentTime}" sms.send( message, [nextofkin_number], callback=on_finish, )
def cheza_sms(recipient): username = os.getenv("AT_USERNAME") api_key = os.getenv("AT_API_KEY") africastalking.initialize(username, api_key) atsms = africastalking.SMS recipients = ["+{}".format(recipient)] message1 = "Who is the president of Kenya? " \ "A. Raila Odinga" \ "B. Uhuru Kenyatta" message2 = "which is the largest county in Kenya?" \ "A. Tana River" \ "B. Makueni" sender = os.getenv("AT_SHORTCODE") try: response = atsms.send(message1, recipients, sender) return jsonify(response) except Exception as e: return jsonify('Encountered an error while sending: %s' % str(e))
def send_receipt(message, customer): # Initialize SDK username = config('AF_USERNAME') api_key = config('AF_KEY') af.initialize(username, api_key) # Initialize a service e.g. SMS receipt = af.SMS # Use the service synchronously customers = [ "+" + customer, ] response = receipt.send(message, customers) print(response) # Or use it asynchronously def on_finish(error, response): if error is not None: raise error # print(response) return response
def notification(): # Initialize SDK username = "******" api_key = "1d988c1ab828a49631413ae985e9ee72d6533458d18cc3b9570033e398c261b0" africastalking.initialize(username, api_key) # Initialize a service sms = africastalking.SMS if request.method == 'POST': try: # fetch all records allRecords = Operators.fetch_all() # get the phone numbers(number.telephoneNo) for number in allRecords: # convert to a string newNumbers = str(number.telephoneNo) # add +254 to each number allNumbers = ['+254' + newNumbers] # send the message/Notification to all phone numbers for x in allNumbers: message = request.form['message'] # send the message response = sms.send(message, [x]) print(response) flash('Message sent successfully', 'success') except Exception as e: flash('Error! Unable to send message', 'danger') print(e) return redirect(url_for('dashboard'))
def bulk_pay(request): data = {} if request.method == "POST": #get file content csv_file = request.FILES["receiver"] #reason reason = request.POST.get("mm_reason") #read into file file_data = csv_file.read().decode("utf-8") #split at line end rowz = re.split('\n', file_data) #what I want recipients = [] for user in rowz[1:]: user_items = re.split(',', user) if len(user_items) > 1: recipient = {} recipient['name'] = user_items[0] recipient['phoneNumber'] = "+256" + user_items[1] recipient['currencyCode'] = "UGX" recipient['amount'] = user_items[2] recipient['reason'] = "SalaryPaymentWithWithdrawalChargePaid" recipient['metadata'] = {} recipients.append(recipient) #save history hist = Bulkpayhist(name=user_items[0], amount="UGX" + user_items[2], status="successful", destination="+256" + user_items[1]) hist.save() else: pass #send sand_key = "db76dc5eb626a86afb261dc1eb729a5bd6c4c1ea04b5cec23162ae36f24bf377" if len(recipients) <= 10: africastalking.initialize(username='******', api_key=sand_key) payment = africastalking.Payment res = payment.mobile_b2c(product_name='0zz', consumers=recipients) print(res) else: new_dict_list = [ recipients[i:i + 10] for i in range(0, len(recipients), 10) ] recipient = [] #send to each group for recipient in new_dict_list: africastalking.initialize(username='******', api_key=sand_key) payment = africastalking.Payment res = payment.mobile_b2c(product_name='0zz', consumers=recipient) #history return redirect('bulkpayhist') else: return render(request, "payments/bulk_pay.html")
def __init__(self): # Set your app credentials self.username = "******" self.api_key = "d9db994263bb40651311842a76b9935709989ddeceab55c0798de7809291d864" # Initialize the SDK africastalking.initialize(self.username, self.api_key) # Get the SMS service self.sms = africastalking.SMS
def __init__(self): # Set your app credentials self.username = "******" self.api_key = "API_KEY" # Initialize the SDK africastalking.initialize(self.username, self.api_key) # Get the SMS service self.sms = africastalking.SMS
def __init__(self): # Set your app credentials self.username = "******" self.api_key = "657d265600a307dac2e623fca122f9a71703e28eaa10175cd6815b136562cb3f" # Initialize the SDK africastalking.initialize(self.username, self.api_key) # Get the SMS service self.sms = africastalking.SMS
def __init__(self): # Set your app credentials self.username = "******" self.api_key = "d9135795e446b9b25430f33da3be70c79d868428898fdb7b356f9eb0cb06bcf4" # Initialize the SDK africastalking.initialize(self.username, self.api_key) # Get the voice service self.voice = africastalking.Voice
def get_balance(): africastalking.initialize(username, apikey) application = africastalking.Application results = application.fetch_application_data() credit_balance = results['UserData']['balance'] final_float = float(credit_balance.strip('KES ')) return dict(final_float=final_float)
def __init__(self): # Set your app credentials self.username = "******" self.api_key = "18696560f647f921b072950f4ef9e5c24a76e583ec26b6ceb4f2ef6d34403daa" # Initialize the SDK africastalking.initialize(self.username, self.api_key) # Get the SMS service self.sms = africastalking.SMS
def get_balance(): africastalking.initialize(username, apikey) application = africastalking.Application results = application.fetch_application_data() credit_balance = results['UserData']['balance'] final_float = float(credit_balance.strip('KES ')) return dict(final_float=final_float)
def __init__(self): super(SMSRequest, self).__init__() self.username = "******" self.api_key = "" africastalking.initialize(self.username, self.api_key) self.sms = africastalking.SMS self.clients = [] self.shortCode = ""
def __init__(self): # Set your app credentials self.username = "******" self.api_key = "7417c45fb32c32198da30d2773f2b557367c97239a7369d9df1d3442f898f0b6" # Initialize the SDK africastalking.initialize(self.username, self.api_key) # Get the SMS service self.sms = africastalking.SMS
def sms_create(request): if request.method == 'POST': form = SmsForm(request.user, request.POST) username = request.user.company.africastalking_username api_key = request.user.company.africastalking_api_key sender = request.user.company.africastalking_sender_id bulkSMSMode = 1 enqueue = 1 if api_key: africastalking.initialize(username, api_key) # Initialize SMS service sms = africastalking.SMS if form.is_valid(): category = form.cleaned_data['category'] message = form.cleaned_data['message'] category_name = Group.objects.filter(id__in=category) contacts = [] for item in category_name: category_id = item.id recipients = Contact.objects.values_list( 'mobile', flat=True).filter( category=category_id).distinct().order_by() mobiles = ",".join(recipients) contacts.append(recipients) flat_list = [] for sublist in contacts: for item in sublist: flat_list.append(item) to = list(set(flat_list)) results = sms.send(message, to, sender, enqueue) for recipient in results.get('SMSMessageData')['Recipients']: user = request.user message = message number = recipient['number'] messageId = recipient['messageId'] status = recipient['status'] cost = recipient['cost'] instance = Sms.objects.create(user=user, message=message, number=number, messageId=messageId, status=status, cost=cost) instance.category.set(category_name) messages.success(request, "Message Successfully delivered.") else: messages.error( request, u'Hi there! Please provide an API_KEY in you profile') else: form = SmsForm(request.user) return render(request, 'sms/sms_create.html', {'form': form})
def __init__(self): # Set your app credentials self.username = '******' self.api_key = '****' # Initialize the SDK africastalking.initialize(self.username, self.api_key) # Get the SMS service self.sms = africastalking.SMS
def run_queued_messages(): with application.app_context(): sms_messages = SMSMessage.query.filter( SMSMessage.last_status == 'Queued', # TODO: Fix this, its actually not filtering on the model SMSMessage.send_at <= datetime.now(), SMSMessage.sent == False).all() for sms_message in sms_messages: id = sms_message.id phone_number = sms_message.phone message = sms_message.message username = os.getenv("AT_USERNAME") api_key = os.getenv("AT_API_KEY") short_code = os.getenv("AT_SENDER_SHORT_CODE") # account balance # if balance is low # create sms and log as queued # else send sms #account_balance = get_at_account_balance() #print('account balance: ', account_balance) # TODO::Uncomment this on production, its only here because we are using sandbox which does not have a balance #if account_balance <= 0: # return try: africastalking.initialize(username, api_key) sms = africastalking.SMS response = sms.send(message, [phone_number], short_code) # process response recipients = response['SMSMessageData']['Recipients'] sms_entry = SMSMessage.query.filter_by(id=id).first() sms_entry.at_sms_id = recipients[0]['messageId'] sms_entry.at_sms_cost = recipients[0]['cost'] status_code = recipients[0]['statusCode'] # status code 101 means sent if status_code == 101: sms_message.sent = True db.session.flush() sms_log_entry = SMSLog(sms_id=sms_entry.id, at_status_code=recipients[0]['status']) db.session.add(sms_log_entry) db.session.commit() except Exception as e: db.session.rollback() current_app.logger.error(e, exc_info=True)
def post(self, request, format=None): """ { "q1": "", "q2": "", "q3": "", "q4": "", "q5": "", "q6": "", "q7": "", "q8": "", "q9": "", "q10": "", "q11email": "", "q12": "", "dispose": "", "othersystems": "", "timetocall": "", "escalation": "", "email": "", "phone": "" } """ print(request.data) try: script = Script.objects.create(**request.data) if (request.data['email'] != None): try: subject = 'Test Escalation subject' message = 'Hello, there is an Escalation, Kindly look in to it asap' mail_sent_to_org = send_mail( subject, message, "*****@*****.**", [request.data['email']] ### TODO: ) except Exception as e: return Response(data={"Error": str(e)}, status=status.HTTP_400_BAD_REQUEST) if (request.data['phone'] != None): try: username = "******" api_key = "b2d343802e57a93079abbf8db8b6be34eabe638cdff16b65391a533b0a3256f5" africastalking.initialize(username, api_key) sms = africastalking.SMS response = sms.send("Hello Test Escalation!", [request.data['phone']]) print(response) except Exception as e: return Response(data={"Error": str(e)}, status=status.HTTP_400_BAD_REQUEST) except Exception as e: return Response(data={"Error": str(e)}, status=status.HTTP_400_BAD_REQUEST) return Response(status=status.HTTP_201_CREATED)
def transmit(self): GLOBALVARS = Globs() config = GLOBALVARS.fetchConfig() APINAME = config['AfricasTalking']['USERNAME'] APIKEY = config['AfricasTalking']['API_KEY'] ATG.initialize(APINAME, APIKEY) ENGINE = ATG.SMS response = ENGINE.send( self.message, [self.destination], self.sender) return response