Exemplo n.º 1
0
def deal_with_universal_command(p, message_obj):
    text_input = message_obj.text
    if text_input.startswith('/start'):
        restart(p)
        return True
    if text_input == '/state':
        state = p.state
        msg = "You are in state {}".format(state)
        send_message(p, msg, markdown=False)
        return True
    if text_input == '/update':
        send_message(p, '💤 Please wait...', markdown=False)
        bot_ux.reload_ux()
        send_message(p, '💨 Reloaded localization table!', markdown=False)
        send_message(p, bot_ux.get_error_for_lang(p), markdown=False)
        return True
    if text_input == '/refresh':
        repeat_state(p)
        return True
    if text_input in ['/help', 'HELP', 'AIUTO']:
        pass
        return True
    if text_input in ['/stop']:
        p.set_enabled(False, put=True)
        msg = "🚫 Hai *disabilitato* il bot.\n" \
              "In qualsiasi momento puoi riattivarmi scrivendomi qualcosa."
        send_message(p, msg)
        return True
    return False
def deal_with_request(request_json):
    # retrieve the message in JSON and then transform it to Telegram object
    update_obj = telegram.Update.de_json(request_json, BOT)
    message_obj = update_obj.message    
    user_obj = message_obj.from_user
    chat_id = user_obj.id    
    username = user_obj.username
    last_name = user_obj.last_name if user_obj.last_name else ''
    name = (user_obj.first_name + ' ' + last_name).strip()

    user = bot_ndb_user.get_person_by_id_and_application(user_obj.id, 'telegram')

    if user == None:
        user = bot_ndb_user.add_person(chat_id, name, last_name, username, 'telegram')
        report_master('New user: {}'.format(user.get_first_last_username()))
    else:
        _, was_disabled = user.update_info(name, last_name, username)
        if was_disabled:
            msg = "Bot riattivato!"
            send_message(user, msg)
    
    if message_obj.text:
        if deal_with_commands(user, message_obj.text):
            return

    repeat_state(user, message_obj=message_obj)
def convert_csv_to_tbx(user, file_id, file_name):
    import codecs
    from utility import check_file_encoding
    reply_text = "Conversion of `{}`, please wait ...".format(file_name)
    send_message(user, reply_text, markdown=False)    
    new_file_name = file_name.split('.')[0] + '.tbx'
    file_content = get_raw_content_from_file(file_id)             
    try:
        file_text = codecs.decode(file_content, 'utf-8')
    except UnicodeDecodeError:
        error_msg = "🤯 The file is not encoded as utf-8."
        send_message(user, error_msg, markdown=False)
    try:
        # import CsvFormatError, csv2tbx
        #lines = file_text.splitlines()
        tbx_string = csv2tbx.csv2tbx(
            lines = file_text,
            lang = user.get_tmp_variable('LANG'),
            subjectField = user.get_tmp_variable('SUBJECT'), 
            id_prefix = user.get_tmp_variable('ID_PREFIX'), 
            ontology_name = user.get_tmp_variable('ONTOLOGY_NAME'),
            ontology_link = user.get_tmp_variable('ONTOLOGY_LINK')
        )
    
        send_message(user, ux.MSG_FILE_READY, sleep=1)
        send_text_document(user, new_file_name, tbx_string)  
        restart(user)
    except csv2tbx.CsvFormatError as e:
        send_message(user, e.message, markdown=False)
    except Exception as e:
        error_msg = """🤯 Encountered problem to segment file {}. Please contact
        @kercos.""".format(e)
        send_message(user, error_msg, markdown=False)
        restart(user)
def deal_with_commands(user, text):
    if text in ['/start', '/help', ux.BUTTON_INFO]:
        restart(user)
        return True
    if text == '/exception':
        1/0
        return True
    if text.startswith('/'):
        send_message(user, ux.wrong_input(text))    
        return True
    return False
Exemplo n.º 5
0
def repeat_state(user, message_obj=None):
    state = user.state
    if state is None:
        restart(user)
        return
    method = possibles.get(state, None)
    if not method:
        logging.debug("⚠️ User {} sent to unknown method state: {}".format(user.get_name_last_name_username(), state))
        send_message(user, user.ux().MSG_INTERFACE_CHANGED, sleep=2)
        restart(user)
    else:
        method(user, message_obj)
 def dec(*args, **kwargs):
     try:
         func(*args, **kwargs)
     except Exception:
         report_string = '❗️ Exception {}'.format(traceback.format_exc()) #.splitlines()
         logging.error(report_string)          
         try:  
             report_master(report_string)
             send_message(user, report_string)
         except Exception:
             report_string = '❗️ Exception {}'.format(traceback.format_exc())
             logging.error(report_string)
             send_message(user, report_string)
Exemplo n.º 7
0
def deal_with_manager_commands(p, message_obj):
    text_input = message_obj.text
    # logging.debug("In deal_with_manager_commands with user:{} ismanager:{}".format(p.get_id(), p.is_manager()))
    if p.is_manager():
        if text_input == '/admin':
            msg = "No commands available for now.\n"
            send_message(p, msg, markdown=False)
            return True
        if text_input == '/info':
            return True
        if text_input == '/stats':
            return True
        return False
def state_CONVERT_ASK_LANG_MULTI(user, message_obj=None, **kwargs):
    if message_obj is None:
        kb = [[ux.BUTTON_BACK]]
        if user.get_tmp_variable('IF_MULTI') == True:
            send_message(user, ux.MSG_ASK_LANGUAGE_MULTI, kb)
        else:
            send_message(user, ux.MSG_ASK_LANGUAGE_MONO, kb)
    else: 
        text_input = message_obj.text
        if text_input:            
            kb = user.get_keyboard()
            if text_input in utility.flatten(kb):
                if text_input == ux.BUTTON_BACK:
                    redirect_to_state(user, state_ASK_IF_MULTILINGUAL)
            else:
                input_list = text_input.replace(' ', '')
                input_list = [i.lower() for i in input_list.split(',')]
                check_list = all(elem in iso_list for elem in input_list)
                if check_list:
                    user.set_tmp_variable('LANG_LIST', input_list)
                    user.set_tmp_variable('COUNTER',
                    0)
                    redirect_to_state(user, state_CONVERT_ASK_SUBJECT)
                else:
                    send_message(user, ux.MSG_WRONG_ISO_CODE)
                    redirect_to_state(user, state_ASK_IF_MULTILINGUAL)
        else:
            send_message(user, ux.MSG_WRONG_INPUT)
Exemplo n.º 9
0
def state_CHANGE_LANGUAGE_INTERFACE_EXERCISE(p, message_obj=None, **kwargs):    
    pux = p.ux()
    give_instruction = message_obj is None
    localized_lang = lambda l: pux['LANG_{}'.format(l)]
    language_list = [
        '{} {}'.format(v['flag'], localized_lang(k))
        for k,v in sorted(LANGUAGES.items(), key=lambda x:localized_lang(x[0]))
    ]
    lang_selection_is_exercise = p.get_variable('lang_selection_type') == 'exercise'
    
    if give_instruction:
        kb = [[b] for b in language_list]
        kb.insert(0, [pux.BUTTON_BACK])
        kb.append([pux.BUTTON_BACK])
        if lang_selection_is_exercise:
            lang = p.language_exercise if p.language_exercise in LANGUAGES else params.default_language_exercise
            msg_lang = pux.MSG_YOU_ARE_LEARNING_X
            msg_select_language = pux.MSG_SELECT_NEW_LANGUAGE_EXERCISE
        else:
            lang = p.language_interface if p.language_interface in LANGUAGES else params.default_language_interface
            msg_lang = pux.MSG_INTERFACE_IS_IN_X
            msg_select_language = pux.MSG_SELECT_NEW_LANGUAGE_INTERFACE
        lang_info = LANGUAGES[lang]
        flag_lang = '{} {}'.format(lang_info['flag'],localized_lang(lang))
        msg_lang = msg_lang.format(flag_lang)                
        msg = '\n'.join([msg_lang, msg_select_language])
        send_message(p, msg, kb)
    else:
        text_input = message_obj.text
        if text_input is None:
            send_message(p, pux.MSG_NOT_VALID_INPUT)
            return        
        kb = p.get_keyboard()
        if text_input in utility.flatten(kb):
            if text_input in language_list:
                lang = next(
                    k for k,v in LANGUAGES.items() 
                    if text_input.startswith('{} '.format(v['flag']))
                )
                if lang_selection_is_exercise:
                    p.set_language_exercise(lang)
                else:
                    p.set_language_interface(lang)                
                
                api.update_user(
                    p.user_telegram_id(), 
                    p.name, 
                    language_exercise = p.language_exercise, 
                    language_interface = p.language_interface
                )
                restart(p)
            elif text_input == pux.BUTTON_BACK:
                redirect_to_state(p, state_CHANGE_LANGUAGE)
            else: 
                send_message(p, p.ux().MSG_INTERFACE_CHANGED, sleep=2)
                restart(p)
        else:
            send_message(p, pux.MSG_NOT_VALID_INPUT)
def state_CONVERT_ASK_ONTOLOGY_NAME(user, message_obj=None, **kwargs):    
    if message_obj is None:
        kb = [[ux.BUTTON_BACK]]
        send_message(user, ux.MSG_ASK_ONTOLOGY_NAME, kb)
    else: 
        text_input = message_obj.text
        if text_input:            
            kb = user.get_keyboard()
            if text_input in utility.flatten(kb):
                if text_input == ux.BUTTON_BACK:
                    redirect_to_state(user, state_CONVERT_ASK_ONTOLOGY_YES_NO)
            else:
                user.set_tmp_variable('ONTOLOGY_NAME', text_input)
                redirect_to_state(user, state_CONVERT_ASK_ONTOLOGY_LINK)
        else:
            send_message(user, ux.MSG_WRONG_INPUT)
Exemplo n.º 11
0
def state_CONVERT_ASK_SUBJECT(user, message_obj=None, **kwargs):
    if message_obj is None:
        kb = [[ux.BUTTON_BACK]]
        send_message(user, ux.MSG_ASK_SUBJECT, kb)
    else:
        text_input = message_obj.text
        if text_input:
            kb = user.get_keyboard()
            if text_input in utility.flatten(kb):
                if text_input == ux.BUTTON_BACK:
                    redirect_to_state(user, state_CONVERT_ASK_LANG)
            else:
                user.set_tmp_variable('SUBJECT', text_input)
                redirect_to_state(user, state_CONVERT_ASK_ID_PREFIX)
        else:
            send_message(user, ux.MSG_WRONG_INPUT)
def deal_with_document_request_multi(user, document_obj):
    if DISABLED:
        reply_text = "Temporary disabled"
        send_message(user, reply_text, markdown=False)    
        return
    file_id = document_obj.file_id
    file_name = document_obj.file_name    
    mime_type = document_obj.mime_type
    file_size = document_obj.file_size #bytes    
    logging.debug('Receiving document: {}'.format(file_name))
    logging.debug("File size: {}".format(file_size))
    #if file_size > 102400:
    #    reply_text = "File too big."
    #    send_message(user, reply_text)    
    #    return
    #if file_name.endswith('.csv'):
    return file_id, file_name
def state_CONVERT_ASK_ID_PREFIX(user, message_obj=None, **kwargs):    
    if message_obj is None:
        kb = [[ux.BUTTON_BACK]]
        subject_upper_2_char = user.get_tmp_variable('SUBJECT').upper()[:2]
        send_message(user, ux.MSG_ASK_ID_PREFIX.format(subject_upper_2_char), kb)
    else: 
        text_input = message_obj.text
        if text_input:            
            kb = user.get_keyboard()
            if text_input in utility.flatten(kb):
                if text_input == ux.BUTTON_BACK:
                    redirect_to_state(user, state_CONVERT_ASK_SUBJECT)
            else:
                user.set_tmp_variable('ID_PREFIX', text_input)
                redirect_to_state(user, state_CONVERT_ASK_ONTOLOGY_YES_NO)
        else:
            send_message(user, ux.MSG_WRONG_INPUT)
Exemplo n.º 14
0
def deal_with_request(request_json):
    # retrieve the message in JSON and then transform it to Telegram object
    update_obj = telegram.Update.de_json(request_json, BOT)
    # if update_obj.callback_query:
    #     deal_with_callback_query(update_obj.callback_query)
    #     return 
    message_obj = update_obj.message    
    user_obj = message_obj.from_user
    chat_id = user_obj.id    
    username = user_obj.username
    last_name = user_obj.last_name if user_obj.last_name else ''
    name = (user_obj.first_name + ' ' + last_name).strip()
    # language = user_obj.language_code
    
    p = ndb_person.get_person_by_id(user_obj.id)
    user_name = 'telegram_{}'.format(chat_id)

    if not api.is_user_registered(user_name):
        api.add_user(user_name, name)

    if p == None:
        p = ndb_person.add_person(chat_id, name, last_name, username)
        tell_admin('New user: {}'.format(p.get_name_last_name_username()))
    else:
        p.update_user(name, last_name, username)

    if message_obj.forward_from and not p.is_manager():
        send_message(p, p.bot_ux().MSG_NO_FORWARDING_ALLOWED)
        return

    text = message_obj.text
    if text:
        text_input = message_obj.text        
        logging.debug('Message from @{} in state {} with text {}'.format(chat_id, p.state, text_input))
        if WORK_IN_PROGRESS and not p.is_manager():
            send_message(p, p.bot_ux().MSG_WORK_IN_PROGRESS)    
            return
        if deal_with_admin_commands(p, message_obj):
            return
        if deal_with_universal_command(p, message_obj):
            return
        if deal_with_manager_commands(p, message_obj):
            return
    logging.debug("Sending {} to state {} with input message_obj {}".format(p.get_name_last_name_username(), p.state, message_obj))
    repeat_state(p, message_obj=message_obj)
def state_CONVERT_ASK_ONTOLOGY_LINK(user, message_obj=None, **kwargs):    
    if message_obj is None:
        kb = [[ux.BUTTON_BACK]]
        send_message(user, ux.MSG_ASK_ONTOLOGY_LINK, kb)
    else: 
        text_input = message_obj.text
        if text_input:            
            kb = user.get_keyboard()
            if text_input in utility.flatten(kb):
                if text_input == ux.BUTTON_BACK:
                    redirect_to_state(user, state_CONVERT_ASK_ONTOLOGY_NAME)
            else:
                user.set_tmp_variable('ONTOLOGY_LINK', text_input)
                if user.get_tmp_variable('IF_MULTI') == True:
                    redirect_to_state(user, state_CONVERT_ASK_DOC_MULTI)
                elif user.get_tmp_variable('IF_MULTI') == False:
                    redirect_to_state(user, state_CONVERT_ASK_DOC_MULTI)
        else:
            send_message(user, ux.MSG_WRONG_INPUT)
def deal_with_document_request(user, document_obj):          
    if DISABLED:
        reply_text = "Temporary disabled"
        send_message(user, reply_text, markdown=False)    
        return
    file_id = document_obj.file_id
    file_name = document_obj.file_name    
    mime_type = document_obj.mime_type
    file_size = document_obj.file_size #bytes    
    logging.debug('Receiving document: {}'.format(file_name))
    logging.debug("File size: {}".format(file_size))
    #if file_size > 102400:
    #    reply_text = "File too big."
    #    send_message(user, reply_text)    
    #    return
    if file_name.endswith('.csv'):
        run_new_thread_and_report_exception(convert_csv_to_tbx, user, file_id, file_name)        
    else:
        send_message(user, ux.MSG_WRONG_EXTENSION)    
        return
Exemplo n.º 17
0
def state_CHANGE_LANGUAGE(p, message_obj=None, **kwargs):    
    pux = p.ux()
    give_instruction = message_obj is None
    if give_instruction:
        localized_lang = lambda l: pux['LANG_{}'.format(l)]
        lang_exercise = p.language_exercise
        lang_interface = p.language_interface
        flag_lang_exercise = '{} {}'.format(LANGUAGES[lang_exercise]['flag'],localized_lang(lang_exercise))
        flag_lang_interface = '{} {}'.format(LANGUAGES[lang_interface]['flag'],localized_lang(lang_interface))        
        msg = '\n'.join([
            pux.MSG_YOU_ARE_LEARNING_X.format(flag_lang_exercise),
            pux.MSG_INTERFACE_IS_IN_X.format(flag_lang_interface), 
            '',
            pux.MSG_CHANGE_LANGUAGE_INTERFACE_EXERCISE
        ])
        kb = [
            [pux.BUTTON_LANGUAGE_INTERFACE, pux.BUTTON_LANGUAGE_EXERCISE],
            [pux.BUTTON_CANCEL],
        ]
        send_message(p, msg, kb)
    else:
        text_input = message_obj.text
        if text_input is None:
            send_message(p, pux.MSG_NOT_VALID_INPUT)
            return        
        kb = p.get_keyboard()
        if text_input in utility.flatten(kb):
            if text_input == pux.BUTTON_LANGUAGE_INTERFACE:
                p.set_variable('lang_selection_type', 'interface')
                redirect_to_state(p, state_CHANGE_LANGUAGE_INTERFACE_EXERCISE)
            elif text_input == pux.BUTTON_LANGUAGE_EXERCISE:
                p.set_variable('lang_selection_type', 'exercise')
                redirect_to_state(p, state_CHANGE_LANGUAGE_INTERFACE_EXERCISE)
            elif text_input == pux.BUTTON_CANCEL:
                restart(p)
            else: 
                send_message(p, p.ux().MSG_INTERFACE_CHANGED, sleep=2)
                restart(p)
        else:
            send_message(p, pux.MSG_NOT_VALID_INPUT)
def state_INITIAL(user, message_obj=None, **kwargs):    
    if message_obj is None:
        kb = [[ux.BUTTON_START_CONVERSION]]
        send_message(user, ux.MSG_INTRO, kb)
    else: 
        text_input = message_obj.text
        if text_input:            
            kb = user.get_keyboard()
            if text_input in utility.flatten(kb):
                if text_input == ux.BUTTON_START_CONVERSION:
                    user.reset_tmp_variables()
                    redirect_to_state(user, state_ASK_IF_MULTILINGUAL)
            else:
                send_message(user, ux.MSG_WRONG_INPUT, kb)
        else:
           send_message(user, ux.MSG_WRONG_INPUT)
def state_ASK_IF_MULTILINGUAL(user, message_obj=None, **kwargs):
    if message_obj is None:
        kb = [[ux.BUTTON_YES, ux.BUTTON_NO],[ux.BUTTON_BACK,]]
        send_message(user, ux.MSG_ASK_IF_MULTILINGUAL, kb)
    else: 
        text_input = message_obj.text
        if text_input:            
            kb = user.get_keyboard()
            if text_input in utility.flatten(kb):
                if text_input == ux.BUTTON_BACK:
                    redirect_to_state(user, state_INITIAL)
                elif text_input == ux.BUTTON_YES:
                    user.set_tmp_variable('IF_MULTI', True)
                    redirect_to_state(user, state_CONVERT_ASK_LANG_MULTI)
                elif text_input == ux.BUTTON_NO:
                    user.set_tmp_variable('IF_MULTI', False)
                    redirect_to_state(user, state_CONVERT_ASK_LANG_MULTI)
            else:
                send_message(user, ux.MSG_WRONG_INPUT)
        else:
            send_message(user, ux.MSG_WRONG_INPUT)
def state_CONVERT_ASK_DOC_MONO(user, message_obj=None, **kwargs):    
    if message_obj is None:
        kb = [[ux.BUTTON_BACK]]
        send_message(user, ux.MSG_SEND_CSV, kb)
    else: 
        text_input = message_obj.text
        if text_input:            
            kb = user.get_keyboard()
            if text_input in utility.flatten(kb):
                if text_input == ux.BUTTON_BACK:
                    ontology_enabled = user.get_tmp_variable('ONTOLOGY_NAME') is not None
                    if ontology_enabled:
                        redirect_to_state(user, state_CONVERT_ASK_ONTOLOGY_LINK)
                    else:
                        redirect_to_state(user, state_CONVERT_ASK_ONTOLOGY_YES_NO)
            else:
                send_message(user, ux.MSG_SEND_FILE_NO_TEXT)
        elif message_obj.document:
            deal_with_document_request(user, message_obj.document)                
        else:
            send_message(user, ux.MSG_SEND_FILE_NO_TEXT)
def state_CONVERT_ASK_DOC_MULTI(user, message_obj=None, **kwargs):    
    counter = user.get_tmp_variable('COUNTER')
    lang_list = user.get_tmp_variable('LANG_LIST')
    print(counter)
    if counter < len(lang_list):      
        print(counter)
        if message_obj is None:
            kb = [[ux.BUTTON_BACK]]
            msg = ux.MSG_SEND_CSV_MULTI.format(len(lang_list)-counter, \
            lang_list)
            send_message(user, msg, kb)
        else:
            text_input = message_obj.text
            if text_input:            
                kb = user.get_keyboard()
                if text_input in utility.flatten(kb):
                    if text_input == ux.BUTTON_BACK:
                        ontology_enabled = user.get_tmp_variable('ONTOLOGY_NAME') is not None
                        if ontology_enabled:
                            redirect_to_state(user, state_CONVERT_ASK_ONTOLOGY_LINK)
                        else:
                            redirect_to_state(user, state_CONVERT_ASK_ONTOLOGY_YES_NO)
                else:
                    send_message(user, ux.MSG_SEND_FILE_NO_TEXT)
            elif message_obj.document:
                id, file_name = deal_with_document_request_multi(user,
                message_obj.document)
                language = str(lang_list[counter])
                user.set_tmp_variable(str(language)+'_file_id', id)
                user.set_tmp_variable(str(language)+'_filename', file_name)
                user.set_tmp_variable('COUNTER', counter+1)
                redirect_to_state(user, state_CONVERT_ASK_DOC_MULTI)
            else:
                send_message(user, ux.MSG_SEND_FILE_NO_TEXT)
    else:
        run_new_thread_and_report_exception(convert_csv_to_tbx_multi, user,
        lang_list)
Exemplo n.º 22
0
def deal_with_admin_commands(p, message_obj):
    text_input = message_obj.text
    if p.is_manager():
        if text_input.startswith('/textUser '):
            text_input_split = text_input.split(' ', 2)
            if len(text_input_split)!=3:
                msg = "Error: /textUser needs 2 arguments (/textUser <id_number> <text>)"
                send_message(p, msg, markdown=False)
                return True
            u_id, text = text_input.split(' ', 2)[1:]
            user = Person.get_by_id(u_id)
            if user == None:
                msg = 'Error: No user found with id: {}'.format(u_id)
            elif send_message(user, text):
                msg = 'Message sent successfully to {}'.format(user.get_name_last_name())
            else:
                msg = 'Error: Problems sending message to {}'.format(user.get_name_last_name())
            send_message(p, msg, markdown=False)
            return True
    elif p.is_admin():
        if text_input == '/debug':
            #send_message(p, game.debugTmpVariables(p), markdown=False)
            send_text_document(p, 'tmp_vars.json', p.variables)
            return True
        # if text_input == '/testInlineKb':
        #     send_message(p, "Test inline keypboard", kb=[[p.bot_ux().BUTTON_YES_CALLBACK('test'), p.bot_ux().BUTTON_NO_CALLBACK('test')]], inline_keyboard=True)
        #     return True
        if text_input == '/random':
            from random import shuffle
            numbers = ['1','2','3','4','5']
            shuffle(numbers)
            numbers_str = ', '.join(numbers)
            send_message(p, numbers_str)
            return True
        if text_input == '/exception':
            1/0
            return True
        if text_input == '/wait':
            import time
            for i in range(5):
                send_message(p, str(i+1))
                time.sleep(i+1)
            send_message(p, "end")
            return True
        if text_input.startswith('/testText '):
            text = text_input.split(' ', 1)[1]
            msg = '🔔 *Messagge from LingoGame* 🔔\n\n' + text
            logging.debug("Test broadcast " + msg)
            send_message(p, msg)
            return True
        if text_input.startswith('/broadcast '):
            text = text_input.split(' ', 1)[1]
            msg = '🔔 *Messagge from LingoGame* 🔔\n\n' + text
            logging.debug("Starting to broadcast " + msg)
            broadcast(p, msg)
            return True
        if text_input.startswith('/restartUser '):
            u_id = ' '.join(text_input.split(' ')[1:])
            user = Person.get_by_id(u_id)
            if user:
                restart(user)
                msg_admin = 'User restarted: {}'.format(user.get_name_last_name())
                tell_admin(msg_admin)                
            else:
                msg_admin = 'No user found: {}'.format(u_id)
                tell_admin(msg_admin)
            return True
        if text_input == '/reset_all_users':            
            reset_all_users(message=None) #message=p.bot_ux().MSG_THANKS_FOR_PARTECIPATING
            return True
    return False
Exemplo n.º 23
0
def state_CLOSE_EXERCISE(p, message_obj=None, **kwargs):    
    pux = p.ux()
    give_instruction = message_obj is None
    user_telegram_id = p.user_telegram_id()
    if give_instruction:        
        response = api.get_close_exercise(user_telegram_id) #elevel='', etype='RelatedTo'
        if response is None:
            error_msg = "⚠️ None response in get_close_exercise ({})".format(user_telegram_id)
            tell_admin(error_msg)
            return
        if response.get('success', True) == False:
            error_msg = '⚠️ Detected success false in get_close_exercise ({})'.format(user_telegram_id)
            tell_admin(error_msg)
            return
        r_eid = response['eid']
        relation = response['relation']
        subject = response['subject']
        object = response['object']
        # exercise = response['exercise'] # "exercise": "Is it true that sheep is related to herd?",

        relation_msg_mapping = {
            'RelatedTo': 'MSG_CLOSE_EXERCISE_RELATEDTO_X',
            'AtLocation': 'MSG_CLOSE_EXERCISE_LOCATEDAT_X',
            'PartOf': 'MSG_CLOSE_EXERCISE_PARTOF_X',
            'Synonym': 'MSG_CLOSE_EXERCISE_SYNONYMOF_X'
        }
        
        exercise = pux[relation_msg_mapping[relation]].format(subject, object)
        msg = exercise
        p.set_variable('eid',r_eid)
        p.set_variable('exercise',exercise)
        kb = [[pux.BUTTON_YES, pux.BUTTON_NO], [pux.BUTTON_DONT_KNOW], [pux.BUTTON_EXIT]]
        send_message(p, msg, kb)  
    else:
        text_input = message_obj.text
        if text_input is None:
            send_message(p, pux.MSG_NOT_VALID_INPUT)
            return        
        kb = p.get_keyboard()
        eid = p.get_variable('eid')
        msg_yes = pux.MSG_YES
        msg_no = pux.MSG_NO
        msg_y = msg_yes[0]
        msg_n = msg_no[0]
        if text_input in utility.flatten(kb):
            if text_input == pux.BUTTON_EXIT:
                restart(p)
                return
            elif text_input in [pux.BUTTON_YES, pux.BUTTON_NO, pux.BUTTON_DONT_KNOW]:
                pass # dealing with it below together with text
            else:
                send_message(p, p.ux().MSG_INTERFACE_CHANGED, sleep=2)
                restart(p)
        if text_input.upper() in [pux.BUTTON_YES, msg_yes, msg_y, pux.BUTTON_NO, msg_no, msg_n, pux.BUTTON_DONT_KNOW]:
            response = 1 if text_input.upper() in [pux.BUTTON_YES, msg_yes, msg_y] \
                else -1 if text_input.upper() in [pux.BUTTON_NO, msg_no, msg_n] \
                else 0
            evalutaion_json = api.store_close_response(eid, user_telegram_id, response)
            if response==0:
                correct_response = pux.BUTTON_YES if evalutaion_json['correct_response'] == 1 else pux.BUTTON_NO
                msg = pux.MSG_DONT_WORRY_CORRECT_RESPONSE.format(correct_response)    
            else:
                correct = evalutaion_json['points']==1            
                msg = pux.MSG_CORRECT if correct else pux.MSG_WRONG
            send_message(p, msg, sleepDelay=True, remove_keyboard=True)            
            send_typing_action(p, sleep_time=1)
            redirect_to_exercise_type(p)
        else:
            send_message(p, pux.MSG_NOT_VALID_INPUT)
Exemplo n.º 24
0
def state_OPEN_EXERCISE(p, message_obj=None, **kwargs):    
    pux = p.ux()
    give_instruction = message_obj is None
    user_telegram_id = p.user_telegram_id()
    if give_instruction:
        kb = [[pux.BUTTON_DONT_KNOW],[pux.BUTTON_EXIT]]
        response = api.get_exercise(user_telegram_id) #elevel='', etype=''        
        # send_message(key.FEDE_CHAT_ID, 'DEBUG:\n{}'.format(json.dumps(response)), markdown=False)
        if response is None:
            error_msg = "⚠️ None response in get_exercise ({})".format(user_telegram_id)
            tell_admin(error_msg)
            return
        if response.get('success', True) == False:
            error_msg = '⚠️ Detected success false in get_exercise ({})'.format(user_telegram_id)
            tell_admin(error_msg)
            return
        r_eid = response['eid']        
        relation = response['relation']
        # exercise = response['exercise'] # "exercise": "Name a thing that is located at a desk",                
        subject = response['subject']
        wiki_url = response.get('hint_url', None)
        previous_responses = response["previous_responses"]
        relation_msg_mapping = {
            'RelatedTo': 'MSG_OPEN_EXERCISE_RELATEDTO_X',
            'AtLocation': 'MSG_OPEN_EXERCISE_LOCATEDAT_X',
            'PartOf': 'MSG_OPEN_EXERCISE_PARTOF_X',
            'Synonym': 'MSG_OPEN_EXERCISE_SYNONYMOF_X',
        }
        exercise = pux[relation_msg_mapping[relation]].format(subject) 
        msg = exercise
        if previous_responses:
            msg += '\n' + pux.MSG_YOU_PREVIOUSLY_INSERTED.format(
                ', '.join('*{}*'.format(pr) for pr in  previous_responses))
        if wiki_url:
            msg += '\n\n' + pux.MSG_INSPIRATION_CHECK_OUT + '\n' + wiki_url
        p.set_variable('eid',r_eid)
        p.set_variable('exercise',exercise)   
        p.set_variable('subject',subject)        
        BUTTON_NUM_NOTIFICATIONS = get_notification_button(p, debug=False)
        if BUTTON_NUM_NOTIFICATIONS:
            kb.insert(1, [BUTTON_NUM_NOTIFICATIONS])
        send_message(p, msg, kb)    
    else:
        text_input = message_obj.text
        if text_input is None:
            send_message(p, pux.MSG_NOT_VALID_INPUT)
            return        
        kb = p.get_keyboard()
        eid = p.get_variable('eid')  
        if text_input in utility.flatten(kb):            
            if text_input == pux.BUTTON_EXIT:
                restart(p)
            elif text_input == pux.BUTTON_DONT_KNOW:
                response_json = api.get_random_response(eid, user_telegram_id)
                msg = pux.MSG_POSSIBLE_SOLUTION.format(response_json['response'])
                send_message(p, msg, sleepDelay=True, remove_keyboard=True)            
                send_typing_action(p, sleep_time=1)
                exercise = p.get_variable('exercise')
                send_message(p, exercise, kb)  
                # repeat the same question and stay in current state
            elif text_input.startswith('🌟'):
                notifications = p.get_variable('notifications')
                logging.debug("New notifications: {}".format(notifications))
                if len(notifications) > 0:
                    notifications_str = '\n'.join(["{} {}: {}".format( # → {}
                        '🏅' if r['badge'] else '•', 
                        r['exercise'],
                        r['response']) for r in notifications]  #r['exercise']
                    )
                    msg = pux.MSG_NEW_NOTIFICATIONS + '\n' + notifications_str
                    send_message(p, msg, kb)
                    p.set_variable('notifications', [])
                    repeat_state(p)                
                else:
                    send_message(p, pux.MSG_NO_NEW_NOTIFICATION)   
                send_typing_action(p, sleep_time=1)
                exercise = p.get_variable('exercise')
                send_message(p, exercise, kb)  
            else: 
                send_message(p, p.ux().MSG_INTERFACE_CHANGED, sleep=2)
                restart(p)
        else:                
            subject = p.get_variable('subject') 
            if text_input == subject:
                msg = pux.MSG_SAME_WORD.format(subject)
                send_message(p, msg, sleepDelay=True, remove_keyboard=True)            
                send_typing_action(p, sleep_time=1)
                exercise = p.get_variable('exercise')
                send_message(p, exercise, kb)  
                return
            response = api.store_response(eid, user_telegram_id, text_input)
            # send_message(key.FEDE_CHAT_ID, 'DEBUG:\n{}'.format(json.dumps(response)), markdown=False)
            logging.debug("Response from store_response eid={}, user_telegram_id={}, text_input={}: {}".format(eid, user_telegram_id, text_input, response))            
            if 'points' in response:
                r_points = response['points']                
                points_str = '*{} {}*'.format(r_points, pux.MSG_POINT_PLURAL) \
                    if r_points and r_points>1 \
                    else '*1 {}*'.format(pux.MSG_POINT_SINGULAR)
                msg_inserted = pux.MSG_YOU_HAVE_INSERTED_X.format(text_input)
                if r_points is None:                    
                    msg_thanks = pux.MSG_THANKS_FOR_YOUR_ANSWER
                    msg_double_point = pux.MSG_DOUBLE_POINT
                    msg = msg_inserted + ' ' + msg_thanks + '\n' + msg_double_point
                elif r_points>0:
                    msg_good_job = pux.MSG_GOOD_JOB_POINT.format(points_str)
                    msg = msg_inserted + '\n' + msg_good_job
                elif r_points == 0:
                    msg_no_points = pux.MSG_NO_POINTS
                    msg = msg_inserted + '\n' + msg_no_points
                send_message(p, msg)
            else:
                # debugging
                error_msg = response['error']                
                msg = '⚠️ Backend found an error with user {}:\n{}.'.format(
                    p.get_name_last_name_username(), error_msg)
                send_message(key.FEDE_CHAT_ID, msg)
                send_message(p, pux.MSG_AN_ERROR_HAS_OCCURED)
            send_typing_action(p, sleep_time=1)    
            redirect_to_exercise_type(p)            
def deal_with_photo_request(user, photo_list):
    reply_text = 'Photo input'
    send_message(user, reply_text)    
Exemplo n.º 26
0
def state_INITIAL(p, message_obj=None, **kwargs):  
    pux = p.ux()  
    if message_obj is None:
        kb = [
            [pux.BUTTON_VOCAB_GAME],
            [pux.BUTTON_POINTS, pux.BUTTON_LEADERBOARD],
            [pux.BUTTON_CHANGE_LANGUAGE, pux.BUTTON_INFO]
        ]
        new_notifications_number = api.update_notifications(p)
        if new_notifications_number>0:
            #send_message(p, "New notification!!")
            pux.BUTTON_NUM_NOTIFICATIONS = '{} ({})'.format('🌟', new_notifications_number)
            kb[1].insert(1, pux.BUTTON_NUM_NOTIFICATIONS)
        lang = p.language_exercise if p.language_exercise in LANGUAGES else params.default_language_exercise
        lang_info = LANGUAGES[lang]
        localized_lang = lambda l: pux['LANG_{}'.format(l)]
        flag_lang = '{} {}'.format(lang_info['flag'],localized_lang(lang))
        send_message(p, pux.MSG_LETS_PLAY.format(flag_lang), kb)
    else: 
        text_input = message_obj.text        
        if text_input is None:
            send_message(p, pux.MSG_NOT_VALID_INPUT)
            return        
        kb = p.get_keyboard()
        if text_input in utility.flatten(kb):
            if text_input == pux.BUTTON_VOCAB_GAME:
                redirect_to_exercise_type(p)            
            elif text_input.startswith('🌟'):
                notifications = p.get_variable('notifications')
                logging.debug("New notifications: {}".format(notifications))
                if len(notifications) > 0:
                    notifications_str = '\n'.join(["{} {}: {}".format( # → {}
                        '🏅' if r['badge'] else '•', 
                        r['exercise'],
                        r['response']) for r in notifications]  #r['exercise']
                    )
                    msg = pux.MSG_NEW_NOTIFICATIONS + '\n' + notifications_str
                    send_message(p, msg)
                    p.set_variable('notifications', [])
                    repeat_state(p)
                else:
                    send_message(p, pux.MSG_NO_NEW_NOTIFICATION)
            elif text_input == pux.BUTTON_POINTS:
                response = api.get_points(p.user_telegram_id())
                summary = response['summary']
                earned_points = summary['earned_points']
                potential_points = summary['potential_points']
                badges = summary['badges']
                msg_earned_points = pux.MSG_EARNED_POINTS.format(earned_points)
                msg_potential_points = pux.MSG_POTENTIAL_POINTS.format(potential_points)
                msg_badges = pux.MSG_BADGES.format(badges)
                msg = '\n'.join([msg_earned_points, msg_potential_points, msg_badges])
                send_message(p, msg, kb)
            elif text_input == pux.BUTTON_LEADERBOARD:
                leaderboard = api.get_leaderboard()
                leaderboard_sorted = sorted(leaderboard, key=lambda e: e["earned_points"], reverse=True)
                leaderboard_sorted = leaderboard_sorted[:9]            
                board_rows = [[
                    pux.MSG_LEADERBOARD_RANK,
                    pux.MSG_LEADERBOARD_NAME,
                    pux.MSG_LEADERBOARD_POINTS,
                    pux.MSG_LEADERBOARD_BADGES
                ]] #potential_points
                alignment = 'clcc'
                for i in range(len(leaderboard_sorted)):
                    row = leaderboard_sorted[i]
                    medal = '🥇' if i==0 else '🥈' if i==1 else '🥉' if i==2 else str(i+1)
                    player_name = row['uname'] #utility.escapeMarkdown(row['uname'])
                    board_rows.append([medal, player_name, str(row['earned_points']), str(row['badges'])])
                import render_leaderboard
                imgData = render_leaderboard.get_image_data_from_table(board_rows,alignment)
                bot_telegram.send_photo_from_data(p.chat_id, 'leaderboard.png', imgData)
            elif text_input == pux.BUTTON_INFO:  
                msg = pux.MSG_INFO.format(params.default_level, p.chat_id)
                send_message(p, msg, kb)
            elif text_input == pux.BUTTON_CHANGE_LANGUAGE:
                redirect_to_state(p, state_CHANGE_LANGUAGE)
            else:
                send_message(p, p.ux().MSG_INTERFACE_CHANGED, sleep=2)
                restart(p)
        else:
            send_message(p, pux.MSG_NOT_VALID_INPUT)
def convert_csv_to_tbx_multi(user, lang_list):
    import codecs
    from utility import check_file_encoding
    file_ids = []
    filenames = []
    for language in lang_list:
        file_ids.append(user.get_tmp_variable(str(language)+'_file_id'))
        filenames.append(user.get_tmp_variable(str(language)+'_filename'))
    reply_text = "Conversion of", ' '.join(filenames), " please wait...."
    send_message(user, reply_text, markdown=False)
    new_file_name = 'output.tbx'
    file_contents = [get_raw_content_from_file(i) for i in file_ids]
    file_texts = []
    for content in file_contents:
        ind = file_contents.index(content)
        try:
            file_text = codecs.decode(content, 'utf-8')
            file_texts.append(file_text)
        except UnicodeDecodeError:
            error_msg = """The file {} is not encoded as
            utf-8.""".format(filenames[ind])
            send_message(user, error_msg, markdown=False)
    inputs = []
    counter_errors = 0
    error_file = {}
    for i in range(len(file_texts)):
        file = file_texts[i]
        single_input = []
        error_file[filenames[i]] = []
        for row in file.splitlines():
            single_row = [str(k) for k in row.split(';')]
            if len(single_row) != 9:
                counter_errors += 1
                ind_row = file.splitlines().index(row)
                error_file[filenames[i]].append(ind_row)
            else:
                single_input.append(single_row)
                continue
        inputs.append(single_input)
    if counter_errors == 0:    
        tbx_string = csv2tbxmultil.csv2tbx(
        inputs = inputs,
        languages = lang_list,
        subjectField = user.get_tmp_variable('SUBJECT'),
        id_prefix = user.get_tmp_variable('ID_PREFIX'),
        ontology_name = user.get_tmp_variable('ONTOLOGY_NAME'),
        ontology_link = user.get_tmp_variable('ONTOLOGY_LINK')
        )
        send_message(user, ux.MSG_FILE_READY, sleep=1)
        send_text_document(user, new_file_name, tbx_string)
        restart(user)
    else:
        msg = """An error was encountered in the following file(s): \n"""
        print(error_file)
        msg_list = ''
        for file in list(error_file.keys()):
            if len(error_file[file]) >= 1:
                frase= file +  ' row(s) num: ' + str(error_file[file])+ '\n'
                msg_list += frase
        send_message(user, msg, markdown= False)
        send_message(user, msg_list, markdown=False)
        user.set_tmp_variable('COUNTER', 0) 
        redirect_to_state(user, state_CONVERT_ASK_DOC_MULTI)