当我向Telegram Bot发送消息时,它没有任何问题。
我想限制访问,以便我和只有我可以向它发送消息。
我怎样才能做到这一点?
按字段update.message.from.id
过滤消息
由于这个问题与python-telegram-bot有关,下面的信息与它有关:
当您向机器人的调度程序添加处理程序时,您可以指定各种预先构建的过滤器(在docs,github上阅读更多内容),或者您可以创建自定义过滤器以过滤传入的更新。
要限制对特定用户的访问,您需要在初始化处理程序时添加Filters.user(username="@telegramusername")
,例如:
dispatcher.add_handler(CommandHandler("start", text_callback, Filters.user(username="@username")))
此处理程序将仅接受来自用户名为/start
的用户的@username
命令。
您也可以指定user-id而不是username,我强烈推荐,因为后者是非常量的,可以随时间更改。
与您的机器人开始对话,并向其发送消息。这将为包含消息的机器人和对话的聊天ID排队更新。
要查看最近的更新,请调用getUpdates方法。这是通过向URL https://api.telegram.org/bot $ TOKEN / getUpdates发出HTTP GET请求来完成的。其中$ TOKEN是BotFather提供的令牌。就像是:
"chat":{
"id":12345,
"first_name":"Bob",
"last_name":"Jones",
"username":"bjones",
"type":"private"},
"date":1452933785,
"text":"Hi there, bot!"}}]}
确定聊天ID后,您可以在机器人中编写一段代码,如:
id_a = [111111,2222222,3333333,4444444,5555555]
def handle(msg):
chat_id = msg['chat']['id']
command = msg['text']
sender = msg['from']['id']
if sender in id_a:
[...]
else:
bot.sendMessage(chat_id, 'Forbidden access!')
bot.sendMessage(chat_id, sender)
基于python-telegram-bot
代码片段,可以围绕处理程序构建一个简单的包装器:
def restricted(func):
"""Restrict usage of func to allowed users only and replies if necessary"""
@wraps(func)
def wrapped(bot, update, *args, **kwargs):
user_id = update.effective_user.id
if user_id not in conf['restricted_ids']:
print("WARNING: Unauthorized access denied for {}.".format(user_id))
update.message.reply_text('User disallowed.')
return # quit function
return func(bot, update, *args, **kwargs)
return wrapped
其中conf['restricted_ids']
可能是一个id列表,例如[11111111, 22222222]
。
所以用法看起来像这样:
@restricted
def bot_start(bot, update):
"""Send a message when the command /start is issued"""
update.message.reply_text('Hi! This is {} speaking.'.format(bot.username))
过滤update.message.chat_id
对我有用。要查找您的聊天ID,请向您的机器人发送消息并浏览至
https://api.telegram.org/bot$TOKEN/getUpdates
其中$TOKEN
是BotFather提供的机器人令牌,如fdicarlo的答案中所述,您可以在json结构中找到聊天ID。