首页 > 解决方案 > 如何将 Telegram 机器人的使用限制为仅限某些用户?

问题描述

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

编辑:我对 python 和python-telegram-bot. 如果可能的话,我会很感激以代码片段为例=)。

标签: python-3.xtelegrampython-telegram-botrestriction

解决方案


我从图书馆的官方 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每个功能。


推荐阅读