示例#1
0
async def send_email_message(message: types.Message,
                             state: FSMContext,
                             teacher_email='',
                             user_id=0):
    logger.info('command: /send_email')
    db = SingletonClient.get_data_base()
    telegram_id = message.from_user.id
    if user_id:
        telegram_id = user_id
    user = await db.Users.find_one({"telegram_id": telegram_id})
    # await state.update_data(group_id=user['group_id'])
    logger.info(user)
    if user.get('email_confirmation'):
        if not teacher_email:
            logger.info('Ready to format an email')
            await format_direction(message,
                                   state,
                                   db,
                                   group_id=user['group_id'])
            await SendingEmail.format_email.set()
        else:
            await state.update_data(teacher_email=teacher_email)
            await message.answer('Введите текст заголовка:')
            await FormatEmail.subject.set()

    else:
        logger.info('Can not sand an email.\nNeed email confirmation')
        await message.answer(
            'Во избежание спама и датамусора мне нужно подтвердить ваш email.\nПожалуйста, '
            'введите его:')
        await SendingEmail.confirmation.set()
async def send_treasury_update():
    """
    Отправляет уведомление
    :return:
    """
    await update_data()

    db = SingletonClient.get_data_base()
    collection = db.transactions

    today = datetime.strftime(datetime.today(), '%d.%m.%Y')
    today = datetime.strptime(today + ' 20:00', '%d.%m.%Y %H:%M')
    from_monday = datetime.fromtimestamp(datetime.timestamp(today) - 604800)
    cursor = collection.find({"date": {"$gte": str(from_monday)}})

    week_data = await cursor.to_list(
        length=await collection.count_documents({}))

    users_cursor = db.users.find({})

    users = await users_cursor.to_list(
        length=await db.users.count_documents({}))

    string = 'Транзакции произошедшие за последнюю неделю:\n'
    for data in week_data:
        string += '\n{name}: <b>{amount}</b> ₽ - фонд: {fund_name}\n'.format(
            name=data['from'],
            amount=beauty_sum(data['total']),
            fund_name=data['fund'])

    for user in users:
        print("user: ")
        print(user)
        await bot.send_message(user['user_id'], string, parse_mode='HTML')
async def save_pills_time_list(callback_query: types.CallbackQuery,
                               state: FSMContext):
    logger.info(f"user_id={callback_query.from_user.id}")

    _state = await state.get_data()
    title = _state.get("title")
    pill_time_list = _state.get("pill_time_list")

    db = SingletonClient.get_data_base()

    user = await db.Users.find_one(
        {"telegram_id": callback_query.from_user.id})

    result = await db.Pills.insert_one({
        "title": title,
        "time_list": pill_time_list,
        "time_status": [],
        "user": user.get("_id")
    })
    logger.info(
        f"save pills user_id={callback_query.from_user.id} "
        f"insert_one result={result.acknowledged} id={result.inserted_id}")

    await callback_query.message.edit_reply_markup(
        reply_markup=types.InlineKeyboardMarkup())
    await callback_query.message.answer(
        "The pill is successfully saved, wait for reminders.")
    await state.finish()
    await callback_query.answer()
示例#4
0
async def handle_pill_callback_query(callback_query: types.CallbackQuery):
    """
    handle pill callback and let user control it
    :param callback_query:
    :return:
    """
    logger.info(
        f"user_id={callback_query.from_user.id} data={callback_query.data}")
    pill_id = ObjectId(callback_query.data.split(',')[1])

    db = SingletonClient.get_data_base()
    pill = await db.Pills.find_one({"_id": pill_id})
    if not pill:
        return callback_query.answer("I can't find that pill, sorry.")

    string = "Title: {}\n".format(pill.get("title"))

    string += "\nList of times for notifications:"
    for time in pill.get("time_list"):
        string += "\n{}".format(time)

    markup = types.InlineKeyboardMarkup()
    if not pill.get('paused'):
        pause_text = "Pause pill"
    else:
        pause_text = "Unpause pill"
    markup.add(
        types.InlineKeyboardButton(
            pause_text, callback_data=f"{callback_query.data},pause"))
    markup.add(
        types.InlineKeyboardButton(
            "Delete pill", callback_data=f"{callback_query.data},delete"))

    await callback_query.message.edit_text(string, reply_markup=markup)
    await callback_query.answer()
示例#5
0
async def get_transcations(page: int, mention) -> list:
    """
    Сахар для получения списка транзакций

    Args:
        page (int): Номер страницы из callback data
        mention ([type]): ник пользователя. По нему идет поиск в бд

    Returns:
        list: Возвращает список транзакций соответствующий странице
    """
    db = SingletonClient.get_data_base()

    # Поиск ника с собачкой перед ником. Такой ник означает донат, а не трату.
    if mention[0] != '@':
        cursor = db.transactions.find({
            "from": '@' + mention
        })

        # Если ника с собачкой в базе нет, то поиск производится по введенному нику.
        if await cursor.to_list(length=1):
            mention = '@' + mention

    cursor = db.transactions.find({
        "from": mention
    }).sort('date', -1)

    transactions = await cursor.to_list(length=await db.transactions.count_documents({}))

    try:
        return transactions[page * 10: page * 10 + 10]
    except IndexError:
        return []
示例#6
0
async def get_min_obj_list(user, page):
    db = SingletonClient.get_data_base()
    subjects_cursor = db.Subjects.find(
        {"group_id": ObjectId(user.get("group_id"))})

    subjects_list = await subjects_cursor.to_list(
        length=await db.Subjects.count_documents({}))

    logger.info(subjects_list)

    rrule_list = [(subject,
                   list(
                       rrule(**(subject['freq']),
                             until=datetime(year=2020, month=12, day=31))))
                  for subject in subjects_list]
    min_obj_list = []
    for obj in rrule_list:
        subj = obj[0]
        dts = obj[1]
        for dt in dts:
            if datetime.now() < dt:
                min_obj_list.append((subj, dt))

    min_obj_list.sort(key=lambda x: x[1])

    try:
        return min_obj_list[page * 5:page * 5 + 5]
    except IndexError:
        return []
示例#7
0
async def handle_pill_pause_callback_query(
        callback_query: types.CallbackQuery):
    """
    handle pause pill callback and it from db
    :param callback_query:
    :return:
    """
    logger.info(
        f"user_id={callback_query.from_user.id} data={callback_query.data}")
    pill_id = ObjectId(callback_query.data.split(',')[1])

    db = SingletonClient.get_data_base()

    pill = await db.Pills.find_one({'_id': pill_id})
    if pill.get('paused'):
        pill_paused = False
    else:
        pill_paused = True

    result = await db.Pills.update_one({'_id': pill.get('_id')},
                                       {'$set': {
                                           "paused": pill_paused
                                       }})
    logger.info(f"pause pill user_id={callback_query.from_user.id} "
                f"pause result={result.acknowledged}")
    await callback_query.message.edit_reply_markup(
        reply_markup=types.InlineKeyboardMarkup())
    text = "The pill was successfully "
    if pill_paused:
        text += "paused."
    else:
        text += "unpaused."
    await callback_query.message.answer(text)
    await callback_query.answer()
示例#8
0
async def accept_callback(callback_query: types.CallbackQuery,
                          state: FSMContext):
    db = SingletonClient.get_data_base()

    async with state.proxy() as data:
        result = await db.Users.insert_one({
            'telegram_id':
            data.get('telegram_id'),
            'first_name':
            data.get('first_name'),
            'second_name':
            data.get('second_name'),
            'third_name':
            data.get('third_name'),
            'isu_number':
            data.get('isu_number'),
            'email_confirmation':
            False,
            'group_id':
            data.get('group_id')
        })
        logger.info(f'Start by: {callback_query.message.from_user.id}\n'
                    f'insert_one user in db status: {result.acknowledged}')

    await callback_query.message.edit_reply_markup()
    await callback_query.message.answer('Вы успешно зарегистрировались.')
    await state.finish()
示例#9
0
async def get_homework_deadline(message: types.Message, state: FSMContext):
    try:
        deadline_date = datetime.strptime(message.text, '%d.%m.%Y')

        db = SingletonClient.get_data_base()
        subject = await state.get_data("subject")
        subject = subject['subject']
        text = await state.get_data("text")
        text = text['text']
        date = await state.get_data("date")
        date = datetime.fromisoformat(date['date'])
        result = await db.Homework.insert_one({
            'subject_id': subject['_id'],
            'text': text,
            'date': date,
            'deadline': deadline_date
        })
        if result.acknowledged:
            logger.info(f"new homework for {subject['title']}")
            await message.answer('Домашнее задание добавлено.')
            await Menu.admin.set()
            await choose_action_menu(message)
    except ValueError:
        await message.answer(
            'Неверный формат.\n\nПришлите дедлайн домашнего задания в формате <code>13.12.2020</code>'
        )
示例#10
0
async def get_coming_subjects_string(min_obj, message: types.Message, user):
    db = SingletonClient.get_data_base()
    min_subj = min_obj[0]
    markup = types.InlineKeyboardMarkup()
    if message.chat.type == 'private':
        string = '<b>Ваше ближайшее занятие:</b>\n'
    else:
        string = f'<b>Ближайшие занятие для {user["second_name"]} {user["first_name"]}:</b>\n'
    string += f'{min_subj["title"]}\n'
    string += f'Аудитория: {min_subj["audience"]}\n'
    string += f'Когда: {min_obj[1].strftime("<b>%H:%M</b> %d.%m.%Y")}\n'
    # Прикрепление ссылки на зум.
    zoom_link = await db.ZoomLinks.find_one({
        "date": min_obj[1],
        "subject_id": min_subj['_id']
    })
    if zoom_link:
        string += f"Ссылка на <a href=\"{zoom_link['link']}\">zoom</a>."

    # if teacher_id := min_subj.get('teacher_id'):
    #     teacher = await db.Teachers.find_one({
    #         '_id': objectid.ObjectId(teacher_id)
    #     })
    #     teacher_email = teacher['email']
    #     button = types.InlineKeyboardButton(text="📧 Написать преподавателю",
    #                                         callback_data=f'SendEmail,{teacher_email}')
    #     markup.add(button)
    # кнопка подписки на напоминания
    button = types.InlineKeyboardButton(
        text="🔔 Подписаться на напоминания",
        callback_data=f'SubscribeNotifications,{min_subj["_id"]}')
    markup.add(button)

    return string, markup
示例#11
0
async def handle_cs_callback_query(callback_query: types.CallbackQuery):
    """
    Обработчик нажатия на кнопку под сообщением с ближайшей парой.
    Лямбда проверяет, чтобы обрабатывалось только y кнопки
    Args:
        callback_query (types.CallbackQuery): Документация на сайте телеграма
    """

    split_data = callback_query.data.split(',')
    if split_data[1] == 'n':
        return await callback_query.answer(text='Там больше ничего нет...')

    page = int(split_data[2])
    user_id = objectid.ObjectId(split_data[3])

    db = SingletonClient.get_data_base()

    user = await db.Users.find_one({"_id": user_id})

    subjects_cursor = db.Subjects.find(
        {"group_id": objectid.ObjectId(user.get("group_id"))})

    subjects_list = await subjects_cursor.to_list(
        length=await db.Subjects.count_documents({}))

    min_obj = get_min_obj(subjects_list, page)
    min_subj = min_obj[0]

    string, markup = await get_coming_subjects_string(min_obj,
                                                      callback_query.message,
                                                      user)

    # Проверяет, есть ли пары на предыдущих страницах.
    left_min_obj = get_min_obj(subjects_list, page - 1)
    if left_min_obj:
        left_button = types.InlineKeyboardButton(
            text='⬅️', callback_data=f'cs,l,{page - 1},{user_id}')
    else:
        left_button = types.InlineKeyboardButton(
            text='❌', callback_data=f'cs,n,{page},{user_id}')

    # Проверяет, есть ли пары на следующих страницах.
    right_min_obj = get_min_obj(subjects_list, page + 1)
    if right_min_obj:
        right_button = types.InlineKeyboardButton(
            text='➡️', callback_data=f'cs,r,{page + 1},{user_id}')
    else:
        right_button = types.InlineKeyboardButton(
            text='❌', callback_data=f'cs,n,{page},{user_id}')

    markup.row(left_button, right_button)

    _message = await callback_query.message.edit_text(
        string,
        reply_markup=markup,
        parse_mode='HTML',
        disable_web_page_preview=True)
    await callback_query.answer()
示例#12
0
async def coming_subjects(message: types.Message):
    # TODO: 1) найти пользователя 2) найти его группу 3) найти предметы, которые относятся к его группе 4) найти
    #  ближайший и вернуть информацию 5) добавить кнопку, чтобы перелестнуть на следующий ближайший
    telegram_id = message.from_user.id
    db = SingletonClient.get_data_base()

    user = await db.Users.find_one({"telegram_id": telegram_id})

    if not user:
        return await message.reply(
            'Вы не зарегистрированы. Зайдите в бота и напишите <code>/start</code>'
        )
    elif not user.get('group_id'):
        return await message.reply('Вы не указали группу.')

    group = await db.Groups.find_one({"_id": user.get("group_id")})

    subjects_cursor = db.Subjects.find(
        {"group_id": objectid.ObjectId(user.get("group_id"))})

    subjects_list = await subjects_cursor.to_list(
        length=await db.Subjects.count_documents({}))
    logger.info(user)
    logger.info(group)

    logger.info(
        f'from {user["telegram_id"]}, group {group["title"]}, subjects_list {subjects_list}'
    )

    min_obj = get_min_obj(subjects_list)

    logger.info(
        f'from {user["telegram_id"]}, group {group["title"]}, Closest subj {min_obj[0]}'
    )
    min_subj = min_obj[0]

    string, markup = await get_coming_subjects_string(min_obj, message, user)

    # TODO: добавить кнопку "посмотреть ДЗ"
    # перелистывание предметов
    """
    callback_data:
    1) cs - название модуля
    2) l, r, n - left, right, none
    3) int - номер страницы
    4) user_id
    """
    if get_min_obj(subjects_list, 1):
        button_1 = types.InlineKeyboardButton(
            text="❌", callback_data=f'cs,n,0,{user["_id"]}')
        button_2 = types.InlineKeyboardButton(
            text="➡️", callback_data=f'cs,r,1,{user["_id"]}')
        markup.row(button_1, button_2)

    if _id := min_subj.get('teacher_id'):
        teacher = await db.Teachers.find_one({'_id': _id})
        string += f'Преподаватель: {teacher["second_name"] + " " + teacher["first_name"]}\n'
示例#13
0
async def choose_action_menu(message: types.Message):
    string = 'Меню добавления домашнего задания / ссылки на zoom.\nДомашнее задание | Ссылка на zoom | Название | Дата'
    markup = types.ReplyKeyboardMarkup()
    markup.add(types.KeyboardButton(text='Выйти'))
    await message.answer(string, reply_markup=markup)

    telegram_id = message.from_user.id
    db = SingletonClient.get_data_base()

    user = await db.Users.find_one({"telegram_id": telegram_id})

    markup = types.InlineKeyboardMarkup()
    min_obj_list = await get_min_obj_list(user, 0)

    for obj in min_obj_list:
        subj = obj[0]
        string = ''
        hw = await db.Homework.find_one({
            "subject_id": ObjectId(subj['_id']),
            "date": obj[1]
        })
        if hw:
            string += '✅ | '
        else:
            string += '❌ | '
        zm = await db.ZoomLinks.find_one({
            "subject_id": ObjectId(subj['_id']),
            "date": obj[1]
        })
        if zm:
            string += '✅ | '
        else:
            string += '❌ | '
        string += f"{subj['title']} {obj[1].strftime('%H:%M %d.%m.%Y')}"
        button = types.InlineKeyboardButton(
            text=string, callback_data=f'cha,{subj["_id"]},{obj[1]}')
        markup.add(button)
    """
    callback_data:
    1) am - название модуля
    2) l, r, n - left, right, none
    3) int - номер страницы
    4) user_id
    """
    if await get_min_obj_list(user, 1):
        button_1 = types.InlineKeyboardButton(
            text="❌", callback_data=f'am,n,0,{user["_id"]}')
        button_2 = types.InlineKeyboardButton(
            text="➡️", callback_data=f'am,r,1,{user["_id"]}')
        markup.row(button_1, button_2)

    string = 'Список ближайших пар и статус домашнего задания:'
    await message.answer(string,
                         reply_markup=markup,
                         disable_web_page_preview=True)
示例#14
0
async def rating_string(month=time.strftime("%m"),
                        year=time.strftime("%y")) -> str:
    """
    Метод возвращает строку, которая содержит топ 5 донатеров
    :return:
    """

    year = '20' + year

    # Сделать импорт нужных данных из монго
    db = SingletonClient.get_data_base()
    collection = db.transactions

    cursor = collection.find({
        "date": {
            "$gte":
            str(datetime.strptime("01 {} {}".format(month, year), "%d %m %Y")),
            "$lte":
            str(
                datetime.strptime(
                    "{} {} {}".format(
                        monthrange(int(year), int(month))[1], month, year),
                    "%d %m %Y"))
        }
    })

    contributions = await cursor.to_list(
        length=await collection.count_documents({}))

    dct = {}

    if contributions:
        for i in contributions:
            if i['total'] > 0 and i['comment'] != 'Техническая':
                if dct.get(i['from']):
                    dct[i['from']] += i['total']
                else:
                    dct.update({i['from']: i['total']})
    else:
        return None

    print(dct)
    list_d = list(dct.items())
    list_d.sort(key=lambda j: j[1], reverse=True)
    list_d = list_d[:10]

    string = f'Топ 10 жертвователей за {month}.{year}:\n'

    for i in range(len(list_d)):
        string += '{}) {} - <b>{}</b> ₽\n'.format(i + 1, list_d[i][0],
                                                  beauty_sum(list_d[i][1]))

    return string
示例#15
0
async def pills_list(message: types.Message):
    """
    Send listable list with pills
    :param message:
    :return:
    """
    logger.info(f"/pills user_id={message.from_user.id}")
    db = SingletonClient.get_data_base()
    user = await db.Users.find_one({"telegram_id": message.from_user.id})
    if not user:
        await start(message)

    db = SingletonClient.get_data_base()
    user = await db.Users.find_one({"telegram_id": message.from_user.id})

    markup = types.InlineKeyboardMarkup()
    """
    callback_data:
    1) pl - module name
    2) l, r, n - left, right, none
    3) int - page num
    4) user_id
    """
    string = "List of your current pills:"
    markup = get_pills_list_markup(markup, await get_pills(0, user.get("_id")))
    if not await get_pills(0, user.get("_id")):
        return await message.answer(
            "You haven't added the pills yet. Try via /new.")

    left_button = types.InlineKeyboardButton(
        text='❌', callback_data=f'pl,l,0,{user.get("_id")}')

    right_list = await get_pills(1, user.get("_id"))
    if right_list:
        right_button = types.InlineKeyboardButton(
            text='➡️', callback_data=f'pl,r,1,{user.get("_id")}')

        markup.row(left_button, right_button)

    _message = await message.answer(string, reply_markup=markup)
示例#16
0
async def unsubscribe(message: types.Message):
    db = SingletonClient.get_data_base()
    users_collection = db.users

    user = await users_collection.find_one({"user_id": message.from_user.id})

    if user:
        result = await users_collection.delete_one(
            {"user_id": message.from_user.id})
        print('Unsubscribe. Delete user:\n' + str(result.raw_result))
        await message.reply('Вы успешно отписались от обновлений')
    else:
        await message.reply('Вы не подписаны на обновления')
示例#17
0
async def admin_menu(message: types.Message, state: FSMContext):
    telegram_id = message.from_user.id
    db = SingletonClient.get_data_base()

    user = await db.Users.find_one({"telegram_id": telegram_id})
    logger.info(user)
    if not user:
        return await message.answer('Вы не зарегистрированы в боте.')

    group = await db.Groups.find_one({"admin_id": user['_id']})
    if not group:
        return await message.answer('Вы не админ группы.')

    await Menu.admin.set()
    await choose_action_menu(message)
示例#18
0
async def start(message: types.Message):
    logger.info('command: /start')
    telegram_id = message.from_user.id
    logger.info(telegram_id)
    db = SingletonClient.get_data_base()

    user = await db.Users.find_one({"telegram_id": telegram_id})

    logger.info(user)

    if user:
        logger.info(f'user exist.')
        return await message.reply('Вы уже зарегистрированы.')

    await message.reply('Введите <b>Фамилию Имя Отчество</b>.')
    await Start.name.set()
示例#19
0
async def set_zoom_link(message: types.Message, state: FSMContext):
    db = SingletonClient.get_data_base()
    subject = await state.get_data("subject")
    subject = subject['subject']
    date = await state.get_data("date")
    date = datetime.fromisoformat(date['date'])
    result = await db.ZoomLinks.insert_one({
        'subject_id': subject['_id'],
        'link': message.text,
        'date': date
    })
    if result.acknowledged:
        logger.info(f"new zoom link for {subject['title']}")
        await message.answer('Ссылка на zoom добавлена.')
        await Menu.admin.set()
        await choose_action_menu(message)
示例#20
0
async def new_pill(message: types.Message):
    """
    Creates new pill for user
    :param message:
    :return:
    """
    logger.info(f"/new pill user_id={message.from_user.id}")
    db = SingletonClient.get_data_base()
    user = await db.Users.find_one({"telegram_id": message.from_user.id})
    if not user:
        await start(message)

    await message.answer(
        "Please, send me pill title.\nIf you want to cancel this operation type /cancel."
    )
    await NewPill.title.set()
示例#21
0
async def menu_markup(telegram_id):
    db = SingletonClient.get_data_base()

    user = await db.Users.find_one({"telegram_id": telegram_id})

    group = await db.Groups.find_one({"_id": user.get("group_id")})

    coming_subjects = types.KeyboardButton('Ближайшие пары')
    homework_list = types.KeyboardButton('Список домашних заданий')
    btn_list = [[coming_subjects, homework_list]]
    if user.get('_id') == group.get('admin_id'):
        admin_menu = types.KeyboardButton('Функции админа')
        btn_list.append([admin_menu])

    menu_keyboard_markup = types.ReplyKeyboardMarkup(btn_list)
    return menu_keyboard_markup
示例#22
0
async def took_pill_callback_handler(callback_query: types.CallbackQuery):
    """
    handle took pill callback and update in db
    :param callback_query:
    :return:
    """
    db = SingletonClient.get_data_base()

    split_data = callback_query.data.split(',')
    pill_id = ObjectId(split_data[1])
    t = split_data[2]

    logger.info(f"user_id={callback_query.from_user.id} pill_id={pill_id}")

    pill = await db.Pills.find_one({"_id": pill_id})

    index = pill.get("time_list").index(t)

    time_status = pill.get("time_status")
    if time_status[index]:
        return await callback_query.answer("I've already processed that time.")
    time_status[index] = True

    result = await db.Pills.update_one({"_id": pill_id},
                                       {"$set": {
                                           "time_status": time_status
                                       }})
    logger.info(
        f"user_id={callback_query.from_user.id} pill_id={pill_id} "
        f"update_one result={result.acknowledged} time_status={time_status}")

    good_words = [
        "You did a great job!", "Awesome!", "Good for you!",
        "I hope you feel better."
    ]
    await callback_query.message.reply(
        "I've reminded you to take your medicines! {}".format(
            good_words[random.randint(0,
                                      len(good_words) - 1)]))

    await callback_query.message.edit_reply_markup(
        reply_markup=types.InlineKeyboardMarkup())

    await callback_query.answer()
示例#23
0
async def subscribe(message: types.Message):
    db = SingletonClient.get_data_base()
    users_collection = db.users

    user = await users_collection.find_one({"user_id": message.from_user.id})

    if user:
        await message.reply('Вы уже подписаны на обновления')
    else:
        user_data = {
            "user_id": message.from_user.id,
            "first_name": message.from_user.first_name,
            "username": message.from_user.mention
        }

        result = await users_collection.insert_one(user_data)
        print('Subscribe. Insert user id = ' + str(result.inserted_id))

        await message.reply('Вы успешно подписались на обновления')
示例#24
0
async def get_pills(page: int, parameter: str) -> (list, int):
    """
    Sugar to get pills list
    Args:
        page (int): page num from callback data
        parameter ([type]): user_id to find pills
    Returns:
        list[{'total': int, 'fund': str}]: list of pills for page
    """
    db = SingletonClient.get_data_base()

    pills = db.Pills.find({"user": ObjectId(parameter)})
    pills = await pills.to_list(length=await db.Pills.count_documents({}))

    size = 10

    try:
        return pills[page * size:page * size + size]
    except IndexError:
        return []
示例#25
0
async def choose_action(callback_query: types.CallbackQuery,
                        state: FSMContext):
    db = SingletonClient.get_data_base()
    subject_id = ObjectId(callback_query.data.split(',')[1])
    date = callback_query.data.split(',')[2]
    subject = await db.Subjects.find_one({'_id': ObjectId(subject_id)})
    await state.update_data(subject=subject)
    await state.update_data(date=date)

    markup = types.InlineKeyboardMarkup()
    markup.add(
        types.InlineKeyboardButton(text='Добавить домашнее задание',
                                   callback_data='tp,homework'))
    markup.add(
        types.InlineKeyboardButton(text='Добавить ссылку на zoom',
                                   callback_data='tp,zoom'))
    await callback_query.message.edit_text(
        f'Выберите что вы хотите добавить для <b>{subject["title"]}</b>:',
        reply_markup=markup)
    await Menu.choose_action.set()
示例#26
0
async def set_group(message: types.Message, state: FSMContext):
    try:
        if len(message.text.split(' ')) > 1:
            raise ValueError
        db = SingletonClient.get_data_base()
        group = await db.Groups.find_one({"title": message.text})
        if not group:
            return await message.reply(
                'Такой группы не существует\n\nВведите группу в формате: <b>K3221</b> (Первая буква английская).'
            )

        await state.update_data(group=message.text)
        await state.update_data(group_id=group['_id'])
        logger.info(f'Start by: {message.from_user.id}. Group: {message.text}')

        await finish(message, state)

    except ValueError:
        await message.reply(
            'Неверный формат.\n\nВведите группу в формате: <b>K3221</b> (Первая буква английская).'
        )
示例#27
0
async def subscribe_update(callback_query: types.CallbackQuery):
    subject_id = callback_query.data.split(',')[1]
    db = SingletonClient.get_data_base()
    telegram_id = callback_query.from_user.id
    user = await db.Users.find_one({"telegram_id": telegram_id})

    logger.info(f'subscribe notifications request from {telegram_id}')

    if not user:
        logger.info(
            f'subscribe notifications request from {telegram_id}. user not registered'
        )
        return await callback_query.answer('Вы не зарегистрированы в боте.')

    subscription = await db.SubjectNotifications.find_one({
        "user_id":
        user['_id'],
        "subject_id":
        objectid.ObjectId(subject_id)
    })

    if subscription:
        logger.info(
            f'subscribe notifications request from {telegram_id}. user already subscribed'
        )
        return await callback_query.answer('Вы уже подписаны на напоминания.')

    result = await db.SubjectNotifications.insert_one({
        "user_id":
        user['_id'],
        "subject_id":
        objectid.ObjectId(subject_id)
    })

    if result.acknowledged:
        logger.info(
            f'subscribe notifications request from {telegram_id}. user successfully subscribed'
        )
        return await callback_query.answer(
            'Вы подписались на напоминания о паре.')
示例#28
0
async def send_everyday_subj_notification():
    logger.info('Начинаю отправку ежедневных уведомлений о занятиях')
    day_start = datetime(datetime.now().year,
                         datetime.now().month,
                         datetime.now().day, 0, 0) + timedelta(days=1)
    day_end = datetime(datetime.now().year,
                       datetime.now().month,
                       datetime.now().day, 23, 59) + timedelta(days=1)

    db = SingletonClient.get_data_base()
    subscriptions_list = db.SubjectNotifications.find({}).sort(
        'user_id', 1).limit(await db.SubjectNotifications.count_documents({}))
    users = {}

    async for subscription in subscriptions_list:
        subject_id = ObjectId(subscription['subject_id'])
        user = await db.Users.find_one(
            {'_id': ObjectId(subscription['user_id'])})

        subject = await db.Subjects.find_one({'_id': subject_id})
        min_obj = get_min_obj([subject])
        if users.get(user.get('telegram_id')):
            users[user['telegram_id']].append(min_obj)
            logger.info('append new min_obj')
        else:
            users.update({user['telegram_id']: [min_obj]})
            logger.info('update users dict')

    logger.info(users)
    for telegram_id in users.keys():
        logger.info(telegram_id)
        string = 'Список занятий на завтра:\n\n'
        for min_obj in users[telegram_id]:
            if day_start < min_obj[1] < day_end:
                string += f'{min_obj[1].strftime("<b>%H:%M</b>")} - {min_obj[0]["title"]} - Аудитория {min_obj[0]["audience"]}\n'
        if string != 'Список занятий на завтра:\n\n':
            await bot.send_message(chat_id=telegram_id, text=string)
        else:
            await bot.send_message(chat_id=telegram_id,
                                   text='Завтра занятий нет :)')
示例#29
0
async def update_data():
    _data = await get_from_excel("Транзакции", "A1", "K10000")
    _data = _data['values'][1:]

    _lst = []
    list_of_rows = []
    for i in range(len(_data)):
        if not (bool(_data[i][0]) and bool(_data[i][5]) and bool(_data[i][6])):
            _lst.append(i)
        else:
            row_dict = {"from": _data[i][0].lower()}
            row_dict.update({"total_currency": _data[i][1]})
            row_dict.update({"currency_name": _data[i][2]})
            row_dict.update({"fund": _data[i][3]})
            row_dict.update({"comment": _data[i][4]})
            row_dict.update(
                {"date": str(datetime.strptime(_data[i][5], "%d.%m.%Y"))})
            row_dict.update({"total": _data[i][6]})
            row_dict.update({"currency": _data[i][7]})
            if _data[i][8] == "TRUE":
                row_dict.update({"taxFree": True})
            else:
                row_dict.update({"taxFree": False})
            row_dict.update({"treasuryBalance": _data[i][10]})

            list_of_rows.append(row_dict)

    db = SingletonClient.get_data_base()
    collection = db.transactions

    # Удаляются все данные из коллекции
    delete_result = await collection.delete_many({})
    print('Update data. Delete transactions:\n' +
          str(delete_result.raw_result))

    # Таблица заполняется обновленным данными
    insert_result = await collection.insert_many(list_of_rows)
    print('Update data. Insert transactions = ' +
          str(insert_result.inserted_ids))
示例#30
0
async def code_accepting(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        code = data.get('code')
        user_email = data.get('email')
    db = SingletonClient.get_data_base()
    user = await db.Users.find_one({"telegram_id": message.from_user.id})
    if message.text == code:
        logger.info('email has been accepted')
        await message.answer(
            'Вы успешно подтвердили свою почту\nТеперь вы можете пользоваться командой /send_email'
        )
        await db.Users.update_one(
            {"telegram_id": message.from_user.id},
            {'$set': {
                "email": user_email,
                "email_confirmation": True
            }})
        await format_direction(message, state, db, group_id=user['group_id'])
        await SendingEmail.format_email.set()
    else:
        logger.info('got an incorrect confirmation code')
        await message.reply('Вы ввели неправильный код. Попробуйте еще раз.')