def fallback_support_file_not_found(self, batch, topic): name = self.get_cookie("name") email= self.get_cookie("email") email_sender = EmailSender() email_sender.sendEmailToSupportForFileNotFound(name, email, batch, topic) response = "Email sent to support team! You will be contacted soon" return response
def processRequest(res): log = logger.Log() sessionID = req.get('responseId') result = req.get("queryResult") user_says = result.get("queryText") log.write_log(sessionID, "User Says: " + user_says) parameters = result.get("parameters") cust_name = parameters.get("cust_name") cust_contact = parameters.get("cust_contact") cust_email = parameters.get("cust_email") course_name = parameters.get("course_name") intent = reuslt.get("intent").get('displayName') if(intent == 'course_selection'): email_sender = EmailSender() template = template_reader.TemplateReader() email_message = template.read_course_template(course_name) emaile_sender.send_email_to_student(cust_email, email_message) email_file_support = open("email_templates/support_team_Template.html", "r") email_message_support = email_file_support.read() email_sender.send_email_to_support(cust_name=cust_name,cust_contact=cust_contact,cust_email=cust_email,course_name=course_name,body=email_message_support) fulfillmentText="We have sent the course syllabus and other relevant details to you via email. An email has been sent to the Support Team with your contact information, you'll be contacted soon. Do you have further queries?" log.write_log(seesionID, "Bot Says: " + fulfillmentText) return { "fulfillmentText": fulfillmentText } else: log.write_log(sessionID, "Bot Says: " + result.fulfillmentText)
def fallback_support(self, user_query): name = self.get_cookie("name") email= self.get_cookie("email") email_sender = EmailSender() email_sender.sendEmailToSupport(name, email, user_query) response = "Email sent to support team! You will be contacted soon" return response
def fallback_support_recording(self, batch, day): name = self.get_cookie("name") email= self.get_cookie("email") email_sender = EmailSender() email_sender.sendEmailToSupportForRecording(name, email, batch, day) response = "Email sent to support team! You will be contacted soon" return response
def fallback_support_dashboard_access(self, batch): name = self.get_cookie("name") email= self.get_cookie("email") email_sender = EmailSender() email_sender.sendEmailToSupportForDashboardAccess(name, email, batch) response = "Email sent to support team! You will be contacted soon" return response
def processRequest(req): log = logger.Log() sessionID = req.get('responseId') result = req.get("queryResult") user_says = result.get("queryText") log.write_log(sessionID, "User Says: " + user_says) # log.write_mongodb(sessionID, "User Says: " + user_says) parameters = result.get("parameters") cust_name = parameters.get("user_name") #print(cust_name) cust_contact = parameters.get("user_phone") cust_email = parameters.get("user_email") cust_pincode = parameters.get("user_pincode") cust_pincode = re.sub(' ', '', str(cust_pincode)) intent = result.get("intent").get('displayName') if (intent == 'ZipcodeSelection'): # covid19 = CoronaDataScrap() # data = covid19.scrap_data() #data = pd.read_csv('/DataScrap/Corona_reports.csv') email_sender = EmailSender() template = template_reader.TemplateReader() email_message = template.read_course_template('covid_19_template.html') email_sender.send_email_to_student(cust_email, email_message) # email_file_support = open("email_templates/support_team_Template.html", "r") # #email_message_support = email_file_support.read() #email_sender.send_email_to_support(cust_name=cust_name,cust_contact=cust_contact,cust_email=cust_email,course_name=course_name,body=email_message_support) fulfillmentText = "We have sent the Precautionary Measures and India's covid details to you via email. Stay safe and take care." log.write_log(sessionID, "Bot Says: " + fulfillmentText) #log.write_mongodb(sessionID, "Bot Says: " + fulfillmentText) return {"fulfillmentText": fulfillmentText} else: log.write_log(sessionID, "Bot Says: " + result.fulfillmentText)
def processRequest(req): log = logger.Log() sessionID = req.get('responseId') result = req.get("queryResult") user_says = result.get("queryText") log.write_log(sessionID, "User is: " + user_says) parameters = result.get("parameters") cust_name = parameters.get("usr_name") #print(cust_name) cust_email = parameters.get("usr_email") intent = result.get("intent").get('displayName') if (intent == 'Send_Resume'): email_sender = EmailSender() #template= template_reader.TemplateReader() email_message = "Hello. PFA Shivam Chauhan Resume" email_sender.send_email_to_student(cust_email, email_message) #email_file_support = open("email_templates/support_team_Template.html", "r") #email_message_support = email_file_support.read() #email_sender.send_email_to_support(cust_name=cust_name,cust_contact=cust_contact,cust_email=cust_email,course_name=course_name,body=email_message_support) fulfillmentText = "We have sent the Resume and other details to your email. Thanks you. Do you have further queries?" log.write_log(sessionID, "Bot Says: " + fulfillmentText) return {"fulfillmentText": fulfillmentText} else: log.write_log(sessionID, "Bot Says: " + result.fulfillmentText)
def predict(): ''' For rendering results on HTML GUI ''' #int_features = [22582, 2, 170, 90.0, 120, 80, 1, 1, 1, 1, 1, 31] i = 0 myList = [] for x in request.form.values(): if i == 0: name = x elif i == 1: email = x else: myList.append(x) i = i + 1 int_features = [int(x) for x in myList] int_features[0] = int_features[0] * 365 data = int_features[3] / (int_features[2] / 100)**2 int_features.append(data) final_features = pd.DataFrame([int_features]) prediction = model.predict(final_features) email_sender = EmailSender() email_file = open("email-templates/email-template-district.html", "r") email_message = email_file.read() if prediction[0] == 0: email_pred = "Hey! you are healthy. keep going on..Check your email for more information" else: email_pred = "Hey! you are more likely to have a cardio vascular outbreak. Take care. Check your email or the below link for more information" email_sender.sendEmailDistrict(name, email, email_message, email_pred) if prediction[0] == 0: return render_template( 'index.html', prediction_text= 'Hey! you seem not to have any cardio issues. you are healthy!. keep going on..' ) return render_template( 'index.html', prediction_text= 'Hey! you are more likely to have a cardio vascular outbreak. Take care of your health. For more details about the disease check the below link or your email' )
def processRequest(req): #log = logger.Log() sessionID = req.get('responseId') result = req.get("queryResult") user_says = result.get("queryText") #log.write_log(sessionID, "User Says: "+user_says) parameters = result.get("parameters") cust_contact = parameters.get("phn_no") course_no = parameters.get("number") cust_name = parameters.get("name") cust_email = parameters.get("email") print(cust_name) print(cust_contact) print(cust_email) print(course_no) if (course_no == 1): course_name = 'DataScienceMasters' elif (course_no == 2): course_name = 'MachineLearningMasters' elif (course_no == 3): course_name = 'DeepLearningMasters' else: course_name = 'NLPMasters' intent = result.get("intent").get('displayName') print(course_name) if (intent == 'course_selection'): email_sender = EmailSender() template = template_reader.TemplateReader() email_message = template.read_course_template(course_name) email_sender.send_email_to_student(cust_email, email_message) fulfillmentText = "We have sent course syllabus and other relevant details to your given email address. An email has sent to support team having your contact information, you will be contacted soon. Do you have further queries?" return {"fulfillmentText": fulfillmentText} else: return "nothing found"
def processRequest(req): log = logger.Log() sessionID=req.get('responseId') result = req.get("queryResult") user_says=result.get("queryText") log.write_log(sessionID, "User Says: "+user_says) parameters = result.get("parameters") cust_name=parameters.get("cust_name") #print(cust_name) cust_contact = parameters.get("cust_contact") cust_email=parameters.get("cust_email") person_name= parameters.get("person_name") intent = result.get("intent").get('displayName') if (intent=='Person_info'): email_sender=EmailSender() #template= template_reader.TemplateReader() #email_message=template.read_person_name(person_name) email_sender.send_email_to_student(cust_email,email_message) # email_file_support = open("email_templates/support_team_Template.html", "r") #email_message_support = email_file_support.read() email_sender.send_email_to_support(cust_name=cust_name,cust_contact=cust_contact,cust_email=cust_email,person_name=person_name,body=email_message_support) fulfillmentText="Happy botting" log.write_log(sessionID, "Bot Says: "+fulfillmentText) return { "fulfillmentText": fulfillmentText } else: log.write_log(sessionID, "Bot Says: " + result.fulfillmentText)
def processRequest(req): log = logger.Log() sessionID = req.get('responseId') result = req.get("queryResult") user_says = result.get("queryText") log.write_log(sessionID, "User Says: "+user_says) parameters = result.get("parameters") #cust_name = parameters.get("name") #cust_contact = parameters.get("mobile") cust_email = parameters.get("mail") cust_city = parameters.get("state") custdistrict = parameters.get('district') intent = result.get("intent").get('displayName') message = 'No Data Found' api_data = get_api_data(custdistrict,cust_city) if api_data.get('status',False): message = api_data['message'] log.write_log('cust', "Cust Details%r"%[cust_city, cust_email, custdistrict]) if (intent== 'zip'): email_sender = EmailSender() email_file = open("email_templates/bot.html", "r") email_message = email_file.read() email_sender.send_email_to_student(cust_email, email_message, message) fulfillmentText = "We have sent the course syllabus " log.write_log('fulfillmentText', "Bot Says: " + fulfillmentText) return { "fulfillmentText": fulfillmentText } else: pass
def processRequest(req): log = logger.Log() sessionID = req.get("responseId") user_says = req.get("queryText") result = reg.get("queryResult") log.writeLog(sessionID, "User Says : " + user_says) parameters = req.get("parameters") name = parameters.get("name") pin = parameters.get("pin") mailid = parameters.get("mailid") phone = parameters.get("phone") option_name = paramerers.get("option_name") intent = result.get("intent").get('displayName') if intent == "covid_intent": email_sender = EmailSender() template = template_reader.TemplateReader() email_message = template.select_info(option_name) email_sender.send_email_to_student(mailid, email_message) email_file_support = open("email_templates/preventive_Template.html", "r") email_message_support = email_file_support.read() email_sender.send_email_to_support(name=name, phone=phone, mailid=mailid, option_name=option_name, body=email_message_support) fulfillmentText = "We have sent the details to you via email. An email has been sent to the Support Team with your contact information, you'll be contacted soon. Do you have further queries?" log.write_log(sessionID, "Bot Says: " + fulfillmentText) return {"fulfillmentText": fulfillmentText} else: log.write_log(sessionID, "Bot Says: " + result.fulfillmentText)
def processRequest(req): log = logger.Log() sessionID = req.get('responseId') result = req.get("queryResult") user_says = result.get("queryText") bot_says = result.get("fulfillmentText") log.write_log(sessionID, "User Says: " + user_says) parameters = result.get("parameters") cust_name = parameters.get("cust_name") #print(cust_name) cust_contact = parameters.get("cust_contact") cust_email = parameters.get("cust_email") course_name = parameters.get("course_name") intent = result.get("intent").get('displayName') if (intent == 'course_selection'): dbConn = pymongo.MongoClient("mongodb://localhost:27017/") db = dbConn['Chatbot'] collection = db['GD_INeuron_Course_Details'] if collection['SessionID'] == sessionID: collection.update_one( {"SessionId": sessionID}, {"$push": { "Event": { "$each": [user_says, bot_says] } }}, True) else: collection.insert_one({ "SessionId": sessionID, "Name": cust_name, "Contact": cust_contact, "EmailId": cust_email, "Course": course_name, "Events": [user_says, bot_says] }) email_sender = EmailSender() template = template_reader.TemplateReader() email_message = template.read_course_template(course_name) email_sender.send_email_to_student(cust_email, email_message) email_file_support = open("email_templates/support_team_Template.html", "r") email_message_support = email_file_support.read() email_sender.send_email_to_support(cust_name=cust_name, cust_contact=cust_contact, cust_email=cust_email, course_name=course_name, body=email_message_support) fulfillmentText = "We have sent the course syllabus and other relevant details to you via email. An email has been sent to the Support Team with your contact information, you'll be contacted soon. Do you have further queries?" log.write_log(sessionID, "Bot Says: " + fulfillmentText) return {"fulfillmentText": fulfillmentText} else: log.write_log(sessionID, "Bot Says: " + result.fulfillmentText)
def processRequest(req): log = logger.Log() sessionID=req.get('responseId') result = req.get("queryResult") user_says=result.get("queryText") log.write_log(sessionID, "User Says: "+user_says) parameters = result.get("parameters") cust_name=parameters.get("Name") cust_contact = parameters.get("PhoneNumber") cust_email=parameters.get("Email") course_name= parameters.get("Disease") intent = result.get("intent").get('displayName') if (intent=='appoint_yes_confirm'): email_sender=EmailSender() template= template_reader.TemplateReader() email_message=template.read_course_template(course_name) email_sender.send_email_to_student(cust_email,email_message) email_file_support = open("email_templates/support_team_Template.html", "r") email_message_support = email_file_support.read() email_sender.send_email_to_support(cust_name=cust_name,cust_contact=cust_contact,cust_email=cust_email,course_name=course_name,body=email_message_support) fulfillmentText="An email has been sent to the Support Team with your contact information, you'll be contacted soon with appointment details. " log.write_log(sessionID, "Bot Says: "+fulfillmentText) return { "fulfillmentText": fulfillmentText } if (intent == 'Welcome_Intent'): return { "fulfillmentMessages": [ { "card": { "title": "Hello. Good day. Please choose any of the below.", "buttons": [ { "text": "Need advise.", "postback": "Advise" }, { "text": "Consultation", "postback": "Consultation" }, { "text": "Book Appointment ?", "postback": "Appointment" } ] } } ] } else: log.write_log(sessionID, "Bot Says: " + result.fulfillmentText)
def processRequest(req): log = logger.Log() sessionID = req.get('responseId') result = req.get("queryResult") user_says = result.get("queryText") log.write_log(sessionID, "User Says: " + user_says) parameters = result.get("parameters") user_name = parameters.get("user_name") option_name = parameters.get("option_name") option_name_2 = parameters.get("option_name_2") user_location = parameters.get("user_location") user_location = user_location.upper() user_mobile = parameters.get("user_mobile") user_email = parameters.get("user_email") #intent = result.get("intent").get('displayName') cases = CovidCases() email_sender = EmailSender() content_email = email_content.EmailContent() if (option_name == 'Covid-19 in India'): cases_india = cases.covid_india(user_location) content_india = content_email.email_india(cases_india) email_sender.send_email_to_user(user_email, content_india) fulfillmentText = "The total confirmed cases in {} state is {}.For more details please check your Email and for visualization please check below link. https://www.covid19india.org/".format( cases_india.get("response").get('name'), cases_india.get("response").get('confirmed')) log.write_log(sessionID, "Bot Says: " + fulfillmentText) return {"fulfillmentText": fulfillmentText} elif (option_name_2 == 'Covid-19 in World'): cases_world = cases.covid_world(user_location) content_world = content_email.email_world(cases_world) email_sender.send_email_to_user(user_email, content_world) fulfillmentText = "The total confirmed cases in {} is {}.For more details please check your Email and for visualization please check below link. https://www.covidvisualizer.com/".format( cases_world.get('country'), cases_world.get('confirmed')) log.write_log(sessionID, "Bot Says: " + fulfillmentText) return {"fulfillmentText": fulfillmentText} else: log.write_log(sessionID, "Bot Says: " + result.fulfillmentText)
def processRequest(req): global webhookresponse, webhookresponse1, fulfillmentText log = logger.Log() sessionID = req.get('responseId') result = req.get("queryResult") user_says = result.get("queryText") ##log.write_log(sessionID, "User Says: "+user_says,webhookresponse,intent) parameters = result.get("parameters") cust_name = parameters.get("cust_name") #print(cust_name) cust_contact = parameters.get("cust_contact") cust_email = parameters.get("cust_email") course_name = parameters.get("course_name") intent = result.get("intent").get('displayName') if (intent == 'country_selection'): cust_country = parameters.get("cust-country") if (cust_country == "United States"): cust_country = "USA" if (cust_country == "United Arab Emirates"): cust_country = "UAE" if (cust_country == "United Kingdom"): cust_country = "UK" fulfillmentText, deaths_data, testsdone_data = makeApiRequest( cust_country) webhookresponse = "***Covid Report*** \n\n" +\ " New cases :" + str( fulfillmentText.get( 'new' ) ) + \ "\n" + " Active cases : " + str( fulfillmentText.get( 'active' ) ) + "\n" + " Critical cases : " + str( fulfillmentText.get( 'critical' ) ) + \ "\n" + " Recovered cases : " + str( fulfillmentText.get( 'recovered' ) ) + "\n" + " Total cases : " + str( fulfillmentText.get( 'total' ) ) + \ "\n" + " New Deaths : " + str( deaths_data.get( 'new' ) ) + "\n" + " Total Deaths : " + str( deaths_data.get( 'total' ) ) + \ "\n" + " Total Test Done : " + str( testsdone_data.get( 'total' ) ) + "\n\n*******END********* \n " print("Country Name :", cust_country) print(webhookresponse) fulfillmentText = cust_country + "\n" + webhookresponse + "\n\n" + "Do you want me to share COVID-19 related information on your email id? Please chose from the below \n 1. Sure! \n 2. No. Thanks!" log.write_log(sessionID, "Current Cases", webhookresponse, intent) return { "fulfillmentText": fulfillmentText # "fulfillmentTextMessages" : [ # { # "text":{ # "text":[ # cust_country # ] # } # }, # { # "text":{ # "text":[ # webhookresponse # ] # } # }, # { # "text":{ # "text":[ # "Do you want me to share COVID-19 related information on your email id? Please chose from the below \n 1. Sure! \n 2. No. Thanks!" # ] # } # } # ] } elif intent == "Welcome" or intent == "continue_conversation" or intent == "not_send_email" or intent == "endConversation" \ or intent == "Fallback" or intent == "FAQ" : fulfillmentText = result.get("fulfillmentText") log.write_log(sessionID, user_says, fulfillmentText, intent) elif intent == "Send_Email": # print("Please enter your name", cust_name) # while True: # if not cust_name.isalpha(): # print( "Please Enter valid name" ) # else: # break # print("Please enter your email id", cust_email) # print("Please enter your contact number", cust_contact) fulfillmentText = result.get("fulfillmentText") log.write_log(sessionID, "Sure send email", fulfillmentText, intent) email_sender = EmailSender() template = templatereader.TemplateReader() email_message = template.read_course_template() email_sender.sendEmail(cust_email, email_message) #fulfillmentText = "We have sent the Covid19 related information on your email address.Please chose from the below \n 1. Main Menu \n 2. Exit" log.write_log(sessionID, "Sure send email", fulfillmentText, intent) return {"fulfillmentText": fulfillmentText} elif intent == "worldwide_data": fulfillmentText = makeApiRequest("world") webhookresponse = "***Worldwide Cases Report*** \n\n" + " Recovered :" + str( fulfillmentText.__getitem__( 'recovered' ) ) + \ "\n" + " Deaths : " + str(fulfillmentText.__getitem__( 'deaths' ) ) + "\n" + " Confirmed cases : " + str( fulfillmentText.__getitem__( 'confirmed' ) ) + \ "\n" + "Last Checked :" + str(fulfillmentText.__getitem__('lastChecked') ) + "\n" + "Last Reported :" + str( fulfillmentText.__getitem__( 'lastReported' ) ) + \ "\n\n*******END********* \n " print(webhookresponse) fulfillmentText = webhookresponse + "\n\n" + "Do you want me to share COVID-19 related information on your email id? Please chose from the below \n 1. Sure! \n 2. No. Thanks!" log.write_log(sessionID, "Worldwide Cases", webhookresponse, intent) return {"fulfillmentText": fulfillmentText} elif intent == "COVID_Headlines": fulfillmentText = makeApiRequest("headlines") webhookresponse = "***COVID Headlines*** \n\n" + str(fulfillmentText[0:-1]) +\ "\n\n*******END*******\n" print(webhookresponse) fulfillmentText = webhookresponse + "\n\n" + "Do you want me to share COVID19 related information on your email id? Please chose from the below \n 1. Sure! \n 2. No. Thanks!" log.write_log(sessionID, "COVID Headlines", webhookresponse, intent) return {"fulfillmentText": fulfillmentText} elif intent == "indian_states": fulfillmentText = makeApiRequest("state") print(len(fulfillmentText)) webhookresponse1 = '' webhookresponse2 = '' webhookresponse3 = '' for i in range(0, 11): webhookresponse = fulfillmentText[i] webhookresponse1 += "*********\n" + " State :" + str( webhookresponse[ 'state' ] ) + \ "\n" + " Confirmed cases : " + str(webhookresponse[ 'confirmed' ] ) + "\n" + " Recovered cases : " + str( webhookresponse[ 'recovered' ] ) + \ "\n"+ "Death cases : " + str( webhookresponse[ 'deaths' ] ) + \ "\n***********" for i in range(11, 21): webhookresponse = fulfillmentText[i] webhookresponse2 += "*********\n" + " State :" + str( webhookresponse[ 'state' ] ) + \ "\n" + " Confirmed cases : " + str(webhookresponse[ 'confirmed' ] ) + "\n" + " Recovered cases : " + str( webhookresponse[ 'recovered' ] ) + \ "\n"+ "Death cases : " + str( webhookresponse[ 'deaths' ] ) + \ "\n***********" for i in range(21, 38): webhookresponse = fulfillmentText[i] webhookresponse3 += "*********\n" + " State :" + str( webhookresponse[ 'state' ] ) + \ "\n" + " Confirmed cases : " + str(webhookresponse[ 'confirmed' ] ) + "\n" + " Recovered cases : " + str( webhookresponse[ 'recovered' ] ) + \ "\n"+ "Death cases : " + str( webhookresponse[ 'deaths' ] ) + \ "\n***********" print("***Statewise Cases*** \n\n" + webhookresponse1 + "\n\n") print("***Statewise Cases*** \n\n" + webhookresponse2 + "\n\n") print("***Statewise Cases*** \n\n" + webhookresponse3 + "\n\n*******END********* \n") #fulfillmentText = webhookresponse1 + "\n" + webhookresponse2 + "\n" + webhookresponse3 + "\n\n" + "Do you want me to share COVID-19 related information on your email id? Please chose from the below \n 1. Sure! \n 2. No. Thanks!" log.write_log(sessionID, "Indian State Cases", webhookresponse1, intent) return { "fulfillmentText": "***Statewise Cases*** \n\n" + webhookresponse1 + "\n" + webhookresponse2 + "\n" + webhookresponse3 + "\n\n" + "Do you want me to share COVID-19 related information on your email id? Please chose from the below \n 1. Sure! \n 2. No. Thanks!" }
def worldData(req): sessionID = req.get('responseId') result = req.get("queryResult") user_says = result.get("queryText") parameters = result.get("parameters") cur = mysql.connection.cursor() cur.execute( "INSERT INTO user_chat_history(sessionId,message, updated_time) VALUES (%s, %s, %s)", (sessionID, "User says: " + user_says + "With parameters:- " + str(parameters), datetime.datetime.utcnow())) mysql.connection.commit() cur.close() name = parameters.get("name") email = parameters.get("email") url = " https://corona-api.com/countries" headers = {} response = requests.request("GET", url, headers=headers) data = json.loads(response.text) country = [] country_code = [] latitude = [] longitude = [] population = [] confirmed = [] recoverd = [] deaths = [] for items in data["data"]: latitude.append(items["coordinates"]["latitude"]) longitude.append(items["coordinates"]["longitude"]) population.append(items["population"]) country.append(items["name"]) country_code.append(items["code"]) confirmed.append(items["latest_data"]["confirmed"]) recoverd.append(items["latest_data"]["recovered"]) deaths.append(items["latest_data"]["deaths"]) dict1 = { 'country': country, 'county_code': country_code, 'latitude': latitude, 'longitude': longitude, 'population': population, 'confirmed': confirmed, 'recoverd': recoverd, 'deaths': deaths } df = pd.DataFrame(dict1) # saving the dataframe df.to_csv('world_stats.csv') a = createMap() email_sender = EmailSender() template = template_reader.TemplateReader() email_message = template.read_course_template("Worldwide_Template") email_message = email_message.replace('User', name) email_message = email_message.replace( 'corona-url', os.path.join(BASE_DIR, 'covid-19\email_templates\world_map.html')) email_sender.send_email_to_student(email, email_message) fulfillmentText = "We have sent the visulization of corona effects world wide and other relevant details to you via email.Do you have further queries?" cur = mysql.connection.cursor() cur.execute( "INSERT INTO user_chat_history(sessionId,message, updated_time) VALUES (%s, %s, %s)", (sessionID, "Bot says: " + fulfillmentText, datetime.datetime.utcnow())) mysql.connection.commit() cur.close() return {"fulfillmentText": fulfillmentText}
def processRequest(req): sessionID = req.get('responseId') result = req.get("queryResult") user_says = result.get("queryText") parameters = result.get("parameters") cur = mysql.connection.cursor() cur.execute( "INSERT INTO user_chat_history(sessionId,message, updated_time) VALUES (%s, %s, %s)", (sessionID, "User says: " + user_says + "With parameters:- " + str(parameters), datetime.datetime.utcnow())) mysql.connection.commit() cur.close() name = parameters.get("name") mobile_number = parameters.get("mobile_number") email = parameters.get("email") pin_code = parameters.get("pin_code") geolocator = Nominatim(user_agent="geoapiExercises") location = geolocator.geocode(pin_code) address_info = location.raw["display_name"] print(address_info) data_from_address = geolocator.geocode(address_info, addressdetails=True) address = data_from_address.raw["address"] print(address) country = address["country"] country_code = address["country_code"] if ("state" in address.keys()): state = address["state"] elif ("state_district" in address.keys()): state = address["state_district"] else: state = country if ("city" in address.keys()): city = address["city"] elif ("state_district" in address.keys()): city = address["state_district"] elif ("city_district" in address.keys()): city = address["city_district"] else: city = country if city == "Ahmedabad District": city = "Ahmadabad" if (country == "India"): url = "https://api.covid19india.org/v2/state_district_wise.json" headers = {} response = requests.request("GET", url, headers=headers) res = next( (sub for sub in json.loads(response.text) if sub['state'] == state), None) state_data = res city_data = next( (sub for sub in state_data['districtData'] if sub['district'] in city), None) if city_data != None: total_confimred_cases_in_district = city_data["confirmed"] total_confimred_cases_in_state = sum( d['confirmed'] for d in state_data['districtData'] if d) else: total_confimred_cases_in_district = 0 total_confimred_cases_in_state = 0 print(total_confimred_cases_in_district, total_confimred_cases_in_state) email_sender = EmailSender() template = template_reader.TemplateReader() email_message = template.read_course_template("India_template") email_message = email_message.replace('User', name) email_message = email_message.replace('pin_code', pin_code) email_message = email_message.replace('state', state) email_message = email_message.replace('city', city) email_message = email_message.replace( 'total_No_cases_c', str(total_confimred_cases_in_district)) email_message = email_message.replace( 'total_No_cases_s', str(total_confimred_cases_in_state)) email_sender.send_email_to_student(email, email_message) fulfillmentText = "We have sent the number of corona virus cases in your area and other relevant details to you via email.Do you have further queries?" cur = mysql.connection.cursor() cur.execute( "INSERT INTO user_chat_history(sessionId,message, updated_time) VALUES (%s, %s, %s)", (sessionID, "Bot says: " + fulfillmentText, datetime.datetime.utcnow())) mysql.connection.commit() cur.close() return {"fulfillmentText": fulfillmentText} else: url = "https://covid-19-data.p.rapidapi.com/country/code" querystring = {"format": "json", "code": country_code} headers = { 'x-rapidapi-host': "covid-19-data.p.rapidapi.com", 'x-rapidapi-key': "API-KEY" } response = requests.request("GET", url, headers=headers, params=querystring) counntry_info = json.loads(response.text) confirmed = counntry_info[0]["confirmed"] recovered = counntry_info[0]["recovered"] critical = counntry_info[0]["critical"] deaths = counntry_info[0]["deaths"] email_sender = EmailSender() template = template_reader.TemplateReader() email_message = template.read_course_template("NotIndia_template") email_message = email_message.replace('User', name) email_message = email_message.replace('pin_code', pin_code) email_message = email_message.replace('Country', country) email_message = email_message.replace('total_No_cases_c', str(confirmed)) email_message = email_message.replace('total_No_cases_r', str(recovered)) email_message = email_message.replace('total_No_cases_t', str(critical)) email_message = email_message.replace('total_No_cases_d', str(deaths)) email_sender.send_email_to_student(email, email_message) fulfillmentText = "We have sent the number of corona virus cases in your area and other relevant details to you via email.Do you have further queries?" cur = mysql.connection.cursor() cur.execute( "INSERT INTO user_chat_history(sessionId,message, updated_time) VALUES (%s, %s, %s)", (sessionID, "Bot says: " + fulfillmentText, datetime.datetime.utcnow())) mysql.connection.commit() cur.close() return {"fulfillmentText": fulfillmentText}
def getUserDetails(req): result = req.get("queryResult") user_says = result.get("queryText") name = result.get("parameters").get("user_name") email = result.get("parameters").get("user_mail") mobile = result.get("parameters").get("user_phone") pincode = result.get("parameters").get("user_pin") try: url = "https://api.postalpincode.in/pincode/" + pincode res = requests.get(url) jsonRes = res.json() postOffice = jsonRes[0]["PostOffice"] state = str(postOffice[0]["State"]) if "&" in state: state = state.replace("&", "and") district = str(postOffice[0]["District"]) if "&" in district: district = district.replace("&", "and") if district == "Ahmedabad": district = "Ahmadabad" elif district == "Bangalore": district = "Bengaluru" elif district == "Central Delhi": district = "New Delhi" print(state, end=',') print(district) try: url1 = "https://api.covid19india.org/v2/state_district_wise.json" res1 = requests.get(url1) jsonRes1 = res1.json() stateDistrictData = jsonRes1 for i in range(len(stateDistrictData)): stateDistrictData1 = stateDistrictData[i] if stateDistrictData1["state"] == state: districtData = stateDistrictData1["districtData"] for j in range(len(districtData)): email_sender = EmailSender() if districtData[j]["district"] == district: confirmed = str(districtData[j]["confirmed"]) print(f"\n Confirmed Cases are: {confirmed}") email_file = open( "email-templates/email-template-district.html", "r") email_message = email_file.read() email_sender.sendEmailDistrict( name, email, district, confirmed, email_message) fulfillmentText = "A mail has been sent to you with current COVID-19 cases in your area." bot_says = fulfillmentText return {"fulfillmentText": fulfillmentText} else: fulfillmentText = "Sorry we did not found any data of COVID-19 in " + district + ". It might be a misspelling or we don't have record of the district." bot_says = fulfillmentText return {"fulfillmentText": fulfillmentText} except HTTPError as http_err: print(f"HTTP error occurred: {http_err}") except Exception as err: print(f"Other error occurred: {err}") except HTTPError as http_err: print(f"HTTP error occurred: {http_err}") except Exception as err: print(f"Other error occurred: {err}")
def getUserDetails(req, db): sessionID = req.get("session") session = re.compile("sessions/(.*)") sessionID = session.findall(sessionID)[0] result = req.get("queryResult") user_says = result.get("queryText") name = result.get("parameters").get("name") email = result.get("parameters").get("email") mobile = result.get("parameters").get("mobile") pincode = result.get("parameters").get("pincode") regex_email = "^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$" regex_mobile = "[0-9]{10}" regex_pincode = "[0-9]{6}" if re.search(regex_email, email) is None: fulfillmentText = "Not a valid email. Please start again and enter valid email." bot_says = fulfillmentText if db.conversations.find({"sessionID": sessionID}).count() > 0: db.conversations.update_one( {"sessionID": sessionID}, {"$push": { "events": { "$each": [user_says, bot_says] } }}) else: db.conversations.insert_one({ "sessionID": sessionID, "events": [user_says, bot_says] }) return {"fulfillmentText": fulfillmentText} if re.search(regex_mobile, mobile) is None: fulfillmentText = "Not a valid mobile number. Please start again and enter valid mobile number." bot_says = fulfillmentText if db.conversations.find({"sessionID": sessionID}).count() > 0: db.conversations.update_one( {"sessionID": sessionID}, {"$push": { "events": { "$each": [user_says, bot_says] } }}) else: db.conversations.insert_one({ "sessionID": sessionID, "events": [user_says, bot_says] }) return {"fulfillmentText": fulfillmentText} if re.search(regex_pincode, pincode) is None: fulfillmentText = "Not a valid pincode. Please start again and enter valid pincode." bot_says = fulfillmentText if db.conversations.find({"sessionID": sessionID}).count() > 0: db.conversations.update_one( {"sessionID": sessionID}, {"$push": { "events": { "$each": [user_says, bot_says] } }}) else: db.conversations.insert_one({ "sessionID": sessionID, "events": [user_says, bot_says] }) return {"fulfillmentText": fulfillmentText} try: url = "https://api.postalpincode.in/pincode/" + pincode res = requests.get(url) jsonRes = res.json() postOffice = jsonRes[0]["PostOffice"] state = str(postOffice[0]["State"]) if "&" in state: state = state.replace("&", "and") district = str(postOffice[0]["District"]) if "&" in district: district = district.replace("&", "and") if district == "Ahmedabad": district = "Ahmadabad" elif district == "Bangalore": district = "Bengaluru" elif district == "Central Delhi": district = "New Delhi" print(state, end=',') print(district) try: url1 = "https://api.covid19india.org/v2/state_district_wise.json" res1 = requests.get(url1) jsonRes1 = res1.json() stateDistrictData = jsonRes1 for i in range(len(stateDistrictData)): stateDistrictData1 = stateDistrictData[i] if stateDistrictData1["state"] == state: districtData = stateDistrictData1["districtData"] for j in range(len(districtData)): email_sender = EmailSender() if districtData[j]["district"] == district: confirmed = str(districtData[j]["confirmed"]) print(f"\n Confirmed Cases are: {confirmed}") email_file = open( "email-templates/email-template-district.html", "r") email_message = email_file.read() email_sender.sendEmailDistrict( name, email, district, confirmed, email_message) fulfillmentText = "A mail has been sent to you with current COVID-19 cases in your area." bot_says = fulfillmentText if db.conversations.find({ "sessionID": sessionID }).count() > 0: db.conversations.update_one( {"sessionID": sessionID}, { "$push": { "events": { "$each": [user_says, bot_says] } } }) else: db.conversations.insert_one({ "sessionID": sessionID, "events": [user_says, bot_says] }) return {"fulfillmentText": fulfillmentText} else: fulfillmentText = "Sorry we did not found any data of COVID-19 in " + district + ". It might be a misspelling or we don't have record of the district." bot_says = fulfillmentText if db.conversations.find({ "sessionID": sessionID }).count() > 0: db.conversations.update_one( {"sessionID": sessionID}, { "$push": { "events": { "$each": [user_says, bot_says] } } }) else: db.conversations.insert_one({ "sessionID": sessionID, "events": [user_says, bot_says] }) return {"fulfillmentText": fulfillmentText} except HTTPError as http_err: print(f"HTTP error occurred: {http_err}") except Exception as err: print(f"Other error occurred: {err}") except HTTPError as http_err: print(f"HTTP error occurred: {http_err}") except Exception as err: print(f"Other error occurred: {err}")
def processRequest(req): log = logger.Log() sessionID = req.get('responseId') result = req.get("queryResult") user_says = result.get("queryText") log.write_log(sessionID, "User Says: " + user_says) parameters = result.get("parameters") cust_name = parameters.get("cust_name") cust_contact = parameters.get("cust_contact") cust_email = parameters.get("cust_email") pin_code = parameters.get("pin_code") intent = result.get("intent").get('displayName') if (intent == 'CORONA_BY_PINCODE'): results = getFrmPincode(pin_code) district_name = results[0]["PostOffice"][0]["District"] state_name = results[0]["PostOffice"][0]["State"] country_name = results[0]["PostOffice"][0]["Country"] print(district_name) # delete fulfillmentText = " " state_data = getStateCovidCases(state_name) print(state_data) print(len(state_data['districtData'])) try: district_data = getDistrictCovidCases(state_data, district_name) if district_data['active'] > 0: messageTxt = getCovidDist(district_data) fulfillmentText = district_name + '(' + pin_code + ')' + ' -- ' + messageTxt print(fulfillmentText) #delete # Store the details to database dbConn = pymongo.MongoClient("mongodb://localhost:27017/" ) # opening a connection to Mongo db = dbConn[ 'covidReqDB'] # connect to the database called covidReqDB dateTimeObj = datetime.now() mydict = { "Name": cust_name, "Email": cust_email, "Pincode": pin_code, "Contact": cust_contact, "Time_Stamp": dateTimeObj } # saving that detail to a dictionary collection = db[cust_email] collection.insert_one(mydict) # inserting the dictionary except Exception as e: messageTxt = getCovidState(state_data) fulfillmentText = messageTxt template = template_reader.TemplateReader() email_message = template.read_covid_template() email_sender = EmailSender() email_sender.send_email(cust_name, cust_email, email_message, fulfillmentText) fulfillmentText += "We have sent the preventive measures of Carona(Covid-19) disease to you via email. Do you have any queries?" log.write_log(sessionID, "Bot Says: " + fulfillmentText) return {"fulfillmentText": fulfillmentText} else: log.write_log(sessionID, "Bot Says: " + result.fulfillmentText) if (intent == 'CORONA_MAP_INDIA'): webbrowser.open('https://www.covid19india.org/') if (intent == 'CORONA_BY_WORLD'): webbrowser.open( 'https://news.google.com/covid19/map?hl=en-IN&gl=IN&ceid=IN:en')