Skip to content Skip to sidebar Skip to footer

How To Restrict The Acess To A Few Users In Pytelegrambotapi?

I'm using telebot (https://github.com/eternnoir/pyTelegramBotAPI) to create a bot to send photos to its users. The point is I didn't see a way to restrict the access to this bot as

Solution 1:

A bit late tot the party - perhaps for future post readers. You can wrap the function to disallow access.

An example below:

from functools import wraps


defis_known_username(username):
    '''
    Returns a boolean if the username is known in the user-list.
    '''
    known_usernames = ['username1', 'username2']

    return username in known_usernames


defprivate_access():
    """
    Restrict access to the command to users allowed by the is_known_username function.
    """defdeco_restrict(f):

        @wraps(f)deff_restrict(message, *args, **kwargs):
            username = message.from_user.username

            if is_known_username(username):
                return f(message, *args, **kwargs)
            else:
                bot.reply_to(message, text='Who are you?  Keep on walking...')

        return f_restrict  # true decoratorreturn deco_restrict

Then where you are handling commands you can restrict access to the command like this:

@bot.message_handler(commands=['start'])
@private_access()
def send_welcome(message):
    bot.reply_to(message, "Hi and welcome")

Keep in mind, order matters. First the message-handler and then your custom decorator - or it will not work.

Solution 2:

The easiest way is probably a hard coded check on the user id.

# The allowed user id 
my_user_id = '12345678'# Handle command@bot.message_handler(commands=['picture'])defsend_picture(message):

    # Get user id from message
    to_check_id = message.message_id

    if my_user_id = to_check_id:
        response_message = 'Pretty picture'else:
        response_message = 'Sorry, this is a private bot!'# Send response message
    bot.reply_to(message, response_message)

Post a Comment for "How To Restrict The Acess To A Few Users In Pytelegrambotapi?"