Ejemplo n.º 1
0
def send_whatsapp_message_image(url, to, media_link, media_caption):
    add_message(to[2:], bot_number, to[2:], media_link, "image", "whatsapp",
                "outgoing")
    url = url + '/v1/messages'
    authkey = get_auth_key()
    ##print("Inside message")
    data = {
        "to": to,
        "type": "image",
        "recipient_type": "individual",
        "image": {
            "provider": {
                "name": "covidsos"
            },
            "link": "<Link to Image, https>",
            "caption": "<Media Caption>"
        }
    }
    headers = {
        'Content-type': 'application/json',
        'Authorization': "Bearer " + authkey
    }
    try:
        response = requests.request("POST",
                                    url,
                                    data=json.dumps(data),
                                    headers=headers,
                                    verify=False).json()
        print("message sent", flush=True)
        if (response.get("errors") is None):
            return True
        return False
    except Exception as e:
        print(e, flush=True)
        return False
Ejemplo n.º 2
0
def send_whatsapp_message(url, to, message, preview_url=False):
    add_message(to[2:], bot_number, to[2:], message, "text", "whatsapp",
                "outgoing")
    url = url + '/v1/messages'
    authkey = get_auth_key()
    ##print("Inside message")
    data = {
        "to": to,
        "type": "text",
        "recipient_type": "individual",
        "text": {
            "body": message
        },
        "preview_url": preview_url
    }
    headers = {
        'Content-type': 'application/json',
        'Authorization': "Bearer " + authkey
    }
    try:
        response = requests.request("POST",
                                    url,
                                    data=json.dumps(data),
                                    headers=headers,
                                    verify=False)
        print("message sent")
    except Exception as e:
        print(e)
    return response
Ejemplo n.º 3
0
def process_whatsapp_received_text_message(message):
    body = str(message.get("text").get("body"))
    whatsapp_id = str(message.get('from'))
    add_message(whatsapp_id, whatsapp_id, bot_number, body, "text", "whatsapp",
                "incoming")

    current_time = int(time.time())
    timestamp = int(message.get('timestamp', current_time))
    whatsapp_id = str(message.get('from'))
    if (current_time - timestamp > stale_whatsapp_message_threshold):
        if check_mesage_to_number_already_sent(whatsapp_id):
            print("Message to whatsapp_id {wa_id} already processed skipping".
                  format(wa_id=whatsapp_id))
            return
        else:
            mark_number_as_processed_for_stale_message(whatsapp_id)

    #Storing Message, Media or Location
    #elif (response.get("messages")[0].get("type")=='image'):

    #Replace with functions from data_fetching

    ## query for volunteer
    checkState = """SELECT name, timestamp, id, whatsapp_id from volunteers where mob_number='{mob_number}'""".format(
        mob_number=int(whatsapp_id[2:]))
    print(checkState)
    records_a = pd.read_sql(checkState, connections('prod_db_read'))
    ## query for requester
    checkState = """SELECT name, timestamp, id, whatsapp_id from requests where mob_number='{mob_number}'""".format(
        mob_number=whatsapp_id[2:])
    records_b = pd.read_sql(checkState, connections('prod_db_read'))

    ## check for volunteer
    if records_a.shape[0] > 0:
        if (records_a.loc[0, 'whatsapp_id'] != whatsapp_id):
            check_contact("+" + str(whatsapp_id), 'volunteers')
        name = records_a.loc[0, 'name']
        send_whatsapp_message(whatsapp_api_url, whatsapp_id,
                              a.format(v_name=name))

    ## check for requester
    elif records_b.shape[0] > 0:
        if (records_b.loc[0, 'whatsapp_id'] != whatsapp_id):
            check_contact("+" + str(whatsapp_id), 'requests')
        name = records_b.loc[0, 'name']
        send_whatsapp_message(whatsapp_api_url, whatsapp_id,
                              b.format(r_name=name))

    ## if new user
    else:
        if body != '1' and body != '2':
            send_whatsapp_message(whatsapp_api_url, whatsapp_id, c)
        if body == '1':
            send_whatsapp_message(whatsapp_api_url, whatsapp_id, c1)
        if body == '2':
            send_whatsapp_message(whatsapp_api_url, whatsapp_id, c2)

    print('\n The whatsapp ID is ' + whatsapp_id + '\n', flush=True)
Ejemplo n.º 4
0
def send_whatsapp_template_message(url, to, namespace, element_name,
                                   message_template, body_parameter):
    message = message_template.format(body_parameter)
    add_message(to[2:], bot_number, to[2:], message, "text", "whatsapp",
                "outgoing")
    url = url + '/v1/messages'
    authkey = get_auth_key()
    print("Inside message", flush=True)
    data = {
        "to": to,
        "type": "hsm",
        "hsm": {
            "namespace": namespace,
            "element_name": element_name,
            "language": {
                "policy": "deterministic",
                "code": "en"
            },
            "localizable_params": body_parameter
        }
    }
    headers = {
        'Content-type': 'application/json',
        'Authorization': "Bearer " + authkey
    }
    try:
        response = requests.request("POST",
                                    url,
                                    data=json.dumps(data),
                                    headers=headers,
                                    verify=False).json()
        print(response, flush=True)
        if response.get("errors") is None:
            print("WhatsApp message sent", flush=True)
            return True
        else:
            print("message {message} not sent, received response {txt}".format(
                message=message, txt=str(response.text)),
                  flush=True)
            return False
    except Exception as e:
        print("message {message} not sent, received exception {exception}".
              format(message=message, exception=str(e)),
              flush=True)
        return False
Ejemplo n.º 5
0
def send_whatsapp_message_image(url, to, media_link, media_caption):
    add_message(to[2:], bot_number, to[2:], media_link, "image", "whatsapp",
                "outgoing")
    url = url + '/v1/messages'
    authkey = get_auth_key()
    ##print("Inside message")
    data = {
        "to": to,
        "type": "image",
        "recipient_type": "individual",
        "image": {
            "provider": {
                "name": "covidsos"
            },
            "link": "<Link to Image, https>",
            "caption": "<Media Caption>"
        }
    }
    headers = {
        'Content-type': 'application/json',
        'Authorization': "Bearer " + authkey
    }
    try:
        response = requests.request("POST",
                                    url,
                                    data=json.dumps(data),
                                    headers=headers,
                                    verify=False)
        print("message sent")
        if (str(response) == '<Response [201]>'):
            output = {
                'Response': json.loads(response.text)['messages'],
                'status': True,
                'string_response': 'Successfully sent'
            }
    except Exception as e:
        output = {
            'Response': {},
            'status': False,
            'string_response': 'Failure'
        }
        print(e)
    return output
Ejemplo n.º 6
0
def Get_Message():
    # now = str(dt.datetime.now().date())
    # now_time = str(dt.datetime.now())
    response = request.json
    print(response)

    frm = str(response["messages"][0]["from"])
    text = str(response["messages"][0]["text"]["body"])
    ## query for volunteer
    checkState = """SELECT name, timestamp, id from volunteers where mob_number='{mob_number}'""".format(
        mob_number=frm[2:])
    records_a = pd.read_sql(checkState, connections('prod_db_read'))

    ## query for requester
    checkState = """SELECT name, timestamp, id from requests where mob_number='{mob_number}'""".format(
        mob_number=frm[2:])
    records_b = pd.read_sql(checkState, connections('prod_db_read'))

    ## check for volunteer
    if records_a.shape[0] > 0:
        name = records_a.loc[0, 'name']
        add_message(frm, frm, bot_number, text, "text", "whatsapp", "incoming")
        send_whatsapp_message(whatsapp_api_url, frm, a.format(v_name=name))

    ## check for requester
    elif records_b.shape[0] > 0:
        name = records_b.loc[0, 'name']
        add_message(frm, frm, bot_number, text, "text", "whatsapp", "incoming")
        send_whatsapp_message(whatsapp_api_url, frm, b.format(r_name=name))
    ## if new user
    else:
        print(text)
        if text != '1' and text != '2':
            send_whatsapp_message(whatsapp_api_url, frm, c)
        if text == '1':
            send_whatsapp_message(whatsapp_api_url, frm, c1)
        if text == '2':
            send_whatsapp_message(whatsapp_api_url, frm, c2)

    print('\n' + frm + '\n')
Ejemplo n.º 7
0
def send_whatsapp_template_message(url, to, namespace, element_name,
                                   message_template, body_parameter):
    message = message_template.format(body_parameter)
    add_message(to[2:], bot_number, to[2:], message, "text", "whatsapp",
                "outgoing")
    url = url + '/v1/messages'
    authkey = get_auth_key()
    print("Inside message")
    data = {
        "to": to,
        "type": "hsm",
        "hsm": {
            "namespace": namespace,
            "element_name": element_name,
            "language": {
                "policy": "deterministic",
                "code": "en"
            },
            "localizable_params": body_parameter
        }
    }
    headers = {
        'Content-type': 'application/json',
        'Authorization': "Bearer " + authkey
    }
    print(json.dumps(data))
    try:
        response = requests.request("POST",
                                    url,
                                    data=json.dumps(data),
                                    headers=headers,
                                    verify=False)
        print("message sent")
    except Exception as e:
        print(e)
    return response