示例#1
0
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))
示例#2
0
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}))
示例#3
0
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()