【问题标题】:How can I restrict a Telegram bot's use to some users only?如何将 Telegram 机器人的使用限制为仅限某些用户?
【发布时间】:2020-10-09 11:30:43
【问题描述】:

我正在使用 python3.x 的 python-telegram-bot 库在 python 中编写 Telegram 机器人 这是一个仅供私人使用的机器人(我和一些亲戚),所以我想防止其他用户使用它。我的想法是创建一个授权用户 ID 列表,并且机器人不能回答从不在列表中的用户收到的消息。我该怎么做?

编辑:我对 python 和 python-telegram-bot 都是新手。如果可能的话,我希望以代码 sn-p 为例 =)。

【问题讨论】:

标签: python-3.x telegram python-telegram-bot restriction


【解决方案1】:

使用聊天 ID。创建一个包含您想要允许的聊天 ID 的小列表,您可以忽略其余部分。

您可以在其中找到详细信息的文档链接 https://python-telegram-bot.readthedocs.io/en/stable/telegram.chat.html

【讨论】:

  • 这就是我正在尝试做的事情,但有一些困难。可以发个代码 sn-p 吗?
【解决方案2】:

我找到了使用装饰器的库的a solution from the official wiki。代码:

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`.

我只是@restricted每个函数。

【讨论】:

    【解决方案3】:
    admins=[123456,456789]    
    if update.message.from_user.id in admins:  
        update.message.reply_text('You are authorized to use this BOT!')
        
    else:
        update.message.reply_text('You are not authorized to access this BOT')
    

    【讨论】:

      【解决方案4】:

      您还可以创建自定义处理程序来限制正在执行的消息处理程序。

      import telegram
      from telegram import Update
      from telegram.ext import Handler
      
      admin_ids = [123456, 456789, 1231515]
      
      class AdminHandler(Handler):
          def __init__(self):
              super().__init__(self.cb)
      
          def cb(self, update: telegram.Update, context):
              update.message.reply_text('Unauthorized access')
      
          def check_update(self, update: telegram.update.Update):
              if update.message is None or update.message.from_user.id not in admin_ids:
                  return True
      
              return False
      

      只需确保将AdminHandler 注册为第一个处理程序即可:

      dispatcher.add_handler(AdminHandler())
      

      现在,如果不是来自授权用户 (admin_ids),Bot 收到的每个更新(或消息)都将被拒绝。

      【讨论】:

        猜你喜欢
        • 2022-11-01
        • 1970-01-01
        • 2021-09-04
        • 1970-01-01
        • 2017-11-04
        • 2023-04-10
        • 1970-01-01
        • 2017-10-09
        • 2019-10-23
        相关资源
        最近更新 更多