def edit_name(message, chat_id, args): try: user_id = args['user_id'] name = message backend.update_user(user_id, {'name': name, 'active_name': name}) print_admin_user_information(chat_id, user_id) except Exception as err: print('Произошла ошибка при изменении имени', err) bot.send_message(chat_id, 'Произошла ошибка при изменении имени')
def step_most_similar(message): try: user = search_or_save_user(mdb, message.from_user, message) user['selected_photo'] = int(message.text) result = most_similar(int(message.text), data) user['the_most_similar_photo'] = int(result) update_user(mdb, user) except Exception as e: pass
def change_participant(message, chat_id): try: user_id = message[message.find('change_participant ') + 19: len(message)] user = backend.get_user(user_id) newparticipant = True if user['is_participant']: newparticipant = False backend.update_user(user_id, {'is_participant': newparticipant}) print_admin_user_information(chat_id, user_id) except Exception as err: print('Не удалось поменять состояние участника контеста', err) bot.send_message(chat_id, 'Не удалось поменять состояние участника контеста')
def edit_handle(message, chat_id, args): try: user_id = args['user_id'] handle = message backend.update_user(user_id, {'handle': handle}) print_admin_user_information(chat_id, user_id) except Exception as err: print('Произошла ошибка при изменении имени', err) bot.send_message(chat_id, 'Произошла ошибка при изменении имени') ########################################################################################################################
def change_div(message, chat_id): try: user_id = message[message.find('change_div ') + 11: len(message)] user = backend.get_user(user_id) newdiv = user['division'] + 1 if newdiv == 4: newdiv = 1 backend.update_user(user_id, {'division': newdiv}) print_admin_user_information(chat_id, user_id) except Exception as err: print('Не удалось сменить дивизион пользователя', err) bot.send_message(chat_id, 'Не удалось сменить дивизион пользователя')
def edit_achievement(message, chat_id): try: number = int(message[message.find('achievement: ') + 13: message.rfind(' ')]) user_id = str(message[message.rfind(' ') + 1: len(message)]) user = backend.get_user(user_id) custom_achievements = [] if 'custom_achievements' in user: custom_achievements = user['custom_achievements'] del custom_achievements[number] backend.update_user(user_id, {'custom_achievements': custom_achievements}) print_admin_user_information(chat_id, user_id) except Exception as err: print('Не удалось изменить достижения участника', err) bot.send_message(chat_id, 'Не удалось изменить достижения участника')
def new_achievement(message, chat_id, args): try: backend.erase_session(chat_id) user_id = args['user_id'] user = backend.get_user(user_id) custom_achievements = [] if 'custom_achievements' in user: custom_achievements = user['custom_achievements'] custom_achievements.append(message) backend.update_user(user_id, {'custom_achievements': custom_achievements}) print_admin_user_information(chat_id, user_id) except Exception as err: print('Не удалось добавить новое достижение участнику', err) bot.send_message(chat_id, 'Не удалось добавить новое достижение участнику')
def hello_world(message): bot.send_chat_action(message.chat.id, 'typing') # want_to_know_photo = True if message.chat.type == 'private': if message.text == 'Рандомное число': bot.send_message(message.chat.id, str(random.randint(0,100))) elif message.text == 'Как дела?': markup = types.InlineKeyboardMarkup(row_width=2) item1 = types.InlineKeyboardButton('Хорошо', callback_data='good') item2 = types.InlineKeyboardButton('Не очень', callback_data='bad') markup.add(item1, item2) bot.send_message(message.chat.id, 'У меня дела отлично. А у тебя как?', reply_markup=markup) elif message.text == 'Привет' or message.text == 'привет': user = search_or_save_user(mdb, message.from_user, message) if user['first_time'] == True: welcome(message) user['first_time'] = False update_user(mdb, user) else: bot.send_message(message.chat.id, 'Привет! Ознакомиться с командами можно написав /help') elif message.text == 'Самая похожая фотография': try: markup = types.ForceReply(selective=False) replied = bot.send_message(message.chat.id, "Введите номер картинки, для которой вы хотите найти самую похожую фотографию:\n", reply_markup=markup) timing = time.time() bot.register_next_step_handler(replied, step_most_similar) time.sleep(5) user = search_or_save_user(mdb, message.from_user, message) bot.send_message(message.chat.id, 'Выбранная фотография:') DIR_SEL = r'C:/Users/Dmitry/PycharmProjects/telegrambots/first_bot/data/' + str(user['selected_photo']) + '.png' DIR_SIM = r'C:/Users/Dmitry/PycharmProjects/telegrambots/first_bot/data/' + str(user['the_most_similar_photo']) + '.png' bot.send_photo(chat_id=message.chat.id, photo=open(DIR_SEL, 'rb')) while(user['the_most_similar_photo'] == None): user = search_or_save_user(mdb, message.from_user, message) if time.time() - timing > 20.0: bot.send_message(message.chat.id, 'Время ожидания истекло!') if user['the_most_similar_photo'] != None: bot.send_message(message.chat.id, 'IDшник самой похожей на вашу фотографию: {0}'.format(user['the_most_similar_photo'])) bot.send_photo(message.chat.id, photo=open(DIR_SIM, 'rb')) except Exception as e: bot.send_message(message.chat.id, 'ERROR with finding photo') else: bot.send_message(message.chat.id, 'Пока что я не научился отвечать на это =) Update soon.')
print >> sys.stderr, 'ID', fields[0], \ 'not found in users. Skipping' skip_count += 1 continue # Update the user with the data # Either print or execute the query label_dict = dict(zip(labels, fields[1:])) if dryRun: print >> sys.stderr, "Insert {'_id': " + str(user_doc) + '}' print >> sys.stderr, label_dict else: print >> sys.stderr, "Insert {'_id': " + str(user_doc) + '}' print >> sys.stderr, label_dict result = mongodb.update_user({'_id': user_doc}, label_dict) line_number += 1 # Done. Close connection mongodb.disconnect() print >> sys.stderr, 'Done' print >> sys.stderr, 'Summary:' if drop: print >> sys.stderr, ' - Deleted:', line_number else: print >> sys.stderr, ' - Inserted:', line_number print >> sys.stderr, ' - Skipped IDs (not found):', skip_count if __name__ == "__main__":
def callback_text(text): backend.erase_session( text.from_user.id) # удаление сессии при нажатии на кнопку try: message = text.data print( str(text.message.chat.id) + ' ' + str(text.from_user.username) + ' ' + str(text.from_user.first_name) + ' ' + str(text.from_user.last_name) + ': ' + str(message)) # логи if message == "getcontest": print_contests(text.message.chat.id, '') elif message == "getuser": print_users(text.message.chat.id, 'info', False) elif message.find('infologin: '******'infologin: '******'admin_info_login: '******'admin_info_login: '******'Не удалось вывести пользователя админу', err) bot.send_message(text.message.chat.id, 'Не удалось вывести пользователя') elif message.find('change_div ') != -1: admin.change_div(message, text.from_user.id) elif message.find('change_participant ') != -1: admin.change_participant(message, text.from_user.id) elif message.find('change_name ') != -1: admin.change_name(message, text.from_user.id) elif message.find('change_handle ') != -1: admin.change_handle(message, text.from_user.id) elif message.find('show_achievements ') != -1: admin.show_achievements(message, text.from_user.id) elif message.find('achievement: ') != -1: admin.edit_achievement(message, text.from_user.id) elif message.find('+achievement') != -1: admin.add_achievement(message, text.from_user.id) elif message.find('not_admin_contest_id') != -1: id = message[message.find('not_admin_contest_id') + 20:len(message)] admin.show_contest(id, text.message.chat.id, False) elif message.find('admin_contest_id') != -1: id = message[message.find('admin_contest_id') + 16:len(message)] admin.show_contest(id, text.message.chat.id, True) elif message.find('id') != -1: print_contest_information( text.message.chat.id, message[message.find('id') + 2:len(message)]) elif message.find('notifications') != -1: user = backend.get_user(text.message.chat.id) new_notifications = not user['notifications'] backend.update_user(text.message.chat.id, {'notifications': new_notifications}) print_settings(text.message.chat.id) elif message.find('admin_users') != -1: print_users(text.message.chat.id, 'admin_info_', True) # вывод пользователей для админа elif message.find('admin_contests') != -1: print_contests(text.message.chat.id, 'admin_contest_') elif message.find('choose_div') != -1: contestId = message[message.find(' ') + 1:message.rfind(' ')] chatId = message[message.rfind(' ') + 1:len(message)] admin.choose_div(contestId, chatId) elif message.find('div_') != -1: contestId = message[message.find(' ') + 1:message.rfind(' ')] chatId = message[message.rfind(' ') + 1:len(message)] div = message[message.find('_') + 1:message.find(' ')] admin.edit_activity(contestId, chatId, div) except Exception as err: print("Проблемы с callback", 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)