def send_questions(context, team_db_id, questions): standups_ids = db_teams.find_one({'_id': team_db_id})['standups'] standup_num = len(standups_ids) title = 'Начало стендапа #' + str(standup_num) + '\n\n' text = team_questions_text(questions) title += get_title(team_db_id) members = db_teams.find_one({'_id': team_db_id})['members'] for member in members: chat_id = collection.users.find_one({'_id': member})['chat_id'] context.bot.send_message(chat_id=chat_id, text=title + text)
def send_answers_job(context): team_db_id = context.job.context team = db_teams.find_one({'_id': team_db_id}) last_send_standup = team['last_send_standup'] db_teams.update_one({'_id': team_db_id}, {'$set': { 'last_send_standup': last_send_standup + 1 }}) team = db_teams.find_one({'_id': team_db_id}) team_standups = team['standups'] last_send_standup = team['last_send_standup'] standup_db_id = team_standups[last_send_standup] send_standup_to_connect_chats(team_db_id, standup_db_id, context)
def create_first_standup(team_db_id, context, chat_id, update): team = db_teams.find_one({'_id': team_db_id}) schedule = team['schedule'] duration = team['duration'].split(' ') duration = datetime.timedelta(hours=int(duration[0]), minutes=int(duration[1])) # получаем словарь дата: интервал всех ближайших стендапов на каждый из дней недели standup_dates = get_standup_dates_from_schedule(schedule) send_questions_jobs = [] send_answers_jobs = [] time = team['timezone'].split(' ') delta = datetime.timedelta(hours=int(time[0]), minutes=int(time[1])) for date in standup_dates: interval = datetime.timedelta(days=7 * standup_dates[date]) job = context.job_queue.run_repeating(standup_job, interval=interval, first=date + delta, context=team_db_id) send_questions_jobs.append(job) send_answers_date = date + duration job = context.job_queue.run_repeating(send_answers_job, interval=interval, first=send_answers_date + delta, context=team_db_id) send_answers_jobs.append(job) return send_questions_jobs, send_answers_jobs
def send_standup_to_connect_chats(team_db_id, standup_db_id, context): # TODO сделать проверку на пришедший тип: является ли ObjectId connect_chats = get_team_connect_chats(team_db_id) answers = get_standup_answers(standup_db_id) standups_ids = db_teams.find_one({'_id': team_db_id})['standups'] standup_num = len(standups_ids) questions = db_standups.find_one({'_id': standup_db_id})['questions'] questions_text = team_questions_text(questions) title = 'Результаты стендапа #' + str(standup_num) + '\n\n' title += get_title(team_db_id) title += questions_text + '\n' merged_standup = '' for member_chat_id in answers: member_answers = answers[member_chat_id] member_answers_text = '' member_answers.sort(key=lambda x: x[0]) for answer in member_answers: member_answers_text += str(answer[0]) + '. ' + answer[1] + '\n' user_username = get_user_username(member_chat_id) merged_standup += 'Ответы от ' + str( user_username) + '\n' + member_answers_text if merged_standup == '': merged_standup = 'К сожалению, пока ни один из участников не ответил на вопросы' for chat in connect_chats: user_chat_id = collection.users.find_one({'_id': chat})['chat_id'] context.bot.send_message(chat_id=user_chat_id, text=title + merged_standup)
def write_answer_to_db(update, context): user_id = update.effective_chat.id min_args_number = 2 if str(user_id)[0] == '-': raise BotUserException( "Вы не можете отвечать на вопросы стендапа из общего чата.") if len(context.args) < min_args_number: raise BotUserException("Недостаточно аргументов.") q_num, q_ans = get_answer_command_args(context.args) team_db_id, err_message = get_team_db_id(user_id) # TODO: если get_team_db_id в предыдущей строке все-таки будет бросать исключение, # то следующие две строчки можно убрать if not team_db_id: raise BotUserException(err_message) team = db_teams.find_one({'_id': team_db_id}) st_ids = team['standups'] if len(st_ids) == 0: raise BotUserException("В вашей команде пока не проводились стендапы.") questions = team['questions'] if q_num > len(questions): raise BotUserException("Вопроса с номером " + str(q_num) + " нет.") st_id = st_ids[-1] if is_answer_exists(st_id, user_id, q_num): db_standups.update_one( {'_id': st_id}, {'$pull': { 'answers': { 'id': user_id, 'question_num': q_num } }}, ) db_standups.update_one({'_id': st_id}, { '$addToSet': { 'answers': { 'id': user_id, 'question_num': q_num, 'answer': q_ans } } })
def set_standups(update, context): chat_id = update.effective_chat.id team_db_id, err_message = get_team_db_id(chat_id) if not team_db_id: context.bot.send_message(chat_id=chat_id, text=err_message) return if not is_owner(team_db_id, user_chat_id=chat_id): context.bot.send_message( chat_id=chat_id, text="Данное действие доступно только владельцу команды.") return err_message = check_standups_input(chat_id, context.args) if err_message is not None: context.bot.send_message(chat_id=chat_id, text=err_message) return team = db_teams.find_one({'_id': team_db_id}) prev_standups = team['standups'] db_teams.update_one( {'_id': team_db_id}, {'$set': { 'last_send_standup': len(prev_standups) - 1 }}) write_schedule_to_db(context.args, team_db_id) # остановим старые работы этой команды, если они были old_jobs = jobs[team_db_id] for weekday_jobs in old_jobs: for job in weekday_jobs: job.schedule_removal( ) # остановили работу по отправке вопросов и ответов send_questions_jobs, send_answers_jobs = create_first_standup( team_db_id, context, chat_id, update) # вернули список с указателями на созданные работы, теперь они хранятся в словаре jobs[team_db_id] = [send_questions_jobs, send_answers_jobs] context.bot.send_message(chat_id=update.effective_chat.id, text="Расписание стендапов обновлено.")
def new_standup(questions, team_db_id): timezone = db_teams.find_one({'_id': team_db_id})['timezone'].split(' ') curr_local_time = datetime.datetime.utcnow() - datetime.timedelta( hours=int(timezone[0]), minutes=int(timezone[1])) standup = get_new_standup_document(questions=questions, answers=[], date={ 'day': curr_local_time.day, 'month': curr_local_time.month, 'year': curr_local_time.year }, time={ 'hour': curr_local_time.hour, 'minute': curr_local_time.minute }, team_db_id=team_db_id) standup_db_id = db_standups.insert_one(standup).inserted_id db_teams.update_one({"_id": team_db_id}, {"$addToSet": { 'standups': standup_db_id }})
def get_standup_dates_from_db(team_db_id): return db_teams.find_one({'_id': team_db_id})['standup_dates']
def get_title(team_db_id): team_name = db_teams.find_one({'_id': team_db_id})['name'] title = 'Название команды:\n' + str(team_name) + '\n\nID:\n' + str(team_db_id) + \ '\n\n' return title