python-3.x - 如何将 Telegram 机器人的使用限制为仅限某些用户?
问题描述
我正在使用python-telegram-bot
python3.x 库在 python 中编写 Telegram 机器人。它是一个仅供私人使用的机器人(我和一些亲戚),所以我想阻止其他用户使用它。我的想法是创建一个授权用户 ID 列表,并且机器人不能回答从不在列表中的用户收到的消息。我怎样才能做到这一点?
编辑:我对 python 和python-telegram-bot
. 如果可能的话,我会很感激以代码片段为例=)。
解决方案
我从图书馆的官方 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
每个功能。
推荐阅读
- jquery - 如何在 HTML 中冻结嵌套/复杂表的标题
- ios - Mapbox离线地图加载问题
- mysql - Mysql - 将 int 字段与另一个表中的逗号分隔字段进行比较
- javascript - 脚本泛化
- c++ - boost::mpl 不使用(甚至不兼容)std::pair 的原因是什么?
- javascript - 如何在javascript中获取变化数组的平均值
- java - 如何使用 Google Snapshot Api 在线存储应用数据?
- javascript - firestore上传文件:不支持的字段值:自定义文件对象
- node.js - 将单个文件复制到节点js中的新文件夹
- mysql - Sequelize 将此作为响应 [{'primaryKey':null}] 返回到 findAll 方法