def assignment_link(r_id): v_list_q = """Select id as v_id,mob_number,name, latitude,longitude from volunteers where status=1""" v_list = pd.read_sql(v_list_q,connections('prod_db_read')) v_list['dist'] = get_haversine_distance(lat,lon,) v_list = v_list.sort_values(by='dist',ascending=True) for i in v_list.index: if(v_list.loc[i,'dist']<'radius'): sms_text = 'Dear, '+v_list.loc[i,'name']+' someone in your area needs help. Click here to help '+link send_sms(sms_text,sms_to=v_list.loc[i,'mob_number'],sms_type='transactional',send=True) #incomplete return None
def send_moderator_msg(mob_number, message, preview_url=False): print(message, flush=True) m_num = str(91) + str(mob_number) print(m_num, flush=True) if has_user_replied(m_num): try: check_contact("+" + str(m_num), 'users') wa_msg = send_whatsapp_message(whatsapp_api_url, m_num, message, preview_url) if wa_msg: return { 'status': True, 'string_response': 'WhatsApp Message Sent' } else: send_sms(message, int(mob_number)) return {'status': True, 'string_response': 'SMS Sent'} except Exception as e: send_sms(message, int(mob_number)) print("Exception in sending message {e}".format(e=e), flush=True) return { 'status': False, 'string_response': 'Error in send_moderator_msg' } else: print( "User has not replied since last 24 hours; sending message {message} to {number}" .format(message=message, number=m_num)) send_sms(message, int(mob_number)) admin_reminder = 'Dear admin, Click https://wa.me/91{bot_number}?text=Hi and receive further message on whatsapp'.format( bot_number=bot_number) send_sms(admin_reminder, int(mob_number)) return {'status': True, 'string_response': 'SMS Sent'}
def add_volunteer(): name = request.form.get('name') mob_number = request.form.get('mob_number') email_id = request.form.get('email_id', '') address = request.form.get('address') geoaddress = request.form.get('geoaddress', address) latitude = request.form.get('latitude', 0.0) longitude = request.form.get('longitude', 0.0) source = request.form.get('source') status = request.form.get('status', 1) country = request.form.get('country', 'India') support_type = request.form.get('support_type', 'Deliver groceries and/or medicines') current_time = dt.datetime.utcnow() + dt.timedelta(minutes=330) req_dict = { 'timestamp': [current_time], 'name': [name], 'mob_number': [mob_number], 'email_id': [email_id], 'country': [country], 'address': [address], 'geoaddress': [geoaddress], 'latitude': [latitude], 'longitude': [longitude], 'source': [source], 'status': [status], 'support_type': [support_type] } df = pd.DataFrame(req_dict) expected_columns = [ 'timestamp', 'name', 'mob_number', 'email_id', 'country', 'address', 'geoaddress', 'latitude', 'longitude', 'source', 'status', 'support_type' ] x, y = add_volunteers_to_db(df) if (x): #Use from message_templates.py file url = "https://wa.me/918618948661?text=" + urllib.parse.quote_plus( "Hi") if (y == 'Volunteer already exists. No New Volunteers to be added'): sms_text = "[COVIDSOS] You are already registered with us. Click here to contact us " + url else: sms_text = "[COVIDSOS] Thank you for registering. Click here to contact us:" + url send_sms(sms_text, sms_to=int(mob_number), sms_type='transactional', send=True) response = {'Response': {}, 'status': x, 'string_response': y} return json.dumps(response)
def message_all_volunteers(uuid,radius,search_radius): v_list_q = """Select id as v_id,mob_number,name, latitude,longitude from volunteers where status=1""" v_list = pd.read_sql(v_list_q,connections('prod_db_read')) r_df = request_data_by_uuid(uuid) r_id = r_df.loc[0,'r_id'] lat = r_df.loc[0,'latitude'] lon = r_df.loc[0,'longitude'] v_list['dist'] = get_haversine_distance(float(lat),float(lon),v_list['latitude'].astype(float).values,v_list['longitude'].astype(float).values) v_list = v_list.sort_values(by='dist',ascending=True) v_ids = pd.DataFrame() df = pd.DataFrame() df2 = pd.DataFrame() count=0 orig_link = url_start+"accept/"+uuid link = url_shortener_fn(orig_link) print(link) save_request_sms_url(uuid, 'accept_link', link) for i in v_list.index: if(v_list.loc[i,'dist']<radius): count = count +1 if(count>20): break sms_text = nearby_v_sms_text.format(v_name=v_list.loc[i,'name'],link=link) sms_to = int(v_list.loc[i,'mob_number']) df = df.append(v_list.loc[i,['v_id']]) if((server_type=='prod')): send_sms(sms_text,sms_to,sms_type='transactional',send=True) print('SMS sent') else: print('Sending sms:',sms_text,' to ',str(sms_to)) if((v_list.loc[i,'dist']>radius)&(v_list.loc[i,'dist']<search_radius)): count = count +1 if(count>20): break sms_text = far_v_sms_text.format(address=r_df.loc[0,'geoaddress'][0:40],link=link) sms_to=int(v_list.loc[i,'mob_number']) df2 = df2.append(v_list.loc[i,['v_id']]) if((server_type=='prod')): send_sms(sms_text,sms_to,sms_type='transactional',send=True) print('SMS sent') else: print('Sending sms:',sms_text,' to ',str(sms_to)) df['r_id']=r_id df['status']='pending' print(v_list) print(df) print(df2) if((server_type=='prod')): engine = connections('prod_db_write') df.to_sql(name = 'nearby_volunteers', con = engine, schema='covidsos', if_exists='append', index = False,index_label=None) mod_sms_text = request_verified_m_sms1.format(r_id=str(r_df.loc[0,'r_id']),name=r_df.loc[0,'name'],geoaddress=r_df.loc[0,'geoaddress'][0:50],mob_number=str(r_df.loc[0,'mob_number']),v_count_1=str(df.shape[0]),v_count_2=str(df2.shape[0])) str_broadcast = "For request #"+str(r_df.loc[0,'r_id'])+ " " counter_broadcast = 0 for i in v_list.index: counter_broadcast = counter_broadcast+1 if((counter_broadcast>10) or (v_list.loc[i,'dist']>search_radius)): break str_broadcast = str_broadcast + v_list.loc[i,'name']+" m: wa.me/91"+str(v_list.loc[i,'mob_number'])+" " link = url_shortener_fn("https://wa.me/918618948661?text="+p.quote(str_broadcast)) save_request_sms_url(uuid, 'broadcast_link', link) mod_sms_text_2 = request_verified_m_sms2.format(link=link) moderator_list = get_moderator_list() for i_number in moderator_list: if((server_type=='prod')): send_sms(mod_sms_text,sms_to=int(i_number),sms_type='transactional',send=True) send_sms(mod_sms_text_2,sms_to=int(i_number),sms_type='transactional',send=True) print('SMS sent') else: print('Sending sms:',mod_sms_text,' to ',str(i_number)) print('Sending sms:',mod_sms_text_2,' to ',str(i_number)) return None
def create_request(): name = request.form.get('name') mob_number = request.form.get('mob_number') email_id = request.form.get('email_id', '') age = request.form.get('age') address = request.form.get('address') geoaddress = request.form.get('geoaddress', address) user_request = request.form.get('request') latitude = request.form.get('latitude', 0.0) longitude = request.form.get('longitude', 0.0) source = request.form.get('source', 'covidsos') status = request.form.get('status', 'received') country = request.form.get('country', 'India') current_time = dt.datetime.utcnow() + dt.timedelta(minutes=330) uuid = generate_uuid() req_dict = { 'timestamp': [current_time], 'name': [name], 'mob_number': [mob_number], 'email_id': [email_id], 'country': [country], 'address': [address], 'geoaddress': [geoaddress], 'latitude': [latitude], 'longitude': [longitude], 'source': [source], 'age': [age], 'request': [user_request], 'status': [status], 'uuid': [uuid] } df = pd.DataFrame(req_dict) df['email_id'] = df['email_id'].fillna('') expected_columns = [ 'timestamp', 'name', 'mob_number', 'email_id', 'country', 'address', 'geoaddress', 'latitude', 'longitude', 'source', 'request', 'age', 'status', 'uuid' ] x, y = add_requests(df) response = {'Response': {}, 'status': x, 'string_response': y} if (x): #Move to message_templates.py file url = "https://wa.me/918618948661?text=" + urllib.parse.quote_plus( 'Hi') sms_text = "[COVIDSOS] " + name + ", we have received your request. We will call you soon. If urgent, please click " + url send_sms(sms_text, sms_to=int(mob_number), sms_type='transactional', send=True) # mod_url = "https://wa.me/91"+str(mob_number)+"?text="+urllib.parse.quote_plus('Hey') #Add to message_templates.py mod_url = "https://covidsos.org/verify/" + str(uuid) mod_sms_text = 'New query received. Verify lead by clicking here: ' + mod_url moderator_list = get_moderator_list() for i_number in moderator_list: send_sms(mod_sms_text, sms_to=int(i_number), sms_type='transactional', send=True) #move to async # volunteer_request.apply_async((latitude,longitude,neighbourhood_radius,search_radius,uuid),countdown=100) #Move to Async after 5 mins # sms_text = "[COVIDSOS] "+name+", you can track your request at "+url # send_sms(sms_text,sms_to=int(mob_number),sms_type='transactional',send=True) #Send SMS to volunteers via async Task: #NEEDS REVIEW # volunteer_sms_countdown = 30 # volunteer_request.apply_async((latitude,longitude,neighbourhood_radius,search_radius,uuid)) # no_volunteer_assigned.apply_async((latitude,longitude,neighbourhood_radius,search_radius,uuid),countdown=volunteer_sms_countdown) #Schedule message after 30 mins depending on status - Send WhatsApp Link here. return json.dumps(response)
def verify_request(*args, **kwargs): uuid = request.form.get('uuid') what = request.form.get('what') why = request.form.get('why') financial_assistance = request.form.get('financial_assistance', 0) verification_status = request.form.get('verification_status') verified_by = kwargs.get('user_id', 0) r_id = request.form.get('r_id') name = request.form.get('name') where = request.form.get('geoaddress') mob_number = request.form.get('mob_number') urgent_status = request.form.get('urgent', 'no') source = request.form.get('source', 'covidsos') volunteers_reqd = request.form.get('volunteer_count', 1) current_time = dt.datetime.utcnow() + dt.timedelta(minutes=330) if (verification_status is None): return json.dumps({ 'Response': {}, 'status': False, 'string_response': 'Please send verification status' }) if ((r_id is None) or (uuid is None)): return json.dumps({ 'Response': {}, 'status': False, 'string_response': 'Please send UUID/request ID' }) r_df = request_data_by_uuid(uuid) if (r_df.shape[0] == 0): return json.dumps({ 'Response': {}, 'status': False, 'string_response': 'Invalid UUID/request ID' }) if (r_df.loc[0, 'source'] != source): response_0 = update_requests_db({'uuid': uuid}, {'source': source}) if (r_df.loc[0, 'status'] == 'received'): r_v_dict = { 'r_id': [r_id], 'why': [why], 'what': [what], 'where': [where], 'verification_status': [verification_status], 'verified_by': [verified_by], 'timestamp': [current_time], 'financial_assistance': [financial_assistance], 'urgent': [urgent_status] } df = pd.DataFrame(r_v_dict) expected_columns = [ 'timestamp', 'r_id', 'what', 'why', 'where', 'verification_status', 'verified_by', 'financial_assistance', 'urgent' ] response_2 = update_requests_db({'uuid': uuid}, { 'status': verification_status, 'volunteers_reqd': volunteers_reqd }) print('updated the status') past_id, past_status = check_past_verification(str(r_id)) if (past_status == True): r_v_dict = { 'r_id': r_id, 'why': why, 'what': what, 'where': where, 'verification_status': verification_status, 'verified_by': verified_by, 'timestamp': current_time, 'financial_assistance': financial_assistance, 'urgent': urgent_status } rv_dict = {x: r_v_dict[x] for x in r_v_dict} update_request_v_db({'id': (past_id)}, rv_dict) else: x, y = add_request_verification_db(df) if (verification_status == 'verified'): #Move to message_templates.py file requestor_text = '[COVIDSOS] Your request has been verified. We will look for volunteers in your neighbourhood.' send_sms(requestor_text, sms_to=int(mob_number), sms_type='transactional', send=True) message_all_volunteers(uuid, neighbourhood_radius, search_radius) else: #Move to message_templates.py file requestor_text = '[COVIDSOS] Your request has been cancelled/rejected. If you still need help, please submit request again.' send_sms(requestor_text, sms_to=int(mob_number), sms_type='transactional', send=True) return json.dumps({ 'Response': {}, 'status': response_2['status'], 'string_response': response_2['string_response'] }) else: return json.dumps({ 'Response': {}, 'status': False, 'string_response': 'Request already verified/rejected' })
def auto_assign_volunteer(): v_id = request.form.get('volunteer_id') uuid = request.form.get('uuid') matching_by = 'autoassigned' task_action = request.form.get('task_action') r_df = request_data_by_uuid(uuid) v_df = volunteer_data_by_id(v_id) if (r_df.shape[0] == 0): return json.dumps({ 'status': False, 'string_response': 'Request ID does not exist.', 'Response': {} }) if (v_df.shape[0] == 0): return json.dumps({ 'status': False, 'string_response': 'Volunteer does not exist', 'Response': {} }) else: r_id = r_df.loc[0, 'r_id'] if (((r_df.loc[0, 'status'] == 'received') or (r_df.loc[0, 'status'] == 'verified') or (r_df.loc[0, 'status'] == 'pending')) & (task_action == 'accepted')): current_time = dt.datetime.utcnow() + dt.timedelta(minutes=330) req_dict = { 'volunteer_id': [v_id], 'request_id': [r_id], 'matching_by': [matching_by], 'timestamp': [current_time] } df = pd.DataFrame(req_dict) response = request_matching(df) response_2 = update_requests_db({'id': r_id}, {'status': 'matched'}) response_3 = update_nearby_volunteers_db({'r_id': r_id}, {'status': 'expired'}) #Move to message_templates.py file #Send to Volunteer v_sms_text = '[COVID SOS] Thank you agreeing to help. Name:' + r_df.loc[ 0, 'name'] + ' Mob:' + str( r_df.loc[0, 'mob_number']) + ' Request:' + r_df.loc[ 0, 'request'] + ' Address:' + r_df.loc[0, 'geoaddress'] send_sms(v_sms_text, int(v_df.loc[0, 'mob_number']), sms_type='transactional', send=True) #Send to Requestor v_sms_text = '[COVID SOS] Volunteer ' + v_df.loc[ 0, 'name'] + ' will help you. Mob: ' + str( v_df.loc[0, 'mob_number']) send_sms(v_sms_text, int(r_df.loc[0, 'mob_number']), sms_type='transactional', send=True) return json.dumps(response) elif ((r_df.loc[0, 'status'] == 'received') or (r_df.loc[0, 'status'] == 'verified') or (r_df.loc[0, 'status'] == 'pending')): response_3 = update_nearby_volunteers_db( { 'r_id': r_id, 'v_id': v_id }, {'status': 'expired'}) return json.dumps({ 'status': True, 'string_response': 'Request rejected', 'Response': {} }) else: return json.dumps({ 'status': False, 'string_response': 'Request already assigned', 'Response': {} })
def assign_request_to_volunteer(volunteer_id, request_id, matched_by): r_df = request_data_by_id(request_id) v_df = volunteer_data_by_id(volunteer_id) if (r_df.shape[0] == 0): return { 'status': False, 'string_response': 'Request ID does not exist.', 'Response': {} } if (v_df.shape[0] == 0): return { 'status': False, 'string_response': 'Volunteer does not exist', 'Response': {} } else: if (r_df.loc[0, 'status'] in ['received', 'verified', 'pending']): current_time = dt.datetime.utcnow() + dt.timedelta(minutes=330) req_dict = { 'volunteer_id': [volunteer_id], 'request_id': [r_df.loc[0, 'r_id']], 'matching_by': [matched_by], 'timestamp': [current_time] } df = pd.DataFrame(req_dict) #Add entry in request_matching table response = request_matching(df) #Update request status as matched if response['status'] == True: volunteers_assigned = get_volunteers_assigned_to_request( request_id) if r_df.loc[0, 'volunteers_reqd'] == volunteers_assigned: response_2 = update_requests_db({'id': request_id}, {'status': 'matched'}) response_3 = update_nearby_volunteers_db( {'r_id': request_id}, {'status': 'expired'}) #Move to message_templates.py file #Send to Volunteer v_sms_text = '[COVID SOS] Thank you agreeing to help. Name:' + r_df.loc[ 0, 'name'] + ' Mob:' + str( r_df.loc[0, 'mob_number']) + ' Request:' + r_df.loc[ 0, 'request'] + ' Address:' + r_df.loc[0, 'geoaddress'] send_sms(v_sms_text, int(v_df.loc[0, 'mob_number']), sms_type='transactional', send=True) #Send to Requestor r_sms_text = '[COVID SOS] Volunteer ' + v_df.loc[ 0, 'name'] + ' will help you. Mob: ' + str( v_df.loc[0, 'mob_number']) send_sms(r_sms_text, int(r_df.loc[0, 'mob_number']), sms_type='transactional', send=True) #Send to Moderator m_sms_text = '[COVID SOS] Volunteer ' + v_df.loc[ 0, 'name'] + ' Mob: ' + str( v_df.loc[0, 'mob_number']) + ' assigned to ' + r_df.loc[ 0, 'name'] + ' Mob:' + str(r_df.loc[0, 'mob_number']) moderator_list = get_moderator_list() for i_number in moderator_list: send_sms(m_sms_text, int(i_number), sms_type='transactional', send=True) else: return { 'status': False, 'string_response': 'Request already assigned/closed/completed', 'Response': {} } return response
def send_request_template(uuid, sms_text, mob_number): try: v_df = volunteer_data_by_mob(mob_number) if (v_df.shape[0] == 0): return { 'status': False, 'string_response': 'Volunteer number incorrect' } if (pd.isna(v_df.loc[0, 'whatsapp_id']) or v_df.loc[0, 'whatsapp_id'] == 'processing'): check_contact("+" + str(91) + str(mob_number), 'volunteers', whatsapp_api_url) v_df = volunteer_data_by_mob(mob_number) df = accept_request_page(uuid) v_name = v_df.loc[0, 'name'] requestor_name = df.loc[0, 'name'] Address = df.loc[0, 'request_address'] urgency_status = 'This is an urgent request!' if df.loc[ 0, 'urgent'] == 'yes' else 'This request needs support in 1-2 days' reason = df.loc[0, 'why'] requirement = df.loc[0, 'what'] if (server_type == 'prod'): acceptance_link = 'https://covidsos.org/accept/' + str(uuid) v_name = "from CovidSOS" else: acceptance_link = 'https://stg.covidsos.org/accept/' + str(uuid) v_name = " Test " financial_assistance_status = 'This help-seeker cannot afford to pay.' if df.loc[ 0, 'financial_assistance'] == 1 else 'This help-seeker can afford to pay for items delivered.' body_parameters = [{ "default": v_name }, { "default": requestor_name }, { "default": Address }, { "default": urgency_status }, { "default": requestor_name }, { "default": reason }, { "default": requestor_name }, { "default": requirement }, { "default": financial_assistance_status }, { "default": acceptance_link }] message = whatsapp_temp_1_message.format( v_name=v_name, requestor_name=requestor_name, Address=Address, urgency_status=urgency_status, reason=reason, requirement=requirement, financial_assistance_status=financial_assistance_status, acceptance_link=acceptance_link) print(message, flush=True) m_num = v_df.loc[0, 'whatsapp_id'] print(m_num, flush=True) if ((m_num == 'SMS') or (send_whatsapp_template_message( whatsapp_api_url, m_num, namespace, whatsapp_temp_1, message, body_parameters) == False)): send_sms(sms_text, int(mob_number)) print('SMS sent', flush=True) return {'status': True, 'string_response': 'Message Sent'} except Exception as e: print("Exception in sending message {e}".format(e=e), flush=True) return {'status': False, 'string_response': 'Error occurred'}
def message_all_volunteers(uuid, radius, search_radius): v_list_q = """Select id as v_id,mob_number,name, latitude,longitude from volunteers where status=1""" v_list = pd.read_sql(v_list_q, connections('prod_db_read')) r_df = request_data_by_uuid(uuid) r_id = r_df.loc[0, 'r_id'] lat = r_df.loc[0, 'latitude'] lon = r_df.loc[0, 'longitude'] v_list['dist'] = get_haversine_distance( float(lat), float(lon), v_list['latitude'].astype(float).values, v_list['longitude'].astype(float).values) v_list = v_list.sort_values(by='dist', ascending=True) v_ids = pd.DataFrame() df = pd.DataFrame() df2 = pd.DataFrame() count = 0 if (server_type == 'prod'): key_word = 'COVIDSOS' url_start = "https://covidsos.org/" else: key_word = 'TEST' url_start = "https://stg.covidsos.org/" for i in v_list.index: if (v_list.loc[i, 'dist'] < radius): orig_link = url_start + "accept/" + uuid link = url_shortener_fn(orig_link) sms_text = "[" + key_word + "]. Dear " + v_list.loc[ i, 'name'] + ", HELP NEEDED in your area. Click " + link + " to help." sms_to = int(v_list.loc[i, 'mob_number']) df = df.append(v_list.loc[i, ['v_id']]) print(link) if ((server_type == 'prod')): send_sms(sms_text, sms_to, sms_type='transactional', send=True) print('SMS sent') else: print('Sending sms:', sms_text, ' to ', str(sms_to)) if ((v_list.loc[i, 'dist'] > radius) & (v_list.loc[i, 'dist'] < search_radius)): count = count + 1 if (count > 20): break orig_link = url_start + "accept/" + uuid link = url_shortener_fn(orig_link) print(link) sms_text = "[" + key_word + "] HELP NEEDED in " + r_df.loc[ 0, 'geoaddress'][ 0:40] + ".. Click " + link + " to help or refer someone." sms_to = int(v_list.loc[i, 'mob_number']) df2 = df2.append(v_list.loc[i, ['v_id']]) if ((server_type == 'prod')): send_sms(sms_text, sms_to, sms_type='transactional', send=True) print('SMS sent') else: print('Sending sms:', sms_text, ' to ', str(sms_to)) df['r_id'] = r_id df['status'] = 'pending' print(v_list) print(df) print(df2) if ((server_type == 'prod')): engine = connections('prod_db_write') df.to_sql(name='nearby_volunteers', con=engine, schema='covidsos', if_exists='append', index=False, index_label=None) mod_sms_text = key_word + " New request verified. Sent to " + str( df.shape[0]) + " nearby Volunteers and " + str( df2.shape[0]) + " volunteers further away" mod_sms_text_2 = key_word + " Request #" + str( r_df.loc[0, 'r_id'] ) + " New Request Name: " + r_df.loc[0, 'name'] + " Address: " + r_df.loc[ 0, 'geoaddress'][0:50] + " Mob: " + str( r_df.loc[0, 'mob_number']) + " Req:" + r_df.loc[0, 'request'] str_broadcast = "For request #" + str(r_df.loc[0, 'r_id']) + " " counter_broadcast = 0 for i in v_list.index: counter_broadcast = counter_broadcast + 1 if ((counter_broadcast > 10) or (v_list.loc[i, 'dist'] > search_radius)): break str_broadcast = str_broadcast + v_list.loc[ i, 'name'] + " m: wa.me/91" + str(v_list.loc[i, 'mob_number']) + " " link = url_shortener_fn("https://wa.me/918618948661?text=" + p.quote(str_broadcast)) mod_sms_text_3 = "Broadcast to volunteers using " + link moderator_list = get_moderator_list() for i_number in moderator_list: if ((server_type == 'prod')): send_sms(mod_sms_text, sms_to=int(i_number), sms_type='transactional', send=True) send_sms(mod_sms_text_2, sms_to=int(i_number), sms_type='transactional', send=True) send_sms(mod_sms_text_3, sms_to=int(i_number), sms_type='transactional', send=True) print('SMS sent') else: print('Sending sms:', mod_sms_text, ' to ', str(i_number)) print('Sending sms:', mod_sms_text_2, ' to ', str(i_number)) print('Sending sms:', mod_sms_text_3, ' to ', str(i_number)) return None