通过聊天ID限制telegram bot的访问



我已经附上了代码。我希望从本地机器上的文本文件访问chat_id。

#constants.py
chatid_list = []
file1 = open(r'D:\folder1\chatids.txt', "r")
for chat_id in file1:
chatid_list.append(chat_id)
#main.py
def start(update, context):
chat_id = update.message.chat_id
first_name =update.message.chat.first_name
last_name = update.message.chat.last_name
username = update.message.chat.username
if chat_id in cp.chatid_list:
print("chat_id : {} and firstname : {} lastname : {}  username {}". format(chat_id, first_name, last_name , username))
context.bot.send_message(chat_id, 'Hi ' + first_name + '   Whats up?')
update.message.reply_text( text=main_menu_message(),reply_markup=main_menu_keyboard())
else:
print("WARNING: Unauthorized access denied for {}.".format(chat_id))
update.message.reply_text('User disallowed.')

我的猜测是chatid_list的元素是字符串,因为您从文本文件中读取它们,但chat_id是一个整数。因此,您必须将chat_id转换为字符串,或者将chatid_list的元素转换为整数。

作为一种更干净的替代方案,您可以考虑使用环境变量(例如使用dotenv(来添加聊天ID等配置元素(如@CallMeStag所示,以字符串形式(。

这将消除为此必须格式化和读取文件的必要性。在这种情况下,您可以将.env文件与放在同一目录中

#.env file
# allowed ids - users allowed to use bot
ALLOWED_IDS = 12345678, 24567896

我假设您使用的是python 3,并且可以使用f-string。所以,你可以把你的constants.py扔掉,你的main.py看起来如下:

#main.py file
import os
from dotenv import load_dotenv
load_dotenv()
def start(update, context):
chat_id = update.message.chat_id
first_name = update.message.chat.first_name
last_name = update.message.chat.last_name
username = update.message.chat.username
if chat_id in os.getenv('ALLOWED_IDS'):
print(f'chat_id : {chat_id } and firstname : {first_name } lastname : {last_name }  username {username }')
context.bot.send_message(chat_id, f'Hi {first_name}, Whats up?')
update.message.reply_text(text=main_menu_message(),reply_markup=main_menu_keyboard())
else:
print(f'WARNING: Unauthorized access denied for {chat_id}.')
update.message.reply_text('User disallowed.')

最后,如果您希望多个函数是";"受保护";,您可以使用如图所示的包装器。


编辑:在OP的注释后添加可选的本地文件类型

您还可以将允许的用户存储在JSON(ids.json(:中

{
"allowed_users": [
{
"name": "john wick",
"id": 1234567
},
{
"name": "rick wick",
"id": 2345738
}
]
}

然后按如下方式读取允许的ID:

import json
with open(r'./ids.json', 'r') as in_file:
allowed_users = json.load(in_file)['allowed_users']
allowed_ids = [user['id'] for user in allowed_users]

或者,您可以简单地将所有ID放入一个文本文件(ids.txt(中,每行一个ID:

1234567
2345738

然后按如下方式阅读:

allowed_ids = []
with open(r'./ids.txt', 'r') as in_file:
for row in in_file:
allowed_ids.append(int(row.strip()))

最后,用allowed_ids替换上面代码片段中的os.getenv('ALLOWED_IDS')

最新更新