def glog(text: str, severity=logging.INFO, at_row=None): try: cfg = get_config() if not cfg.spreadsheet_logs_sheet: hr_logger.error( 'Не вдалося надіслати лог в гуглтаблицю - у налаштуваннях відсутня назва листа' ) logger.error( 'Cannot insert log into a google sheet - sheet name is missing' ) return if at_row is None: stored_logs = LogsSheet.get_all_logs() if stored_logs is None: stored_logs = [] at_row = len(stored_logs) + 2 update_data( cfg.spreadsheet_id, f'{cfg.spreadsheet_logs_sheet}!A{at_row}:C', values=[[ datetime.now(tz=_k_tz).strftime('%d/%m/%Y %H:%M:%S (%Z)'), _logging_severity_to_str_dict[severity], text ]]) except: logger.exception( 'Exception occurred while uploading log to gsheet')
def upload_canceled_result(winner: Competitor, looser: Competitor, level_change=None, was_dismissed=False, was_ignored=False, at_row=None): try: if not was_dismissed and not was_ignored: logger.error( 'upload_canceled_result called without both was_dismissed and was_ignored - one must be set') return if was_dismissed and was_ignored: logger.error( 'upload_canceled_result called with both was_dismissed and was_ignored - only one must be set') return cfg = get_config() if not cfg.spreadsheet_results_sheet: hr_logger.error( 'Не вдалося надіслати результат матчу в гуглтаблицю - у налаштуваннях відсутня назва листа') logger.error('Cannot insert result into a google sheet - sheet name is missing') return if not at_row: results = ResultsSheet.get_all_canceled_results() if results is None: results = [] at_row = len(results) + 2 t = '' if was_ignored: t = get_translation_for('gsheet_technical_win_ignored_str') if was_dismissed: t = get_translation_for('gsheet_technical_win_dismissed_str') update_data( cfg.spreadsheet_id, f'{cfg.spreadsheet_results_sheet}!H{at_row}:L', values=[ [ datetime.now(tz=_k_tz).strftime('%d/%m/%Y'), looser.name, t, winner.name, level_change or '-' ] ] ) except: logger.exception('Exception occurred while uploading canceled match results')
def change_status(self, new_status, bot=None, do_not_notify_admin=False): from google_integration.sheets.users import UsersSheet from localization.translations import get_translation_for from bot.settings_interface import get_config from telebot import TeleBot from config import BOT_TOKEN from logger_settings import hr_logger, logger update_sheet = False if self.status_code_to_str_dict[self.status] != self.status_code_to_str_dict[new_status]: update_sheet = True cfg = get_config() if update_sheet and cfg.admin_username and not do_not_notify_admin: try: if self.status in (COMPETITOR_STATUS.INJUIRY, COMPETITOR_STATUS.INACTIVE) or \ new_status in (COMPETITOR_STATUS.INJUIRY, COMPETITOR_STATUS.INACTIVE): admin_user = User.objects(username=cfg.admin_username).first() if admin_user: name = self.name associated_user = self.get_relevant_user() if associated_user: name = f'<a href="tg://user?id={associated_user.user_id}">{name}</a>' t = get_translation_for('admin_notification_competitor_changed_status').format( name, self.status_code_to_str_dict[self.status], self.status_code_to_str_dict[new_status] ) if bot is None: bot = TeleBot(BOT_TOKEN, threaded=False) bot.send_message( admin_user.user_id, t, parse_mode='html' ) except: logger.exception('Exception occurred while sending message to admin') hr_logger.error(f'Не вдалося надіслати адміністратору повідомлення про зміну стану користувача {self.name}') self.status = new_status if update_sheet: UsersSheet.update_competitor_status(self)
def upload_result(result: Result, at_row=None): try: cfg = get_config() if not cfg.spreadsheet_results_sheet: hr_logger.error( 'Не вдалося надіслати результат матчу в гуглтаблицю - у налаштуваннях відсутня назва листа') logger.error('Cannot insert result into a google sheet - sheet name is missing') return if at_row is None: results = ResultsSheet.get_all_successful_results() if results is None: results = [] at_row = len(results) + 2 if result.result in (RESULT.A_WINS, RESULT.B_WINS): winner = result.player_a.fetch() if result.result == RESULT.A_WINS else result.player_b.fetch() looser = result.player_b.fetch() if result.result == RESULT.A_WINS else result.player_a.fetch() score = result.repr_score() update_data( cfg.spreadsheet_id, f'{cfg.spreadsheet_results_sheet}!A{at_row}:E', values=[ [ mongo_time_to_local(result.date, tz=_k_tz).strftime('%d/%m/%Y'), winner.name, score, looser.name, result.level_change or '-' ] ] ) else: logger.error(f"Wrong method called for result {result.id}. Call upload_canceled_result instead") except: logger.exception('Exception occurred while uploading match result')
def process_callback(self, callback: CallbackQuery, user, bot: TeleBot): data = callback.data if data.find('auth_') != 0: return RET.ANSWER_CALLBACK, None, callback, user data = data.replace('auth_', '') if data.find('user='******'=') if len(ds) == 2: competitor_id = ds[1] try: competitor = Competitor.objects(id=competitor_id).first() if competitor is not None: competitor.change_status(COMPETITOR_STATUS.ACTIVE) competitor.associated_user_vanished = False competitor.save() user.associated_with = competitor user.save() competitor.reload() hr_logger.info( f'Користувач {user.str_repr()} аутентифікувався як {competitor.name}' ) return RET.ANSWER_AND_GO_TO_STATE, 'MenuState', callback, user else: hr_logger.error( f'Сталася помилка при аутентифікації користувача {user.str_repr()} - не вдається знайти в базі обраного ним гравця' ) return RET.ANSWER_CALLBACK, get_translation_for( 'authentication_specified_competitor_not_found_clb' ), callback, user except ValidationError: logger.exception( f'Incorrect competitor_id: {competitor_id} from user with user_id: {user.user_id}' ) elif data.find('paginate=') == 0: ds = data.split('=') if len(ds) == 2: page = ds[1] page = to_int(page, 1) try: available_competitors = Competitor.objects( status=COMPETITOR_STATUS.UNAUTHORIZED).paginate( page=page, per_page=10) except NotFound: logger.exception( f'User {user.user_id} tried to switch to nonexistent page {page}' ) available_competitors = Competitor.objects( status=COMPETITOR_STATUS.UNAUTHORIZED).paginate( page=1, per_page=10) if not render_pagination( available_competitors, callback.message, bot, get_translation_for('authentication_msg'), self.__base_keyboard, update=True): bot.send_message( callback.message.chat.id, get_translation_for( 'authentication_cannot_find_competitors_msg')) hr_logger.error( f'При авторизації користувача {user.str_repr()} не вдалося знайти жодного гравця' ) elif data.find('none') == 0: return RET.ANSWER_CALLBACK, None, callback, user elif data.find('refresh') == 0: if guard.get_allowed()[0] and guard.update_allowed()[0]: UsersSheet.update_model() available_competitors = Competitor.objects( status=COMPETITOR_STATUS.UNAUTHORIZED).paginate(page=1, per_page=10) if not render_pagination( available_competitors, callback.message, bot, get_translation_for('authentication_msg'), self.__base_keyboard, ): bot.send_message( callback.message.chat.id, get_translation_for( 'authentication_cannot_find_competitors_msg')) hr_logger.error( f'При авторизації користувача {user.str_repr()} не вдалося знайти жодного гравця' ) return RET.ANSWER_CALLBACK, None, callback, user