Exemple #1
0
async def add_handlers(dispatcher):
    from aiogram import (
        filters,
        types,
    )
    from aiogram.utils.markdown import escape_md
    from matebot.aio_matebot.controllers.callbacks import (
        command_callback,
        message_callback,
    )
    from matebot.plugins.personalidades import (
        gerar_texto, )

    ## Padrão de boas vindas. Exclui grupos 'omega' pra evitar de mandar mensagem
    ## de boas vindas em grupos onde o bot só é utilizado com os comandos básicos.
    ## Requer que grupos que queiram ativar o plugin de boas vindas sejam
    ## adicionados pelo menos às listas 'delta' ou 'gama'.
    @dispatcher.message_handler(
        filters.IDFilter(chat_id=dispatcher.bot.users.get('delta', -1) +
                         dispatcher.bot.users.get('gamma', -1), ),
        content_types=types.ContentTypes.NEW_CHAT_MEMBERS,
    )
    async def welcome_callback(message: types.Message):
        await message_callback(message, ['welcome', message.chat.type])
        text = await gerar_texto('welcome', dispatcher.bot, message)
        command = await message.reply(text)
        await command_callback(command, ['welcome', message.chat.type])
Exemple #2
0
def register_handlers(dp: Dispatcher):
    dp.register_message_handler(
        admin.send_message,
        filters.IDFilter(user_id=BotConfig.ADMINS),
        commands=["send"],
    )
    dp.register_message_handler(
        admin.ask_for_feedback,
        filters.IDFilter(user_id=BotConfig.ADMINS),
        commands=["feedback"],
    )
    dp.register_message_handler(
        admin.send_push,
        filters.IDFilter(user_id=BotConfig.ADMINS),
        commands=["push"],
    )
    dp.register_message_handler(
        matcher.randomize,
        filters.IDFilter(user_id=BotConfig.ADMINS),
        commands=["roll"],
    )

    dp.register_message_handler(extra.contact, commands=["contact"])
    dp.register_message_handler(extra.change_status, commands=["status"])
    dp.register_message_handler(extra.change_payment, commands=["payment"])

    dp.register_message_handler(registration.cmd_start,
                                commands=["start", "settings"])
    dp.register_message_handler(registration.cmd_text_go,
                                state=RegisterSteps.go)
    dp.register_message_handler(registration.stage_name,
                                state=RegisterSteps.name)
    dp.register_message_handler(registration.stage_graduate,
                                state=RegisterSteps.is_graduate)
    dp.register_message_handler(registration.stage_university,
                                state=RegisterSteps.university)
    dp.register_message_handler(registration.stage_grad_year,
                                state=RegisterSteps.grad_year)
    dp.register_message_handler(registration.stage_payment,
                                state=RegisterSteps.payment)
    dp.register_message_handler(registration.stage_active,
                                state=RegisterSteps.active)
Exemple #3
0
 def __init__(self,
              token,
              user_id,
              callbacks: dict[str, collections.abc.Callable] = None):
     self.__token = token
     self.user_id = user_id
     self.api = Bot(token=self.__token)
     self.__dp = Dispatcher(self.api)
     self.__callbacks = callbacks if callbacks is not None else {}
     self.__callbacks['ping'] = self.__on_ping
     self.__dp.register_message_handler(self.__on_command,
                                        filters.IDFilter(self.user_id),
                                        commands=self.__callbacks.keys())
Exemple #4
0
async def add_handlers(dispatcher):
    from aiogram import (
        filters, )
    from matebot.aio_matebot.controllers.callbacks import (
        command_callback,
        message_callback,
    )

    ## Testar o bot. Ecoa o texto enviado ou produz um erro se não tiver nenhum \
    ##  argumento.
    @dispatcher.message_handler(
        filters.IDFilter(
            user_id=dispatcher.bot.users['alpha'] +
            dispatcher.bot.users['beta'],
            chat_id=dispatcher.bot.users['alpha'] +
            dispatcher.bot.users['beta'],
        ),
        commands=['teste', 'test'],
    )
    async def test_callback(message):
        await message_callback(message, ['test', message.chat.type])
        command = await message.reply(message.get_args())
        await command_callback(command, ['test', message.chat.type])

    ## Enviar mensagem para alguém através do bot
    @dispatcher.message_handler(filters.IDFilter(
        user_id=dispatcher.bot.users['alpha'] + dispatcher.bot.users['beta'],
        chat_id=dispatcher.bot.users['alpha'] + dispatcher.bot.users['beta'],
    ),
                                commands=['enviar', 'send'])
    async def send_callback(message):
        await message_callback(message, ['send', message.chat.type])
        args = message.get_args().split(' ')
        command = await dispatcher.bot.send_message(
            chat_id=args[0],
            text=' '.join(args[1::1]),
        )
        await command_callback(command, ['send', message.chat.type])

    ## Responder uma mensagem através do bot
    @dispatcher.message_handler(filters.IDFilter(
        user_id=dispatcher.bot.users['alpha'] + dispatcher.bot.users['beta'],
        chat_id=dispatcher.bot.users['alpha'] + dispatcher.bot.users['beta'],
    ),
                                commands=['responder', 'reply'])
    async def reply_callback(message):
        await message_callback(message, ['reply', message.chat.type])
        args = message.get_args().split(' ')
        command = await dispatcher.bot.send_message(
            chat_id=str(args[0]),
            text=' '.join(args[2::1]),
            reply_to_message_id=int(args[1]),
        )
        await command_callback(command, ['reply', message.chat.type])

    ## Lista de comandos reservados para dev/admin
    @dispatcher.message_handler(
        filters.IDFilter(
            user_id=dispatcher.bot.users['alpha'] +
            dispatcher.bot.users['beta'],
            chat_id=dispatcher.bot.users['alpha'] +
            dispatcher.bot.users['beta'],
        ),
        commands=['admin'],
    )
    async def admin_callback(message):
        await message_callback(message, ['admin', message.chat.type])
        lista = list()
        lista.append(u"""/enviar <chat_id> <texto>: Enviar "texto" para \
"chat_id".""")
        lista.append(u"""/responder <chat_id> <message_id> <texto>: Responder \
"message_id" em "chat_id" com "texto".""")
        lista.append(u"""/tz: Teste de timezone do servidor.""")
        command = await message.reply(
            u"Lista de comandos reservados para dev/admin:\n{lista}".format(
                lista="\n".join(lista), ))
        await command_callback(command, ['admin', message.chat.type])

    ## Teste de timezone do servidor
    @dispatcher.message_handler(
        filters.IDFilter(
            user_id=dispatcher.bot.users['alpha'] +
            dispatcher.bot.users['beta'],
            chat_id=dispatcher.bot.users['alpha'] +
            dispatcher.bot.users['beta'],
        ),
        commands=['tz', 'timezone'],
    )
    async def tz_callback(message):
        await message_callback(message, ['tz', message.chat.type])
        ## lol
        command = await message.reply(
            u"`{}`".format(cmd_tz({'command_type': None})['response']),
            parse_mode="MarkdownV2",
        )
        await command_callback(command, ['tz', message.chat.type])
Exemple #5
0
async def add_handlers(dispatcher):
  from aiogram import (
    filters,
    types,
  )  
  from matebot.aio_matebot.controllers.callbacks import (
    command_callback,
    message_callback,
  )
  from matebot.plugins.personalidades import (
    gerar_texto,
  )

  ## Tropixel Café / Rede Metareciclagem
  @dispatcher.message_handler(
    filters.IDFilter(
      chat_id = dispatcher.bot.users.get('tropixel', -1),
    ),
    content_types = types.ContentTypes.NEW_CHAT_MEMBERS,
  )
  async def welcome_tropixel_callback(message: types.Message):
    await message_callback(message, ['welcome', 'tropixel', message.chat.type])
    text = await gerar_texto('tropixel', dispatcher.bot, message)
    command = await message.reply(text)
    await command_callback(command, ['welcome', 'tropixel', message.chat.type])

  ## Link para o Boteco Tropixel
  @dispatcher.message_handler(
    filters.IDFilter(
      chat_id = dispatcher.bot.users.get('tropixel', -1),
    ),
    commands = ['boteco'],
  )
  async def tropixel_boteco_callback(message):
    await message_callback(message, ['tropixel', 'boteco', message.chat.type])
    command = await message.reply(
      u"Link para o boteco: {}".format(
        dispatcher.bot.info.get(
          'tropixel', dict(boteco = u"Não sei"),
        ).get('boteco', u"Não sei"),
      ),
      disable_web_page_preview = True,
      disable_notification = True,
    )
    await command_callback(command, ['tropixel', 'boteco', message.chat.type])

  ## Link para a Rede Tropixel
  @dispatcher.message_handler(
    filters.IDFilter(
      chat_id = dispatcher.bot.users.get('tropixel', -1),
    ),
    commands = ['forum', 'rede', 'site', 'wiki'],
  )
  async def tropixel_site_callback(message):
    await message_callback(message, ['tropixel', 'site', message.chat.type])
    command = await message.reply(
      u"Link para o site/rede/forum/wiki: {}".format(
          dispatcher.bot.info.get(
          'tropixel', dict(site = u"Não sei"),
        ).get('site', u"Não sei"),
      ),
      disable_web_page_preview = True,
      disable_notification = True,
    )
    await command_callback(command, ['tropixel', 'site', message.chat.type])
Exemple #6
0
async def add_handlers(dispatcher):
    ## Saúda com trollada
    @dispatcher.message_handler(
        filters.IDFilter(
            ## Somente grupos configurados pra receber novas pessoas com pegadinha
            ## Atualmente só o @ZaffariPoa
            chat_id=dispatcher.bot.users.get('pegadinha', -1), ),
        content_types=types.ContentTypes.NEW_CHAT_MEMBERS,
    )
    async def welcome_pegadinha_callback(message: types.Message):
        await message_callback(message,
                               ['welcome', 'pegadinha', message.chat.type])
        command = await pegadinha(message)
        await command_callback(command,
                               ['welcome', 'pegadinha', message.chat.type])

    ## Seja mau vindo
    @dispatcher.message_handler(
        content_types=types.ContentTypes.NEW_CHAT_MEMBERS, )
    async def welcome_callback(message: types.Message):
        await message_callback(message, [
            'welcome',
            dispatcher.bot.info.get('personalidade', 'pave'), message.chat.type
        ])
        text = await welcome(message)
        command = await message.reply(text)
        await command_callback(command, [
            'welcome',
            dispatcher.bot.info.get('personalidade', 'pave'), message.chat.type
        ])

    ## Piadas sem graça
    # ~ @dispatcher.message_handler(
    # ~ commands = ['piada'],
    # ~ )
    # ~ async def piada_callback(message):
    # ~ await message_callback(message, ['piada',
    # ~ dispatcher.bot.get('personalidade', 'pave'), message.chat.type])
    # ~ command = await message.reply(random_texts.piadas())
    # ~ await command_callback(command, ['piada',
    # ~ dispatcher.bot.get('personalidade', 'pave'), message.chat.type])

    ## Versículos bíblicos fora de contexto
    @dispatcher.message_handler(
        commands=['versiculo'], )
    async def versiculo_callback(message):
        await message_callback(message, ['versiculo', message.chat.type])
        command = await message.reply(
            random_texts.versiculos_md(),
            parse_mode="MarkdownV2",
        )
        await command_callback(command, ['versiculo', message.chat.type])

    ## /info
    @dispatcher.message_handler(
        commands=['info'], )
    async def info_callback(message):
        await message_callback(
            message,
            [
                'info',
                dispatcher.bot.get('personalidade', 'pave'), message.chat.type
            ],
        )
        command = await message.reply(await info())
        await command_callback(
            command,
            [
                'info',
                dispatcher.bot.get('personalidade', 'pave'), message.chat.type
            ],
        )

    ## Responde "quanto vale"
    @dispatcher.message_handler(
        filters.Text(contains='quanto', ignore_case=True),
        filters.Regexp('(?i)\\b(vale|custa|cobra)\\b'),
    )
    async def resposta_quanto_callback(message):
        await message_callback(message,
                               ['resposta', 'quanto', message.chat.type])
        command = await message.reply(random_texts.respostas_quanto())
        await command_callback(command,
                               ['resposta', 'quanto', message.chat.type])

    ## Responde toda referência a bebidas
    @dispatcher.message_handler(
        filters.Regexp(r'\b({})\b'.format('|'.join(random_texts.bebidas()))), )
    async def resposta_bebida_callback(message):
        await message_callback(message,
                               ['resposta', 'bebida', message.chat.type])
        command = await message.reply(random_texts.respostas_bebida())
        await command_callback(command,
                               ['resposta', 'bebida', message.chat.type])

    ## Responde mensagens que são respostas a mensagens deste bot
    ## Reponde com patada
    @dispatcher.message_handler(is_reply_to_id=dispatcher.bot.id)
    async def resposta_ignorante_callback(message):
        await message_callback(
            message,
            ['resposta', 'ignorante', message.chat.type],
        )
        admin = message.from_user.first_name
        if message.chat.type in ['group', 'supergroup']:
            admin = [member.user for member in \
              await dispatcher.bot.get_chat_administrators(
              message.chat.id) if member.status == 'creator'][0].first_name \
              or u"@admin"
        command = await message.reply(random_texts.respostas_ignorante(admin))
        await command_callback(command,
                               ['resposta'
                                'ignorante', message.chat.type])
Exemple #7
0
from aiogram.dispatcher.middlewares import BaseMiddleware
from aiogram.types import Message, ReplyKeyboardRemove

from aiogram import filters

from misc import dp, adminUserID
from features.dbInteractions import incrementStatistics, getWholeDb
from handlers.defaultFunctions import getDefaultReplyKeyboard


@dp.message_handler(filters.Text(equals="Статистика"), filters.IDFilter(user_id=adminUserID))
async def getStatsHandler(message: Message):
    stats = getWholeDb()
    stat_message = await message.answer(text=stats)

    from asyncio import sleep
    await sleep(10)     # удаление сообщения статистики после 10ти секунд (оно громоздкое)

    await dp.bot.delete_message(chat_id=message.chat.id, message_id=stat_message.message_id)
    await dp.bot.delete_message(chat_id=message.chat.id, message_id=message.message_id)


@dp.message_handler(commands=["get_keyboard"])
async def set_default_keyboard(message: Message):
	await message.answer("Готово!", reply_markup=getDefaultReplyKeyboard())


@dp.message_handler(commands=["rm_keyboard"])
async def remove_default_keyboard(message: Message):
	await message.answer("Готово!", reply_markup=ReplyKeyboardRemove())