def post(self, request, uidb64=None, token=None, *arg, **kwargs): UserModel = get_user_model() form = self.form_class(request.POST) assert uidb64 is not None and token is not None # checked by URLconf try: uid = urlsafe_base64_decode(uidb64) user = Client.objects.get(user=User.objects.get(id=uid)) u = UserModel._default_manager.get(pk=uid) except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist): user = None if user is not None and shareable_link_token.check_token(u, token): if form.is_valid(): phone_number = form.cleaned_data['phone_number'] first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] gender = form.cleaned_data['gender'] date_of_birth = form.cleaned_data['date_of_birth'] email_address = form.cleaned_data['email_address'] language = form.cleaned_data['language'] country = Country.objects.get(country_name='Kenya') county = form.cleaned_data['county'] constituency = form.cleaned_data['constituency'] ward = form.cleaned_data['ward'] format_number = SMS() phone_number = format_number.format_phone_number(phone_number) if self.validate_phone_number(phone_number, user) is True: asp = Client.objects.get(user=User.objects.get(id=uid)) new_subscriber = Subscriber(first_name=first_name, last_name=last_name, gender=gender, date_of_birth=date_of_birth, email_address=email_address, language=language, is_active=True, phone_number=phone_number, client=asp, country=country, county=county, constituency=constituency, ward=ward) new_subscriber.save() messages.success(request, 'Successful subscription.') return self.render_to_response( self.get_context_data(form=form)) else: messages.error( request, 'Unsuccessful subscription.You are already subscribed to this client.' ) return self.form_invalid(form) else: messages.error(request, 'Unsuccessful subscription.') return self.form_invalid(form) else: messages.error(request, 'The subscription link is no longer valid.') return self.form_invalid(form)
def register_single_subscriber(request): password = request.POST.get('password') return_data = {} if not request.user.check_password(password): return_data['STATUS'] = '0' return_data['MESSAGE'] = 'Wrong password' else: first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') email = request.POST.get('email') date_of_birth = request.POST.get('date_of_birth') phone_number = request.POST.get('phone_number') phone_number = phone_number.replace(' ', '') gender = request.POST.get('gender') language_id = request.POST.get('language_id') county_id = request.POST.get('county_id') constituency_id = request.POST.get('constituency_id') ward_id = request.POST.get('ward_id') subscriber = Subscriber() subscriber.first_name = first_name subscriber.last_name = last_name subscriber.email_address = email subscriber.date_of_birth = datetime.datetime.strptime( date_of_birth, '%Y-%m-%d') sms = SMS() subscriber.phone_number = sms.format_phone_number(phone_number) subscriber.gender = gender subscriber.language = Language.objects.get(id=language_id) subscriber.county = County.objects.get(id=county_id) if constituency_id.isdigit(): subscriber.constituency = Constituency.objects.get( id=constituency_id) if ward_id.isdigit(): subscriber.ward = Ward.objects.get(id=ward_id) subscriber.is_active = True subscriber.aspirant = Volunteer.objects.get(user=request.user).aspirant subscriber.volunteer = Volunteer.objects.get(user=request.user) subscriber.date = datetime.datetime.now() try: subscriber.save() return_data['STATUS'] = '1' return_data[ 'MESSAGE'] = 'Subscriber has been registered on the system' except Exception, exp: return_data['STATUS'] = '0' return_data[ 'MESSAGE'] = 'Subscriber failed to be registered {}'.format( str(exp))
def broadcast_manifesto(request): password = request.POST.get('password') return_data = {} if not request.user.check_password(password): return_data['STATUS'] = '0' return_data['MESSAGE'] = 'Wrong password' else: manifesto_id = request.POST.get('manifesto_id') aspirant = Client.objects.get(user=request.user) manifesto = Campaign.objects.get(client=aspirant, id=manifesto_id) sms_utils = SMS() aspirant = serializers.serialize('json', [ aspirant, ]) manifesto = serializers.serialize('json', [ manifesto, ]) # Celerify this function call #sms_utils.send_manifesto_to_subscribers(campaign, client) task_send_manifesto_to_subscribers.delay(manifesto, aspirant) return_data['STATUS'] = '1' return_data['MESSAGE'] = """ Campaign shall be sent to all you subscribers. """ return HttpResponse(json.dumps(return_data))
def send_batch_sms(request): batch_type = request.POST.get('BATCH_TYPE') message = request.POST.get('message') user_obj = request.user user = serializers.serialize('json', [ user_obj, ]) if batch_type == 'KEYED_NUMBERS' or batch_type == 'SELECT_SUBSCRIBERS': sms = SMS() recipient_arr = json.loads(request.POST.get('recipientsArr')) #sms.send_batch_sms_from_recipient_list(recipient_arr, message, request.user.id) task_send_batch_sms_from_recipient_list.delay(recipient_arr, message, user) elif batch_type == 'UPLOAD_LIST': file_name = request.session['RECIPIENT_FILE_URL'] sms = SMS() #sms.send_batch_sms_from_excel_upload(file_name, message, request.user.id) task_send_batch_sms_from_excel_upload.delay(file_name, message, user) elif batch_type == 'ALL_SUBSCRIBERS': sms = SMS() user_id = request.user.id subscriber_filter = json.loads(request.POST.get('subscriberFilter')) subscriber_filter['user'] = request.user subscribers = sms.filter_sms_recipients(subscriber_filter) phone_numbers = [subscriber.phone_number for subscriber in subscribers] phone_numbers = json.dumps(phone_numbers) #sms.send_batch_sms_to_all_subscribers(user_id, phone_numbers, message) task_send_batch_sms_to_all_subscribers.delay(user_id, phone_numbers, message) elif batch_type == 'VOLUNTEERS': sms = SMS() user_id = request.user.id volunteers = Volunteer.objects.filter(aspirant=Client.objects.get( user=request.user)) phone_numbers = [volunteer.phone_number for volunteer in volunteers] phone_numbers = json.dumps(phone_numbers) #sms.send_batch_sms_to_all_subscribers(user_id, phone_numbers, message) task_send_batch_sms_to_all_subscribers.delay(user_id, phone_numbers, message) else: pass return HttpResponse( json.dumps({ 'MESSAGE': 'Message sent successfully', 'STATUS': '1' }))
def broadcast_survey(request): password = request.POST.get('password') return_data = {} if not request.user.check_password(password): return_data['STATUS'] = '0' return_data['MESSAGE'] = 'Wrong password' else: survey_id = request.POST.get('survey_id') survey = Survey.objects.get(id=survey_id) survey_recipients = SurveyRecipient.objects.filter(survey=survey) sms_util = SmsUtil() shortcode = 1234 try: for recipient in survey_recipients: subscriber = recipient.subscriber phone_number = sms_util.format_phone_number(subscriber.phone_number) try: if len(subscriber.first_name) > 0: msg = """{}, {} is requesting that you participate in this survey. To participate in this survey, send 1 to {}""".format( subscriber.first_name, subscriber.aspirant.alias_name, shortcode) except: msg = """Dear subscriber, {} is requesting that you participate in this survey. To participate in this survey, send 1 to {}""".format( subscriber.aspirant.alias_name, shortcode) sms_menu_log = SMSMenuLog( phone_number=phone_number, date_created=datetime.datetime.now(), menu_type='SURVEY', allowed_options=json.dumps([1]), extra_info=json.dumps({ 'WAS_QUESTION': 0, 'SURVEY_ID': survey_id, 'NEXT_QUESTION_NUMBER': 1 })) sms_menu_log.save() sms_util.send_single_sms(phone_number, msg) recipient.has_been_notified = True recipient.date_notified = datetime.datetime.now() recipient.save() survey.is_sent = True survey.save() return_data['STATUS'] = '1' return_data['MESSAGE'] = 'Survey has been sent to the set subscribers' except Exception, e: return_data['STATUS'] = '0' return_data['MESSAGE'] = 'Survey failed to be sent. Error {}'.format(str(e))
def reply_to_single_message(request): message_id = request.POST.get('message_id') message = request.POST.get('message') inbox = Inbox.objects.get(id=message_id) phone_number = inbox.phone_number sms_utils = SMS() send_sms = sms_utils.send_single_sms(phone_number, message) outbox = Outbox(phone_number=phone_number, message=message, date_sent=datetime.datetime.now()) outbox.is_sent = True if send_sms else False status = '1' if send_sms else '0' try: outbox.subscriber = Subscriber.objects.get( phone_number__exact=phone_number, aspirant=Client.objects.get(user=request.user)) except: pass outbox.save() return HttpResponse(json.dumps({'STATUS': status}))
def approve_batch_aspirants_upload(request): password = request.POST.get('password') return_data = {} if not request.user.check_password(password): return_data['STATUS'] = '0' return_data['MESSAGE'] = 'Wrong password' else: return_data['ASPIRANTS_REG'] = [] excel_file = ExcelFile(request.session['ASPIRANTS_FILE_URL']) records = excel_file.get_records(True) for record in records: record = list(record) aspirant_reg = {'full_name': '{} {}'.format(record[0], record[1])} try: user_create = User.objects.create_user( first_name=record[0], last_name=record[1], username=record[4], email=record[4], is_superuser=False, is_staff=True, date_joined=datetime.datetime.now()) aspirant_reg['registered_as_user'] = '******' aspirant = Client() aspirant.alias_name = record[2] aspirant.phone_number = SMS.format_phone_number(record[3]) aspirant.user = User.objects.get(username=record[4]) aspirant.seat = Seat.objects.get( Q(seat_name__icontains=record[5]) | Q(short_code__icontains=record[5])) aspirant.region_name = record[6] aspirant.country = Country.objects.get(country_name='Kenya') aspirant.county = County.objects.get(county_name=record[7]) aspirant.constituency = Constituency.objects.get( constituency_name=record[8]) aspirant.ward = Ward.objects.get(ward_name=record[9]) try: aspirant.save() aspirant_reg['registered_as_aspirant'] = '1' except: aspirant_reg['registered_as_aspirant'] = '0' except: aspirant_reg['registered_as_user'] = '******' return_data['ASPIRANTS_REG'].append(aspirant_reg) return HttpResponse(json.dumps(return_data))
def batch_approve_subscribers_from_file(request): password = request.POST.get('password') user = User.objects.get(id=request.user.id) return_data = {} if not user.check_password(password): return_data['STATUS'] = '0' return_data['MESSAGE'] = 'Wrong password' else: excel_file = ExcelFile(request.session['SUBSCRIBERS_FILE_URL']) records = excel_file.get_records(True) num_of_records = len(records) i = 0 return_data['MESSAGE'] = [] for record in records: try: record = list(record) subscriber = Subscriber() subscriber.first_name = record[0] subscriber.last_name = record[1] sms_utility = SMS() subscriber.phone_number = sms_utility.format_phone_number( record[2]) subscriber.email_address = record[3] subscriber.country = Country.objects.get(country_name='Kenya') subscriber.gender = record[6] if request.user.is_staff is True and request.user.is_superuser is False: subscriber.aspirant = Client.objects.get(user=request.user) elif request.user.is_staff is False and request.user.is_superuser is False: subscriber.aspirant = Volunteer.objects.get( user=request.user).aspirant subscriber.volunteer = Volunteer.objects.get( user=request.user) if len(record[7]) > 0: subscriber.county = County.objects.get( county_name=record[7]) if len(record[8]) > 0: subscriber.constituency = Constituency.objects.get( constituency_name=record[8]) if len(record[9]) > 0: subscriber.ward = Ward.objects.get(ward_name=record[9]) try: subscriber.date_of_birth = record[5] get_age = lambda dob: datetime.datetime.today().year - dob.year \ - ((datetime.datetime.today().month, datetime.datetime.today().day) \ < (dob.month, dob.day)) subscriber.current_age = get_age(record[5]) except: pass subscriber.date = datetime.datetime.now() subscriber.is_active = True subscriber.save() i += 1 return_data['MESSAGE'].append({ 'STATUS': '1', 'MESSAGE': '{} {} has been registered successfully'.format( record[0], record[1]) }) except Exception as exp: print('Errorr while registering {}'.format(exp)) return_data['MESSAGE'].append({ 'STATUS': '0', 'MESSAGE': '{} {} has not been registered'.format( record[0], record[1]) }) return_data['STATUS'] = '1' return_data['FINAL_MSG'] = '{} subscribers have been uploaded'.format( i) return HttpResponse(json.dumps(return_data))
def register_single_aspirant(request): password = request.POST.get('password') return_data = {} if not request.user.check_password(password): return_data['STATUS'] = '0' return_data['MESSAGE'] = 'Wrong password' else: first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') email = request.POST.get('email') alias_name = request.POST.get('alias_name') sms = SMS() phone_number = sms.format_phone_number( request.POST.get('phone_number')) seat = Seat.objects.get(id=request.POST.get('seat')) region_name = request.POST.get('region_name') county_id = request.POST.get('county_id') constituency_id = request.POST.get('constituency_id') ward_id = request.POST.get('ward_id') try: user_create = User.objects.create_user( first_name=first_name, last_name=last_name, username=email, email=email, is_superuser=False, is_staff=True, date_joined=datetime.datetime.now()) aspirant_reg = {'full_name': '{} {}'.format(first_name, last_name)} return_data['MESSAGE'] = [] return_data['STATUS'] = '1' return_data['MESSAGE'].append({ 'STATUS': '1', 'MESSAGE': 'Client has been registered as system user' }) aspirant = Client() aspirant.alias_name = alias_name aspirant.phone_number = phone_number aspirant.user = User.objects.get(username=email) aspirant.seat = seat aspirant.region_name = region_name aspirant.country = Country.objects.get(country_name='Kenya') aspirant.county = County.objects.get(id=county_id) if len(constituency_id) > 0 and constituency_id != 'NULL': aspirant.constituency = Constituency.objects.get( id=constituency_id) if len(ward_id) > 0 and ward_id != 'NULL': aspirant.ward = Ward.objects.get(id=ward_id) try: aspirant.save() return_data['MESSAGE'].append({ 'STATUS': '1', 'MESSAGE': 'Client has been registered as a system admin for {}'. format(region_name) }) try: recipient = [user_create] email = SendEmail() txt_template = 'email/email_temlate_aspirant_registration.txt' print("0000000") html_template = 'email/email_template_aspirant_registration.html' print("11111111") send_mail = email.send_email(recipient, request, txt_template, html_template) print("222222222") if send_mail[0]['STATUS'] == '1': return_data['MESSAGE'].append({ 'STATUS': '1', 'MESSAGE': 'An email has been sent to the client' }) else: print("*****") print(send_mail) return_data['MESSAGE'].append({ 'STATUS': '0', 'MESSAGE': 'Email delivery to client failed permanently' }) except Exception, exp: print(str(exp)) return_data['MESSAGE'].append({ 'STATUS': '0', 'MESSAGE': 'Email delivery to client failed permanently' }) except: return_data['MESSAGE'].append({ 'STATUS': '0', 'MESSAGE': 'Client has not been registered as a system admin for {}'. format(region_name) }) except: return_data['MESSAGE'].append({ 'STATUS': '0', 'MESSAGE': 'Client was not registered' }) return HttpResponse(json.dumps(return_data))
def publish_new_survey(request): password = request.POST.get('password') return_data = {} if not request.user.check_password(password): return_data['STATUS'] = '0' return_data['MESSAGE'] = 'Wrong password' else: survey_title = request.POST.get('surveyTitle') survey_description = request.POST.get('surveyDescription') survey_content = json.loads(request.POST.get('surveyContent')) survey = Survey() survey.survey_title = survey_title survey.survey_desc = survey_description survey.aspirant = Client.objects.get(user=request.user) return_data['MESSAGE'] = [] try: survey.save() return_data['MESSAGE'].append({ 'STATUS': '1', 'MESSAGE': 'Survey has been created.' }) for content in survey_content: survey_question = SurveyQuestion() survey_question.survey = survey survey_question.question_number = content['question_number'] survey_question.question = content['question'] try: survey_question.save() return_data['MESSAGE'].append({ 'STATUS': '1', 'MESSAGE': "'{}' survey question has been added.".format(content['question']) }) options_list = content['option'].split('#') for option in options_list: try: survey_options = SurveyOptions() survey_options.option = option survey_options.survey_question = survey_question survey_options.save() return_data['MESSAGE'].append({ 'STATUS': '1', 'MESSAGE': "'{}' survey option has been added.".format(option) }) except Exception as ex: return_data['MESSAGE'].append({ 'STATUS': '0', 'MESSAGE': "'{}' survey option failed to be added. Error: {}".format(option, str(ex)) }) except Exception as ex: return_data['MESSAGE'].append({ 'STATUS': '0', 'MESSAGE': "'{}' survey question failed to be added. Error: ".format(content['question'], str(ex)) }) subscriber_filter = json.loads(request.POST.get('subscriber_filter')) subscriber_filter['user'] = request.user try: sms_utils = SmsUtil() subscribers = sms_utils.filter_sms_recipients(subscriber_filter) for subscriber in subscribers: survey_recipient = SurveyRecipient( survey=survey, subscriber=subscriber) survey_recipient.save() except Exception as exe: print(str(exe)) pass except Exception as ex: return_data['MESSAGE'].append({ 'STATUS': '0', 'MESSAGE': 'Survey failed to be created. Error: '.format(str(ex)) }) return HttpResponse(json.dumps(return_data))
def task_send_batch_sms_from_excel_upload(file_name, message, user): sms = SMS() sms.send_batch_sms_from_excel_upload(file_name, message, user) logger.info("Finished sending batch sms from excel upload")
def inbox_list(request, offset=0): template = 'sms/inbox_list.html' inboxmsgs = Inbox.objects.filter( message_type='CHAT', user=request.user, is_archived=False).order_by('-date_received') context = {} if request.method == 'POST': start_date = str(request.POST.get('start_date')) end_date = str(request.POST.get('end_date')) sentiment = str(request.POST.get('sentiment')) key_word = str(request.POST.get('key_word')) key_word = str(key_word.strip()) if len(start_date) == 10 and len(end_date) == 10: start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d') end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d') end_date += datetime.timedelta(days=1) inboxmsgs = inboxmsgs.filter(date_received__gte=start_date, date_received__lte=end_date) elif len(start_date) == 10 and len(end_date) != 10: start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d') inboxmsgs = inboxmsgs.filter(date_received__gte=start_date) elif len(end_date) == 10 and len(start_date) != 10: end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d') end_date += datetime.timedelta(days=1) inboxmsgs = inboxmsgs.filter(date_received__lte=end_date) if len(key_word) != 0: if key_word.isdigit() and len(key_word) >= 10: sms_util = SMS() phone_number = sms_util.format_phone_number(key_word) inboxmsgs = inboxmsgs.filter(phone_number=phone_number) else: inboxmsgs = inboxmsgs.filter(message__icontains=key_word) if len(sentiment) != 0: inboxmsgs = inboxmsgs.filter(sentiment__icontains=sentiment) context["inboxmsgs"] = inboxmsgs else: offset = int(offset) limit = offset + settings.PAGINATION_OFFSET prev_offset = offset - settings.PAGINATION_OFFSET if prev_offset < 0: prev_offset = 0 next_offset = (offset + settings.PAGINATION_OFFSET) if next_offset > len(inboxmsgs): next_offset = offset print("{} {}".format(offset, limit)) context["inboxmsgs"] = inboxmsgs[offset:limit] context["prevOffset"] = prev_offset context["nextOffset"] = next_offset context["currentOffset"] = offset context["offsetExist"] = True return render(request, template, context)
def receive_sms(request): try: f = open("log.log", "a+") data_to_log = request.POST data_to_log['date_time'] = str(datetime.datetime.now()) f.write("{}\n".format(json.dumps(data_to_log))) f.close() except Exception as e: f = open("log.log", "a+") f.write(str(e)) f.close() sender = request.POST.get( 'from') # phone number from which the message originated from message = request.POST.get('text') # Message from sender message = message.strip() date = request.POST.get('date') # Date time when the message was sent msg_id = request.POST.get('id') # Message ID from Africa's Talking aspirant = Client.objects.all()[0] sms_inbox = Inbox(africastalking_msg_id=msg_id, phone_number=sender, message=message, date_created=datetime.datetime.now(), date_received=date, user=aspirant.user) subscriber_exist = Subscriber.objects.filter(phone_number=sender).exists() volunteer_exist = Volunteer.objects.filter(phone_number=sender).exists() try: message_arr = message.split(' ') first_word = message_arr[0].lower() first_word = first_word.strip() sms_util = SMS() if len(message_arr) == 1: if first_word == 'vote' and subscriber_exist is False: # subscriber user sms_inbox.message_type = 'SUBSCRIBE' sms_inbox.save() subscriber = Subscriber( phone_number=sms_util.format_phone_number(sender), aspirant=aspirant, is_active=True) subscriber.save() ret_msg = """You have successfully subscribe to {}. Send the word campaign to {} to view his campaign."""\ .format(aspirant.alias_name, settings.SMS_SHORT_CODE) sms_util.send_single_sms(sms_util.format_phone_number(sender), ret_msg) Outbox(phone_number=sms_util.format_phone_number(sender), message=ret_msg, message_type="ACK", is_sent=True, user=aspirant.user, date_sent=datetime.datetime.now()).save() return elif first_word == 'volunteer': ret_msg = """To register as {}'s volunteer, send the word volunteer followed by your email address to {}.""" \ .format(aspirant.alias_name, settings.SMS_SHORT_CODE) sms_util.send_single_sms(sms_util.format_phone_number(sender), ret_msg) Outbox(phone_number=sms_util.format_phone_number(sender), message=ret_msg, message_type="ACK", is_sent=True, user=aspirant.user, date_sent=datetime.datetime.now()).save() elif first_word.isdigit(): # SMS menu phone_number = sms_util.format_phone_number(sender) sms_menu_log = SMSMenuLog.objects.filter( phone_number=phone_number).order_by('-date_created')[0] allowed_options = json.loads(sms_menu_log.allowed_options) extra_info = json.loads(sms_menu_log.extra_info) menu_type = sms_menu_log.menu_type menu_option = int(first_word) if menu_option not in allowed_options: msg = extra_info['FALL_BACK_SMS'] sms_util.send_single_sms(phone_number, msg) return if menu_type == 'MANIFESTO': #Send campaign sms_inbox.message_type = 'MANIFESTO' sms_inbox.save() manifesto_id = extra_info['MANIFESTO_ID'] options_mapping = extra_info['OPTIONS_MAPPING'] manifesto = Campaign.objects.get(id=manifesto_id) manifesto_item_id = options_mapping[first_word] manifesto_item = CampaignItems.objects.get( campaign=manifesto, id=manifesto_item_id) manifesto_msg = """{}\n{}""".format( manifesto_item.title, manifesto_item.content) sms_util.send_single_sms(phone_number, manifesto_msg) manifesto_item_reception = CampaignItemsReception( campaign_item=CampaignItems.objects.get( id=manifesto_item_id), date_read=datetime.datetime.now()) try: manifesto_item_reception.subscriber = Subscriber.objects.get( phone_number=phone_number) except: pass manifesto_item_reception.save() elif menu_type == 'SURVEY': #Send survey sms_inbox.message_type = 'SURVEY' sms_inbox.save() survey_id = extra_info['SURVEY_ID'] was_question = extra_info['WAS_QUESTION'] if was_question == 1: # Save survey response options_mapping = extra_info['OPTIONS_MAPPING'] survey_response = SurveyResponse() survey_response.survey_option = SurveyOptions.objects.get( id=options_mapping[first_word]) try: survey_response.subscriber = Subscriber.objects.get( phone_number=sms_util.format_phone_number( phone_number)) except: pass survey_response.save() next_question_number = extra_info['NEXT_QUESTION_NUMBER'] survey = Survey.objects.get(id=survey_id) try: survey_question = SurveyQuestion.objects.get( survey=survey, question_number=next_question_number) question_options = SurveyOptions.objects.filter( survey_question=survey_question) msg = "{}\n".format(survey_question.question) fall_back_sms = "Invalid option.\n" allowed_options = [] options_mapping = {} for i in range(0, len(question_options)): msg += "{}. {}\n".format( i + 1, question_options[i].option) fall_back_sms += "{}. {}\n".format( i + 1, question_options[i].option) allowed_options.append(i + 1) options_mapping[i + 1] = question_options[i].id SMSMenuLog(date_created=datetime.datetime.now(), phone_number=phone_number, menu_type='SURVEY', allowed_options=json.dumps(allowed_options), extra_info=json.dumps({ 'WAS_QUESTION': 1, 'NEXT_QUESTION_NUMBER': next_question_number + 1, 'SURVEY_ID': survey_id, 'FALL_BACK_SMS': fall_back_sms, 'OPTIONS_MAPPING': options_mapping })).save() sms_util.send_single_sms(phone_number, msg) except: msg = "Thank you for participating in this survey." sms_util.send_single_sms(phone_number, msg) elif first_word == 'volunteer' and volunteer_exist is False: # Register volunteer sms_inbox.message_type = 'VOLUNTEER' sms_inbox.save() email_address = message_arr[1] try: validate_email(email_address) user = User(username=email_address, email=email_address) user.save() volunteer = Volunteer( phone_number=sms_util.format_phone_number(sender), aspirant=aspirant, is_active=True, user=user) volunteer.save() try: recipient = [user] email = SendEmail() txt_template = 'email/email_template_volunteer_registration.txt' html_template = 'email/email_template_volunteer_registration.html' send_mail = email.tuma_mail(recipient, txt_template, html_template) if send_mail: ret_msg = """You have successfully been registered as {}'s volunteer. A verification link has been sent to {}.""" \ .format(aspirant.alias_name, email_address) else: ret_msg = """Unsuccessful registration.Unable to sent verification link to {}""" \ .format(email_address) volunteer.delete() user.delete() except Exception, e: ret_msg = """Unsuccessful registration.Unable to sent verification link to {}""" \ .format(email_address) volunteer.delete() user.delete() sms_util.send_single_sms(sms_util.format_phone_number(sender), ret_msg) Outbox(phone_number=sms_util.format_phone_number(sender), message=ret_msg, message_type="ACK", is_sent=True, user=aspirant.user, date_sent=datetime.datetime.now()).save() return except: ret_msg = """Invalid email address.Please send the word volunteer followed by a valid email address to {}.""" \ .format(aspirant.alias_name, settings.SMS_SHORT_CODE) sms_util.send_single_sms(sms_util.format_phone_number(sender), ret_msg) Outbox(phone_number=sms_util.format_phone_number(sender), user=aspirant.user, message=ret_msg, message_type="ACK", is_sent=True, date_sent=datetime.datetime.now()).save()
def task_send_manifesto_to_subscribers(manifesto, aspirant): sms = SMS() sms.send_manifesto_to_subscribers(manifesto, aspirant) logger.info("Finished sending batch campaign to all subscribers")
def task_send_batch_sms_to_all_subscribers(user_id, phone_numbers, message): sms = SMS() sms.send_batch_sms_to_all_subscribers(user_id, phone_numbers, message) logger.info("Finished sending batch sms to all subscriber")
def post(self, request, uidb64=None, token=None, *arg, **kwargs): UserModel = get_user_model() form = self.form_class(request.POST) assert uidb64 is not None and token is not None # checked by URLconf try: uid = urlsafe_base64_decode(uidb64) asp = Client.objects.get(user=User.objects.get(id=uid)) user = UserModel._default_manager.get(pk=uid) except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist): user = None if user is not None and shareable_link_token.check_token(user, token): if form.is_valid(): phone_number = form.cleaned_data['phone_number'] first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] county = form.cleaned_data['county'] constituency = form.cleaned_data['constituency'] ward = form.cleaned_data['ward'] country = Country.objects.get(country_name='Kenya') format_number = SMS() phone_number = format_number.format_phone_number(phone_number) if self.validate_phone_number(phone_number, asp): new_user = User.objects.create_user(first_name=first_name, last_name=last_name, username=email, password=password, email=email, is_staff=False, is_superuser=False, is_active=True) new_volunteer = Volunteer(phone_number=phone_number, aspirant=asp, user=new_user, country=country, county=county, constituency=constituency, ward=ward, is_active=True) try: new_volunteer.save() messages.success( request, format_html( "{}<a id='anchor_redirect' href='{}://{}/{}'>{}</a>{}", 'Successful volunteer registration.', 'http', request.META['HTTP_HOST'], 'login_page', 'Click Here', ' to access your account.')) txt_template = 'email/volunteer_registration_email.txt' html_template = 'email/volunteer_registration_email.html' recipient = [new_user] try: email = SendEmail() email.tuma_mail(recipient, txt_template, html_template) except Exception, e: print(str(e)) return self.form_valid(form) except Exception, e: new_user.delete() messages.error( request, format_html( "<span class='w3-text-red'>{}</span>", 'Unsuccessful volunteer registration.')) return self.render_to_response( self.get_context_data(form=form)) else: messages.error( request, 'Phone Number exists.Unsuccessful volunteer registration.' ) return self.form_invalid(form)
def task_send_batch_sms_from_recipient_list(recipient_arr, message, user): sms = SMS() sms.send_batch_sms_from_recipient_list(recipient_arr, message, user) logger.info("Finished sending batch sms from recipient list")