Exemplo n.º 1
0
 def run(self, dispatcher, tracker, domain):
     category = tracker.get_slot('category') if tracker.get_slot('category') else 'None'
     category = str(category) 
     with open('./data/skills.json') as f:
         skillData = json.load(f)
     if 'categories' not in skillData:
         dispatcher.utter_message('Keine Skills sinds vorhanden')
         return []
     for persistedCategory in skillData['categories']:
         if persistedCategory.lower() != category.lower():
             continue
         topics = skillData['categories'][persistedCategory]
         if len(topics) == 0:
             dispatcher.utter_message('Kein Topic gefunden in Kategroie: '+category)
             return []
         topicsString = ''
         for topic in topics:
             topicsString += ', '+topic
         dispatcher.utter_message('Folgen Topics habe ich in Kategoie '+category+' gefunden: '+topicsString)
         return [AllSlotsReset()]
     
     categories = ''
     for category in skillData['categories']:
         categories += ', '+category
     dispatcher.utter_message('Keine Kategorie mit dem name '+category+' gefunden, wähle doch eine von '+categories)
     
     return [AllSlotsReset()]
Exemplo n.º 2
0
    def run(self, dispatcher, tracker, domain):
        global x
        print("actiongencalc")
        this = tracker.get_slot('this')
        opcalc = tracker.get_slot('opcalc')
        para = get_para(tracker.get_slot('pnum'))

        if this is None:
            x = dfmaster  # reload db

        try:
            if (opcalc == 'mean') or (opcalc == 'average'):
                ans = x[para].mean()
            elif opcalc == 'median':
                ans = x[para].median()
            elif opcalc == 'mode':
                ans = x[para].mode()
            else:
                ans = x[para].sum()
            dispatcher.utter_message("The " + str(opcalc) + " of " +
                                     str(para) + " is " + str(ans))
        except:
            dispatcher.utter_message("I didn't get you... please try again.")

        return [AllSlotsReset()]
Exemplo n.º 3
0
    def run(self, dispatcher, tracker, domain):
        topic = tracker.get_slot('topic') if tracker.get_slot(
            'topic') else None
        if topic is None:
            dispatcher.utter_message('Ich habe kein Topic bekommen')
            return []

        topic = str(topic)
        bests = []
        with open('./data/skills.json') as f:
            skillData = json.load(f)
        if 'skills' not in skillData:
            return []

        for persistedTopic in skillData['skills']:
            if topic.lower() != persistedTopic.lower() or len(
                    skillData['skills'][persistedTopic]) == 0:
                continue
            for user in skillData['skills'][persistedTopic]:
                bests.append(user)
        if len(bests) == 0:
            dispatcher.utter_message(
                'Kein Kollege weiß etwas zun Thema {}'.format(topic))
        else:
            bestsString = ''
            for user in bests:
                bestsString += user['name'] + ' (Score: ' + str(
                    user['score']) + '), '
            if bestsString.endswith(", "): bestsString = bestsString[:-2]
            dispatcher.utter_message(
                'Die folgenden Kollegen meinen Ahnung zu haben: ' +
                bestsString)
        return [AllSlotsReset()]
    def run(self, dispatcher, tracker, domain):

        email = tracker.get_slot('email')

        # for slack handling
        if len(email.split("|")) == 2:
            email = email.split("|")[1]

        import smtplib
        s = smtplib.SMTP('smtp.gmail.com', 587)
        s.starttls()
        s.login("*****@*****.**", "Upgrad2019#")
        message = "Details of all the restaurants you inquried \n \n"
        global result_of_last_query
        message = message + result_of_last_query

        from email.message import EmailMessage
        msg = EmailMessage()
        msg['Subject'] = "FoodieBot - Restaurant search results"
        msg['From'] = "FoodieBot"
        msg['To'] = str(email)
        msg.set_content(message)

        try:
            s.send_message(msg)
            s.quit()
        except:
            print("error in sending email")
            dispatcher.utter_message(email)

        result_of_last_query = ""
        return [AllSlotsReset()]
Exemplo n.º 5
0
    def run(self, dispatcher, tracker, domain):
        global x, hi
        print("filtercomp")
        this = tracker.get_slot('this')
        opcomp = tracker.get_slot('opcomp')
        pnum = get_para(tracker.get_slot('pnum'))
        numall = tracker.get_slot('numall')

        if this is None:
            x = dfmaster  # reload db

        try:
            if opcomp == 'greater than':
                x = x[x[pnum] > int(numall)]
            elif opcomp == 'less than':
                x = x[x[pnum] < int(numall)]
            else:
                x = x[x[pnum] == int(numall)]

            # Generate table
            htmlgen(para)

            dispatcher.utter_message("See the filtered results.")
            dispatcher.utter_message("results/file" + str(hi - 1) + ".html")

        except:
            dispatcher.utter_message("Please try again.")

        return [AllSlotsReset()]
Exemplo n.º 6
0
    def run(self, dispatcher, tracker, domain):
        tracker.clear_follow_up_action()

        print("Current slot-values %s" % tracker.current_slot_values())
        print("Current state %s" % tracker.current_state())

        return [AllSlotsReset()]
Exemplo n.º 7
0
    def run(self, dispatcher, tracker, domain):
        topic = tracker.get_slot('topic')
        user = tracker.get_slot('user')
        if topic is None:
            dispatcher.utter_message('No topic given')
            return []
        if user is None:
            dispatcher.utter_message('No user given')
            return []
        topic = str(topic) 
        with open('./data/skills.json') as f:
            skillData = json.load(f)
        if 'skills' not in skillData:
            dispatcher.utter_message('Keine Skills sinds vorhanden')
            return []
        if topic not in skillData['skills']:
            skillData['skills'][topic] = []
            dispatcher.utter_message('Das Topic '+topic+' ist noch nicht bekannt, wird angelegt')
        persistedTopic = skillData['skills'][topic]

        foundUser = False
        for key in persistedTopic:
            if persistedTopic[key].name == user:
                persistedTopic[key].score = persistedTopic[key].score + 1 
                dispatcher.utter_message('User '+user+'` Score um eins erhöht für Topic: '+topic)
                foundUser = True
                break
        if foundUser is True:
            skillData[topic].append({"name": user, "score": 1})
            dispatcher.utter_message('User '+user+'` wurde für das Topic vermerkt: '+topic)
        
        return [AllSlotsReset()]
Exemplo n.º 8
0
    def run(self, dispatcher, tracker, domain):

        name = tracker.get_slot("r_name")
        if name is None:
            name = '^""$'

        location = tracker.get_slot("location")
        if location is None:
            location = '^""$'

        df = pd.read_csv("yelp_business.csv")
        result = df.loc[(df['name'].str.contains(name, case=False)) |
                        (df['city'].str.contains(location, case=False)),
                        df.notnull().any(axis=0)]
        if result.empty:
            dispatcher.utter_message("Restaurant address Unavailable :(")
            y = None
        else:
            dispatcher.utter_message("Here's what I found:")
            y = result["address"].reset_index(drop=True)
            name = None
            location = None
        if y is not None:
            dispatcher.utter_message("Address :")
            dispatcher.utter_message(y[0])

        return [AllSlotsReset()]
Exemplo n.º 9
0
    def run(self, dispatcher, tracker, domain):
        tracker.clear_follow_up_action()

        logging.info("All Slots reset.")
        logging.debug("Current slot-values %s" % tracker.current_slot_values())
        logging.debug("Current state %s" % tracker.current_state())

        return [AllSlotsReset()]
Exemplo n.º 10
0
def test_json_parse_reset():
    # DOCS MARKER AllSlotsReset
    evt = \
        {
            'event': 'reset_slots'
        }
    # DOCS END
    assert Event.from_parameters(evt) == AllSlotsReset()
Exemplo n.º 11
0
 def run(self, dispatcher, tracker, domain):
     print("imdb")
     title = tracker.get_slot('movie')
     if title:
         ex = get_movie_name(title)
         ans = ex['imdb_id'].tolist()[0]
         webbrowser.open('https://www.imdb.com/title/' + ans)
         dispatcher.utter_message("There you go.")
     else:
         dispatcher.utter_message("I didn't get you... please try again.")
     return [AllSlotsReset()]
Exemplo n.º 12
0
 def run(self, dispatcher, tracker, domain):
     search_type = str(tracker.get_slot('searchType'))
     word = str(tracker.get_slot('searchWord'))
     if search_type != "None" and word != "None":
         message = search_word_meaning(word)
         dispatcher.utter_message(message)
         return [AllSlotsReset()]
     elif search_type == "None":
         tracker.trigger_follow_up_action(domain.action_for_name("utter_specific"))
     elif word == "None":
         tracker.trigger_follow_up_action(domain.action_for_name("utter_ask_word"))
Exemplo n.º 13
0
 def run(self, dispatcher, tracker, domain):
     search_type = str(tracker.get_slot('searchType'))
     location = str(tracker.get_slot('GPE'))
     if search_type != "None" and location != "None":
         message = search_weather_details(location)
         dispatcher.utter_message(message)
         return [AllSlotsReset()]
     elif search_type == "None":
         tracker.trigger_follow_up_action(domain.action_for_name("utter_specific"))
     elif location == "None":
         tracker.trigger_follow_up_action(domain.action_for_name("utter_ask_location"))
Exemplo n.º 14
0
 def run(self, dispatcher, tracker, domain):
     car_type = tracker.get_slot("car_type")
     if car_type.lower() == "diesel":
         dispatcher.utter_message(
             "Following options are available in Diesel Variant: Exide 4500, Amaron 4200"
         )
     else:
         dispatcher.utter_message(
             "Following options are available in Petrol Variant: Exide 4250, Amaron 3900"
         )
     return [AllSlotsReset()]
Exemplo n.º 15
0
 def run(self, dispatcher, tracker, domain):
     customer_id = str(tracker.get_slot('iD'))
     id_type = str(tracker.get_slot('idType'))
     if id_type != "None" and customer_id != "None":
         message = get_customer_details(customer_id)
         if message == "None":
             dispatcher.utter_message("Customer not found")
         else:
             dispatcher.utter_message(message)
         return [AllSlotsReset()]
     elif id_type == "None":
         tracker.trigger_follow_up_action(domain.action_for_name("utter_ask_IdType"))
     elif customer_id == "None":
         tracker.trigger_follow_up_action(domain.action_for_name("utter_ask_Id"))
Exemplo n.º 16
0
 def run(self, dispatcher, tracker, domain):
     order_id = str(tracker.get_slot('iD'))
     id_type = str(tracker.get_slot('idType'))
     if id_type != "None" and order_id != "None":
         message = get_order_details(order_id)
         if message == "None":
             dispatcher.utter_message("Order ID does not exist")
         else:
             dispatcher.utter_message(message)
         return [AllSlotsReset()]
     elif id_type == "None":
         tracker.trigger_follow_up_action(domain.action_for_name("utter_ask_IdType"))
     elif order_id == "None":
         tracker.trigger_follow_up_action(domain.action_for_name("utter_ask_Id"))
Exemplo n.º 17
0
 def run(self, dispatcher, tracker, domain):
     word = str(tracker.get_slot('searchWord'))
     language = str(tracker.get_slot('language'))
     search_type = str(tracker.get_slot('searchType'))
     if search_type != "None" and word != "None" and language != "None":
         message = translate_word(word, language)
         dispatcher.utter_message(message)
         return [AllSlotsReset()]
     elif search_type == "None":
         tracker.trigger_follow_up_action(domain.action_for_name("utter_specific"))
     elif word == "None":
         tracker.trigger_follow_up_action(domain.action_for_name("utter_ask_word"))
     elif language == "None":
         tracker.trigger_follow_up_action(domain.action_for_name("utter_ask_language"))
Exemplo n.º 18
0
 def run(self, dispatcher, tracker, domain):
     ticket_id = str(tracker.get_slot('iD'))
     id_type = str(tracker.get_slot('idType'))
     if id_type != "None" and ticket_id != "None":
         message = get_ticket_status(ticket_id)
         if message == "None":
             dispatcher.utter_message("No ticket exists with that ID")
         else:
             dispatcher.utter_message(message)
         return [AllSlotsReset()]
     elif id_type == "None":
         tracker.trigger_follow_up_action(domain.action_for_name("utter_ask_IdType"))
     elif ticket_id == "None":
         tracker.trigger_follow_up_action(domain.action_for_name("utter_ask_Id"))
Exemplo n.º 19
0
 def run(self, dispatcher, tracker, domain):
     print("action genq")
     try:
         para = tracker.get_slot('param')
         title = tracker.get_slot('movie')
         ex = get_movie_name(title)
         ext = ex[get_para(para)].tolist()[0]
         ans = json_list(ext)
         poster = ex['poster_path'].tolist()[0]
         dispatcher.utter_message("The " + para + " of " + title + " is " +
                                  str(ans))
         dispatcher.utter_message('http://image.tmdb.org/t/p/w342/' +
                                  poster)
     except:
         dispatcher.utter_message("Please try again!")
     return [AllSlotsReset()]
Exemplo n.º 20
0
    def run(self, dispatcher, tracker, domain):
        # check again if user is logged in, just in case
        isLogged = tracker.get_slot("loggedIn")
        Cresults = tracker.get_slot("candidate_results")
        debugMsg(isLogged)

        if isLogged == '1' and Cresults:
            # TODO: Create a file of candidate result in any meaningful format
            debugMsg(Cresults)

            # attachmentResult = "<converted-file>"
            attachmentResult = "https://i2.wp.com/zimtrending.co.zw/wp-content/uploads/2020/01/WhatsApp-Image-2020-01-17-at-5.00.04-PM.jpeg"  # demo image file
            dispatcher.utter_attachment(attachment=attachmentResult)

        # it should be the end of a conversation now, we hope. So reset everything yoh!
        return [AllSlotsReset()]
Exemplo n.º 21
0
    def submit(self, dispatcher, tracker, domain):
        # construct and return candidate dict
        candidateDict = CandidateRegister(tracker)
        Cusername, Cpassword = CandidateCredentials(candidateDict.get("Cname"))
        # TODO: Register candidate to database
        # TODO: Since pswd and username is auto generated, save to db too and show it to user

        debugMsg(candidateDict)

        resp = "You are now registered. Use the following details to login to your ZIMSEC portal\nUsername: {cuser}\nPassword: {pwd}".format(
            cuser=Cusername, pwd=Cpassword)
        dispatcher.utter_message(resp)  # show user auto generated credentials

        dispatcher.utter_template(template="utter_proceed_login")

        # reset everything on successful candidate register
        return [AllSlotsReset()]
Exemplo n.º 22
0
	def run(self, dispatcher, tracker, domain):
		try:
			emailid = tracker.get_slot('emailid')
			print("sending mail to ", emailid)

			smtp = smtplib.SMTP('smtp.gmail.com:587')
			smtp.ehlo()
			smtp.starttls()
			print(smtp.login("tekwanikapil1124", "kapil9tekwani@#$"))

			#Send the mail
			smtp.sendmail("*****@*****.**", emailid, os.environ["EMAIL_CONTENT"])
			time.sleep(5)
			print("mail sent")

			return [AllSlotsReset()]
		except Exception as e:
			print ("Exception is : ", e)
Exemplo n.º 23
0
    def run(self, dispatcher, tracker, domain):

        if tracker.get_slot('guestname') and tracker.get_slot('room') and tracker.get_slot('is_authenticated') is None:
            tracker.update(SlotSet('is_authenticated', True))

        if tracker.get_slot('is_authenticated') is None:
            # reset all slots to None in begin
            tracker.update(AllSlotsReset())

            # send the introduce
            dispatcher.utter_template("utter_general.greet.initial")
            dispatcher.utter_template("utter_general.bot.whoareyou")
            dispatcher.utter_template("utter_general.bot.capabilities")
            dispatcher.utter_template("utter_general.guest.name")
        else:
            # send 'hello'
            dispatcher.utter_template("utter_general.greet", guestname=tracker.get_slot('guestname'))
        return []
Exemplo n.º 24
0
    def run(self, dispatcher, tracker, domain): 		
        return[AllSlotsReset()]		


# def run():
#     nse = Nse()
#     isValid = nse.is_valid_code('5PAISA')
#     print(isValid)
#     if isValid == True:
#         response = nse.get_quote('5PAISA')
#         print(response)
#         print("lastPrice: " + str(response["lastPrice"]))
#     else :
#         print('not valid')


# def run():
#         try:
#             # print('Inside get stock')
#             nse = Nse()
#             response = nse.get_top_gainers()
#             print(response)
#             GainerHtml = ''
#             for GainerVal in response:
#                 GainerHtml += "------{}------ \n".format(GainerVal["symbol"]) 
#                 # GainerHtml += "Company Symbol {} \n".format(GainerVal["symbol"])
#                 GainerHtml += "openPrice Rs {} \n".format(GainerVal["openPrice"]) 
#                 GainerHtml += "highPrice Rs {} \n".format(GainerVal["highPrice"]) 
#                 GainerHtml += "lowPrice Rs {} \n".format(GainerVal["lowPrice"]) 
#                 GainerHtml += "Last trading price Rs {} \n".format(GainerVal["ltp"]) 
#                 GainerHtml += "previousPrice Rs {} \n".format(GainerVal["previousPrice"]) 
#                 GainerHtml += "tradedQuantity {} \n".format(GainerVal["tradedQuantity"]) 
#                 GainerHtml += "-------------- \n\n"
            
#             print(GainerHtml)

#         except Exception:
#             print(Exception)
        

# if __name__ == '__main__':
#     # train("./data/nlu_data.json","./config.yml","./models/nlu")
#     run()
Exemplo n.º 25
0
    def run(self, dispatcher, tracker, domain):
        global list_of_restaurants

        try:

            email = tracker.get_slot('emailid')
            #print(email)
            if list_of_restaurants != "":

                email_text = 'Please find the requested restaurant details: \n'
                email_text += '------------------------------------------------\n'
                email_text += list_of_restaurants
            else:
                email_text = 'Sorry, I could not find any restaurants matching your search criteria :( \n'

            msg = EmailMessage()

            msg['Subject'] = 'Restaurant Details by Foodie!'
            msg['From'] = MY_ADDRESS

            msg['To'] = email
            msg.set_content(email_text)

            # set up the SMTP server
            server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
            server.ehlo()
            server.login(MY_ADDRESS, PASSWORD)
            server.send_message(msg)
            server.close()

            #print('Email sent!')
            list_of_restaurants = ""
            dispatcher.utter_template("utter_emailsent", tracker)
        except:
            #print('Exception!!!')
            list_of_restaurants = ""
            dispatcher.utter_message(
                "Oops, looks like the email couldn't go through. Sorry!")
            dispatcher.utter_template("utter_goodbye", tracker)
            return [Restarted()]

        return [AllSlotsReset()]
Exemplo n.º 26
0
	def run(self, dispatcher, tracker, domain):

		try:
			global global_search_result

			recipient_email = tracker.get_slot('email')

			gmail_user = '******'
			gmail_password = '******'

			sender_addr = "gmail_user"
			to_addr = [str(recipient_email)]
			#to_addr = ['*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**']
			#to_addr = ['*****@*****.**']
			subject = 'Restaurant details from RestaurantBot by AkiPunSaiGan'
			body_msg = """\
Hello, \n\n Thank you for using the Resturant-Bot by AkiPunSaiGan. Below are top rated restaurant results of your recent search.

%s

Bon Appitet. Enjoy your food and have a wonderful day.

Regards
Akila,Puneet,Sai,Ganga
""" % ('\n'+ global_search_result)
			print(body_msg)
			message = 'Subject: {}\n\n{}'.format(subject, body_msg)
			try:
				server = smtplib.SMTP('smtp.gmail.com', 587)
				server.starttls()
				server.login(gmail_user, gmail_password)
				server.sendmail(sender_addr, to_addr, message)
				server.close()

				print('Email sent!')
			except:
				print('Something went wrong...')

		except:
			print('Something went wrong...')

		return[AllSlotsReset()]
Exemplo n.º 27
0
    def run(self, dispatcher, tracker, domain):

        global x
        try:
            op = tracker.get_slot('format')
            if op == 'excel':
                writer = pd.ExcelWriter('output/output.xlsx')
                dispatcher.utter_message(
                    'Exported to .xlsx format. Click on link to download.')
                x.to_excel(writer, 'Sheet1')
                writer.save()
                dispatcher.utter_message("output/output.xlsx")
            else:
                x.to_csv('output/output.csv')
                dispatcher.utter_message(
                    'Exported to .csv format. Click on link to download.')
                dispatcher.utter_message("output/output.csv")
        except:
            dispatcher.utter_message("Please try exporting again!")

        return [AllSlotsReset()]
Exemplo n.º 28
0
    def run(self, dispatcher, tracker, domain):
        global x, i
        print("filternum")
        this = tracker.get_slot('this')
        para = get_para(tracker.get_slot('pnum'))
        num = tracker.get_slot('num')
        up = tracker.get_slot('up')
        print('got slots')
        if this is None:
            x = dfmaster
        print('this is none')
        try:
            if up is not None:  # show most first
                x.sort_values(by=para, ascending=False, inplace=True)
            else:  # least first
                x.sort_values(by=para, ascending=True, inplace=True)

            if num is not None:
                x = x.head(int(num))
            else:
                x = x.head()

            # Generate graph
            plotter(para)
            print('plotter done')

            # Generate table
            htmlgen(para)
            print('html done')

            dispatcher.utter_message("Check out the results window.")
            dispatcher.utter_message("graphs/graph" + str(i - 1) + ".png")

        except:
            dispatcher.utter_message("I didn't get you... please try again.")

        return [AllSlotsReset()]
Exemplo n.º 29
0
 def run(self, dispatcher, tracker, domain):
     return [Restarted(), AllSlotsReset()]
Exemplo n.º 30
0
                              ConversationResumed, ConversationPaused,
                              StoryExported, ActionReverted, BotUttered)


@pytest.mark.parametrize("one_event,another_event", [
    (UserUttered("/greet", {
        "name": "greet",
        "confidence": 1.0
    }, []), UserUttered("/goodbye", {
        "name": "goodbye",
        "confidence": 1.0
    }, [])),
    (TopicSet("my_topic"), TopicSet("my_other_topic")),
    (SlotSet("my_slot", "value"), SlotSet("my__other_slot", "value")),
    (Restarted(), None),
    (AllSlotsReset(), None),
    (ConversationPaused(), None),
    (ConversationResumed(), None),
    (StoryExported(), None),
    (ActionReverted(), None),
    (ActionExecuted("my_action"), ActionExecuted("my_other_action")),
    (BotUttered("my_text",
                "my_data"), BotUttered("my_other_test", "my_other_data")),
    (ReminderScheduled("my_action",
                       "now"), ReminderScheduled("my_other_action", "now")),
])
def test_event_has_proper_implementation(one_event, another_event):
    # equals tests
    assert one_event != another_event, \
        "Same events with different values need to be different"
    assert one_event == deepcopy(one_event), \