Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add ChatType builtin filter #356

Merged
merged 14 commits into from
Jul 2, 2020
12 changes: 8 additions & 4 deletions aiogram/dispatcher/filters/builtin.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import inspect
import re
import typing
from collections import Container
from contextvars import ContextVar
from dataclasses import dataclass, field
from typing import Any, Dict, Iterable, Optional, Union
Expand Down Expand Up @@ -694,14 +695,17 @@ async def check(self, message: Message):


class ChatTypeFilter(BoundFilter):
key = 'chat_types'
key = 'chat_type'

def __init__(self, chat_types: typing.List[ChatType]):
self.chat_types = chat_types
def __init__(self, chat_type: typing.Container[ChatType]):
if isinstance(chat_type, str):
chat_type = {chat_type}

self.chat_type: typing.Set[str] = set(chat_type)

async def check(self, obj: Union[Message, CallbackQuery]):
if isinstance(obj, Message):
obj = obj.chat
if isinstance(obj, CallbackQuery):
obj = obj.message.chat
return obj.type in self.chat_types
return obj.type in self.chat_type
uwinx marked this conversation as resolved.
Show resolved Hide resolved
14 changes: 13 additions & 1 deletion examples/chat_types_filter.py → examples/chat_type_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import logging

from aiogram import Bot, Dispatcher, executor, types
from aiogram.dispatcher.handler import SkipHandler
from aiogram.types import ChatType

API_TOKEN = 'BOT TOKEN HERE'
Expand All @@ -18,13 +19,24 @@
dp = Dispatcher(bot)


@dp.message_handler(chat_types=[ChatType.PRIVATE, ChatType.CHANNEL])
@dp.message_handler(chat_type=[ChatType.PRIVATE, ChatType.CHANNEL])
async def send_welcome(message: types.Message):
"""
This handler will be called when user sends `/start` or `/help` command
"""
await message.reply("Hi!\nI'm hearing your messages in private chats and channels")

# propagate message to the next handler
raise SkipHandler


@dp.message_handler(chat_type=ChatType.PRIVATE)
async def send_welcome(message: types.Message):
"""
This handler will be called when user sends `/start` or `/help` command
"""
await message.reply("Hi!\nI'm hearing your messages only in private chats")


if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True)