How to find out what rights a user has in a telegram group using an aiogram bot

28 Views Asked by At

How to find out what rights a user has in a telegram group using an aiogram bot? I am using the latest version of aiogram 3.4.1

1

There are 1 best solutions below

2
Gygabrain On

The Telegram Bot API has a special method to retrieve data about a chat member: GetChatMember (=> bot.get_chat_member(chat_id, user_id) in Aiogram).

This method returns the object inherited from the ChatMember object. According to the documentation, there are 6 types of chat members, but we are interested only in ChatMemberAdministrator and ChatMemberRestricted, because ChatMemberOwner has absolutely all permissions, ChatMemberMember does not have any additional permissions or restrictions other than global chat settings, and ChatMemberLeft and ChatMemberBanned are clear: they are not in the chat, they do not have any permissions/restrictions.

So first we need to check if the member object is an instance of the ChatMemberAdministrator or ChatMemberRestricted classes:

from aiogram import Bot, Dispatcher
from aiogram.types import Message, ChatMemberAdministrator, ChatMemberRestricted

bot = Bot(token="TOKEN")
dp = Dispatcher()


@dp.message()
async def test(message: Message):
    member = await bot.get_chat_member(message.chat.id, message.from_user.id)
    if isinstance(member, ChatMemberAdministrator):
        ...
    elif isinstance(member, ChatMemberRestricted):
        ...
    else:
        ...

dp.run_polling(bot)

Because there are two different classes with permissions and restrictions, I would create 1 that combines them all and all fields have default values (user permissions default = True, admin permissions default = False), then create an instance of this class and pass rights values in the args, depending on the member type. Remember to set all values to True if the member object is an object of type ChatMemberOwner, or set all values to False if it is an object of type ChatMemberLeft or ChatMemberBanned.

However, note that this method does not include global chat settings and you should keep this in mind when using an instance of this class.