pythonpython-3.xtelegram-botpython-telegram-bot

Administrator Permissions Check (aiogram)


i make a telegram bot for administrate telegram groups, but this filter just check admin status:

import aiogram
import functools
from aiogram.dispatcher.filters import BoundFilter

class CheckFilter(BoundFilter):
    key = 'is_admin'
    def __init__(self, is_admin):
        self.is_admin = is_admin
    async def check(self, message: types.Message):
       member = await bot.get_chat_member(message.chat.id, message.from_user.id)
       return member.is_chat_admin() == self.is_admin
dp.filters_factory.bind(CheckFilter)

i need to check administrator permissions. Example: for use command !ban you need to ban users permission.


Solution

  • bot.get_chat_member(chat_id, bot_id) will do the trick.

    aiogram documentation says:

    Returns: Returns a ChatMember object on success

    And what Telegram API documentation says about ChatMember:

    ...

    can_edit_messages Boolean Optional. Administrators only. True, if the administrator can edit messages of other users and can pin messages; channels only

    can_delete_messages Boolean Optional. Administrators only. True, if the administrator can delete messages of other users

    can_restrict_members Boolean Optional. Administrators only. True, if the administrator can restrict, ban or unban chat members

    ...

    Here is an example:

    @dp.message_handler(commands=['rights'])
    async def myrights(message: types.Message):
        member = await bot.get_chat_member(message.chat.id, TOKEN.split(":")[0])
        for x in member:
            print(x)
    

    And its output (on my terminal) when I write /rights@BOTUSERNAME on the group:

    ('user', {'id': xxxxxxxxxx, 'is_bot': True, 'first_name': 'xxxxx', 'username': 'xxxxx'})
    ('status', 'administrator')
    ('can_be_edited', False)
    ('can_change_info', True)
    ('can_delete_messages', True)
    ('can_invite_users', True)
    ('can_restrict_members', True)
    ('can_pin_messages', True)
    ('can_promote_members', False)