【问题标题】:How to restrict the acess to a few users in pyTelegramBotAPI?如何在 pyTelegramBotAPI 中限制对少数用户的访问?
【发布时间】:2019-08-21 14:14:01
【问题描述】:

我正在使用 Telebot (https://github.com/eternnoir/pyTelegramBotAPI) 创建一个机器人来向其用户发送照片。关键是我没有看到限制对这个机器人的访问的方法,因为我打算通过这个机器人共享私人图像。

我在这个论坛上读到,通过 python-telegram-bot 有一种方法可以限制来自发件人消息 (How To Limit Access To A Telegram Bot) 的访问,但我不知道是否可以通过 pyTelegramBotAPI。

你知道我该如何解决吗?

【问题讨论】:

    标签: python bots telegram telegram-bot py-telegram-bot-api


    【解决方案1】:

    聚会有点晚了——也许是为了以后的帖子读者。您可以包装该函数以禁止访问。

    以下示例:

    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
    

    然后,在您处理命令的地方,您可以像这样限制对命令的访问:

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

    请记住,顺序很重要。首先是消息处理程序,然后是您的自定义装饰器 - 否则它将不起作用。

    【讨论】:

      【解决方案2】:

      最简单的方法可能是对用户 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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-11
        • 1970-01-01
        相关资源
        最近更新 更多