如何限制 Telegram 机器人仅对某些用户使用?

Nta*_*tet 2 restriction python-3.x telegram python-telegram-bot

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

编辑:我对 python 和python-telegram-bot. 如果可能的话,我希望有一个代码片段作为示例 =)。

Nta*_*tet 10

我从图书馆的官方 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`.
Run Code Online (Sandbox Code Playgroud)

我只是@restricted每个功能。