예제 #1
0
파일: me.py 프로젝트: mnl88/cod_bot_2
    intro = State()
    no_person_in_db = State()
    show_profile_or_stats = State()
    showing_person_data = State()
    showing_statistics = State()
    edit_profile = State()
    choose_what_to_edit = State()
    edit_value_selected_before = State()
    input_device_is_selected = State()
    platform_is_selected = State()
    account_is_selected = State()
    account_is_entered = State()


# при нажатии /me
@dp.message_handler(Command('me'), IsPrivate())
async def command_me(message: types.Message, state: FSMContext):
    logger.info(
        f'Пользователь {message.from_user.full_name} (ID: {message.from_user.id}) нажал команду ME'
    )
    text = 'Привет, друг! Подожди буквально пару секунд, я проверю, зарегистрирован ли ты в базе данных...'
    main_message = await message.answer(text=text)
    async with state.proxy() as data:
        data['main_message_id'] = main_message.message_id
    await types.ChatActions.typing()
    await asyncio.sleep(1)
    db = DB()
    tg_account = db.get_tg_account(tg_id=message.from_user.id)
    if db.is_person_exists(tg_account):  # если пользователь уже есть в БД
        logger.info('Пользователь уже был зарегистрирован ранее в БД')
        text = [
from data.config import TIMEZONE
from loader import dp
from aiogram.utils.markdown import hbold, hitalic
from states.registration import RegistrationStates
from states.different_group_search import DifferentGroupSearchStates
from aiogram.dispatcher.filters.builtin import Command
from utils import schedule_to_text, group_name
from utils.db_api.methods.schedule_methods import get_all_groups, get_day_schedule_by_groupname, \
    get_week_schedule_by_groupname, get_available_faculties
from keyboards.callbackdatas.different_group_schedule_callbackdata import diffgroup_schedule_callback
from keyboards.inline.different_group import prompt_after_getting_diffgroup_schedule, cancel_different_group_search, \
    different_group_schedule_selection
from keyboards.callbackdatas.redirect_to_diffgroup_schedule_selection_callbackdata import redirect_to_schedule_selection_callback


@dp.message_handler(Command("differentgroupschedule"),
                    state=RegistrationStates.RegistrationComplete)
async def show_different_group_search_prompt(message: Message):
    await DifferentGroupSearchStates.FindGroup.set()
    await message.answer(
        text=f"Пожалуйста, напиши мне номер группы, для которой ты "
        f"хочешь узнать расписание.\n"
        f"Номер группы можно писать без - и в любом регистре.\n\n"
        f"Например, вот так {hitalic('1дасм1')} или так {hitalic('1ДАСМ1')}",
        reply_markup=cancel_different_group_search.keyboard)


@dp.callback_query_handler(text="abort_different_group_search",
                           state=DifferentGroupSearchStates)
async def cancel_search(callback: CallbackQuery):
    await RegistrationStates.RegistrationComplete.set()
예제 #3
0
import datetime
from aiogram.types import Message, CallbackQuery

from data.config import TIMEZONE
from loader import dp
from aiogram.utils.markdown import hbold
from aiogram.dispatcher.filters.builtin import Command
from states.registration import RegistrationStates
from utils import schedule_to_text
from utils.db_api.methods.schedule_methods import get_day_schedule_by_userid, get_week_schedule_by_userid, get_week_info
from keyboards.inline import schedule_selection, share_schedule
from keyboards.callbackdatas.schedule_callbackdata import schedule_callback


@dp.message_handler(Command("selectschedule"),
                    state=RegistrationStates.RegistrationComplete)
async def show_schedule_selection(message: Message):
    week_info = await get_week_info()
    week_type_name = week_info[1]

    await message.answer(text=f"Выбери нужный день(или всю неделю).\n\n"
                         f"Текущая неделя - {hbold(week_type_name)}",
                         reply_markup=schedule_selection.keyboard)


# _callback is appended to func name to avoid having same name as handler in today_schedule
@dp.callback_query_handler(schedule_callback.filter(is_weekday="False",
                                                    time="today"),
                           state=RegistrationStates.RegistrationComplete)
async def show_today_schedule_callback(callback: CallbackQuery):
    await callback.answer(text="Получаю расписание на сегодня")
예제 #4
0
from aiogram import types
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.builtin import Command
from aiogram.types import ReplyKeyboardRemove
from aiogram.utils.markdown import hcode

from data.config import admins
from keyboards.default import contact_button, location_button
from loader import dp
from utils.db_api import quick_commands as commands


@dp.message_handler(Command("tel"))
async def bot_start(message: types.Message, state: FSMContext):
    await message.answer("Пришли мне свой номер телефона",
                         reply_markup=contact_button.keyboard)
    await state.set_state("tel")


@dp.message_handler(state="tel", content_types=types.ContentType.CONTACT)
async def enter_email(message: types.Message, state: FSMContext):
    # contact = message.contact
    tel = message.contact
    # await message.answer(text=f"{tel.phone_number}, {tel.user_id}", reply_markup=ReplyKeyboardRemove())
    await commands.update_user_email(tel=tel.phone_number,
                                     id=message.from_user.id)
    user = await commands.select_user(id=message.from_user.id)
    await message.answer("Данные обновлены. Запись в БД: \n" +
                         hcode(f"id={user.id}\n"
                               f"name={user.name}\n"
                               f"tel={user.tel}"),
예제 #5
0
    try:
        user = await commands.add_new_user(id=chat_id, referral=referral)
    except asyncpg.exceptions.UniqueViolationError:
        pass
    id = user.user_id
    bot_username = (await bot.me).username
    bot_link = f"https://t.me/{bot_username}?start={id}"
    count_users = await commands.count_users()
    text = _("Welcome\n"
             "Now in base {count_users} users\n"
             "Your referral link: {bot_link}"
             "Check referrals command /referrals\n"
             "Items list: /items").format(count_users=count_users,
                                          bot_link=bot_link)
    await message.answer(text, reply_markup=languages_markup)


@dp.callback_query_handler(text_contains="lang")
async def choose_language(call: CallbackQuery):
    await call.message.edit_reply_markup()
    lang = call.data[-2:]
    await commands.set_language(language=lang)
    await call.message.answer(_("Your language was changed.", locale=lang))


@dp.message_handler(Command("referrals"))
async def check_referrals(message: types.Message):
    referrals = await commands.check_referrals()
    text = _("Your referrals: {referrals}").format(referrals=referrals)
    await message.answer(text)
예제 #6
0
import asyncio
from aiogram import types
from aiogram.dispatcher.filters.builtin import CommandStart, Command
from aiogram.dispatcher import FSMContext
from loader import dp
from states import New
from utils.db_api import quick_commands


@dp.message_handler(Command('salom'))
async def bot_start(message: types.Message, state: FSMContext):
    await message.answer('Please insert your student_id')
    await New.student_id.set()


@dp.message_handler(state=New.student_id)
async def enter_email(message: types.Message, state: FSMContext):
    message_text = message.text
    users = await quick_commands.select_all_users()
    n = []
    for data in users:
        n.append(data.student_id)
    if message_text in n:
        print("studentID mavjud")
    [print(data) for data in users]
    await state.finish()
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.builtin import Command
from aiogram.types import ReplyKeyboardRemove

from data import poll_questions
from handlers.users import show_goods_basket, ask_user, get_user_data, show_main_menu
from keyboards.default import edit_basket_menu, position_keyboard
from loader import dp
from states import EditBasketDeletePos, EditBasketEditPos
from utils.db_api.db_commands import get_basket_size, get_user_database_data, update_user_data


# Edit current user basket
@dp.message_handler(text='Редактировать корзину')
@dp.message_handler(text='Редактировать корзину ✏')
@dp.message_handler(Command('edit_basket'))
async def edit_basket(message: types.Message):
    await message.answer(text=f'Вы вошли в режим редакирования',
                         reply_markup=edit_basket_menu)


@dp.message_handler(text='Выйти 🔙')
async def back(message: types.Message):
    await show_goods_basket(message)


@dp.message_handler(text='Очистить корзину 🎇')
async def clear_basket(message: types.Message):
    user_id: int = message.from_user.id

    await update_user_data(user_id,
예제 #8
0

@dp.message_handler(CommandStart("start"))
async def bot_start(message: types.Message):
    await message.answer(f'Добрый день, {message.from_user.full_name}.\n\n'
                         'Вы вступили в переписку с робоэдвайзером, который помогает осуществлять ребалансировку'
                         ' инвестиционного портфеля, состоящего из ценных бумаг\n\n'
                         'Чат-бот использует модельные данные по акциям из {источник} ***\n\n'
                         'По вопросам, связанным с робоэвдайзером, можно обращаться'
                         ' к основателю проекта @elais_loladze')
    #await message.answer("Перейти к робоэдвайзеру?", reply_markup=yes_markup)
    await PortfolioStates.Set_Budget.set()
    #await message.answer(f'Привет, {message.from_user.full_name}!')


@dp.message_handler(Command("start"))
async def bot_start(message: types.Message):
    await message.answer(f'Добрый день, {message.from_user.full_name}.\n\n'
                         'Вы вступили в переписку с робоэдвайзером, который помогает осуществлять ребалансировку'
                         ' инвестиционного портфеля, состоящего из ценных бумаг\n\n'
                         'Чат-бот использует модельные данные по акциям из {источник} ***\n\n'
                         'По вопросам, связанным с робоэвдайзером, можно обращаться'
                         ' к основателю проекта @elais_loladze')
    #await message.answer("Перейти к робоэдвайзеру?", reply_markup=yes_markup)
    await message.answer("Введите сумму, которую вы планируете инвестировать в долларах США (минимальная сумма 20.000):"
                         , reply_markup=ReplyKeyboardRemove())
    await PortfolioStates.Check_Budget.set()

'''
@dp.message_handler(text="Перейти к робоэдвайзеру")
async def get_bugdet(message: types.Message):
예제 #9
0
from aiogram import types
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.builtin import Command
from states.admin import Admin
from loader import dp, db
from utils.db_api.quick_commands import add_user


@dp.message_handler(Command("admin"))
async def bot_get_email(message: types.Message, state: FSMContext):
    await message.answer("Add user")
    await Admin.student_id.set()


@dp.message_handler(state=Admin.student_id)
async def enter_email(message: types.Message, state: FSMContext):
    message_user = message.text
    await add_user(student_id=message_user)
    await message.answer(f'Added {message_user}')
    await state.finish()
예제 #10
0
파일: add.py 프로젝트: Na3aga/gmbot
from aiogram import types
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.builtin import Command
from aiogoogle.auth.utils import create_secret

from TgBot.loader import dp
from TgBot.utils.misc import rate_limit
from TgBot.states.add import AddGmail
from loader import gmail_API, current_states
from re import match
import logging


@rate_limit(1, 'add')
@dp.message_handler(Command('add'), state=None)
async def start_gmail_add(message: types.Message):
    text = 'Надішліть електронну адресу у відповідь на це повідомлення '\
        '(тільки GMail)'
    await message.answer(text)

    await AddGmail.Add.set()


@dp.message_handler(state=AddGmail.Add)
async def add(message: types.Message, state: FSMContext):
    email = message.text.strip()
    if not match(r'^[\w\.-]+@gmail\.com$', email):
        logging.info(f"Mail {email} was rejected")
        await message.answer('Невідомий формат пошти')
        await state.finish()
        return
import logging

from aiogram import types
from aiogram.dispatcher.filters.builtin import Command
from handlers.users.main_menu import show_main_menu
from keyboards.default import basket_menu, edit_basket_menu
from loader import dp


# Show current user basket
@dp.message_handler(text='Корзина')
@dp.message_handler(text='Корзина 🧺')
@dp.message_handler(text='Отмена ❌')
@dp.message_handler(Command('basket'))
async def show_goods_basket(message: types.Message, mode: str = 'common'):
    # Get user ID
    user_id: int = message.from_user.id

    # Get User
    user: User = await get_user_by_id(user_id)

    # Get current user basket
    basket_name: list[str] = user.basket_name
    basket_count: list[int] = user.basket_count
    basket_item_price: list[int] = user.basket_item_price

    logging.info('Baskeeeeeeeeeeeeeeeeeet')
    logging.info(basket_name)
    logging.info(basket_count)
    logging.info(basket_item_price)
예제 #12
0
from aiogram import types
from aiogram.dispatcher.filters.builtin import CommandStart, Command
from keyboards.default.test import buy
from keyboards.inline.test_inline import buy_1
from aiogram.types import ReplyKeyboardRemove

from loader import dp


@dp.message_handler(CommandStart())
async def bot_echo(message: types.Message):
    await message.answer("Приветствующие сообщение от бота", reply_markup=buy)


@dp.message_handler(text="🛒 Rates")
async def back(message: types.Message):
    await message.answer("⬇️ Выбери сроки подписки ⬇️", reply_markup=buy_1)


@dp.message_handler(Command("myid"))
async def bot_my_id(message: types.Message):
    await message.answer(f"Твой ID : {message.from_user.id}")
예제 #13
0
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.builtin import Command

from data import poll_questions
from keyboards.default import poll_menu_phone, poll_menu_first, poll_menu_main
from loader import dp
from states import Checkout
from utils import forming_text, send_email, gen_checking_code
from utils.db_api.db_commands import update_user_data
from handlers.users import show_main_menu, ask_user, get_user_data, init_getting


# Start checkout order
@dp.message_handler(text='Оформить заказ')
@dp.message_handler(text='Оформить заказ ✅')
@dp.message_handler(Command('checkout'))
async def start_checkout(message: types.Message):
    # Ask user for his/her name
    await ask_user(message=message, state=Checkout, text=poll_questions['name'], markup=poll_menu_first)


# Get client name, commit it to database and request user phone number
@dp.message_handler(state=Checkout.UserName)
async def get_user_name(message: types.Message, state: FSMContext):
    await init_getting(message=message, state=state)
    await get_user_data(message=message, main_state=state, data_name='name')

    await ask_user(message=message, state=Checkout, text=poll_questions['phone_number'], markup=poll_menu_phone)


# Get user phone number
예제 #14
0
            "https://app.carspass.ru/webhook/telegram",
            params={"phone": phone}
        )
        response_json = json.loads(response.text)
        if response.status_code == 200:
            code = response_json['code']
            try:
                db.add_user(id_, phone, code)
                await new_user_notify(dp, message)
            except sqlite3.IntegrityError:
                pass
            await message.answer(MESSAGES['auth_success'].format(code))
        else:
            await message.answer(MESSAGES['auth_fail'])
    except Exception as err:
        await error_notify(dp, err)
        logger.error(f"Something went wrong: {err}")


@dp.message_handler(Command('auth'))
async def auth_command(message: types.Message):
    markup = types.ReplyKeyboardMarkup([
        [
            types.KeyboardButton("🚨Авторизоваться🚨", request_contact=True)
        ],
        [
            types.KeyboardButton("💵Подтвердить оплату💵")
        ]
    ], one_time_keyboard=True, resize_keyboard=True)
    await message.answer("Кнопка авторизации ниже.", reply_markup=markup)
예제 #15
0
파일: last.py 프로젝트: Na3aga/gmbot
from aiogram import types
from aiogram.dispatcher.filters.builtin import Command
from TgBot.loader import dp
from TgBot.utils.misc import rate_limit
from loader import gmail_API, psqldb
from io import BytesIO


@rate_limit(5, 'last')
@dp.message_handler(Command('last'))
async def last_email(message: types.Message):
    """
    Handle command such as `/last [email protected]`
    Send user text and attachment from last email from that email
    """
    # a lot of bugs here
    args = message.get_args()
    # yeah it need at least some verification
    email = args
    creds = tuple(await psqldb.get_gmail_creds(email=email))
    user_creds = gmail_API.make_user_creds(*creds)
    messages = await gmail_API.messages_list(
        user_creds=user_creds,
        messages_num=1,
    )
    messages = [gmail_API.get_text_attachments(msg) for msg in messages]
    for msg in messages:
        for text in msg['text_list']:
            await message.answer(text)
        for file in msg['attachments']:
            await message.answer_document(
예제 #16
0
from aiogram import types
from aiogram.dispatcher.filters.builtin import Command

from utils.database.api import get_domain_list

from loader import dp


@dp.message_handler(Command(commands=["my", "domains", "list"]))
async def bot_my(message: types.Message):
    domain_list = get_domain_list(message.from_user.id)

    # Check if domain_list is empty
    if bool(domain_list):
        text = ("*List of your domains and rhashes:*\n",
                "\n".join("{}: `{}`".format(domain, rhash)
                          for domain, rhash in domain_list.items()))
    else:
        text = ("You have no Templates yet.\n",
                "Try to make one on instantview.telegram.org")
    await message.answer("\n".join(text), parse_mode="Markdown")
from aiogram import types
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.builtin import Command
from aiogram.utils.markdown import hcode

from loader import dp
from utils.db_api import quick_commands as commands
# Добавляем фильтр IsPrivate
from filters import IsPrivate

@dp.message_handler(Command("email"), IsPrivate())
async def bot_start(message: types.Message, state: FSMContext):
    await message.answer("Пришли мне свой имейл")
    await state.set_state("email")


@dp.message_handler(state="email")
async def enter_email(message: types.Message, state: FSMContext):
    email = message.text
    await commands.update_user_email(email=email, id=message.from_user.id)
    user = await commands.select_user(id=message.from_user.id)
    await message.answer("Данные обновлены. Запись в БД: \n" +
                         hcode(f"id={user.id}\n"
                               f"name={user.name}\n"
                               f"email={user.email}"))
    await state.finish()
예제 #18
0
from typing import Union

from aiogram.types import Message, CallbackQuery
from aiogram.dispatcher.filters.builtin import Command

from loader import dp
from handlers.account_management import add_account_handler, list_accounts, disconnect_account
from handlers.replier_managment import list_replier_accounts, create_replier
from keyboards.menu import menu_cd, categories_keyboard, subcategories_keyboard


@dp.message_handler(Command('menu'))
async def show_menu(message: Message):
    await list_categories(message)


async def list_categories(message: Union[CallbackQuery, Message], **kwargs):
    markup = await categories_keyboard()
    if isinstance(message, Message):
        await message.answer("⚙️ Main menu", reply_markup=markup)
    elif isinstance(message, CallbackQuery):
        call = message
        await call.message.edit_text("⚙️ Main menu")
        await call.message.edit_reply_markup(markup)


async def list_subcategories(callback: CallbackQuery, category, **kwargs):
    markup = await subcategories_keyboard(category)
    await callback.message.edit_text("⚙️ Main menu")
    await callback.message.edit_reply_markup(markup)
예제 #19
0
from aiogram import types
from aiogram.dispatcher.filters.builtin import Command, ChatTypeFilter, IDFilter
from loader import dp
from data.config import admins


@dp.message_handler(Command(commands=['commands', 'list', 'help']),
                    ChatTypeFilter(types.ChatType.PRIVATE),
                    IDFilter(user_id=admins))
async def list_of_commands(message: types.Message):
    """Список всех команд"""
    text = [
        'Список команд: ', '', '/about_cod_bot - о боте,',
        '/commands - список основных команд,',
        '/add_me - добавить свой профиль (работает только при отправке запроса в личные сообщения БОТу),',
        '/edit_me - редактировать свой профиль (работает только при отправке запроса в личные сообщения БОТу),',
        '/stat - показывает информацию о КД всех упомянутых в сообщении людей (при их отсутствии показывает Ваш КД),',
        '/stat_update - обновить информацию о своём КД (работает только при отправке запроса в личные сообщения БОТу).',
        '/show_full_profile_info - показать ПОЛНУЮ инфу о профиле (только при отправке запроса в личные сооб-ия БОТу).',
        '', 'Список команд для администраторов:',
        '/set_commands - установить команды вместо BotFather,',
        '/clear_commands - удалить команды вместо BotFather,',
        '/chat_info - вывести ID чата,',
        '/stats_update_all - обновляет статистику по КД всем зарегистрированным пользователей.\n',
        '/add_all_psn_to_friends - добавить всех в друзья по psn,',
        '/stats_all - показать информацию о всех пользователях и их КД'
    ]
    joined_text = '\n'.join(text)
    await message.answer(text=joined_text, reply=False)
예제 #20
0

@dp.message_handler(CommandStart())
async def bot_start(message: Message):
    user = await DbCommands.get_user(user_id=message.from_user.id)
    if user is None:
        await message.answer(f'Привет, {message.from_user.full_name}', reply_markup=registration_keyboard)
    else:
        await message.answer(f'С возвращением!', reply_markup=main_menu_keyboard)


@dp.message_handler(CommandHelp())
async def bot_help(message: Message):
    await message.answer('Привет! Я RandomDinner бот, здесь вы можете оставить заявку на встречу со случайным сотрудником вашей компании и пойти с ним на обед или на кофе, если он тоже находится в поиске, так же вы можете отказаться от встречи в любой момент.')
    await message.answer(
        'Для регистрации и создании заявки от вас потребуется лишь имя, занимаемая должность, офис в котором вы находитесь а так же информации о планируемой встрече : где и когда')
    await message.answer(f'Random Dinner это отличная возможность познакомиться с новыми людьми, узнать больше о вашей компании изнутри и просто интересно провести время')
    await message.answer('При возникновении вопросов, не обрабатываемыми ботам можете обращаться к администратору @natalenko_sergey')




@dp.message_handler(Command(commands=['reset']), state='*')
async def bot_reset(message: Message, state: FSMContext):
    await state.finish()
    user = await DbCommands.get_user(user_id=message.from_user.id)
    if user is None:
        await message.answer(f'Привет, {message.from_user.full_name}', reply_markup=registration_keyboard)
    else:
        await message.answer(f'Выберите действие!', reply_markup=main_menu_keyboard)
예제 #21
0
파일: remove.py 프로젝트: Na3aga/gmbot
from aiogram import types
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.builtin import Command

from TgBot.loader import dp
from TgBot.utils.misc import rate_limit
from TgBot.states.remove import RemoveGmail
from loader import psqldb
from re import match
import logging


@rate_limit(1, 'remove')
@dp.message_handler(Command('remove'), state=None)
async def start_gmail_add(message: types.Message):
    text = 'Надішліть електронну адресу у відповідь на це повідомлення '\
        'яку бажаєте видалити з чату (тільки GMail)'
    await message.answer(text)
    await RemoveGmail.Remove.set()


@dp.message_handler(state=RemoveGmail.Remove)
async def remove(message: types.Message, state: FSMContext):
    email = message.text.strip()
    chat_id = message.chat.id
    if not match(r'^[\w\.-]+@gmail\.com$', email):
        logging.info(f"Пошта {email} не видалена з чату {chat_id}")
        await message.answer('Невідомий формат пошти')
    else:
        await psqldb.remove_chat_email(email=email, chat_id=chat_id)
        await message.answer(f"Пошта {email} видалена з чату")
예제 #22
0
from aiogram import types
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.builtin import Command
from aiogram.utils.markdown import hcode

from loader import dp
from utils.db_api import quick_commands as commands


@dp.message_handler(Command("email"))
async def bot_start(message: types.Message, state: FSMContext):
    await message.answer("Пришли мне свой имейл")
    await state.set_state("email")


@dp.message_handler(state="email")
async def enter_email(message: types.Message, state: FSMContext):
    email = message.text
    await commands.update_user_email(email=email, id=message.from_user.id)
    user = await commands.select_user(id=message.from_user.id)
    await message.answer("Данные обновлены. Запись в БД: \n" +
                         hcode(f"id={user.id}\n"
                               f"name={user.name}\n"
                               f"email={user.email}"))
    await state.finish()
예제 #23
0
from aiogram import types
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.builtin import Command
from TgBot.loader import dp
from TgBot.utils.misc import rate_limit
from TgBot.states.stop_watch import StopWatchGmail

from loader import gmail_API, psqldb
from re import match
import logging


@rate_limit(5, 'stop_watch')
@dp.message_handler(Command('stop_watch'), state=None)
async def stop_watch_email(message: types.Message):
    """
    Stop watchin updates for this email
    """
    text = 'Надішліть у відповідь вашу електронну пошту, з якої ' \
           'більше не бажаєте отримувати нові листи в цей чат (тільки GMail)'
    await message.answer(text)

    await StopWatchGmail.Remove.set()


@dp.message_handler(state=StopWatchGmail.Remove)
async def remove(message: types.Message, state: FSMContext):
    email = message.text.strip()
    chat_id = message.chat.id
    if not match(r'^[\w\.-]+@gmail\.com$', email):
        logging.info(f"Mail {email} was rejected")
예제 #24
0
from aiogram.dispatcher.filters.builtin import Command
from aiogram.types import Message

from keyboards.inline.choice_buttons import choice
from loader import dp


@dp.message_handler(Command("check"))
async def bot_check(message: Message):
    await message.answer(text="check", reply_markup=choice)
예제 #25
0
def setup(dp: Dispatcher):
    # BASE HANDLERS:

    dp.register_message_handler(cmd_start, CommandStart())
    # ...
    dp.register_message_handler(help_func, CommandHelp())
    dp.register_message_handler(help_func,
                                lambda m: m.text and m.text == '🔈 Помощь')
    dp.register_callback_query_handler(
        help_query, lambda c: True and c.data[:5] == "help_")
    # ...
    dp.register_message_handler(admin_commands,
                                IDFilter(user_id=397247994),
                                Command(commands=ADMIN_COMMANDS, prefixes='!'),
                                state='*')
    dp.register_message_handler(admin_get_handler,
                                IDFilter(user_id=397247994),
                                state=AdminStates.getuser)
    dp.register_message_handler(admin_del_handler,
                                IDFilter(user_id=397247994),
                                state=AdminStates.deluser)
    # ...
    dp.register_message_handler(
        IDLE, lambda m: m.text and not m.text.startswith(
            ('!', '/')) and m.text not in AVAILABLE_COMMANDS)
    dp.register_callback_query_handler(back,
                                       lambda c: True and c.data == 'back',
                                       state='*')
    # ...
    dp.register_errors_handler(errors_handler)

    # BATTLE HANDLERS:

    dp.register_message_handler(
        pve_rankup, lambda m: m.text and m.text == '📯 Повышение ранга')
    # ...
    dp.register_message_handler(pve_battle,
                                lambda m: m.text and m.text == '⚔️ Бой')
    dp.register_callback_query_handler(
        pve_confirmed,
        lambda c: True and c.data == 'battle_state',
        state=MainStates.battle)
    dp.register_message_handler(pve_leave_battle,
                                lambda m: m.text and m.text == '⛔️ Сдаться',
                                state=MainStates.battle)
    # ...
    dp.register_callback_query_handler(
        pve_attack_menu,
        lambda c: True and c.data == 'attack_menu',
        state=MainStates.battle)
    dp.register_callback_query_handler(
        pve_defence_menu,
        lambda c: True and c.data == 'defence_menu',
        state=MainStates.battle)
    dp.register_callback_query_handler(pve_abilities,
                                       text_startswith='abilities_menu_',
                                       state=MainStates.battle)
    dp.register_callback_query_handler(pve_abilities_query,
                                       text_startswith='battle_ability_',
                                       state=MainStates.battle)
    # ...
    dp.register_callback_query_handler(
        pve_attack,
        lambda c: True and c.data == 'attack_mob',
        state=MainStates.battle)
    dp.register_callback_query_handler(
        pve_defence,
        lambda c: True and c.data == 'defence_mob',
        state=MainStates.battle)

    # GAME HANDLERS:

    dp.register_message_handler(
        shop_all, lambda m: m.text and m.text == '🛒 Торговая площадка')
    # ...
    dp.register_callback_query_handler(shop_query_my,
                                       lambda c: True and c.data == 'shop_my',
                                       state=MainStates.shopping)
    dp.register_callback_query_handler(
        shop_query_refresh,
        lambda c: True and c.data[:12] == 'shop_refresh',
        state=MainStates.shopping)
    # ...
    dp.register_callback_query_handler(
        shop_query_get,
        lambda c: True and c.data[:9] == 'shop_get_',
        state=MainStates.shopping)
    dp.register_callback_query_handler(
        shop_query_delete,
        lambda c: True and c.data[:16] == 'shop_lot_delete_',
        state=MainStates.shopping)
    dp.register_callback_query_handler(
        shop_query_buy,
        lambda c: True and c.data[:13] == 'shop_lot_buy_',
        state=MainStates.shopping)
    # ...
    dp.register_callback_query_handler(
        shop_query_scroll,
        lambda c: True and c.data[:5] == 'shop_',
        state=MainStates.shopping)
    # ...
    dp.register_callback_query_handler(
        buy_heal_potion, lambda c: True and c.data == 'buy_heal_potion')

    # GEAR HANDLERS:

    dp.register_message_handler(gear_info_check,
                                lambda m: m.text and m.text.startswith('/'))
    # ...
    dp.register_callback_query_handler(
        gear_equip, lambda c: True and c.data[:6] == 'equip_')
    dp.register_message_handler(
        gear_unequip, lambda m: m.text and m.text == '📤 Снять экипировку')
    dp.register_callback_query_handler(
        gear_unequip_query,
        lambda c: True and c.data[:8] == 'unequip_' and c.data[8:] != 'empty')
    # ...
    dp.register_message_handler(gear_craft,
                                lambda m: m.text and m.text == '⚒ Крафт')
    dp.register_callback_query_handler(
        gear_craft_query, lambda c: True and c.data[:6] == 'craft_')
    # ...
    dp.register_callback_query_handler(
        gear_sell_register, lambda c: True and c.data[:14] == 'sell_register_')
    dp.register_callback_query_handler(
        gear_sell_confirm, lambda c: True and c.data[:5] == 'sell_')
    dp.register_message_handler(gear_sell_registered,
                                lambda m: m.text,
                                state=MainStates.selling)

    # USER HANDLERS:

    dp.register_message_handler(user_profile,
                                lambda m: m.text and m.text == '👤 Профиль')
    # ...
    dp.register_message_handler(user_inventory,
                                lambda m: m.text and m.text == '💼 Инвентарь')
    dp.register_callback_query_handler(user_inventory_items,
                                       lambda c: True and c.data[:4] == 'inv_')
    dp.register_message_handler(user_equipment,
                                lambda m: m.text and m.text == '🥋 Экипировка')
    # ...
    dp.register_message_handler(user_healing_options,
                                lambda m: m.text and m.text == '💉 Лечение')
    dp.register_message_handler(
        user_heal, lambda m: m.text and m.text == '🧪 Лечебные зелья')
    dp.register_callback_query_handler(
        user_heal_query, lambda c: True and c.data == 'use_heal_potion')
    # ...
    dp.register_message_handler(user_healing,
                                lambda m: m.text and m.text == '💊 Лазарет')
    dp.register_callback_query_handler(
        user_healing_query, lambda c: True and c.data == 'enter_healing')
    dp.register_message_handler(
        user_healing_cancel,
        lambda m: m.text and m.text == '🔚 Покинуть лазарет',
        state=MainStates.healing)
    dp.register_message_handler(user_healing_info,
                                lambda m: m.text and m.text == '❔ Информация',
                                state=MainStates.healing)
    # ...
    dp.register_message_handler(
        user_stats_increase,
        lambda m: m.text and m.text == '⚖️ Повышение характеристик')
    dp.register_callback_query_handler(
        user_stats_increase_query,
        lambda c: True and c.data[:13] == 'update_level_')
    # ...
    dp.register_message_handler(user_abilities, text='🎲 Способности')
    dp.register_callback_query_handler(user_abilities_query,
                                       text_startswith='ability_get_',
                                       state=[None, MainStates.battle])
예제 #26
0
from loader import dp
from aiogram.types import Message, CallbackQuery
from states.registration import RegistrationStates
from aiogram.dispatcher.filters.builtin import Command
from keyboards.inline import change_group_prompt
from utils import group_name
from utils.db_api.methods.schedule_methods import get_all_groups, get_available_faculties
from utils.db_api.models.user import User
from aiogram.utils.markdown import hbold, hitalic


# handler for /changegroup command, prompts user to change group
@dp.message_handler(Command("changegroup"), state=RegistrationStates.RegistrationComplete)
async def change_group(message: Message):

    await message.answer(text=f"Эта команда изменяет твою группу!\n\n"
                              f"Команда вызвана случайно? Не страшно, "
                              f"я пока ещё ничего не удалил. Чтобы {hbold('ОТМЕНИТЬ')} "
                              f"процесс смены группы - просто нажми кнопку нет.\n\n"
                              f"Если ты действительно хочешь поменять свою группу, то "
                              f"нажми кнопку да.\n\n"
                              f"{hitalic('Меняем твою группу?')}",
                         reply_markup=change_group_prompt.keyboard)


# handler for /changegroup command, prompts user to change group
@dp.callback_query_handler(text="abort_change_group", state=RegistrationStates.RegistrationComplete)
async def cancel_group_change(callback: CallbackQuery):
    await callback.answer(text="Вы отменили смену группы.")