def process_single_message(update): # discard estrange messages try: telegram_id_from = int(update.get('message').get('from').get('id')) except AttributeError: return # check user "credentials" is_registered, username, role = account_check(telegram_id_from) logging.info(f'{telegram_id_from} is_registered -> {is_registered}') # kind of message to the bot; allowed: plain text and call_back if 'callback_query' in update: input_text = str(update.get('callback_query').get('data')) elif 'message' in update: input_text = str(update.get('message').get('text')) else: input_text = None # Discard incorrect message formats if input_text is None: logger.info( send_message( 'This bot only supports text messages, commands and callbacks', telegram_id_from)) return # TODO maybe not create an instace every time??? dbm = DBManager() # User is not registered if not is_registered: # check if the message is a code! if dbm.exist_code(input_text): # pick info about the user and register it field_username = update.get('message').get('from').get( 'username', '') field_first_name = update.get('message').get('from').get( 'first_name', '') field_last_name = update.get('message').get('from').get( 'last_name', '') if username: username = field_username else: username = f"{field_first_name} {field_last_name}" dbm.add_user(telegram_id_from, username, role='user', password=None) dbm.delete_code(input_text) logger.info(f'User {username} added correctly') logger.info( send_message('Registration successful ', telegram_id_from)) return else: send_message( 'To register yourself in the bot, copy a valid registration code', telegram_id_from) return # Users only can get the conectivity info if role == 'admin': dbm = DBManager() if input_text == 'gettemp': logger.info( send_message(f'Temperature -> {get_temperature()}ºC', telegram_id_from)) elif input_text == 'listcodes': codes = dbm.list_codes() codes_msg = '\n'.join(codes) if codes else 'No codes yet!' logging.info(send_message(codes_msg, chat_id=telegram_id_from)) # generate, add the code, send it to the user elif input_text == 'addcode': new_code = get_random_string(CODE_LENGTH) dbm.add_code(new_code) logger.info( send_message(f'New code generated: {new_code}', chat_id=telegram_id_from)) # only remove last code to not overcomplicate logic # this is VERY suboptimal, but it works atm elif input_text == 'removecode': all_codes = dbm.list_codes() if all_codes: dbm.delete_code(all_codes[-1]) # remove last element codes = all_codes[:-1] codes_msg = '\n'.join(codes) if codes else 'No codes yet!' logging.info(send_message(codes_msg, chat_id=telegram_id_from)) # add a default message on the admin side too else: info_message(telegram_id_from) else: info_message(telegram_id_from)