def start_quiz(): users = mongodb.get_users() bot = telebot.TeleBot(config.TOKEN) for x in users: bot.send_message(x[mongodb.AvailableFields.ID], 'Игра началась!!!\n!quiz - присоединиться') mongodb.switch_game_status()
def finish_quiz(): users = mongodb.get_users() bot = telebot.TeleBot(config.TOKEN) for x in users: bot.send_message(x[mongodb.AvailableFields.ID], 'Игра окончена!!!') update_stat(bot) mongodb.switch_game_status()
def is_participant(handle): users = backend.get_users({'is_participant': True}) is_participant = False for user in users: if user['handle'] == handle: is_participant = True return is_participant
def reminder(): for user in backend.get_users({'is_participant': True}): try: bot.send_message(user['user_id'], "Бот Сашка напоминает вам о том, что до начала контеста осталось меньше 17 часов! 🖥") except Exception as err: print('Пользователь ' + user['name'] + ' удалил чат', err)
def print_users(chatId, prefix, admin): try: key = InlineKeyboardMarkup() if not admin: users = backend.get_users({ 'is_participant': not admin }).sort('is_participant') else: users = backend.get_users({}).sort('is_participant') for user in users: id = user['user_id'] button = InlineKeyboardButton(text=user['active_name'], callback_data=prefix + 'login: '******'Произошла ошибка при выводе пользователей', err)
def update_stat(bot): users = mongodb.get_users() for x in users: if x[mongodb.AvailableFields.STATE] == mongodb.AvailableStates.IN_GAME: right_ans = mongodb.get_field_value( x[mongodb.AvailableFields.ID], mongodb.AvailableFields.RIGHT_ANSWERS) total_ans = mongodb.get_field_value( x[mongodb.AvailableFields.ID], mongodb.AvailableFields.TOTAL_RIGHT_ANSWERS) total_games = mongodb.get_field_value( x[mongodb.AvailableFields.ID], mongodb.AvailableFields.TOTAL_GAMES) average = mongodb.get_field_value(x[mongodb.AvailableFields.ID], mongodb.AvailableFields.AVERAGE) new_average = (total_ans + right_ans) // (total_games + 1) new_tickets = right_ans res_str = "Ваша статистика\nВсего игр - {0}({1})\n" \ "Правильных ответов за игру - {2} из 30\n" \ "Среднее правильных ответов по играм - {3}({4})".format(total_games + 1, total_games, right_ans, new_average, average) bot.send_message(x[mongodb.AvailableFields.ID], res_str) to_update = { mongodb.AvailableFields.RIGHT_ANSWERS: 0, mongodb.AvailableFields.AVERAGE: new_average, mongodb.AvailableFields.TOTAL_GAMES: total_games + 1, mongodb.AvailableFields.TOTAL_RIGHT_ANSWERS: total_ans + right_ans, mongodb.AvailableFields.QST_COUNT: 1, mongodb.AvailableFields.STATE: mongodb.AvailableStates.AFK, mongodb.AvailableFields.TICKETS: new_tickets } mongodb.update_db(x[mongodb.AvailableFields.ID], to_update) users = mongodb.get_users() users = sorted(users, key=lambda k: k[mongodb.AvailableFields.AVERAGE], reverse=True) for idx, x in enumerate(users): mongodb.update_db(x[mongodb.AvailableFields.ID], {mongodb.AvailableFields.GLOBAL_RANK: idx + 1})
def weather(now): try: rate = None try: DOLLAR_RUB = 'https://www.google.com/search?sxsrf=ALeKk01NWm6viYijAo3HXYOEQUyDEDtFEw%3A1584716087546&source=hp&ei=N9l0XtDXHs716QTcuaXoAg&q=%D0%B4%D0%BE%D0%BB%D0%BB%D0%B0%D1%80+%D0%BA+%D1%80%D1%83%D0%B1%D0%BB%D1%8E&oq=%D0%B4%D0%BE%D0%BB%D0%BB%D0%B0%D1%80+&gs_l=psy-ab.3.0.35i39i70i258j0i131l4j0j0i131l4.3044.4178..5294...1.0..0.83.544.7......0....1..gws-wiz.......35i39.5QL6Ev1Kfk4' headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36'} full_page = requests.get(DOLLAR_RUB, headers=headers) soup = BS(full_page.content, 'html.parser') rate = soup.findAll("span", {"class": "DFlfde", "class": "SwHCTb", "data-precision": 2})[0].text rate = rate.replace(',', '.') rate = float(rate) rate = round(rate * 100) / 100 rate = str(rate) except Exception as err: print('Не удалось получить курс', err) r = requests.get('https://sinoptik.ua/погода-ставрополь') html = BS(r.content, 'html.parser') for el in html.select('#content'): t_min = el.select('.temperature .min')[0].text t_max = el.select('.temperature .max')[0].text text = el.select('.wDescription .description')[0].text t_min = t_min[t_min.find(' '): len(t_min)] t_max = t_max[t_max.find(' '): len(t_max)] while text[0] == ' ': text = text[1:len(text)] backend.add_weather(now) for user in backend.get_users({'notifications': True}): name = '!' if user['name'] != user['user_id']: name = ', ' + user['name'] + '!' mes = "Доброе утро" + name + "\n\n" + "Бот Сашка подготовил прогноз погоды на сегодня:\n\n" + \ "Мин. температура воздуха: " + str(t_min) + '\n' + "Макс. температура воздуха: " \ + str(t_max) + '\n\n' + str(text) if rate is not None: mes += '\n\nКурс ЦБ: 1$ = ' + rate + '₽' try: bot.send_message(user['user_id'], mes) except Exception as err: print('Пользователь ' + user['name'] + ' удалил чат', err) except Exception as err: print('Не получилось сделать прогноз погоды', err)
def on_top(): res_str = '' users = mongodb.get_users() users = sorted(users, key=lambda k: k[mongodb.AvailableFields.GLOBAL_RANK], reverse=True) skip = 0 for idx, x in enumerate(users): if x[mongodb.AvailableFields.GLOBAL_RANK] == 0: skip += 1 continue if idx == 10 + skip: break res_str += '{0}. {1} {2}, возраст: {3}\n' \ 'Всего игр - {4}\n' \ 'Всего правильных ответов - {5}\n' \ 'Средний показатель ответов к игре - {6}\n\n'.format(x[mongodb.AvailableFields.GLOBAL_RANK], x[mongodb.AvailableFields.FIRST_NAME], x[mongodb.AvailableFields.LAST_NAME], x[mongodb.AvailableFields.AGE], x[mongodb.AvailableFields.TOTAL_GAMES], x[mongodb.AvailableFields.TOTAL_RIGHT_ANSWERS], x[mongodb.AvailableFields.AVERAGE]) return res_str if res_str else 'Увы никого в топе нет('
def continue_chat(message): if message.chat.type == "private": backend.insert_user( message.from_user.id) # запоминаем пользователя в бд print( str(message.chat.id) + ' ' + str(message.from_user.username) + ' ' + str(message.from_user.first_name) + ' ' + str(message.from_user.last_name) + ': ' + str(message.text)) # логи if backend.find_session( message.from_user.id) is not None: # проверка сессий session = backend.find_session(message.from_user.id) backend.erase_session(message.from_user.id) if session['name'] == 'achievement': admin.new_achievement(message.text, message.from_user.id, session['args']) elif session['name'] == 'change_contest_activity': admin.change_activity(message.text, message.from_user.id, session['args']) elif session['name'] == 'name': admin.edit_name(message.text, message.from_user.id, session['args']) elif session['name'] == 'handle': admin.edit_handle(message.text, message.from_user.id, session['args']) elif message.text == "Меню": key = InlineKeyboardMarkup() # кнопки взаимодействия but_1 = InlineKeyboardButton(text="Тренировки", callback_data="getcontest") but_3 = InlineKeyboardButton(text="Личная информация", callback_data="getuser") key.add(but_1, but_3) bot.send_message(message.chat.id, "Выберите:", reply_markup=key) elif message.text.find('/all ') != -1 and str( message.chat.id ) in const.admins: # вывод сообщения всем пользователям for user in backend.get_users({}): userId = user['user_id'] try: bot.send_message( userId, message.text[message.text.find('/all ') + 5:len(message.text)]) except Exception as err: print('Пользователь ' + userId + ' удалил чат', err) elif message.text.find('/admin') != -1: if str(message.chat.id) in const.admins: key = InlineKeyboardMarkup() # кнопки взаимодействия but_1 = InlineKeyboardButton(text="Пользователи", callback_data="admin_users") but_2 = InlineKeyboardButton(text="Контесты", callback_data="admin_contests") key.add(but_1) key.add(but_2) bot.send_message(message.chat.id, "Выберите:", reply_markup=key) else: img = open('Who_are_u?.jpg', 'rb') bot.send_photo(message.chat.id, img) elif message.text.find('/settings') != -1: # настройки print_settings(message.chat.id) elif message.text.find('/send_my_id') != -1: bot.send_message('374683082', "Id: " + str(message.chat.id)) elif message.chat.type == "supergroup": if message.text == "/rating@HQcontests_bot": print_all_rating(message.chat.id)
def get_contest_information(contestId): try: contestId = str(contestId) contest = backend.get_contest_information(contestId) standings = req.get_codeforces_contest_stadings(contestId, contest['apis'][0], contest['apis'][1], True) contestInformation = {} contestInformation['name'] = req.get_contestName(contestId, contest['apis'][0], contest['apis'][1]) users = {} maxSolved = 1 problemCount = len(standings['result']['problems']) contestInformation['problemCount'] = problemCount for user in standings['result']['rows']: userName = user['party']['members'][0]['handle'] userName = get_username(userName) if not is_participant(userName): continue user_id = backend.get_users({'handle': userName})[0]['user_id'] user_inf = backend.get_user(user_id) if not (user_inf['is_participant']): continue if not (user_id in users): users[user_id] = {} users[user_id]['rank'] = user['rank'] users[user_id]['solved'] = [False for i in range(problemCount)] users[user_id]['upsolved'] = [False for i in range(problemCount)] for user in standings['result']['rows']: userName = user['party']['members'][0]['handle'] if userName.find('=') == -1: continue userName = get_username(userName) if not is_participant(userName): continue user_id = backend.get_users({'handle': userName})[0]['user_id'] user_inf = backend.get_user(user_id) if not (user_inf['is_participant']): continue if user['rank'] != 0: users[user_id]['rank'] = user['rank'] for index, problem in enumerate(user['problemResults']): if user['rank'] != 0: if problem['points'] == 1: users[user_id]['solved'][index] = True else: if problem['points'] == 1: users[user_id]['upsolved'][index] = True official = 0 used = [0] * 200 for user in users: user_inf = users[user] if user_inf['rank'] != 0: official += 1 used[int(user_inf['rank'])] = user users[user]['solvedCount'], users[user]['upsolvedCount'] = get_solved_count(users[user]['solved'], users[user]['upsolved']) maxSolved = max(maxSolved, users[user]['solvedCount']) top = 1 for i in range(0, len(users)): if used[i] != 0: users[used[i]]['rank'] = top top += 1 for user in backend.get_users({'is_participant': True}): user_id = user['user_id'] if not (user_id in users): users[user_id] = {} users[user_id]['rank'] = 0 users[user_id]['solvedCount'] = 0 users[user_id]['upsolvedCount'] = 0 users[user_id]['solved'] = [False for i in range(problemCount)] users[user_id]['upsolved'] = [False for i in range(problemCount)] for user in users: contest_activity = contest['activity'] user_inf = backend.get_user(int(user)) user_div = int(user_inf['division']) user_activity = -1 for kol in contest_activity[user_div - 1]: if kol <= users[user]['solvedCount'] + users[user]['upsolvedCount']: user_activity += 1 users[user]['user_activity'] = user_activity contestInformation['users'] = users status = req.get_codeforces_contest_status(contestId, contest['apis'][0], contest['apis'][1]) try: for submission in range(len(status['result']) - 1, -1, -1): name = get_username(status['result'][submission]['author']['members'][0]['handle']) if not is_participant(name): continue user_id = backend.get_users({'handle': name})[0]['user_id'] user_inf = backend.get_user(user_id) if not (user_inf['is_participant']): continue if status['result'][submission]['verdict'] == 'OK': contestInformation['firstSubmission'] = {} contestInformation['firstSubmission']['name'] = backend.get_users({'handle': name})[0]['user_id'] contestInformation['firstSubmission']['time'] = status['result'][submission][ 'relativeTimeSeconds'] // 60 break except Exception as err: print("Trouble with status", err) backend.update_contest(contestId, contestInformation) except Exception as err: print("Failed Contest Information", err)
def get_all_rating(): global print_rating try: hq_rating = {} solved = {} upsolved = {} for user in backend.get_users({'is_participant': True}): handle = user['user_id'] hq_rating[handle] = 0 solved[handle] = 0 upsolved[handle] = 0 for contest in backend.get_contests(): for user in contest['users']: is_participant = backend.get_user(user)['is_participant'] if is_participant: hq_rating[user] += contest['users'][user]['solvedCount'] + contest['users'][user]['upsolvedCount'] solved[user] += contest['users'][user]['solvedCount'] upsolved[user] += contest['users'][user]['upsolvedCount'] rating = [] def compare(x, y): if x[1] > y[1] or x[1] == y[1] and solved[x[0]] > solved[y[0]]: return -1 elif x[1] < y[1] or x[1] == y[1] and solved[x[0]] < solved[y[0]]: return 1 else: return 0 for item in hq_rating.items(): rating.append([item[0], item[1]]) rating = sorted(rating, key=cmp_to_key(compare)) hq_rating_information = {} for item in rating: user = item[0] hq_rating_information[user] = {} hq_rating_information[user]['solved'] = solved[user] hq_rating_information[user]['upsolved'] = upsolved[user] hq_rating_information[user]['rating'] = item[1] try: print_rating = table.Texttable() print_rating.set_deco(table.Texttable.HEADER) print_rating.set_cols_align(["l", "c", "c"]) print_rating.set_cols_valign(["t", "t", "m"]) print_rating.set_cols_dtype(['t', 'i', 'i']) print_rating.add_row(["Фамилия\n", "🏆\n", "Задачи\n"]) except: print('Ошибка при выводе топа рейтинга') try: space = ' ' for index, user in enumerate(hq_rating_information): userName = backend.get_user(user)['name'] name = userName[userName.find(' ') + 1:] if index == 9: space = ' ' print_rating.add_row([str(index + 1) + space + name, str(hq_rating_information[user]['rating']), str(hq_rating_information[user]['solved']) + "/" + str(hq_rating_information[user]['upsolved']) ]) backend.update_rating({'rating': print_rating.draw()}) except Exception as err: print("Не удалось получить таблицу рейтинга", err) except Exception as err: print('Не удалось получить общий рейтинг', err)
def get_user_infomation(): try: user_information = {} contest = {} for contest_inf in backend.get_contests(): contestId = contest_inf['contest_id'] contest[contestId] = {} contest[contestId] = backend.get_contest_information(contestId) for user in backend.get_users({'is_participant': True}): user_id = user['user_id'] user_information[user_id] = {} user_information[user_id]['name'] = backend.get_user(user_id)['name'] user_information[user_id]['achievements'] = '' user_information[user_id]['activity'] = 0 user_information[user_id]['last_activities'] = [] unsolvedCount = 0 solvedCount = 0 solvedCountLast = 0 allCount = 0 for (index, contest_inf) in enumerate(backend.get_contests()): contestId = contest_inf['contest_id'] if user_id in contest[contestId]['users']: unsolvedCount += contest[contestId]['problemCount'] - \ (contest[contestId]['users'][user_id]['solvedCount'] + contest[contestId]['users'][user_id]['upsolvedCount']) solvedCount += contest[contestId]['users'][user_id]['solvedCount'] + \ contest[contestId]['users'][user_id][ 'upsolvedCount'] rank = contest[contestId]['users'][user_id]['rank'] if rank == 1: user_information[user_id]['achievements'] += "🥇" elif rank == 2: user_information[user_id]['achievements'] += "🥈" elif rank == 3: user_information[user_id]['achievements'] += "🥉" if len(contest) - index <= 5: solvedCountLast += contest[contestId]['users'][user_id]['solvedCount'] + \ contest[contestId]['users'][user_id]['upsolvedCount'] allCount += contest[contestId]['problemCount'] user_information[user_id]['last_activities'].append( contest[contestId]['users'][user_id]['user_activity']) user_information[user_id]['activity'] += contest[contestId]['users'][user_id]['user_activity'] user_information[user_id]['activity'] = round( user_information[user_id]['activity'] / min(5, max(1, len(contest)))) user_inf = backend.get_user(user_id) if user_information[user_id]['achievements'] == '' and ( 'custom_achievements' in user_inf and len(user_inf['custom_achievements']) == 0 or not ( 'custom_achievements' in user_inf)): user_information[user_id]['achievements'] = 'Пока тут ничего нет :(' user_information[user_id]['solved'] = solvedCount user_information[user_id]['unsolved'] = unsolvedCount user_information[user_id]['solvedLast'] = solvedCountLast user_information[user_id]['allLast'] = allCount user_information[user_id]['active_name'] = user_information[user_id]['name'] + ' ' + \ const.activity[user_information[user_id]['activity']][0] updates = user_information[user_id] backend.update_user(user_id, updates) except Exception as err: print('Не удалось взять личную информацию пользователей', err)
def good_luck(): for user in backend.get_users({'is_participant': True}): try: bot.send_message(user['user_id'], "Бот Сашка желает тебе удачи на контесте! 🏆") except Exception as err: print('Пользователь ' + user['name'] + ' удалил чат', err)
def on_game_alarm(): bot = telebot.TeleBot(config.TOKEN) users = mongodb.get_users() for x in users: bot.send_message(x[mongodb.AvailableFields.ID], on_time_to())