示例#1
0
文件: main.py 项目: kercos/LingoBot
def tell(chat_id,
         msg,
         kb=None,
         markdown=True,
         inlineKeyboardMarkup=False,
         one_time_keyboard=True,
         sleepDelay=False):
    replyMarkup = {
        'resize_keyboard': True,
        'one_time_keyboard': one_time_keyboard
    }
    if kb:
        if inlineKeyboardMarkup:
            replyMarkup['inline_keyboard'] = kb
        else:
            replyMarkup['keyboard'] = kb
    try:
        data = {
            'chat_id': chat_id,
            'text': msg,
            'disable_web_page_preview': 'true',
            'parse_mode': 'Markdown' if markdown else '',
            'reply_markup': json.dumps(replyMarkup),
        }
        resp = requests.post(key.BASE_URL + 'sendMessage', data)
        logging.info('Response: {}'.format(resp.text))
        #logging.info('Json: {}'.format(resp.json()))
        respJson = json.loads(resp.text)
        success = respJson['ok']
        if success:
            if sleepDelay:
                sleep(0.1)
            return True
        else:
            status_code = resp.status_code
            error_code = respJson['error_code']
            description = respJson['description']
            if error_code == 403:
                # Disabled user
                p = person.getPersonByChatId(chat_id)
                p.setEnabled(False, put=True)
                logging.info('Disabled user: '******'❗ Input user disactivated: ' + p.getUserInfoString(
                )
                logging.debug(debugMessage)
                tell(key.FEDE_CHAT_ID, debugMessage, markdown=False)
            else:
                debugMessage = '❗ Raising unknown err in tell() when sending msg={} kb={}.' \
                          '\nStatus code: {}\nerror code: {}\ndescription: {}.'.format(
                    msg, kb, status_code, error_code, description)
                logging.error(debugMessage)
                tell(key.FEDE_CHAT_ID, debugMessage, markdown=False)
    except:
        report_exception()
示例#2
0
def tell(chat_id, msg, kb=None, markdown=True, inlineKeyboardMarkup=False,
         one_time_keyboard=True, sleepDelay=False):
    replyMarkup = {
        'resize_keyboard': True,
        'one_time_keyboard': one_time_keyboard
    }
    if kb:
        if inlineKeyboardMarkup:
            replyMarkup['inline_keyboard'] = kb
        else:
            replyMarkup['keyboard'] = kb
    try:
        resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
            'chat_id': chat_id,
            'text': msg,  # .encode('utf-8'),
            'disable_web_page_preview': 'true',
            'parse_mode': 'Markdown' if markdown else '',
            # 'reply_to_message_id': str(message_id),
            'reply_markup': json.dumps(replyMarkup),
        })).read()
        logging.info('send response: ')
        logging.info(resp)
    except urllib2.HTTPError, err:
        if err.code == 403:
            p = person.getPersonByChatId(chat_id)
            p.setEnabled(False)
            logging.info('Disabled user: '******'utf-8') + ' ' + str(chat_id))
def createGeoJsonElement(rec, addRandomCoordNoise=True):
    longitude = rec.location.lon
    latitude = rec.location.lat
    if addRandomCoordNoise:
        longitude += utility.getRandomFloat(MAX_COORDINATES_RANDOM_NOISE)
        latitude += utility.getRandomFloat(MAX_COORDINATES_RANDOM_NOISE)
    name_text = person.getPersonByChatId(rec.chat_id).getFirstName()
    translation_text = rec.translation.encode('utf-8') if rec.translation else "(nessuna traduzione)"
    audioUrl = "http://dialectbot.appspot.com/recordings/{0}.oga".format(rec.file_id)
    element = {
        "type": "Feature",
        "properties": {
            "person": name_text,
            "translation": translation_text,
            # "place"
            "date": rec.date_time.strftime("%d-%m-%Y"),
            "audio": "<p><audio width='300' height='32' src='{0}' "
                     "controls='controls' preload='none' type='audio/ogg; codecs=vorbis'><br />"
                     "Your browser does not support the audio element.<br /></audio></p>".format(audioUrl)
        },
        "geometry": {
            "type": "Point",
            "coordinates": [longitude, latitude]
        }
    }
    return element
def getRecordingNames():
    recs =  Recording.query(Recording.url == None).fetch()
    chat_id_set = set([r.chat_id for r in recs])
    names = []
    for id in chat_id_set:
        p = person.getPersonByChatId(id)
        names.append(p.getFirstName())
    print(', '.join(names))
    print(str(len(names)))
def getAllRecordings(p):
    recordings = ''
    qry = Recording.query(Recording.chat_id > 0)
    for r in qry:
        name = person.getPersonByChatId(r.chat_id).name
        recordings += '/rec_' + str(r.key.id()) + ' - ' + name + ' - ' + str(
            r.date_time.date()) + '\n'
    send_message(
        p.chat_id,
        "ULTIME REGISTRAZIONI:\n\n" + recordings +
        "\nPremi su uno dei link sopra per ascoltare la registrazione corrispondente.",
        kb=[[BOTTONE_INDIETRO]])
def send_voiceLocationTranslation(p, rec, userInfo=False):
    if userInfo:
        user = person.getPersonByChatId(rec.chat_id)
        send_message(
            p.chat_id,
            'Registrazione eseguita da: {}'.format(user.getFirstName()))
    send_message(p.chat_id, 'Audio:')
    send_voice(p.chat_id, rec)
    msg = 'Luogo: ' + geoUtils.getComuneProvinciaFromCoordinates(
        rec.location.lat, rec.location.lon)
    send_message(p.chat_id, msg)
    send_location(p.chat_id, rec.location.lat, rec.location.lon)
    sendTranslation(p.chat_id, rec)
def getRecentRecordings(p):
    recordings = ''
    qry = Recording.query(
        Recording.approved == recording.REC_APPROVED_STATE_TRUE).order(
            -Recording.date_time).fetch(8)
    for r in qry:
        name = person.getPersonByChatId(r.chat_id).name.encode('utf-8')
        recordings += '/rec_' + str(r.key.id()) + ' - ' + name + ' - ' + str(
            r.date_time.date()) + '\n'
    send_message(
        p.chat_id,
        "ULTIME REGISTRAZIONI:\n\n" + recordings +
        "\nPremi su uno dei link sopra per ascoltare la registrazione corrispondente.",
        kb=[[BOTTONE_INDIETRO]],
        markdown=False)
def dealWithsendTextCommand(p, sendTextCommand, markdown=False):
    split = sendTextCommand.split()
    if len(split) < 3:
        send_message(p.chat_id, 'Commands should have at least 2 spaces')
        return
    if not split[1].isdigit():
        send_message(p.chat_id, 'Second argumnet should be a valid chat_id')
        return
    id = int(split[1])
    sendTextCommand = ' '.join(split[2:])
    if tell_person(id, sendTextCommand, markdown=markdown):
        user = person.getPersonByChatId(id)
        send_message(p.chat_id,
                     'Successfully sent text to ' + user.getFirstName())
    else:
        send_message(p.chat_id, 'Problems in sending text')
示例#9
0
def sendText(p, text, markdown=False, restartUser=False):
    split = text.split()
    if len(split) < 3:
        tell(p.chat_id, 'Commands should have at least 2 spaces')
        return
    if not split[1].isdigit():
        tell(p.chat_id, 'Second argumnet should be a valid chat_id')
        return
    id = int(split[1])
    text = ' '.join(split[2:])
    if tell_person(id, text, markdown=markdown):
        user = person.getPersonByChatId(id)
        if restartUser:
            restart(user)
        tell(p.chat_id, 'Successfully sent text to ' + user.getFirstName())
    else:
        tell(p.chat_id, 'Problems in sending text')
示例#10
0
def getLastContibutors(daysAgo):
    dateThreshold = time_util.get_time_days_ago(daysAgo)
    names = set()
    recsCommands = []
    count = 0
    recs = Recording.query(
        Recording.date_time > dateThreshold,
        Recording.approved == recording.REC_APPROVED_STATE_TRUE).fetch()
    for r in recs:
        if r.chat_id <= 0:
            continue
        name = person.getPersonByChatId(r.chat_id).name
        names.add(name)
        recsCommands.append(r.getRecCommand())
        count += 1
    namesString = ', '.join([x.encode('utf-8') for x in names])
    recCommandsString = '\n'.join(['🎙 {}'.format(x) for x in recsCommands])
    return count, namesString, recCommandsString
示例#11
0
 def get(self, language):
     #urlfetch.set_default_fetch_deadline(60)
     qry = UserTranslationTag.query(
         UserTranslationTag.dst_language == language)
     full = self.request.get('full') == 'true'
     result = {}
     for entry in qry:
         name = person.getPersonByChatId(entry.chat_id).getLanguageName()
         result[entry.chat_id] = {
             "name": name,
             "total translations": len(entry.emojiSrcTagTranslationTable),
         }
         if full:
             result[entry.chat_id][
                 "translation table"] = entry.emojiSrcTagTranslationTable
     self.response.headers[
         'Content-Type'] = 'application/json; charset=utf-8'
     self.response.out.write(
         json.dumps(result, indent=4, ensure_ascii=False))
 def get(self, lang_code):
     #urlfetch.set_default_fetch_deadline(60)
     full = self.request.get('full') == 'true'
     qry = UserTagging.query(UserTagging.lang_code == lang_code)
     result = {}
     for entry in qry:
         user = person.getPersonByChatId(entry.chat_id)
         result[entry.chat_id] = {
             "name":
             user.getFirstName() if user else "Unknown ({0})".format(
                 str(entry.chat_id)),
             "total taggings":
             len(entry.emojiTagsTable),
         }
         if full:
             result[
                 entry.chat_id]["translation table"] = entry.emojiTagsTable
     self.response.headers[
         'Content-Type'] = 'application/json; charset=utf-8'
     self.response.out.write(
         json.dumps(result, indent=4, ensure_ascii=False))
def sendRequest(chat_id, method, data, files = None, url_api = key.DEFAULT_API_URL, debugInfo=''):
    urlfetch.set_default_fetch_deadline(20)
    try:
        default_timeout = urlfetch.get_default_fetch_deadline()
        logging.info('default_timeout: {}'.format(default_timeout))
        url_api_mathod = url_api + method
        resp = requests.post(url_api_mathod, data=data, files = files)
        logging.info('Response: {}'.format(resp.text))
        respJson = json.loads(resp.text)
        success = respJson['ok']
        if success:
            return True
        else:
            p = person.getPersonByChatId(chat_id)
            status_code = resp.status_code
            error_code = respJson['error_code']
            description = respJson['description']
            if error_code == 403:
                # Disabled user
                p.setEnabled(False, put=True)
                #logging.info('Disabled user: '******'❗ Input user disactivated: ' + p.getFirstNameLastNameUserName()
                logging.debug(debugMessage)
                tell_admin(debugMessage)
            elif error_code == 400 and description == "Bad Request: chat not found":
                p.setEnabled(False, put=True)
                # user never opened a chat with this bot
            else:
                debugMessage = '❗ Raising unknown err ({}).' \
                               '\nStatus code: {}\nerror code: {}\ndescription: {}.'.format(
                    debugInfo, status_code, error_code, description)
                logging.error(debugMessage)
                # logging.debug('recipeint_chat_id: {}'.format(recipient_chat_id))
                logging.debug('Telling to {} who is in state {}'.format(p.chat_id, p.state))
                tell_admin(debugMessage)
    except:
        report_exception()
示例#14
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)
示例#15
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)
示例#16
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)
def getQuizAdminName():
    import person
    quizManagerId = getQuizAdminId
    assert quizManagerId
    return person.getPersonByChatId(quizManagerId).getFirstName()
示例#18
0
def tell_person(chat_id, msg, markdown=False):
    tell(chat_id, msg, markdown=markdown)
    p = person.getPersonByChatId(chat_id)
    if p and p.enabled:
        return True
    return False