예제 #1
0
def dealWithUserInteraction(chat_id, name, last_name, username, application, text,
                            location, contact, photo, document, voice):

    p = person.getPersonByChatIdAndApplication(chat_id, application)
    name_safe = ' {}'.format(name) if name else ''

    if p is None:
        p = person.addPerson(chat_id, name, last_name, username, application)
        msg = " 😀 Ciao{},\nbenvenuto/a In ErmesTObot!\n".format(name_safe)
        send_message(p, msg)
        restart(p)
        tellMaster("New {} user: {}".format(application, p.getFirstNameLastNameUserName()))
    else:
        # known user
        modified, was_disabled = p.updateUserInfo(name, last_name, username)
        if WORK_IN_PROGRESS and p.getId() not in key.TESTER_IDS:
            send_message(p, "🏗 Il sistema è in aggiornamento, ti preghiamo di riprovare più tardi.")
        elif was_disabled or text in ['/start', 'start', 'START', 'INIZIO']:
            msg = " 😀 Ciao{}!\nBentornato/a in ErmesTObot!".format(name_safe)
            send_message(p, msg)
            restart(p)
        elif text == '/state':
            msg = "You are in state {}: {}".format(p.state, STATES.get(p.state, '(unknown)'))
            send_message(p, msg)
        elif text in ['/settings', 'IMPOSTAZIONI']:
            redirectToState(p, SETTINGS_STATE)
        elif text in ['/help', 'HELP', 'AIUTO']:
            redirectToState(p, HELP_STATE)
        elif text in ['/stop', 'STOP']:
            p.setEnabled(False, put=True)
            msg = "🚫 Hai *disabilitato* ErmesTObot.\n" \
                  "In qualsiasi momento puoi riattivarmi scrivendomi qualcosa."
            send_message(p, msg)
        elif text == '/testapi':
            import requests
            url = 'https://00b501df.ngrok.io/RestfulService_war_exploded/restresources/cafeteria/0/takenSeats'
            r = requests.get(url)
            result = r.json()
            send_message(p, "result: {}".format(result))
        else:
            if not dealWithUniversalCommands(p, text=text):
                logging.debug("Sending {} to state {} with input {}".format(p.getFirstName(), p.state, text))
                repeatState(p, text=text, location=location, contact=contact, photo=photo, document=document,
                            voice=voice)
예제 #2
0
파일: main.py 프로젝트: kercos/LingoBot
    def post(self):
        urlfetch.set_default_fetch_deadline(60)
        body = json.loads(self.request.body)
        logging.info('request body:')
        logging.info(body)
        self.response.write(json.dumps(body))

        # update_id = body['update_id']
        if 'message' not in body:
            return
        message = body['message']
        # message_id = message.get('message_id')
        # date = message.get('date')
        if "chat" not in message:
            return
        # fr = message.get('from')
        chat = message['chat']
        chat_id = chat['id']
        if "first_name" not in chat:
            return
        text = message.get('text').encode('utf-8') if "text" in message else ''
        name = chat["first_name"].encode('utf-8')
        last_name = chat["last_name"].encode(
            'utf-8') if "last_name" in chat else None
        username = chat["username"] if "username" in chat else None
        location = message["location"] if "location" in message else None
        contact = message["contact"] if "contact" in message else None

        # u'contact': {u'phone_number': u'393496521697', u'first_name': u'Federico', u'last_name': u'Sangati',
        #             u'user_id': 130870321}
        # logging.debug('location: ' + str(location))

        def reply(msg=None,
                  kb=None,
                  markdown=False,
                  inlineKeyboardMarkup=False):
            tell(chat_id, msg, kb, markdown, inlineKeyboardMarkup)

        p = person.getPersonByChatId(chat_id)

        if p is None:
            # new user
            logging.info("Text: " + text)
            if text == '/help':
                reply(ISTRUZIONI)
            elif text.startswith("/start"):
                tell_masters("New user: "******"Ciao {0}, welcome in LingoGameBot!".format(name))
                restart(p)
            else:
                reply("Press on /start if you want to begin. "
                      "If you encounter any problem, please contact @kercos")
        else:
            # known user
            p.updateUsername(username)
            if text == '/state':
                if p.state in STATES:
                    reply("You are in state " + str(p.state) + ": " +
                          STATES[p.state])
                else:
                    reply("You are in state " + str(p.state))
            elif text.startswith("/start"):
                reply("Hi {0}, welcome back in LingoGameBot!".format(name))
                p.setEnabled(True, put=False)
                restart(p)
            elif WORK_IN_PROGRESS and p.chat_id != key.FEDE_CHAT_ID:
                reply(UNDER_CONSTRUCTION +
                      " The system is under maintanance, try again later.")
            else:
                logging.debug("Sending {0} to state {1}. Input: '{2}'".format(
                    p.getName(), str(p.state), text))
                repeatState(p, input=text, contact=contact)
예제 #3
0
    def post(self):
        urlfetch.set_default_fetch_deadline(60)
        body = json.loads(self.request.body)
        logging.info('request body:')
        logging.info(body)
        self.response.write(json.dumps(body))

        # update_id = body['update_id']
        message = body['message']
        #message_id = message.get('message_id')
        # date = message.get('date')
        if "chat" not in message:
            return
        # fr = message.get('from')
        chat = message['chat']
        chat_id = chat['id']
        if "first_name" not in chat:
            return
        text = message.get('text').encode('utf-8') if "text" in message else ""
        name = chat["first_name"].encode('utf-8')
        last_name = chat["last_name"].encode(
            'utf-8') if "last_name" in chat else "-"
        username = chat["username"] if "username" in chat else "-"

        #location = message["location"] if "location" in message else None
        #logging.debug('location: ' + str(location))

        def reply(msg=None, kb=None, hideKb=True, markdown=False):
            tell(chat_id, msg, kb, hideKb, markdown)

        p = ndb.Key(Person, str(chat_id)).get()

        if p is None:
            # new user
            logging.info("Text: " + text)
            if text == '/help':
                reply(INSTRUCTIONS)
            elif text.startswith("/start"):
                tell_masters("New user: "******"Hi " + name + ", " +
                      "welcome to the Parseme Shared Task annotation!")
                restart(p)
            else:
                reply("Something didn't work... please contact @kercos")
        else:
            # known user
            person.updateUsername(p, username)
            if text == '/state':
                if p.state in STATES:
                    reply("You are in state " + str(p.state) + ": " +
                          STATES[p.state])
                else:
                    reply("You are in state " + str(p.state))
            elif text.startswith("/start"):
                reply("Hi " + name + ", " +
                      "welcome back to the Parseme Shared Task annotation!")
                person.reInitializePerson(p, chat_id, name, last_name,
                                          username)
                restart(p)
            #-------------
            # SETTINGS
            #-------------
            elif p.state == -1:
                # settings
                if text == BACK_BUTTON:
                    restart(p)
                elif text == HIGHTLIGHTING_MODE_BUTTON:
                    goToSettingsHighlightingMode(p)
                    # state -11
                elif text == BUTTONS_DENSITY_BUTTON:
                    goToSettingsButtonsDensity(p)
                    # state -12
                else:
                    reply(FROWNING_FACE + " Sorry, I can't understand...")
            elif p.state == -11:
                # settings -> hightlighting mode
                if text == BACK_BUTTON:
                    goToSetting(p)
                elif text in person.MARKDOWN_OPTIONS.keys():
                    person.setHighlightingMode(p, text)
                    reply("Successfully set highlighting mode to " +
                          person.getHighlightedString(p, text),
                          markdown=True)
                    goToSetting(p)
                    #state -1
                else:
                    reply(FROWNING_FACE + " Sorry, I can't understand...")
            elif p.state == -12:
                # settings -> buttons density
                if text == BACK_BUTTON:
                    goToSetting(p)
                elif util.RepresentsInt(text):
                    charPerLine = int(text)
                    tot_sentences = sentAnno.totalSentPersonCurrentLang(p)
                    if charPerLine >= MIN_CHARS_PER_LINE and charPerLine <= MAX_CHARS_PER_LINE:
                        person.setMaxCharsPerLine(p, charPerLine)
                        goToSettingsButtonsDensity(p)
                        # state -1
                    else:
                        reply(
                            "Sorry, not a valid index. Please enter an index between "
                            + person.getHighlightedString(
                                p, str(MIN_CHARS_PER_LINE)) + " and " +
                            person.getHighlightedString(
                                p, str(MAX_CHARS_PER_LINE)) + ".")
                else:
                    reply(FROWNING_FACE + " Sorry, I can't understand...")
            # -------------
            # INITIAL STATE
            # -------------
            elif p.state == 0:
                # INITIAL STATE
                if text in ['/help', HELP_BUTTON]:
                    reply(INSTRUCTIONS)
                elif text == SETTINGS_BUTTON:
                    goToSetting(p)
                    #state -1
                elif text == INFO_BUTTON:
                    textMsg = "Number of annotated sentences per language:\n"
                    for lang, flag in sentAnno.LANGUAGE_FLAGS.iteritems():
                        progress = str(person.getLanguageProgress(p, lang))
                        total = str(sentAnno.totalSentLang(lang))
                        textMsg += flag + ' ' + progress + '/' + total + '\n'
                    reply(textMsg)
                elif text == ANNOTATE_BUTTON_EN:
                    person.setLanguage(p, 'ENGLISH')
                    person.importSelectedMwe(p)
                    displayCurrentSentence(p)
                    #state 1
                elif text == ANNOTATE_BUTTON_IR:
                    person.setLanguage(p, 'FARSI')
                    person.importSelectedMwe(p)
                    displayCurrentSentence(p)
                    # state 1
                elif chat_id in key.MASTER_CHAT_ID:
                    if text == '/test':
                        logging.debug('test')
                        #description = object.getObjectsById(4866725958909952)
                        #logging.debug('description: ' + description)
                        #logging.debug('type: ' + str(type(description)))
                        #reply(description)
                        #reply("Méthode de Français")
                        #deferred.defer(tell_fede, "Hello, world!")
                    elif text == '/testMarkdown':
                        reply(
                            "aaaa*xxxx*zzzzz\naaaa_xxxx_zzzz\naaaa`xxxx`zzzz",
                            markdown=True)
                        #reply("fdsadfa [dfsafd] dsfasdf a", markdown=True)
                        #reply("fdasfd *df\\*as* fa fsa", markdown=True)
                        #text = "*" + util.escapeMarkdown("`[8]") + "*"
                        #reply(text, markdown=True)
                        #logging.debug("reply text: " + text)
                    elif text == '/testBitMap':
                        #bitmaptest.testBitMap(100, 20)
                        bitmaptest.testBitMap(5000, 500)
                        reply('Successfully finished test (see log).')
                    elif text.startswith('/broadcast ') and len(text) > 11:
                        msg = text[11:]  #.encode('utf-8')
                        deferred.defer(broadcast, msg)
                    elif text == '/restartAllUsers':
                        deferred.defer(
                            restartAllUsers,
                            "ParsemeBot v.2 is out! " + GRINNING_FACE)
                    elif text == '/resetAllUsers':
                        c = resetAllUsers()
                        reply("Resetted users: " + str(c))
                    else:
                        reply(FROWNING_FACE + " Sorry, I can't understand...")
                    #setLanguage(d.language)
                else:
                    reply(FROWNING_FACE +
                          "Sorry I didn't understand you ...\n" +
                          "Press the HELP button to get more info.")
            # --------------------------
            # DISPLAY CURRENT SENTENCE
            # --------------------------
            elif p.state == 1:
                # display current sentence
                if text == BACK_BUTTON:
                    restart(p)
                elif text == '/progress':
                    reply("Annotated sentence(s) for " + p.language + ': ' +
                          str(person.getLanguageProgress(p)) + '/' +
                          str(sentAnno.totalSentPersonCurrentLang(p)))
                elif text == '/nextna':
                    index = person.getNextNonAnnSentIndex(p)
                    if index:
                        jumpToSentence(p, index + 1)
                    else:
                        reply(EXCLAMATION + " No next non-annotated sentence")
                elif text == '/prevna':
                    index = person.getPrevNonAnnSentIndex(p)
                    if index:
                        jumpToSentence(p, index + 1)
                    else:
                        reply(EXCLAMATION +
                              " No previous non-annotated sentence")
                elif text == ADD_MWE_BUTTON:
                    prepareToSelectTokens(p)
                    #state 30
                elif text == NO_MWE_BUTTON and p.selectedMwes == None:
                    reply(
                        CHECK +
                        " The current sentence has been marked without MWEs.")
                    sentAnno.setEmptyMwes(p)  #mirroring on person
                    #person.setEmptyMwes(p)
                    person.setCurrentSentenceAnnotated(p)
                    displayCurrentSentence(p)
                    # state 1
                elif text == MOD_MWE_BUTTON and p.selectedMwes != None:
                    # reply(UNDER_CONSTRUCTION + " currently working on this.")
                    askWhichAnnotationToModify(p)
                    # state 50
                elif text == REMOVE_MWE_BUTTON and p.selectedMwes != None:
                    askWhichAnnotationToRemove(p)
                    # state 60
                elif text == NEXT_BUTTON:
                    if person.hasNextSentece(p):
                        person.goToNextSentence(p)
                        person.importSelectedMwe(p)
                        displayCurrentSentence(p)
                        #state 1
                    else:
                        displayCurrentSentence(p)
                        reply(EXCLAMATION + " You reached the last sentence")
                        # state 1
                    # state 1
                elif text == PREV_BUTTON:
                    if person.hasPreviousSentece(p):
                        person.goToPrevSentence(p)
                        person.importSelectedMwe(p)
                        displayCurrentSentence(p)
                        #state 1
                    else:
                        displayCurrentSentence(p)
                        reply(EXCLAMATION + " You reached the first sentence")
                        # state 1
                    # state 1
                elif text == GO_TO_BUTTON:
                    tot_sentences = sentAnno.totalSentPersonCurrentLang(p)
                    reply(
                        "Please insert the index of the sentence you want to jumpt to, between "
                        + person.getHighlightedString(p, str(1)) + " and " +
                        person.getHighlightedString(p, str(tot_sentences)) +
                        " (you can also enter the number without pressing the "
                        + JUMP_ARROW + " button).",
                        markdown=True)
                elif text.startswith('/') and util.RepresentsInt(text[1:]):
                    mwe_number = int(text[1:])
                    jumpToModifySingleMwe(p, mwe_number)
                    #state 40
                elif util.RepresentsInt(text):
                    index = int(text)
                    tot_sentences = sentAnno.totalSentPersonCurrentLang(p)
                    if index > 0 and index <= tot_sentences:
                        jumpToSentence(p, index)
                        # state 1
                    else:
                        reply(
                            EXCLAMATION +
                            "Not a valid index. If you want to jump to a specific sentence, "
                            "please enter an index between " +
                            person.getHighlightedString(p, str(1)) +
                            " and " + person.getHighlightedString(
                                p, str(tot_sentences)) + '.',
                            markdown=True)
                else:
                    reply(FROWNING_FACE + " Sorry, I can't understand...")
            elif p.state == 30:
                # add MWE -> select tokens
                if text == BACK_BUTTON:
                    displayCurrentSentence(p)
                    # state 1
                elif text.endswith(']'):
                    token_number_str = text[text.rindex('[') + 1:-1]
                    #logging.debug('number_str: ' + token_number_str)
                    if util.RepresentsInt(token_number_str):
                        token_number = int(token_number_str)
                        if token_number > 0 and token_number <= len(
                                p.selectedTokens):
                            dealWithTokensSelection(p, token_number - 1)
                            #state 30
                        else:
                            reply("Not a valid token.")
                    else:
                        reply("Not a valid token.")
                elif text == CHOOSE_CAT_BUTTON:
                    currentMwes = p.selectedMwes
                    if currentMwes and person.getSelectedTokensIndexTuple(
                            p) in currentMwes:
                        reply(EXCLAMATION + ' MWE has been already inserted!')
                    else:
                        askAnnotationLabel(p)
                        # state 31
                elif text == CONFIRM_CHANNGES:
                    dealWithChangeMwe(p)
                    # state 1
                else:
                    reply(FROWNING_FACE + " Sorry, I can't understand...")
            elif p.state == 31:
                # add MWE -> select category
                if text == BACK_BUTTON:
                    if p.last_state == 40:
                        displayCurrentSentence(p)
                        # state 1
                    else:
                        dealWithTokensSelection(p)
                        # state 30
                elif text in categories.ANNOTATION_CATS:
                    indexes = person.getSelectedTokensIndexTuple(p)
                    mwe_flat = renderMwe(p, indexes, False, False)
                    reply(CHECK + " The MWE " + mwe_flat +
                          " has been marked with category " +
                          person.getHighlightedString(p, text) + '\n',
                          markdown=True)
                    sentAnno.appendMwe(p, text)  #mirroring on person
                    #person.appendMwe(p, text)
                    person.setCurrentSentenceAnnotated(p)
                    displayCurrentSentence(p)
                    # state 1
                else:
                    reply(FROWNING_FACE + " Sorry, I can't understand...")
            elif p.state == 40:
                # user has selected a single MWE via the /number option
                if text == BACK_BUTTON:
                    displayCurrentSentence(p)
                    # state 1
                elif text == CHANGE_CAT_BUTTON:
                    askAnnotationLabel(p)
                    # state 31
                elif text == REMOVE_BUTTON:
                    mwe_to_remove = person.getSelectedTokensIndexTuple(p)
                    mwe_flat = renderMwe(p, mwe_to_remove, True, False)
                    #logging.debug("after REMOVE_MWE_BUTTON: " + str(mwe_to_remove))
                    #logging.debug("mwe_to_remove: " + str(mwe_to_remove))
                    #logging.debug("current mwes: " + str(p.selectedMwes))
                    sentAnno.removeMwe(p, mwe_to_remove)  #mirroring on person
                    #person.removeMwe(p, mwe_to_remove)
                    tell(p.chat_id,
                         CHECK + " The MWE " + mwe_flat + " has been removed!",
                         markdown=True)
                    displayCurrentSentence(p)
                    # state 1
                elif text == CHANGE_MWE_ELEMENTS:
                    p.currentMweTmp = person.getSelectedTokensIndexTuple(p)
                    dealWithTokensSelection(p)
                    # state 30
                elif text == CHANGE_MWE_CONFIDENCE:
                    askConfidenceLevel(p)
                    # state 70
                else:
                    reply(FROWNING_FACE + " Sorry, I can't understand...")
            elif p.state == 50:
                # modify MWE
                if text == BACK_BUTTON:
                    displayCurrentSentence(p)
                    # state 1
                elif util.RepresentsInt(text):
                    mwe_number = int(text)
                    jumpToModifySingleMwe(p, mwe_number)
                    # state 40
                else:
                    reply(FROWNING_FACE + " Sorry, I can't understand...")
            elif p.state == 60:
                # remove MWE
                if text == BACK_BUTTON:
                    displayCurrentSentence(p)
                    # state 1
                elif util.RepresentsInt(text):
                    mwe_number = int(text)
                    dealWithRemoveMwe(p, mwe_number)
                    # state 1
                else:
                    reply(FROWNING_FACE + " Sorry, I can't understand...")
            elif p.state == 70:
                # change confidence level MWE
                if text == BACK_BUTTON:
                    displayCurrentSentence(p)
                    # state 1
                elif util.RepresentsInt(text):
                    newConf = int(text)
                    dealWithChangeConfidenceLevel(p, newConf)
                    # state 1
                elif text in NUMBERS_0_10[1:]:
                    newConf = NUMBERS_0_10.index(text)
                    dealWithChangeConfidenceLevel(p, newConf)
                    # state 1
                else:
                    reply(FROWNING_FACE + " Sorry, I can't understand...")
            else:
                reply("There is a problem (" + str(p.state).encode('utf-8') +
                      "). Report this to @kercos" + '\n')
                restart(p)
예제 #4
0
    def post(self):
        urlfetch.set_default_fetch_deadline(60)
        body = json.loads(self.request.body)
        logging.info('request body:')
        logging.info(body)
        self.response.write(json.dumps(body))

        # update_id = body['update_id']
        if 'message' not in body:
            return
        message = body['message']
        # message_id = message.get('message_id')
        # date = message.get('date')
        if "chat" not in message:
            return
        # fr = message.get('from')
        chat = message['chat']
        chat_id = chat['id']
        if "first_name" not in chat:
            return
        text = message.get('text').encode('utf-8') if "text" in message else ''
        name = chat["first_name"].encode('utf-8')
        last_name = chat["last_name"].encode('utf-8') if "last_name" in chat else None
        username = chat["username"] if "username" in chat else None
        location = message["location"] if "location" in message else None
        contact = message["contact"] if "contact" in message else None

        # u'contact': {u'phone_number': u'393496521697', u'first_name': u'Federico', u'last_name': u'Sangati',
        #             u'user_id': 130870321}
        # logging.debug('location: ' + str(location))

        def reply(msg=None, kb=None, markdown=False, inlineKeyboardMarkup=False):
            tell(chat_id, msg, kb, markdown, inlineKeyboardMarkup)

        p = person.getPersonByChatId(chat_id)

        if p is None:
            # new user
            logging.info("Text: " + text)
            if text == '/help':
                reply(ISTRUZIONI)
            elif text.startswith("/start"):
                tell_masters("New user: "******"Ciao {0}, welcome in OpenSummerSchoolBot!".format(name))
                restart(p)
            else:
                reply("Press on /start if you want to begin. "
                      "If you encounter any problem, please contact @kercos")
        else:
            # known user
            p.updateUsername(username)
            if text == '/state':
                if p.state in STATES:
                    reply("You are in state " + str(p.state) + ": " + STATES[p.state])
                else:
                    reply("You are in state " + str(p.state))
            elif text.startswith("/start"):
                reply("Hi {0}, welcome back in OpenSummerSchoolBot!".format(name))
                p.setEnabled(True, put=False)
                restart(p)
            elif WORK_IN_PROGRESS and p.chat_id != key.FEDE_CHAT_ID:
                reply(UNDER_CONSTRUCTION + " The system is under maintanance, try again later.")
            else:
                logging.debug("Sending {0} to state {1}. Input: '{2}'".format(p.getName(), str(p.state), text))
                repeatState(p, input=text, contact=contact)
예제 #5
0
    def post(self):
        body = jsonUtil.json_loads_byteified(self.request.body)
        logging.info('request body:')
        logging.info(body)
        self.response.write(json.dumps(body))

        # update_id = body['update_id']
        if 'message' not in body:
            return
        message = body['message']
        #message_id = message.get('message_id')
        # date = message.get('date')
        if "chat" not in message:
            return
        # fr = message.get('from')
        chat = message['chat']
        chat_id = chat['id']
        if "first_name" not in chat:
            return
        text = message.get('text', "")
        name = chat["first_name"]
        last_name = chat.get("last_name", "-")
        username = chat.get("username", "-")
        location = message.get("location", None)
        voice = message.get("voice", None)
        #audio = message.get("audio", None)
        #document = message.get("document", None)

        logging.debug("Received input from {}. Text={} Location={}".format(
            chat_id, text, location))

        def reply(msg=None, kb=None, markdown=True, inline_keyboard=False):
            send_message(chat_id,
                         msg,
                         kb=kb,
                         markdown=markdown,
                         inline_keyboard=inline_keyboard)

        p = person.getPersonByChatId(chat_id)

        if p is None:
            # new user
            logging.info("Text: " + text)
            if text == '/help':
                reply(ISTRUZIONI)
            if text.startswith("/start"):
                p = person.addPerson(chat_id, name)
                reply("Ciao " + p.getFirstName() + ", " + "benvenuta/o!")
                init_user(p, name, last_name, username)
                restart(p)
                # state = -1 or -2
                tell_masters("New user: "******"Premi su /start se vuoi iniziare. "
                    "Se hai qualche domanda o suggerimento non esitare di contattarmi cliccando su @kercos"
                )
        else:
            # known user
            person.updateUsername(p, username)
            if text.startswith("/start"):
                reply("Ciao " + p.getFirstName() + ", " + "ben ritrovata/o!")
                init_user(p, name, last_name, username)
                restart(p)
                # state = -1 or -2
            elif text == '/state':
                if p.state in STATES:
                    reply("You are in state " + str(p.state) + ": " +
                          STATES[p.state])
                else:
                    reply("You are in state " + str(p.state))
            elif WORK_IN_PROGRESS and not p.isAdmin():
                reply(UNDER_CONSTRUCTION +
                      " Il sistema è in aggiornamento, riprova più tardi.")
            elif text.startswith('/rec_'):
                send_voiceLocationTranslationFromCommand(p,
                                                         text,
                                                         userInfo=p.isAdmin())
            elif text.startswith('/sendText') and p.isAdmin():
                dealWithsendTextCommand(p, text, markdown=False)
            elif p.state == -1:
                # INITIAL STATE
                if text in ['/help', BOTTONE_INFO]:
                    redirectToState(p, 8)
                elif text == BOTTONE_REGISTRA:
                    if p.location:
                        dealWithPlaceAndMicInstructions(p)
                    else:
                        reply(
                            "Questa è la tua prima registrazione: "
                            "è necessario che tu inserisca il luogo del dialetto che vuoi registrare.\n"
                            + ISTRUZIONI_POSIZIONE,
                            kb=[[BOTTONE_ANNULLA]])
                        person.setState(p, -2)
                elif text == BOTTONE_ASCOLTA:
                    goToAscolta(p)
                    # state 30
                elif p.isAdmin():
                    if text == BOTTONE_ADMIN:
                        redirectToState(p, 9)
                    elif text == '/test':
                        reply('test')
                        #reply(geoUtils.getLocationTest())
                        #taskqueue.add(url='/worker', params={'key': key})
                        #geoUtils.test_Google_Map_Api()
                    elif text == '/infoCounts':
                        c = person.getPeopleCount()
                        reply("Number of users: " + str(c))
                    elif text == '/restartUsers':
                        text = "Nuova interfaccia e nuove funzionalità :)\n" \
                               "Ora puoi inserire le località digitando il nome del posto (e.g, Perugia).\n" \
                               "Inoltre puoi cercare registrazioni in prossimità di un luogo.\n" \
                               "Buon ascolto e buona registrazione!"
                        deferred.defer(restartAllUsers,
                                       text)  #'New interface :)')
                        #deferred.defer(restartTest, text) #'New interface :)')
                        logging.debug('restarted users')
                    elif text == '/importVivaldi':
                        #logging.debug('nothing')
                        recording.importVivaldi()
                    elif text == '/countVivaldi':
                        c = recording.countVivaldi()
                        reply('Vivaldi recs: ' + str(c))
                    elif text == '/deleteVivaldi':
                        recording.deleteVivaldi()
                        reply('Deleted Vivaldi recs.')
                    elif text == '/remFormatVoice':
                        c = recording.removeFormatVoice()
                        reply("removed rec format voice: " + str(c))
                    elif text == '/stats':
                        msg = recording.getRecodingsStats()
                        send_message(p.chat_id, msg, markdown=False)
                        msg = "People count: {}".format(
                            person.getPeopleCount())
                        send_message(p.chat_id, msg, markdown=False)
                    elif text.startswith('/echo ') and len(text) > 6:
                        msg = text[6:]
                        reply(msg)
                    elif text.startswith('/broadcast ') and len(text) > 11:
                        msg = text[11:]
                        deferred.defer(broadcast,
                                       p.chat_id,
                                       msg,
                                       restart_user=False)
                    elif text.startswith(
                            '/restartBroadcast ') and len(text) > 18:
                        msg = text[18:]
                        deferred.defer(broadcast,
                                       p.chat_id,
                                       msg,
                                       restart_user=True)
                    elif text.startswith('/self ') and len(text) > 6:
                        msg = text[6:]
                        reply(msg)
                    elif text == '/lastContributors':
                        count, namesString, recCommandsString = getLastContibutors(
                            300)
                        msg = "Contributors: " + str(
                            count) + "\nNames: " + namesString
                        reply(msg)
                    elif text == '/testMonthlyMessage':
                        msg = getMonthlyMessage()
                        reply(msg)
                    else:
                        reply('Scusa, capisco solo /help /start '
                              'e altri comandi segreti...')
                    #setLanguage(d.language)
                else:
                    reply(
                        "Scusa non capisco quello che hai detto.\n"
                        "Usa i pulsanti sotto o premi {} per avere informazioni."
                        .format(BOTTONE_INFO))
            elif p.state == -2:
                # POSIZIONE
                if text == BOTTONE_ANNULLA:
                    restart(p, "Operazione annullata.")
                elif location != None:
                    logging.debug('User sending location: {}, {}'.format(
                        location['latitude'], location['longitude']))
                    luogo = geoUtils.getComuneProvinciaFromCoordinates(
                        location['latitude'], location['longitude'])
                    logging.debug('Detected luogo: {}'.format(luogo))
                    if luogo:
                        person.setLocation(p, location['latitude'],
                                           location['longitude'])
                        dealWithPlaceAndMicInstructions(p)
                    else:
                        reply(
                            "Non conosco la località inserita, prova ad essere più precisa/o.\n"
                            + ISTRUZIONI_POSIZIONE,
                            kb=[[BOTTONE_INVIA_LOCATION], [BOTTONE_ANNULLA]])
                        logging.debug(
                            'Problem finding comune and provincia from coordinates {} {}'
                            .format(location['latitude'],
                                    location['longitude']))
                    #state 20
                elif text.startswith('('):
                    text_split = text[1:-1].split(",")
                    latitude = float(text_split[0])
                    longitude = float(text_split[1])
                    person.setLocation(p, latitude, longitude)
                    send_location(p.chat_id, latitude, longitude)
                    dealWithPlaceAndMicInstructions(p)
                    #state 20
                else:
                    place = geoUtils.getLocationFromName(text)
                    if place:
                        person.setLocation(p, place.latitude, place.longitude)
                        dealWithPlaceAndMicInstructions(p)
                        #state 20
                    else:
                        reply(
                            "Non conosco la località inserita, prova ad essere più precisa/o.\n"
                            + ISTRUZIONI_POSIZIONE,
                            kb=[[BOTTONE_INVIA_LOCATION], [BOTTONE_ANNULLA]])
            elif p.state == 20:
                # REGISTRA
                if text == BOTTONE_INDIETRO:
                    restart(p, "Operazione annullata.")
                    # state = -1
                elif text == BOTTONE_CAMBIA_LUOGO:
                    reply("Ok, cambiamo il luogo.\n" + ISTRUZIONI_POSIZIONE,
                          kb=[[BOTTONE_INVIA_LOCATION], [BOTTONE_ANNULLA]])
                    person.setState(p, -2)
                    # state -2
                elif voice != None:
                    reply(
                        "Bene! 😉\n"
                        "Ora riascolta la registrazione e conferma su ✅ OK "
                        "se la registrazione è ben riuscita o premi su 🎙 REGISTRA DI NUOVO per"
                        "effettuare un'altra registrazione.",
                        kb=[['✅ OK'], ['🎙 REGISTRA DI NUOVO'],
                            [BOTTONE_ANNULLA]])
                    file_id = voice['file_id']
                    #send_voice(p.chat_id, file_id)
                    rec = recording.addRecording(p, file_id)
                    person.setLastRecording(p, rec)
                    person.setState(p, 21)
                else:
                    reply(
                        FROWNING_FACE +
                        " Scusa non capisco quello che hai detto, devi inserire la registrazione tenendo premuto il microfono."
                    )
            elif p.state == 21:
                # CONFIRM RECORDING
                if text == BOTTONE_ANNULLA:
                    person.removeLastRecording(p)
                    restart(p, "Operazione annullata.")
                    # state = -1
                elif text == '✅ OK':
                    msg = utility.unindent('''
                        Riteniamo utile avere una traduzione in italiano delle registrazione \
                        in modo da essere comprensibili da tutti gli utenti.\n
                        *Scrivi qua sotto* la traduzione della registrazione \
                        (in aggiunta puoi inserire la trascrizione in dialetto e il significato in caso si tratti di un proverbio)
                        ''')
                    reply(msg, kb=[['Salta Traduzione']])
                    person.setState(p, 22)
                elif text == '🎙 REGISTRA DI NUOVO':
                    person.removeLastRecording(p)
                    reply(MIC_INSTRUCTIONS,
                          kb=[[BOTTONE_CAMBIA_LUOGO], [BOTTONE_ANNULLA]])
                    person.setState(p, 20)
                else:
                    reply(
                        FROWNING_FACE +
                        "Scusa non capisco quello che hai detto, premi *OK* per confermare la registrazione."
                    )
            elif p.state == 22:
                # CHECK IF AVAILABLE FOR TRANSLATION
                if text == 'Salta Traduzione':
                    msg = "👍😀 Grazie per il tuo contributo!\n" \
                          "La registrazione è in attesa di approvazione, riceverai un messaggio a breve."
                    reply(msg)
                    sendNewRecordingNotice(p)
                    restart(p)
                elif text == '':
                    msg = "Input non valido. *Scrivi* qua sotto la traduzione in italiano della registrazione"
                    reply(msg, kb=[['Salta Traduzione']])
                    return
                else:
                    recording.addTranslation(p.last_recording_file_id, text)
                    msg = "👍😀 Grazie per il tuo contributo!\n" \
                          "La registrazione è in attesa di approvazione, riceverai un messaggio a breve."
                    reply(msg)
                    sendNewRecordingNotice(p)
                    restart(p)
            elif p.state == 30:
                if text == BOTTONE_INDIETRO:
                    restart(p)
                    # state = -1
                elif text == BOTTONE_INDOVINA_LUOGO:
                    dealWithRandomRecording(p)
                    # state 31
                elif text == BOTTONE_CERCA_LUOGO:
                    reply(ISTRUZIONI_POSIZIONE_SEARCH, kb=[[BOTTONE_INDIETRO]])
                    person.setState(p, 32)
                    # state 32
                elif text == BOTTONE_RECENTI:
                    getRecentRecordings(p)
                    person.setState(p, 33)
                    # state 33
                elif text == BOTTONE_TUTTE:
                    getAllRecordings(p)
                    person.setState(p, 33)
                    # state 33
                else:
                    msg = "Input non valido. Usa i pulsanti qua sotto."
                    reply(msg)
                    return
            elif p.state == 31:
                # ASCOLTA - INDOVINA LUOGO
                if text in [BOTTONE_INDIETRO, BOTTONE_ANNULLA]:
                    restart(p)
                    # state = -1
                elif text == "ASCOLTA NUOVA REGISTRAZIONE":
                    dealWithRandomRecording(p)
                    # state 31
                elif location != None:
                    dealWithGuessedLocation(p, location)
                else:
                    place = geoUtils.getLocationFromName(text)
                    if place:
                        guessed_loc = {
                            'latitude': place.latitude,
                            'longitude': place.longitude
                        }
                        dealWithGuessedLocation(p, guessed_loc)
                    else:
                        reply(
                            "Non conosco la località inserita, prova ad essere più precisa/o.\n"
                            + ISTRUZIONI_POSIZIONE_GUESS,
                            kb=[[BOTTONE_ANNULLA]])
            elif p.state == 32:
                #ASCOLTA - RICERCA LUOGO
                sendWaitingAction(p.chat_id)
                if location != None:
                    dealWithFindClosestRecording(p, location)
                elif text == BOTTONE_INDIETRO:
                    restart(p)
                else:
                    place = geoUtils.getLocationFromName(text)
                    if place:
                        loc = {
                            'latitude': place.latitude,
                            'longitude': place.longitude
                        }
                        dealWithFindClosestRecording(p, loc)
                    else:
                        reply(
                            "Non conosco la località inserita, prova ad essere più precisa/o.\n"
                            + ISTRUZIONI_POSIZIONE_SEARCH,
                            kb=[[BOTTONE_INDIETRO]])
            elif p.state == 33:
                # REGISTRAZIONI RECENTI
                if text == BOTTONE_INDIETRO:
                    goToAscolta(p)
                else:
                    reply(FROWNING_FACE +
                          "Scusa non capisco quello che hai detto.")
            else:
                logging.debug("Sending {0} to state {1}".format(
                    p.getFirstName(), str(p.state)))
                repeatState(p, input=text)