【问题标题】:How to restrict the acess to a few users in pyTelegramBotAPI?如何在 pyTelegramBotAPI 中限制对少数用户的访问?
【发布时间】:2019-08-21 14:14:01
【问题描述】:
【问题讨论】:
标签:
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)