def index():
    form = PhoneEmailSignUpForm(request.form)
    if request.method == "POST":
        if form.validate():
            app.logger.debug("Form Validated")
            name = request.form["name"]
            phone_number = request.form["phone"]

            # TODO: include this in validation of phone number as well
            processed_phone_number = process_number(phone_number)
            formatted_rapidpro_number = "tel:{}".format(processed_phone_number)

            registration_pin = math.floor(random.uniform(10000, 99999))
            fields = {}
            fields[RAPIDPRO_FIELD] = registration_pin
            try:
                app.logger.debug("Creating Client")
                client = TembaClient(RAPIDPRO_URL, RAPIDPRO_TOKEN)
                app.logger.debug("Creating Contact")
                client.create_contact(
                    name=name,
                    urns=[formatted_rapidpro_number],
                    groups=[RAPIDPRO_GROUP],
                    fields=fields,
                )
                try:
                    app.logger.debug("Starting Flow")
                    client.create_flow_start(
                        RAPIDPRO_FLOW_UUID,
                        urns=[formatted_rapidpro_number],
                        restart_participants=True,
                        extra=None,
                    )
                    return redirect(
                        url_for("success", registration_pin=registration_pin, name=name)
                    )

                except Exception as e_1:
                    # try and delete the number so that they can start again if they want to
                    try:
                        app.logger.error("Flow Start Failed\n{}".format(e_1))
                        client.delete_contact(formatted_rapidpro_number)
                    except Exception as e_2:
                        app.logger.error("Unable to delete contact\n{}".format(e_2))
                    flash("Apologies, something went wrong, please try again.")

            except TembaBadRequestError:
                flash("That number has already been submitted")

    return render_template("index.html", form=form)
Exemplo n.º 2
0
    def POST(self):
        params = web.input()
        web.header("Content-Type", "application/json; charset=utf-8")
        username, password = get_basic_auth_credentials()
        r = auth_user(db, username, password)
        if not r[0]:
            web.header('WWW-Authenticate', 'Basic realm="Auth API"')
            web.ctx.status = '401 Unauthorized'
            return json.dumps({'detail': 'Authentication failed!'})

        client = TembaClient(
            config.get('familyconnect_uri', 'http://localhost:8000/'),
            config['api_token'])

        secreceivers = get_webhook_msg_old(params, 'secreceivers')
        pprint.pprint(secreceivers)
        payload = json.loads(secreceivers)

        optout_option = get_webhook_msg_old(params, 'OptOutOption')
        print("OptOutOption => ", optout_option)
        try:
            contact_details = payload['%s' % int(float(optout_option))]
        except:
            contact_details = None
        if not contact_details:
            return json.dumps({'success': 'False'})

        contact_id = contact_details['contact_id']
        contact_uuid = contact_details['uuid']
        print("contact_id=>", contact_id, " uuid => ", contact_uuid)

        date_of_birth = get_webhook_msg_old(params, 'child_dob')

        try:
            client.create_flow_start(config['babytrigger_flow_uuid'],
                                     contacts=[contact_uuid],
                                     extra={'child_dob': date_of_birth})
        except:
            pass

        return json.dumps({'success': 'True'})
Exemplo n.º 3
0
 def start_flow(self, contact_urn):
     client = TembaClient(self.rapidpro_url, self.rapidpro_apikey)
     #get the groups we need to add them too
     client.create_flow_start(self.rapidpro_message_sending_flow,
                              urns=[contact_urn])
call_start = sys.argv[2]
call_end = sys.argv[3]
direction = "inbound"
if len(sys.argv) > 4:
    direction = sys.argv[4]

# Format the msisdn to match Rapidpro
if msisdn[0] == "0":
    msisdn = "+254{}".format(msisdn[1:])
if msisdn[0] != "+":
    msisdn = "+{}".format(msisdn)
wa_id = msisdn.replace('+', '')  # Strip the + for WA
urns = ["tel:{}".format(msisdn), "whatsapp:{}".format(wa_id)]

# Check if the contact exists in Rapidpro, create it if not
contact = client.get_contacts(urn=urns[0]).first()
if not contact:
    contact = client.get_contacts(urn="whatsapp:{}".format(wa_id)).first()
if not contact:
    contact = client.create_contact(urns=urns)

# Start the contact on the flow that will store the details
client.create_flow_start(flow=flow_uuid,
                         contacts=[contact],
                         restart_participants=True,
                         params={
                             "call_start_time": call_start,
                             "call_end_time": call_end,
                             "direction": direction
                         })
Exemplo n.º 5
0
                            if params['fields']['registered_by'] == 'CHWR':
                                cur.execute(
                                    "UPDATE chwr_reporters SET uuid = %s WHERE id=%s",
                                    [contact_uuid, r["reporter_id"]])
                            else:
                                cur.execute(
                                    "UPDATE reporters SET uuid = %s WHERE id=%s",
                                    [contact_uuid, r["reporter_id"]])
                        else:
                            cur.execute(
                                "UPDATE reporters SET uuid = %s WHERE id=%s",
                                [contact_uuid, r["reporter_id"]])

                    try:
                        client.create_flow_start(
                            config['vht_registration_flow_uuid'],
                            contacts=[contact_uuid],
                            extra=params)
                    except:
                        pass
                    conn.commit()
            elif resp.status_code == 400:
                # perhaps already in familyconnect
                urn = params.get('urns', [])
                if urn:
                    tel = urn[0]
                    url = config['default_api_uri'] + "urn=%s" % tel
                    # print "YYY", url
                    resp2 = get_request(url)
                    xx = json.loads(resp2.text)
                    results = xx.get('results', '')
                    # print results