def sendSms(to,message,subject,actor,tag='user',message_id=None): # Specify your login credentials site = SiteSettings.objects.get(pk=1) username = site.sms_gateway_username apikey = site.sms_gateway_apikey gateway = AfricasTalkingGateway(username, str(apikey), "sandbox") report = [] 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" report.append({ 'number':recipient['number'], 'status':recipient['status'] }) print 'number=%s;status=%s;messageId=%s;cost=%s' % (recipient['number'], recipient['status'], recipient['messageId'], recipient['cost']) if not message_id: send_notification(recipient['number'],actor,tag,message,subject,recipient['status']) else: update_message(message_id,recipient['status']) except AfricasTalkingGatewayException, e: print 'Encountered an error while sending: %s' % str(e) return None
def fetch_messages(): site = SiteSettings.objects.get(pk=1) username = site.sms_gateway_username apikey = site.sms_gateway_apikey # rf = RequestFactory() # post_request = rf.post('/submit/', {'username': username}) # username = post_request.POST.get('username') gateway = AfricasTalkingGateway(username, str(apikey), "sandbox") 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']) lastReceivedId = message['id'] if len(messages) == 0: return False else: return message except AfricasTalkingGatewayException, e: print 'Encountered an error while fetching messages: %s' % str(e)
def sms(): _from = request.values.get('from', None) text = request.values.get('text', None) split_text = text.split('*') name = split_text[0].capitalize() gender = split_text[1].lower() age = split_text[2] preference = split_text[3].lower() count = Member.query.filter_by(phoneNumber = _from).count() if not count > 0: gateway = AfricasTalkingGateway(os.environ.get('username'), os.environ.get('apikey')) gateway.sendMessage(_from, "You have been registered for the Moringa dating session") if gender.lower() == 'male': member = Member(name=name, age=age, preference=preference, status='active', phoneNumber=_from, gender='Male') db.session.add(member) db.session.commit() logging.info("user added {}".format(member)) elif gender.lower() == 'female': member = Member(name=name, age=age, preference=preference, status='active', phoneNumber=_from, gender='Female') db.session.add(member) db.session.commit() logging.info("user added {}".format(member)) else: logging.info("member already exists") resp = make_response("OK", 200 ) return resp
def fetch_messages(): site = SiteSettings.objects.get(pk=1) username = site.sms_gateway_username apikey = site.sms_gateway_apikey # rf = RequestFactory() # post_request = rf.post('/submit/', {'username': username}) # username = post_request.POST.get('username') gateway = AfricasTalkingGateway(username, str(apikey), "sandbox") 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'] ) lastReceivedId = message['id'] if len(messages) == 0: return False else: return message except AfricasTalkingGatewayException, e: print 'Encountered an error while fetching messages: %s' % str(e)
def sms(): _from = request.values.get('from',None) #from means the person from whom the text is coming from. text = request.values.get('text',None) #this gets the text in the message sent by user split_text = text.split('*') name = split_text[0].capitalize() age = split_text[1] gender = split_text[2].lower() count = Contacts.query.filter_by(phoneNumber = _from).count() if not count > 0: #no idea what api key is, what it does. Also, the use of the username is a mystery. #username is your Africa'sTalking username and api key is obtained from website gateway = AfricasTalkingGateway(os.environ.get('username'), os.environ.get('apikey')) gateway.sendMessage (_from, "Thank you for registering for this service. To get inspiration messages, call 20880. Calls charged at 10 bob per minute. Have a blessed day.") #here the details are added to db table contacts contacts = Contacts (name=name, age = age, phoneNumber = _from) db.session.add(contacts) db.session.commit() logging.info("user added{}".format(contacts)) else: logging.info("User already registered.") resp = make_response ("OK", 200) return resp
def sms(request): res = {} nos = [] if request.is_ajax(): points = request.POST thisdict = json.loads(points.get('arr')) # print thisdict for line in thisdict: res.update(line) nos.append(res['farmer_telephone']) x = ",".join(nos) print "x is {}".format(x) username = "******" apikey = "6ee711cfda7e14a74882f0ad4fc864f861f69eafe0c9effa8e61db27e9b7f03b" to = x message = "hello, This is to inform you that there is a severe cow disease called anthrax that has been reported near your farm, please ensure your animals are vaccinated #livestockapp" gateway = AfricasTalkingGateway(username, apikey, "deryqm") try: results = gateway.sendMessage(to, 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: %s' % str(e)
def __africas_talking_send_message(gate_way, message_to, message): gateway = AfricasTalkingGateway(gate_way.api_key, gate_way.api_secret) sms_messages = [] try: results = gateway.sendMessage(clean_phone_number(message_to), message, gate_way.sender_id) for recipient in results: sms_messages.append( SMSMessage(sms_gateway=gate_way, message_type=SMSMessage.SMS_OUT, message=message, sender_id='system', message_id=recipient['messageId'], recipient_id=recipient['number'], status=SMSMessage.SUCCESS, delivered=True)) SMSMessage.objects.bulk_create(sms_messages) except AfricasTalkingGatewayException as e: logger.exception(e) except Exception as e: logger.exception(e) return sms_messages
def sendSms(to, message, subject, actor, tag='user', message_id=None): # Specify your login credentials site = SiteSettings.objects.get(pk=1) username = site.sms_gateway_username.strip() apikey = site.sms_gateway_apikey.strip() gateway = AfricasTalkingGateway(username, str(apikey), "sandbox") report = [] 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" report.append({ 'number': recipient['number'], 'status': recipient['status'] }) print 'number=%s;status=%s;messageId=%s;cost=%s' % ( recipient['number'], recipient['status'], recipient['messageId'], recipient['cost']) if not message_id: send_notification(recipient['number'], actor, tag, message, subject, recipient['status']) else: update_message(message_id, recipient['status']) except AfricasTalkingGatewayException, e: print 'Encountered an error while sending: %s' % str(e) return None
def sendsms(request): # Specify your login credentials for user in Mail.objects.all(): username = "" apikey = "" # Please ensure you include the country code (+254 for Kenya in this case) to = "+254702357053" ID = Survey.objects.last() getvars = ID.id url = 'http://oroni.pythonanywhere.com/survey/' message = "You have received this sms in order to participate in a survey \nThe survey is very brief and will only take about 5 minutes tocomplete. Please click the link below to go to the survey website .Your pass code : " + str( user.user_uuid) + ' link' + url + str(getvars) # 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. 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 send_message(to,message): username = "******" apikey = "5c8ce53d0963fda2013f418ede4c0cd7d867206c1646f71a51cb647eb0524692" gateway = AfricasTalkingGateway(username, apikey) try: results = gateway.sendMessage(to, message) except AfricasTalkingGatewayException: print ('Encountered an error while sending')
def send_sms(to=None, message=None, gateway=SMSGateway.AFRICAS_TALKING, template=None, template_args=None): """ Send """ if to is None: to = [] sms_sent = [] with db_transaction.atomic(): sms_gateway = SMSGateway.objects.filter( service_provider=gateway).first() if sms_gateway is None: raise Exception("Setup SMS gateway first!") # Create a new instance of our awesome gateway class args = (sms_gateway.api_key, sms_gateway.api_secret) if sms_gateway.is_sandbox: args += ("sandbox", ) africas_talking_gateway = AfricasTalkingGateway(*args) if message is None and (template and template_args): try: message = template.template_text % template_args except: message = template.template_text # Thats it, hit send and we'll take care of the rest. results = africas_talking_gateway.sendMessage( to, message, (sms_gateway.short_code or sms_gateway.sender_id)) for result in results: sms_message = SMSMessage(sms_gateway=sms_gateway, message_type=SMSMessage.SMS_OUT) # status is either "Success" or "error message" sms_message.message = message sms_message.recipient_id = result['number'] sms_message.sender_id = \ sms_gateway.short_code or sms_gateway.sender_id or "system" sms_message.status = SMSMessage.SUCCESS \ if result['status'] in ("success", "Success") else SMSMessage.ERROR sms_message.message_id = result['messageId'] sms_message.cost = result['cost'] sms_message.save() sms_sent.append(sms_message) return sms_sent
def gateway(): AT_APIKEY = "your api key" AT_USERNAME = "******" environment = None # change this to 1 for testing if environment is None: gateway = AfricasTalkingGateway(apiKey=AT_APIKEY, username=AT_USERNAME) else: gateway = AfricasTalkingGateway(apiKey=AT_APIKEY, username="******", environment="sandbox") return gateway
def gateway(): AT_APIKEY = Config.API_KEY AT_USERNAME = Config.USERNAME environment = Config.ENVIRONMENT if environment is None: gateway = AfricasTalkingGateway(apiKey=AT_APIKEY, username=AT_USERNAME) else: gateway = AfricasTalkingGateway( apiKey=AT_APIKEY, username="******", environment="sandbox") return gateway
def send(self, phone_numbers: str, message: str) -> None: """ Handles sending of the error message to the provider phone numbers params: phone_numbers: An array of phonenumbers to sms message: This are the contents of the message that is being sent. """ phone_numbers_csv = ','.join(phone_numbers) gateway = AfricasTalkingGateway(self.key, self.secret) gateway.sendMessage(phone_numbers_csv, message)
def send_sms_api(to, message, fro=None): # Create a new instance of our awesome gateway class gateway = AfricasTalkingGateway(username, apikey) result = {} try: number = '+234' + to[1:] results = gateway.sendMessage(number, message, from_=fro) for recipient in results: result['number'] = recipient['number'] result['status'] = recipient['status'] result['messageId'] = recipient['messageId'] result['cost'] = recipient['cost'] return result except AfricasTalkingGatewayException as e: return e
def sms(): _from = request.values.get('from', None) text = request.values.get('text', None) split_text = text.split('*') name = split_text[0].capitalize() gender = split_text[1].lower() age = split_text[2] preference = split_text[3].lower() count = Member.query.filter_by(phoneNumber=_from).count() if not count > 0: gateway = AfricasTalkingGateway(os.environ.get('username'), os.environ.get('apikey')) gateway.sendMessage( _from, "You have been registered for the Moringa dating session") if gender.lower() == 'male': member = Member(name=name, age=age, preference=preference, status='active', phoneNumber=_from, gender='Male') db.session.add(member) db.session.commit() logging.info("user added {}".format(member)) elif gender.lower() == 'female': member = Member(name=name, age=age, preference=preference, status='active', phoneNumber=_from, gender='Female') db.session.add(member) db.session.commit() logging.info("user added {}".format(member)) else: logging.info("member already exists") resp = make_response("OK", 200) return resp
def send_sms(): username = get_user_name() apikey = get_api_key() to = "+254712160428" message = '' # message = message_for_all gateway = AfricasTalkingGateway(username, apikey) try: results = gateway.sendMessage(to, message) for recipient in results: 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))
def sms(): # Specify your login credentials username = "******" apikey = "30e34507d42910e827b2ed32c6ffe53019f42feacf1a7e905c753196dd4454bd" to = "+254787235065,+254708415904" message = "I'm a lumberjack and it's ok, I sleep all night and I work all day" gateway = AfricasTalkingGateway(username, apikey) try: 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 reserve_session(request, session_id): title = 'BADILI' profile = Profile.get_profile(request.user.id) user_contact = profile.phone_number sessions = Session.get_sessions session = Session.objects.get(id=session_id) session.Availability = False session.user = request.user session.save() when = session.sloted_date # send confirmation message to the user username = username1 apikey = apikey1 to = user_contact message = 'Congratulations ' + request.user.username.upper( ) + ' for making an effort to transform.\n' 'Your have reserved a session with iRehab on ' + str( when)[:10] + ' at ' + str(when)[11:16] 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 as e: print('Encountered an error while sending: %s' % str(e)) # # # # return HttpResponse(response, content_type='text/plain') # return redirect('bookings')
def send_sms(number, text): username = "******" apikey = AFRICAS_TALKING_KEY to = number # And of course we want our recipients to know what we really do message = text # Create a new instance of our awesome gateway class gateway = AfricasTalkingGateway(username, apikey) results = gateway.sendMessage(to, message) data=[] for recipient in results: values={ "number":recipient['number'], "status":recipient['status'], "messageId":recipient['messageId'], "cost":recipient['cost'] } data.append(values) return data
def sms(): # Specify your login credentials username = "******" apikey = 'your api key' # NOTE: If connecting to the sandbox, please use your sandbox login credentials # 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 = "+XXXXXXXXXXX, +XXXXXXXXXXX" # 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) # 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) message = "" for recipient in results: # status is either "Success" or "error message" message += 'number=%s;status=%s;messageId=%s;cost=%s' % ( recipient['number'], recipient['status'], recipient['messageId'], recipient['cost']) except AfricasTalkingGatewayException, e: message = 'Encountered an error while sending: %s' % str(e)
def inpatient_reservation(request, inpatient_id): title = 'BADILI' profile = Profile.get_profile(request.user.id) user_contact = profile.phone_number vacancies = Inpatient.get_vacancies vacancy = Inpatient.objects.get(id=inpatient_id) vacancy.Availability = False vacancy.save() starting = vacancy.starting_date ending = vacancy.finish_date # send confirmation message to the user username = username1 apikey = apikey1 to = user_contact message = 'Congratulations ' + request.user.username.upper( ) + '.\n' 'You have reserved a slot at iRehab from ' + str( starting)[:10] + ' to ' + str(ending)[:10] + ' for in-patient services' 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 as e: print('Encountered an error while sending: %s' % str(e)) return redirect('bookings')
def send_message(request): # the username and apiKey below does not belong to me i should change it username = '******' apiKey = 'ccd6a5c49876e24e7408a7f2d5f8d6e04a3a8d56f00d9920874ec94ff656d36b' to = '0712567583' message = 'Test Message' gateway = AfricasTalkingGateway(username, apiKey) try: # That's 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 as e: print('Encountered an error while sending: %s' % str(e)) return HttpResponse(response, content_type='text/plain')
def initialize(): username = "******" apikey = "5c8ce53d0963fda2013f418ede4c0cd7d867206c1646f71a51cb647eb0524692" gateway = AfricasTalkingGateway(username, apikey)
class Sms: def __init__(self): self._username = "******" self._api_key = "9898e481449e39a6051b3d87e07f4de171bedc93a046dd166c0dad2d0d9b6bdc" self._gateway = AfricasTalkingGateway(self._username, self._api_key) def format_phone_number(self, phone_number): to = '' phone_number = str(phone_number).replace(" ", "") if phone_number[0:4] == '+254': to = phone_number elif phone_number[0:4] == '2547': to = '+' + str(phone_number) elif phone_number[0:2] == '07': to = '+254' + phone_number[1:] elif phone_number[0:1] == '7': to = '+254' + phone_number return to def format_amount(self, amount): initial = "KES " amount = int(amount) amount = initial + str(amount) return amount def sendsms(self, to, message): to = self.format_phone_number(to) try: sender = "FLEMISHLTD" response = self._gateway.sendMessage(to, message, sender) print(response) if response[0]['status'] == 'Success': return True else: return False except Exception as e: print(str(e)) return False def sendmultiplesms(self, to, message): try: sender = "FLEMISHLTD" response = self._gateway.sendMessage(to, message, sender) unsent = [ res['number'] for res in response if res['status'] != 'Success' ] return True, unsent except Exception as e: return False, '' def buyairtime(self, phone_number, amount): phone_number, amount = self.format_phone_number( phone_number), self.format_amount(amount) recipient = [{"phoneNumber": phone_number, "amount": amount}] try: response = self._gateway.sendAirtime(recipient) print(response) if response[0]['status'] == 'Success' or response[0][ 'status'] == 'Sent': return True else: return False except AfricasTalkingGatewayException as e: print(str(e)) return False
# Be sure to import helper gateway class from africastalking.AfricasTalkingGateway import ( AfricasTalkingGateway, AfricasTalkingGatewayException) # Specify your login credentials username = "******" apikey = "937d7d123463ebb47b6513f271c4e7ec7611fd92d3546599e36607637f256381" callFrom = "+254722000000" callTo = "+254712534532" # Create a new instance of our awesome gateway class gateway = AfricasTalkingGateway(username, apikey, "sandbox") 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']) # 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)
from africastalking.AfricasTalkingGateway import (AfricasTalkingGateway, AfricasTalkingGatewayException) #create a gateway instance gateway = AfricasTalkingGateway( username = "******", apiKey = "d46192b5e6c1bdf6e24ae3760f5d49cde42e8b09d53f01fc929eec205996f5ce", environment = "sandbox" ) gateway.sendMessage("+254787235065", "Hello......")
from flask import Flask, request, make_response, jsonify from africastalking.AfricasTalkingGateway import AfricasTalkingGateway import json from houndify import houndify clientId = 'KS3xVzZ3e1LYKPYpje8BVA==' clientKey = 'unUgmQ4ZFvjk4LeJVs5oa16H7V-O4DTbDpJ1-KCSnKpVPu6lP59Y4gyTufdn7_EkGHj8EZGzMIAcLd4F8l-GdA==' client = houndify.TextHoundClient(clientId, clientKey, "at-shortcode") app = Flask('smart-text') gateway = AfricasTalkingGateway('aT_username', 'at_api_key') @app.route('/sms', methods=['POST']) def incoming_sms(): to = request.values.get('from', None) message = request.values.get('text', None) print to, message # integrate houndify resp = client.query(message) json_obj = json.loads(resp) toSend = json_obj['AllResults'][0]['SpokenResponse'] print toSend gateway.sendMessage(to, message) # gateway.call('+254711082306', to)
def __init__(self): self._username = "******" self._api_key = "9898e481449e39a6051b3d87e07f4de171bedc93a046dd166c0dad2d0d9b6bdc" self._gateway = AfricasTalkingGateway(self._username, self._api_key)
from africastalking.AfricasTalkingGateway import (AfricasTalkingGateway, AfricasTalkingGatewayException) #create a gateway instance gateway = AfricasTalkingGateway("jani","680fdfa9eae83b8649c7d3884ad0679b827c7393140bc68b85e0e5b0a31dcb68") #send message gateway.sendMessage("0708415904,0702456399","hello DEKUT")
def mobile_payment(request, ticket_id): ''' Function that carries out the payment process ''' # Get ticket with a given id ticket = Ticket.get_single_ticket(ticket_id) # Get the route and convert to string bus_route = str((ticket.schedule.bus.bus_organisation.name)) print(type(bus_route)) # Get the phone number phone_number = ticket.phone_number print(type(phone_number)) # Get the ticket price and convert Decimal to int ticket_price = float(ticket.schedule.price) print(type(ticket_price)) # Africas Talking Set Up # Specify your credentials # username = "******" username = "******" apiKey = config('API_KEY_AFRICAS_TALKING') # Create an instance of our awesome gateway class and pass your credentials gateway = AfricasTalkingGateway(username, apiKey, "sandbox") #************************************************************************************* # NOTE: If connecting to the sandbox: # # 1. Use "sandbox" as the username # 2. Use the apiKey generated from your sandbox application # https://account.africastalking.com/apps/sandbox/settings/key # 3. Add the "sandbox" flag to the constructor # # gateway = AfricasTalkingGateway(username, apiKey, "sandbox"); #************************************************************************************** # Specify the name of your Africa's Talking payment product productName = bus_route # The phone number of the customer checking out phoneNumber = phone_number # The 3-Letter ISO currency code for the checkout amount currencyCode = "KES" # The checkout amount amount = ticket_price print(amount) # 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"} try: # Initiate the checkout. If successful, you will get back a transactionId transaction_id = gateway.initiateMobilePaymentCheckout( productName, phoneNumber, currencyCode, amount, metadata) print("The transactionId is " + transaction_id) ticket.transaction_code = transaction_id ticket.save() print(ticket.transaction_code) return redirect('/ticket/' + str(ticket_id)) except AfricasTalkingGatewayException as e: print("Received error response: %s" % str(e))
# Import the helper gateway class from africastalking.AfricasTalkingGateway import ( AfricasTalkingGateway, AfricasTalkingGatewayException) #create a gateway instance gateway = AfricasTalkingGateway( "jani", "d46192b5e6c1bdf6e24ae3760f5d49cde42e8b09d53f01fc929eec205996f5ce", "sandbox") #send airtime gateway.sendAirtime([{"phoneNumber": "+254708415904", "amount": "KES 20"}])
def callback(request): """Function that handles callback from Afric Stalking API""" if request.method == 'POST' and request.POST: sessionId = request.POST.get('sessionId') serviceCode=request.POST.get('serviceCode') phoneNumber=request.POST.get('phoneNumber') text=request.POST.get('text') now = datetime.datetime.now() textList = text.split('*') userResponse = textList[-1].strip() level = len(textList)-1 try: user, create = User.objects.get_or_create(phonenumber=phoneNumber) except User.DoesNotExist as e: level = 0 if level == 0: if userResponse == "": response = "CON Welcome to onPoint Service. Would you like to buy or sell?\n" response += "1. I am Buying\n" response += "2. I am a Seller\n" return HttpResponse(response, content_type='text/plain') session_level1 = User.objects.get(phonenumber = phoneNumber) session_level1.level=1 session_level1.type_of_user = userResponse session_level1.save() response = "CON Please enter your name:\n" return HttpResponse(response, content_type='text/plain') if level == 1: session_level2 = User.objects.get(phonenumber = phoneNumber) session_level2.level=2 session_level2.name = userResponse session_level2.save() response = "CON Which is your county? e.g.\n Nairobi\n Uasin Gishu\n Machakos\ne.t.c ..." return HttpResponse(response, content_type='text/plain') if level == 2: session_level3 = User.objects.get(phonenumber = phoneNumber) session_level3.level=3 session_level3.location = userResponse session_level3.save() response = "CON What is your closest town or market center?.\n e.g. Makutano" return HttpResponse(response, content_type='text/plain') if level == 3: session_level4 = User.objects.get(phonenumber = phoneNumber) session_level4.level=4 session_level4.nearest_town = userResponse session_level4.save() response = "CON Enter the product name\ne.g. Maize, Beans, Milk" return HttpResponse(response, content_type='text/plain') if level == 4: session_level5 = User.objects.get(phonenumber = phoneNumber) session_level5.level=5 response = "CON Enter the quantity (units: Kgs, Bags, Litres, Trays, e.t.c.)\n e.g 1, 10, 100" return HttpResponse(response, content_type='text/plain') if level == 5: session_level6 = User.objects.get(phonenumber = phoneNumber) session_level6.level=6 response = "CON Enter the price per Kg\n. e.g. 50, 100, 1000" return HttpResponse(response, content_type='text/plain') if level == 6: session_level7 = User.objects.get(phonenumber = phoneNumber) session_level7.level=7 product = Product.objects.create(type_of_product=textList[0],name=textList[4], quantity=textList[5], price=textList[6], user=user) product.save() response = "END Your request has been received. \n We will send you a message with contact details of a buyer/seller that matches your request." # this are variables to be used by the generate details section current_product = textList[4].lower() current_price = textList[6] current_town = textList[3].lower() current_location = textList[2].lower() current_phonenumber = phoneNumber current_type = textList[0] # this is the message generator section that determines the message that will be sent to the current user requested_products = Product.requested_products(current_product) # this is a list of products which satisfy the price requirements of the user list_price = requested_price(current_price, current_type, requested_products) # this is a list of products that satisfy the location requirements of the current user list_town = requested_town(current_town, list_price) # this is a list of products that satisfy the current user's location requirements list_location = requested_location(current_location, list_price) # this is the final list that always returns atleast three products based on availability of those products results_list = final_list(requested_products, list_price, list_location, list_town) # this is a list of phonenumbers that the current users will get found_phonenumbers = get_phonenumbers(results_list) # these are message details to be sent to the farmer contacts = details_generator(found_phonenumbers) print(contacts) username = username1 apiKey = apikey1 to = phoneNumber message = 'Thank you '+ user.name + ' for using our services.\n' \ 'This is your entry:\n\n' \ 'Product Name: '+ textList[4] + '\n' \ 'Quantity: '+ textList[5] + '\n' \ 'Price: ' + textList[6] + '\n\n' \ 'If this entry is accurate, we will send you information matching your request.\n' \ 'If you would like to make another entry dial. \n*384*10446#' message1 = 'Find below contact the numbers below matching your request: \n' + contacts gateway = AfricasTalkingGateway(username, apiKey) try: # That's it, hit send and we'll take care of the rest. results = gateway.sendMessage(to, message) results1 = gateway.sendMessage(to, message1) 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'])) for recipient in results1: # 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)) return HttpResponse(response, content_type='text/plain')