skip to Main Content

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 I intend to share private images through this bot.

I read in this forum that through python-telegram-bot there is a way to limit the access from the sender’s message (How To Limit Access To A Telegram Bot), but I didn’t know if via pyTelegramBotAPI it is possible.

Do you know how can I solve it?

2

Answers


  1. 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'])
    def send_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)
    
    Login or Signup to reply.
  2. 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
    
    
    def is_known_username(username):
        '''
        Returns a boolean if the username is known in the user-list.
        '''
        known_usernames = ['username1', 'username2']
    
        return username in known_usernames
    
    
    def private_access():
        """
        Restrict access to the command to users allowed by the is_known_username function.
        """
        def deco_restrict(f):
    
            @wraps(f)
            def f_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 decorator
    
        return 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search