An Admin-Only Python Decorator for Telegram Bots


TL; DR: Here’s a Python Decorator I wrote for Telegram Bots so certain commands can only be used by group admins.

from telegram.constants import CHATMEMBER_ADMINISTRATOR, CHATMEMBER_CREATOR
from telegram import Update
from telegram.ext import CallbackContext

def admin_only(func):
    def wrapper(*args, **kwargs):
        # all handler function has Update as the first argument
        update = args[0]
        # get the current user's member status
        # https://docs.python-telegram-bot.org/en/stable/telegram.chat.html#telegram.Chat.get_member
        member = update.effective_chat.get_member(update.message.from_user.id)
        if member.status and member.status in [CHATMEMBER_ADMINISTRATOR, CHATMEMBER_CREATOR]:
            # execute the decorated function if it's an admin
            return func(*args, **kwargs)
        else:
            update.message.reply_text("This command is for group admin only.")
    return wrapper

@admin_only
def admin_secret(update: Update, context: CallbackContext) -> None:
    update.message.reply_text("Here's the secret.")