python-3.xtelegrampython-telegram-botrestriction

How can I restrict a Telegram bot's use to some users only?


I'm programming a Telegram bot in python with the python-telegram-bot library for python3.x It's a bot for private use only (me and some relatives), so I would like to prevent other users from using it. My idea is to create a list of authorized user IDs and the bot must not answer to messages received from users not in the list. How can I do that?

Edit: I'm quite a newbie to both python and python-telegram-bot. I'd appreciate a code snippet as example if possible =).


Solution

  • I found a solution from the official wiki of the library which uses a decorator. Code:

    from functools import wraps
    
    LIST_OF_ADMINS = [12345678, 87654321] # List of user_id of authorized users
    
    def restricted(func):
        @wraps(func)
        def wrapped(update, context, *args, **kwargs):
            user_id = update.effective_user.id
            if user_id not in LIST_OF_ADMINS:
                print("Unauthorized access denied for {}.".format(user_id))
                return
            return func(update, context, *args, **kwargs)
        return wrapped
    
    @restricted
    def my_handler(update, context):
        pass  # only accessible if `user_id` is in `LIST_OF_ADMINS`.
    

    I just @restricted each function.