How to check user is admin or not in python-telegram-bot?

Question:

Im using python-telegram-bot

I want to check if the user in the group is an admin or not, if the user is an admin he can use the commands and if the user is not an admin, he will receive a message saying that you are not an admin.

How should I do this?

this is my code:


async def add(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    if update.effective_chat.type == "private":
        await update.message.reply_text(f'این دستور فقط در گروه کار میکند ! برای استفاده ربات را به گروه اضافه کنید و از ادمین بخواهید پیام جدید ایجاد کند !')
    else:
        user_message = update.message.text.lstrip("/add")
        if len(user_message) > 10:
            title = user_message.partition('n')[0]
            body = user_message.lstrip(title)
            author = update.effective_user.username
            await context.bot.send_message(chat_id=update.effective_chat.id, text=f'''
                      {title}
            ➖➖➖➖➖
            {body}

            ➖➖➖➖➖
              پیام ایجاد شده توسط : @{author}
                    ''')

this is the result

Asked By: Mahdi mk

||

Answers:

The method Bot.get_chat_member (Official Telegram docs) allows you to get information about the users current status in the group.
Alternatively, you apparently already found Bot.get_chat_administrators which allows you to get a list of all current chat admins. When using this, you should check if the sender of the update is present in this list. This can e.g. look like this:

chat_admins = await update.effective_chat.get_administrators()
if update.effective_user in (admin.user for admin in chat_admins):
    print("user is admin")
else:
    print("user is not an admin")

Here I used that objects of type User are comparable in terms of equality in PTB.


Disclaimer: I’m currently the maintainer of python-telegram-bot.

Answered By: CallMeStag