Exemplo n.º 1
0
def register_common(dp: Dispatcher):
    dp.register_message_handler(cmd_start, commands=["start", "help"])
    dp.register_message_handler(
        cancel_state,
        state='*',
        commands=["cancel"],
    )
    dp.register_message_handler(
        cancel_state,
        filters.Text(equals='cancel', ignore_case=True),
        state='*',
    )
    dp.register_errors_handler(errors_handler)
from aiogram import types
from aiogram.dispatcher import filters

from app.misc import dp, bot
from app.states.state_fridge_product import FridgeProductState
from app.states.state_shop_list_product import ShopListProductState


@dp.callback_query_handler(filters.Text('add_product_typing_[\'fridge\']'))
async def add_product_typing_fridge_handler(query: types.CallbackQuery):
    await FridgeProductState.name.set()
    await bot.send_message(query.message.chat.id, "Введите название продукта:")
    await query.answer()

@dp.callback_query_handler(filters.Text('add_product_typing_[\'shopping_list\']'))
async def add_product_typing_shoplist_handler(query: types.CallbackQuery):
    await ShopListProductState.name.set()
    await bot.send_message(query.message.chat.id, "Введите название продукта:")
    await query.answer()

Exemplo n.º 3
0
from aiogram import types
from aiogram.dispatcher import filters, FSMContext
from config import ADMIN_ID
from misc import dp, bot
from styles import keyboards
from aiogram.dispatcher.filters.state import State, StatesGroup


class FeedbackInfo(StatesGroup):
    INFORMATION = State()
    FINISH = State()


# Обработка начала подачи жалобы
@dp.message_handler(filters.Text(equals='Обратная связь'))
@dp.message_handler(commands=['feedback'])
async def cmd_create_report(message: types.Message):
    await FeedbackInfo.INFORMATION.set()
    await message.answer(
        'Опишите свой опыт использования бота в одном сообщении',
        reply_markup=keyboards.system_button1)


# Отмена заполнения и возвращение в главное меню
@dp.message_handler(state='*', commands='cancel')
@dp.message_handler(filters.Text(equals='Отмена', ignore_case=True), state='*')
async def cancel_handler(message: types.Message, state: FSMContext):

    await state.finish()
    await message.reply('Возвращаемся в главное меню',
                        reply_markup=keyboards.menu_button)
Exemplo n.º 4
0
    current_state = await state.get_state()
    if current_state is None:
        return

    async with state.proxy() as data:
        try:
            if data['qr']:
                remove(data['qr'])
        except:
            pass

    await state.finish()
    await message.answer('Отменено.')


@dp.message_handler(filters.Text(equals="Распознать QR"), state="*")
@dp.message_handler(commands=["qr"])
async def qrCallingHandler(message: Message, state: FSMContext):
    current_state = await state.get_state()
    if current_state is not None:
        return

    markup = getDefaultReplyKeyboard()

    await QrFSM.qrInput.set()
    await message.answer("Отправьте QR-код, который хотите распознать",
                         reply_markup=markup)


@dp.message_handler(content_types=['photo'], state=QrFSM.qrInput)
async def qrCodeAcceptor(message: Message, state: FSMContext):
Exemplo n.º 5
0
                                 reply_markup=awaitingKeyboard,
                                 thumb_url=foxLogoPreview,
                                 input_message_content=InputTextMessageContent(
                                     f"Таймер на {secCount} сек."))
    ]
    if not isWrong:
        await bot.answer_inline_query(inline_query.id,
                                      results=items,
                                      cache_time=0)


doingTimersFrom = []
doingTimersFrom.clear()


@dp.callback_query_handler(filters.Text(equals="stopTimer"))
@dp.inline_handler(
    lambda inline_query: re.search(r'(?i)stop\s+timer', inline_query.query))
async def some_callback_handler(inline_query: InlineQuery = None,
                                callback_query: CallbackQuery = None):
    userId = inline_query.from_user.id

    if callback_query:
        doingTimersFrom.remove(userId)
        return

    if userId in doingTimersFrom:
        doingTimersFrom.remove(userId)

        items = [
            InlineQueryResultArticle(
Exemplo n.º 6
0
	current_state = await state.get_state()
	if current_state is None:
		return

	async with state.proxy() as data:
		try:
			if data['pic']:
				remove(data['pic'])
		except:
			pass

	await state.finish()
	await message.answer('Отменено.')


@dp.message_handler(filters.Text(equals="Демотиватор"), state="*")
@dp.message_handler(filters.RegexpCommandsFilter(regexp_commands=[r'(?i)demotivator|demo|демо|демотиватор$']), state="*")
async def demoCallingHandler(message: Message, state: FSMContext):
	current_state = await state.get_state()
	if current_state is not None:
		return

	markup = getDefaultReplyKeyboard()

	await DemoFSM.pic.set()
	await message.answer("Отправь картинку, которую хотел бы видеть в демотиваторе", reply_markup=markup)


@dp.message_handler(content_types=['photo'], state=DemoFSM.pic)
async def picDemoHandler(message: Message, state: FSMContext):
	async with state.proxy() as data:
Exemplo n.º 7
0
                   ["Случайный демотиватор", "randomDemotivator"],
                   ["Распознавание QR-кода", "QRdecode"],
                   ["Ничего", "nothing"]]

    translated = [
        options[(options.index(option) + 1) % 2] for options in optionsList
        if option in options
    ]

    return translated[0]


# ----------- HANDLERS -------------------------------------------------------------------------------------------------


@dp.callback_query_handler(filters.Text(equals="close"))
async def closeSettingsMessageCallbackHandler(callback_query: CallbackQuery):
    try:
        await dp.bot.delete_message(
            chat_id=callback_query.message.chat.id,
            message_id=callback_query.message.message_id)
    except aiogram.utils.exceptions.MessageCantBeDeleted:
        await callback_query.answer('Это сообщение уже нельзя удалить')


@dp.message_handler(filters.Text(equals="Настρойки"), state=None)
@dp.message_handler(commands=["settings"])
async def settingsCallingHandler(message: Message,
                                 isBack: bool = False,
                                 userID: int = None):
    """Основное меню настроек"""
Exemplo n.º 8
0
from aiogram import types
from misc import dp
from styles import keyboards
from aiogram.dispatcher import filters

from config import PRIVACY, COMMAND_LIST, ABOUT_MESSAGE, HELP_MESSAGE


# Главное меню
@dp.message_handler(filters.Text(equals="Отмена"))
@dp.message_handler(commands=['start'])
async def cmd_start(message=types.Message):
    await message.answer(
        'Здравствуйте! Для подачи жалобы нажмите кнопку в меню\n\nПеред началом работы '
        'рекомендуем ознакомиться с /help, /privacy, /about',
        reply_markup=keyboards.menu_button)


# Помощь: Выводит словарь COMMAND_LIST
@dp.message_handler(commands=['help'])
async def cmd_start(message=types.Message):
    command_list_message = ''
    for command_name in COMMAND_LIST:
        command_list_message += command_name + ' — ' + COMMAND_LIST[
            command_name] + '\n'
    await message.answer(HELP_MESSAGE + '\n\n' + command_list_message,
                         reply_markup=keyboards.menu_button)


# Политика конфидициальности
@dp.message_handler(filters.Text(equals="Политика конфидициальности"))
Exemplo n.º 9
0
)
@handle_product_params
async def add_bookmark(
    callback_query: types.CallbackQuery,
    *,
    state: FSMContext,
    handled_params: tuple,
    locale: str,
    regexp: Match,
    **kwargs,
) -> None:
    try:
        await dp.throttle(regexp.string, rate=30)
    except Throttled:
        await callback_query.answer(_("Please try again in a minute."))
    else:
        bookmark = await get_bookmark_answer(state, locale, *handled_params)
        await callback_query.message.reply(
            await bookmark.get_caption(),
            parse_mode=types.ParseMode.MARKDOWN,
            disable_web_page_preview=True,
            reply_markup=bookmark.make_keyboard(),
        )
        await callback_query.answer()


@dp.callback_query_handler(filters.Text("bookmark:delete"), state=any_state)
async def delete_bookmark(callback_query: types.CallbackQuery) -> None:
    await callback_query.message.delete()
    await callback_query.answer()
Exemplo n.º 10
0
from aiogram.utils import executor
from aiogram.types import ChatActions
from dotenv import load_dotenv
from keyboard import Keyboard
from htmltopic import get_picture
import excel

load_dotenv()
BOT_TOKEN = os.getenv('BOT_TOKEN')

bot = Bot(token=BOT_TOKEN)
dp = Dispatcher(bot)


@dp.message_handler(commands=['start'])
@dp.message_handler(filters.Text(contains='Вернуться'))
async def process_start_command(message: types.Message):
    excel.check_file_update()
    user_id = message.from_user.id
    if user_id not in excel.user_xls_association:
        excel.user_xls_file.append(excel.excelFile())
        excel.user_xls_association.update([(user_id,
                                            len(excel.user_xls_file) - 1)])
    else:
        excel.user_xls_file[
            excel.user_xls_association[user_id]] = excel.excelFile()
    message_ = 'Чтобы получить расписание выбери курс'
    await message.reply(message_, reply_markup=Keyboard(excel\
        .get_sheetnames(excel.user_xls_file[excel.user_xls_association[user_id]])).get_buttons())
    print(excel.user_xls_association)
Exemplo n.º 11
0
from aiogram.dispatcher.filters.state import State, StatesGroup
from handlers.requests import get_address_from_coords

class ReportInfo(StatesGroup):
    CATEGORY = State()
    TITLE = State()
    DISCRIPTION = State()
    LOCATION = State()
    PHOTO = State()
    FINISH = State()

INFO_MESSAGE = 'Бот находится в стадии тестирования. Мы будем рады, если в конце вы оставите обратную связь\n\n'
INFO_MESSAGE2 = 'Спасибо за использование бота! Сейчас он активно тестируется, поэтому будем рады обратной связи\n\n'

# Обработка начала подачи жалобы
@dp.message_handler(filters.Text(equals = 'Создать жалобу️️'))
@dp.message_handler(commands=['create_report'])
async def cmd_create_report(message: types.Message):
    await ReportInfo.CATEGORY.set()
    await message.answer(INFO_MESSAGE)
    await bot.send_message(ADMIN_ID, 'Внимание, кто-то начал создавать жалобу')
    print('[Начало подачи жалобы] Дата создания: ' + str(message.date))
    await message.answer('Выберите категорию:', reply_markup=keyboards.categories_button)

# Отмена заполнения и возвращение в главное меню
@dp.message_handler(state='*', commands='cancel')
@dp.message_handler(filters.Text(equals='Отмена', ignore_case=True), state='*')
async def cancel_handler(message: types.Message, state: FSMContext):

    await state.finish()
    await message.reply('Вернитесь, когда понадобится', reply_markup = keyboards.menu_button)
Exemplo n.º 12
0
from ..bot import _, dp, settings  # type: ignore
from ..keyboards import PRIME_KEYBOARD_TEXTS, prime_keyboard
from ..states import ProductFiltersForm
from .common import answer_next_filter_or_results


@dp.message_handler(commands=["start"], state=any_state)
async def process_start_command(message: types.Message) -> None:
    text = Template(texts.START.value).substitute(
        first_name=message.from_user.first_name,
        bot_mention=(await message.bot.me).mention,
    )
    await message.answer(text, reply_markup=prime_keyboard)


@dp.message_handler(filters.Text(PRIME_KEYBOARD_TEXTS["help"]))
@dp.message_handler(commands=["help"], state=any_state)
async def process_help_command(message: types.Message) -> None:
    await message.answer(texts.HELP)


@dp.message_handler(filters.Text(PRIME_KEYBOARD_TEXTS["contacts"]))
@dp.message_handler(commands=["contacts"], state=any_state)
async def process_contacts_command(message: types.Message) -> None:
    text = Template(texts.CONTACTS.value).substitute(
        phones="\n".join(settings.CONTACT_PHONES),
        emails="\n".join(settings.CONTACT_EMAILS),
    )
    await message.answer(emojize(text), parse_mode=ParseMode.MARKDOWN)

Exemplo n.º 13
0
import logging

from aiogram import types
from aiogram.dispatcher import FSMContext, filters

from ..bot import dp, settings  # type: ignore
from ..states import ProductFiltersForm
from ..utils import handle_regex_params
from .common import answer_next_filter_or_results

logger = logging.getLogger(__name__)


@dp.callback_query_handler(filters.Text("filter:skip"),
                           state=ProductFiltersForm.all_states)
async def process_filter_skip(callback_query: types.CallbackQuery,
                              state: FSMContext, locale: str) -> None:
    next_filter = await ProductFiltersForm.next()
    await answer_next_filter_or_results(callback_query.message, state, locale,
                                        next_filter)
    await callback_query.answer()


@dp.callback_query_handler(filters.Text(r"filter:skip_all"),
                           state=ProductFiltersForm.all_states)
async def process_filter_skip_all(callback_query: types.CallbackQuery,
                                  state: FSMContext, locale: str) -> None:
    # None state finishes the filtering
    await answer_next_filter_or_results(callback_query.message, state, locale,
                                        None)
    await callback_query.answer()
Exemplo n.º 14
0
import re

from aiogram import types
from aiogram.dispatcher import filters, FSMContext

from app.misc import dp, bot
from app.states import FridgeProductState
from app.states.state_fridge_add_photo import FridgeAddPhotoState, FridgeAddPhotoCheckState
from app.states.state_shop_list_product import ShopListProductState
from app.states.state_shop_list_add_photo import ShoppingAddPhotoState, ShoppingAddPhotoCheckState
from app.keyboards.inline.add_product_method_photo import AddProductMethodChoice


@dp.callback_query_handler(filters.Text('add_product_photo_choice_[\'fridge\']'))
async def add_product_photo_choice_fridge_handler(query: types.CallbackQuery):
    info = re.findall(r'(fridge|shopping_list)', query.data)
    await bot.send_message(query.from_user.id,
                           "Что вы хотите сфотографировать?",
                           reply_markup=AddProductMethodChoice.create(info, query.message.message_id))
    await query.answer()


@dp.callback_query_handler(filters.Text('add_product_photo_choice_[\'shopping_list\']'))
async def add_product_photo_choice_shoplist_handler(query: types.CallbackQuery):
    info = re.findall(r'(fridge|shopping_list)', query.data)
    await bot.send_message(query.from_user.id,
                           "Что вы хотите сфотографировать?",
                           reply_markup=AddProductMethodChoice.create(info, query.message.message_id))
    await query.answer()