コード例 #1
0
def handle(text, mic, profile):
    """
        Responds to user-input, typically speech text, by telling a joke.

        Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone
                   number)
    """
    joke = getRandomJoke()
    old = "JOKE"

    #mic.say("Knock knock")
    client.send_out("knock knock")

    def firstLine(text):
        #mic.say(joke[0])
	client.send_out(joke[0])
	print "firstLine %s" % text
        def punchLine(text):
            #mic.say(joke[1])
	    client.send_out(joke[1])
	    print "firstLine %s" % text
	old = is_new(text)
        punchLine(old)

    old=is_new(old)
    firstLine(old)
コード例 #2
0
ファイル: News.py プロジェクト: hTrap/jasper-client
    def handleResponse(text):

        def extractOrdinals(text):
            output = []
            service = NumberService()
            for w in text.split():
                if w in service.__ordinals__:
                    output.append(service.__ordinals__[w])
            return [service.parse(w) for w in output]

        chosen_articles = extractOrdinals(text)
        send_all = not chosen_articles and app_utils.isPositive(text)

        if send_all or chosen_articles:
            tcp.send_out("Sure, just give me a moment")

            if profile['prefers_email']:
                body = "<ul>"

            def formatArticle(article):
                tiny_url = app_utils.generateTinyURL(article.URL)

                if profile['prefers_email']:
                    return "<li><a href=\'%s\'>%s</a></li>" % (tiny_url,
                                                               article.title)
                else:
                    return article.title + " -- " + tiny_url

            for idx, article in enumerate(articles):
                if send_all or (idx + 1) in chosen_articles:
                    article_link = formatArticle(article)

                    if profile['prefers_email']:
                        body += article_link
                    else:
                        if not app_utils.emailUser(profile, SUBJECT="",
                                                   BODY=article_link):
                            tcp.send_out("I'm having trouble sending you these " +
                                    "articles. Please make sure that your " +
                                    "phone number and carrier are correct " +
                                    "on the dashboard.")
                            return

            # if prefers email, we send once, at the end
            if profile['prefers_email']:
                body += "</ul>"
                if not app_utils.emailUser(profile,
                                           SUBJECT="Your Top Headlines",
                                           BODY=body):
                    tcp.send_out("I'm having trouble sending you these articles. " +
                            "Please make sure that your phone number and " +
                            "carrier are correct on the dashboard.")
                    return

            tcp.send_out("All set")

        else:

            tcp.send_out("OK I will not send any articles")
コード例 #3
0
    def handleResponse(text):
        def extractOrdinals(text):
            output = []
            service = NumberService()
            for w in text.split():
                if w in service.__ordinals__:
                    output.append(service.__ordinals__[w])
            return [service.parse(w) for w in output]

        chosen_articles = extractOrdinals(text)
        send_all = not chosen_articles and app_utils.isPositive(text)

        if send_all or chosen_articles:
            tcp.send_out("Sure, just give me a moment")

            if profile['prefers_email']:
                body = "<ul>"

            def formatArticle(article):
                tiny_url = app_utils.generateTinyURL(article.URL)

                if profile['prefers_email']:
                    return "<li><a href=\'%s\'>%s</a></li>" % (tiny_url,
                                                               article.title)
                else:
                    return article.title + " -- " + tiny_url

            for idx, article in enumerate(articles):
                if send_all or (idx + 1) in chosen_articles:
                    article_link = formatArticle(article)

                    if profile['prefers_email']:
                        body += article_link
                    else:
                        if not app_utils.emailUser(
                                profile, SUBJECT="", BODY=article_link):
                            tcp.send_out(
                                "I'm having trouble sending you these " +
                                "articles. Please make sure that your " +
                                "phone number and carrier are correct " +
                                "on the dashboard.")
                            return

            # if prefers email, we send once, at the end
            if profile['prefers_email']:
                body += "</ul>"
                if not app_utils.emailUser(
                        profile, SUBJECT="Your Top Headlines", BODY=body):
                    tcp.send_out(
                        "I'm having trouble sending you these articles. " +
                        "Please make sure that your phone number and " +
                        "carrier are correct on the dashboard.")
                    return

            tcp.send_out("All set")

        else:

            tcp.send_out("OK I will not send any articles")
コード例 #4
0
ファイル: lighton.py プロジェクト: devagul93/Jarvis-System
def handle(text, mic, profile):

    # SWITCH light on
    # STATIC SEARCH
    gpio.setmode(gpio.BOARD)
    gpio.setup(12, gpio.OUT)
    gpio.output(12, 1)
    ny = "LIGHTS are TURNED ON"
    #mic.say("%s"% ny)
    client.send_out(ny)
コード例 #5
0
    def firstLine(text):
        #mic.say(joke[0])
	client.send_out(joke[0])
	print "firstLine %s" % text
        def punchLine(text):
            #mic.say(joke[1])
	    client.send_out(joke[1])
	    print "firstLine %s" % text
	old = is_new(text)
        punchLine(old)
コード例 #6
0
ファイル: lightoff.py プロジェクト: devagul93/Jarvis-System
def handle(text,mic,profile):
 

# SWITCH light on	
# STATIC SEARCH
	gpio.setmode(gpio.BOARD)
	gpio.setup(12,gpio.OUT)
	gpio.output(12,0)
	ny = "LIGHTS are TURNED OFF"
	#mic.say("%s"% ny)
	client.send_out(ny)
コード例 #7
0
ファイル: Gmail.py プロジェクト: devagul93/Jarvis-System
def handle(text, mic, profile):
    """
        Responds to user-input, typically speech text, with a summary of
        the user's Gmail inbox, reporting on the number of unread emails
        in the inbox, as well as their senders.

        Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., Gmail
                   address)
    """
    print "in handle"
    try:
        msgs = fetchUnreadEmails(profile, limit=5)

        if isinstance(msgs, int):
	    print "UNREAD MESSAGES UNREAD MESSAGES UNREAD MESSAGES UNREAD MESSAGES UNREAD MESSAGES UNREAD MESSAGES UNREAD MESSAGES"
            response = "You have %d unread emails." % msgs
            tcp.send_out(response)
            return

        senders = [getSender(e) for e in msgs]
    except imaplib.IMAP4.error:
        tcp.send_out(
            "I'm sorry. I'm not authenticated to work with your Gmail.")
        return

    if not senders:
	
	print "READ MESSAGES READ MESSAGES READ MESSAGES READ MESSAGES READ MESSAGES READ MESSAGES READ MESSAGES!!!!!!!!!!!!"
        tcp.send_out("You have no unread emails.")
    elif len(senders) == 1:
        tcp.send_out("You have one unread email from " + senders[0] + ".")
    else:
        response = "You have %d unread emails" % len(
            senders)
        unique_senders = list(set(senders))
	print "!!!!!!!!!!!!READ MESSAGES READ MESSAGES READ MESSAGES READ MESSAGES READ MESSAGES READ MESSAGES READ MESSAGES!!!!!!!!!!!!"
        if len(unique_senders) > 1:
            unique_senders[-1] = 'and ' + unique_senders[-1]
            response += ". Senders include: "
            response += '...'.join(senders)
        else:
            response += " from " + unique_senders[0]

        tcp.send_out(response)
コード例 #8
0
def handle(text, mic, profile):
    """
        Responds to user-input, typically speech text, with a summary of
        the user's Gmail inbox, reporting on the number of unread emails
        in the inbox, as well as their senders.

        Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., Gmail
                   address)
    """
    print "in handle"
    try:
        msgs = fetchUnreadEmails(profile, limit=5)

        if isinstance(msgs, int):
            print "UNREAD MESSAGES UNREAD MESSAGES UNREAD MESSAGES UNREAD MESSAGES UNREAD MESSAGES UNREAD MESSAGES UNREAD MESSAGES"
            response = "You have %d unread emails." % msgs
            tcp.send_out(response)
            return

        senders = [getSender(e) for e in msgs]
    except imaplib.IMAP4.error:
        tcp.send_out(
            "I'm sorry. I'm not authenticated to work with your Gmail.")
        return

    if not senders:

        print "READ MESSAGES READ MESSAGES READ MESSAGES READ MESSAGES READ MESSAGES READ MESSAGES READ MESSAGES!!!!!!!!!!!!"
        tcp.send_out("You have no unread emails.")
    elif len(senders) == 1:
        tcp.send_out("You have one unread email from " + senders[0] + ".")
    else:
        response = "You have %d unread emails" % len(senders)
        unique_senders = list(set(senders))
        print "!!!!!!!!!!!!READ MESSAGES READ MESSAGES READ MESSAGES READ MESSAGES READ MESSAGES READ MESSAGES READ MESSAGES!!!!!!!!!!!!"
        if len(unique_senders) > 1:
            unique_senders[-1] = 'and ' + unique_senders[-1]
            response += ". Senders include: "
            response += '...'.join(senders)
        else:
            response += " from " + unique_senders[0]

        tcp.send_out(response)
コード例 #9
0
ファイル: Time.py プロジェクト: devagul93/Jarvis-System
def handle(text, mic, profile):
    """
        Reports the current time based on the user's timezone.

        Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone
                   number)
    """

    tz = getTimezone(profile)
    now = datetime.datetime.now(tz=tz)
    service = DateService()
    response = service.convertTime(now)
    #mic.say("It is %s right now." % response)
    timeNow =  "It is "+response+" right now"
    tcp.send_out(timeNow)
コード例 #10
0
def handle(text, mic, profile):
    """
        Reports the current time based on the user's timezone.

        Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone
                   number)
    """

    tz = getTimezone(profile)
    now = datetime.datetime.now(tz=tz)
    service = DateService()
    response = service.convertTime(now)
    #mic.say("It is %s right now." % response)
    timeNow = "It is " + response + " right now"
    tcp.send_out(timeNow)
コード例 #11
0
ファイル: Wikipedia.py プロジェクト: devagul93/Jarvis-System
def handle(text, mic, profile):

    # SEARCH ON WIKIPEDIA
    #	ny = wikipedia.summary("New York",sentences=3);
    #	mic.say("%s"% ny)

    #mic.say("What you want to search about")
    #text = mic.activeListen()
    print "entering wiki term"
    text = client.grab_input()
    while text.upper() == "WIKIPEDIA":
        print "entering while"
        text = client.grab_input()
        print text

    answer = wikipedia.summary(text, sentences=3)
    answer += "\n"
    print answer
    client.send_out(answer)
コード例 #12
0
ファイル: Wikipedia.py プロジェクト: devagul93/Jarvis-System
def handle(text,mic,profile):
 

# SEARCH ON WIKIPEDIA	
#	ny = wikipedia.summary("New York",sentences=3);
#	mic.say("%s"% ny)
	
	#mic.say("What you want to search about")
	#text = mic.activeListen()
	print "entering wiki term"
        text = client.grab_input()
	while text.upper()=="WIKIPEDIA":
            print "entering while"
	    text = client.grab_input()
	    print text

	answer = wikipedia.summary(text,sentences=3)
	answer +="\n" 
	print answer
	client.send_out(answer)
コード例 #13
0
 def sendFile(self):  # 发送文件至服务端
     global clientSocket, whichProtocol, serverPort, serverName
     fileNamePlus = QtWidgets.QFileDialog.getOpenFileName(self, '选择文件', '')
     file = fileNamePlus[0]
     # Socket发送文件
     if whichProtocol == 'TCP':
         ACK = TCPclient.sendFile(clientSocket, file)
         self.serverACKEdit.append('¥ ' + file + ACK)
         self.serverACKEdit.append("¥ TCP连接已被服务端关闭")
     else:
         ACK = UDPclient.sendFile(clientSocket, file, serverPort,
                                  serverName)
         self.serverACKEdit.append('¥ ' + file + ACK)
         self.serverACKEdit.append("¥ 单次UDP发送结束")
コード例 #14
0
 def sendText(self):  # 发送文本至服务端
     global clientSocket, whichProtocol, serverPort, serverName
     text = self.sendTextEdit.toPlainText()
     if whichProtocol == 'TCP':
         recvData = TCPclient.sendText(clientSocket, text)
         self.serverACKEdit.append('¥ ' + recvData)
         self.serverACKEdit.append("¥ TCP连接已被服务端关闭")
     else:
         print(text)
         recvData = UDPclient.sendText(clientSocket, text, serverPort,
                                       serverName)
         print(text)
         self.serverACKEdit.append('¥ ' + recvData)
         self.serverACKEdit.append("¥ 单次UDP发送结束")
コード例 #15
0
    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while True:
            # Print notifications until empty
            #notifications = self.notifier.getAllNotifications()
            #for notif in notifications:
            #    self._logger.info("Received notification: '%s'", str(notif))

            #self._logger.debug("Started listening for keyword '%s'",self.persona)
            #threshold, transcribed = self.mic.passiveListen(self.persona)
            #self._logger.debug("Stopped listening for keyword '%s'",
                              # self.persona)

            #if not transcribed or not threshold:
                #self._logger.info("Nothing has been said or transcribed.")
                #continue
            #self._logger.info("Keyword '%s' has been said!", self.persona)

            #self._logger.debug("Started to listen actively with threshold: %r",
                              # threshold)
	    input = []
	    print "entering input"
            input = client.grab_input().strip().split()
            #input = self.mic.activeListenToAllOptions(threshold)
            #self._logger.debug("Stopped to listen actively with threshold: %r",
                              # threshold)
	    print input

            if input:
		print "if entered"
                self.brain.query(input)
            else:
                self.mic.say("Pardon?")
		print "else entered"
コード例 #16
0
    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while True:
            # Print notifications until empty
            #notifications = self.notifier.getAllNotifications()
            #for notif in notifications:
            #    self._logger.info("Received notification: '%s'", str(notif))

            #self._logger.debug("Started listening for keyword '%s'",self.persona)
            #threshold, transcribed = self.mic.passiveListen(self.persona)
            #self._logger.debug("Stopped listening for keyword '%s'",
            # self.persona)

            #if not transcribed or not threshold:
            #self._logger.info("Nothing has been said or transcribed.")
            #continue
            #self._logger.info("Keyword '%s' has been said!", self.persona)

            #self._logger.debug("Started to listen actively with threshold: %r",
            # threshold)
            input = []
            print "entering input"
            input = client.grab_input().strip().split()
            #input = self.mic.activeListenToAllOptions(threshold)
            #self._logger.debug("Stopped to listen actively with threshold: %r",
            # threshold)
            print input

            if input:
                print "if entered"
                self.brain.query(input)
            else:
                self.mic.say("Pardon?")
                print "else entered"
コード例 #17
0
    def login(self):  # 登录
        global clientid, whichProtocol
        idText = str(self.idInput.text())
        pwText = str(self.pwInput.text())
        clientid = idText
        if whichProtocol == "TCP":
            if TCPclient.clientlogin(idText, pwText) == True:
                # 切换为连接界面
                self.idInput.clear()
                self.pwInput.clear()  #切换为服务端地址和端口号的输入框
                self.serverNameLabel.setVisible(True)
                self.serverPortLabel.setVisible(True)
                self.connectButton.setVisible(True)
                self.loginButton.setVisible(False)
                self.idLabel.setVisible(False)
                self.pwLabel.setVisible(False)
                self.errMessage.setVisible(False)

            else:
                self.errMessage.setVisible(True)
        else:
            if UDPclient.clientlogin(idText, pwText) == True:
                # 切换为连接界面
                self.idInput.clear()
                self.pwInput.clear()  # 切换为服务端地址和端口号的输入框
                self.serverNameLabel.setVisible(True)
                self.serverPortLabel.setVisible(True)
                self.connectButton.setText("确认")
                self.connectButton.setVisible(True)
                self.loginButton.setVisible(False)
                self.idLabel.setVisible(False)
                self.pwLabel.setVisible(False)
                self.errMessage.setVisible(False)

            else:
                self.errMessage.setVisible(True)
コード例 #18
0
def handle(text,mic,profile):
 

# SEARCH ON WIKIPEDIA	
#	ny = wikipedia.summary("New York",sentences=3);
#	mic.say("%s"% ny)
	
	#mic.say("")
	#text = mic.activeListen()
	list = "8 AM   go to college "
	client.send_out("ADD or LISTEN")
        text = client.grab_input()
	while text.upper()=="SCHEDULER":
	    text = client.grab_input()
	if text.upper()=="ADD":
	    while text.upper()=="ADD":
                text = client.grab_input()
	    list += text + "              "
	    client.send_out("added to list, your schedule for today is " + list)
	    client.send_out(list)
	else:
	    client.send_out("Your schedule for today is ")
	    client.send_out(list)
コード例 #19
0
ファイル: News.py プロジェクト: hTrap/jasper-client
def handle(text, mic, profile):
    """
        Responds to user-input, typically speech text, with a summary of
        the day's top news headlines, sending them to the user over email
        if desired.

        Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone
                   number)
    """
    tcp.send_out("Pulling up the news")
    articles = getTopArticles(maxResults=3)
    titles = [" ".join(x.title.split(" - ")[:-1]) for x in articles]
    all_titles = "... ".join(str(idx + 1) + ")" +
                             title for idx, title in enumerate(titles))

    def handleResponse(text):

        def extractOrdinals(text):
            output = []
            service = NumberService()
            for w in text.split():
                if w in service.__ordinals__:
                    output.append(service.__ordinals__[w])
            return [service.parse(w) for w in output]

        chosen_articles = extractOrdinals(text)
        send_all = not chosen_articles and app_utils.isPositive(text)

        if send_all or chosen_articles:
            tcp.send_out("Sure, just give me a moment")

            if profile['prefers_email']:
                body = "<ul>"

            def formatArticle(article):
                tiny_url = app_utils.generateTinyURL(article.URL)

                if profile['prefers_email']:
                    return "<li><a href=\'%s\'>%s</a></li>" % (tiny_url,
                                                               article.title)
                else:
                    return article.title + " -- " + tiny_url

            for idx, article in enumerate(articles):
                if send_all or (idx + 1) in chosen_articles:
                    article_link = formatArticle(article)

                    if profile['prefers_email']:
                        body += article_link
                    else:
                        if not app_utils.emailUser(profile, SUBJECT="",
                                                   BODY=article_link):
                            tcp.send_out("I'm having trouble sending you these " +
                                    "articles. Please make sure that your " +
                                    "phone number and carrier are correct " +
                                    "on the dashboard.")
                            return

            # if prefers email, we send once, at the end
            if profile['prefers_email']:
                body += "</ul>"
                if not app_utils.emailUser(profile,
                                           SUBJECT="Your Top Headlines",
                                           BODY=body):
                    tcp.send_out("I'm having trouble sending you these articles. " +
                            "Please make sure that your phone number and " +
                            "carrier are correct on the dashboard.")
                    return

            tcp.send_out("All set")

        else:

            tcp.send_out("OK I will not send any articles")

    if 'phone_number' in profile:
        tcp.send_out("Here are the current top headlines. " + all_titles +
                ". Would you like me to send you these articles? " +
                "If so, which?")
       #handleResponse()

    else:
        tcp.send_out(
            "Here are the current top headlines. " + all_titles)
コード例 #20
0
        def punchLine(text):
            #mic.say(joke[1])
	    client.send_out(joke[1])
	    print "firstLine %s" % text
コード例 #21
0
def handle(text, mic, profile):
    """
        Responds to user-input, typically speech text, with a summary of
        the day's top news headlines, sending them to the user over email
        if desired.

        Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone
                   number)
    """
    tcp.send_out(tcp.is_new("Pulling up the news"))
    articles = getTopArticles(maxResults=3)
    titles = [" ".join(x.title.split(" - ")[:-1]) for x in articles]
    all_titles = "... ".join(
        str(idx + 1) + ")" + title for idx, title in enumerate(titles))

    def handleResponse(text):
        def extractOrdinals(text):
            output = []
            service = NumberService()
            for w in text.split():
                if w in service.__ordinals__:
                    output.append(service.__ordinals__[w])
            return [service.parse(w) for w in output]

        chosen_articles = extractOrdinals(text)
        send_all = not chosen_articles and app_utils.isPositive(text)

        if send_all or chosen_articles:
            tcp.send_out("Sure, just give me a moment")

            if profile['prefers_email']:
                body = "<ul>"

            def formatArticle(article):
                tiny_url = app_utils.generateTinyURL(article.URL)

                if profile['prefers_email']:
                    return "<li><a href=\'%s\'>%s</a></li>" % (tiny_url,
                                                               article.title)
                else:
                    return article.title + " -- " + tiny_url

            for idx, article in enumerate(articles):
                if send_all or (idx + 1) in chosen_articles:
                    article_link = formatArticle(article)

                    if profile['prefers_email']:
                        body += article_link
                    else:
                        if not app_utils.emailUser(
                                profile, SUBJECT="", BODY=article_link):
                            tcp.send_out(
                                "I'm having trouble sending you these " +
                                "articles. Please make sure that your " +
                                "phone number and carrier are correct " +
                                "on the dashboard.")
                            return

            # if prefers email, we send once, at the end
            if profile['prefers_email']:
                body += "</ul>"
                if not app_utils.emailUser(
                        profile, SUBJECT="Your Top Headlines", BODY=body):
                    tcp.send_out(
                        "I'm having trouble sending you these articles. " +
                        "Please make sure that your phone number and " +
                        "carrier are correct on the dashboard.")
                    return

            tcp.send_out("All set")

        else:

            tcp.send_out("OK I will not send any articles")

    if 'phone_number' in profile:
        tcp.send_out("Here are the current top headlines. " + all_titles +
                     ". Would you like me to send you these articles? " +
                     "If so, which?")
    #handleResponse()

    else:
        tcp.send_out("Here are the current top headlines. " + all_titles)
コード例 #22
0
ファイル: Weather.py プロジェクト: hTrap/jasper-client
def handle(text, mic, profile):
    """
    Responds to user-input, typically speech text, with a summary of
    the relevant weather for the requested date (typically, weather
    information will not be available for days beyond tomorrow).

    Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone
                   number)
    """
    forecast = None
    if 'wmo_id' in profile:
        forecast = get_forecast_by_wmo_id(str(profile['wmo_id']))
    elif 'location' in profile:
        forecast = get_forecast_by_name(str(profile['location']))

    if not forecast:
        client.send_out("I'm sorry, I can't seem to access that information. Please " +
                "make sure that you've set your location on the dashboard.")
        return

    tz = getTimezone(profile)

    service = DateService(tz=tz)
    date = service.extractDay(text)
    if not date:
        date = datetime.datetime.now(tz=tz)
    weekday = service.__daysOfWeek__[date.weekday()]

    if date.weekday() == datetime.datetime.now(tz=tz).weekday():
        date_keyword = "Today"
    elif date.weekday() == (
            datetime.datetime.now(tz=tz).weekday() + 1) % 7:
        date_keyword = "Tomorrow"
    else:
        date_keyword = "On " + weekday

    output = None

    for entry in forecast:
        try:
            date_desc = entry['title'].split()[0].strip().lower()
            if date_desc == 'forecast':
                # For global forecasts
                date_desc = entry['title'].split()[2].strip().lower()
                weather_desc = entry['summary']
            elif date_desc == 'current':
                # For first item of global forecasts
                continue
            else:
                # US forecasts
                weather_desc = entry['summary'].split('-')[1]

            if weekday == date_desc:
                output = date_keyword + \
                    ", the weather will be " + weather_desc + "."
                break
        except:
            continue

    if output:
        output = replaceAcronyms(output)
        client.send_out(output)
    else:
        client.send_out(
            "I'm sorry. I can't see that far ahead.")
コード例 #23
0
def is_new(old):
    new = client.grab_input().upper()
    while new==old:
	new = client.grab_input().upper()
    return new
コード例 #24
0
ファイル: Weather.py プロジェクト: devagul93/Jarvis-System
def handle(text, mic, profile):
    """
    Responds to user-input, typically speech text, with a summary of
    the relevant weather for the requested date (typically, weather
    information will not be available for days beyond tomorrow).

    Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone
                   number)
    """
    forecast = None
    if 'wmo_id' in profile:
        forecast = get_forecast_by_wmo_id(str(profile['wmo_id']))
    elif 'location' in profile:
        forecast = get_forecast_by_name(str(profile['location']))

    if not forecast:
        tcp.send_out("I'm sorry, I can't seem to access that information. Please " +
                "make sure that you've set your location on the dashboard.")
        return

    tz = getTimezone(profile)

    service = DateService(tz=tz)
    date = service.extractDay(text)
    if not date:
        date = datetime.datetime.now(tz=tz)
    weekday = service.__daysOfWeek__[date.weekday()]

    if date.weekday() == datetime.datetime.now(tz=tz).weekday():
        date_keyword = "Today"
    elif date.weekday() == (
            datetime.datetime.now(tz=tz).weekday() + 1) % 7:
        date_keyword = "Tomorrow"
    else:
        date_keyword = "On " + weekday

    output = None

    for entry in forecast:
        try:
            date_desc = entry['title'].split()[0].strip().lower()
            if date_desc == 'forecast':
                # For global forecasts
                date_desc = entry['title'].split()[2].strip().lower()
                weather_desc = entry['summary']
            elif date_desc == 'current':
                # For first item of global forecasts
                continue
            else:
                # US forecasts
                weather_desc = entry['summary'].split('-')[1]

            if weekday == date_desc:
                output = date_keyword + \
                    ", the weather will be " + weather_desc + "."
                break
        except:
            continue

    if output:
        output = replaceAcronyms(output)
        tcp.send_out(output)
    else:
        tcp.send_out("I'm sorry. I can't see that far ahead.")