You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Telegram Bot白名单功能异常问题求助

Telegram Bot白名单文件读写权限验证问题

问题描述

之前用简单列表whitelist = []实现白名单功能,通过if chat_id not in whitelist:判断权限,运行正常。现在为了支持从文件添加/移除用户,改用whitelist.txt存储ID,但读取文件后无法正确验证用户权限。

现存代码

权限验证读取代码

chat_id = update.message.chat_id
username = update.message.chat.username
with open("whitelist.txt", 'r') as whitelist:
    if chat_id not in whitelist:
        update.message.reply_text('Unauthorised user!')
        print(f'User {username} ({chat_id}) tried issuing a command but was not allowed.')

添加ID代码

chat_id = update.message.chat_id
if chat_id == admin_id:
    add_id = update.message.text.split(" ")[1]
    with open("whitelist.txt", 'w') as f:
        f.write(f'{add_id}')
        f.close()
        update.message.reply_text(f'ChatID `{add_id}` has been added!')

问题原因

  1. 类型不匹配:chat_id是数字类型,而从文件读取的内容是字符串类型,直接用in判断会失效。
  2. 文件读取方式错误:直接遍历文件对象whitelist是按行读取,但未处理每行的空白字符,也没有转换为整数。
  3. 添加ID时覆盖文件:使用'w'模式写入会清空原有内容,无法添加多个ID。

修复方案

1. 修正权限验证读取逻辑

读取文件时将每行内容转换为整数,同时过滤无效行:

chat_id = update.message.chat_id
username = update.message.chat.username

# 读取白名单并转换为整数列表,过滤空行和非数字内容
with open("whitelist.txt", 'r') as f:
    whitelist = [int(line.strip()) for line in f if line.strip().isdigit()]

if chat_id not in whitelist:
    update.message.reply_text('Unauthorised user!')
    print(f'User {username} ({chat_id}) tried issuing a command but was not allowed.')

2. 修正添加ID逻辑

使用追加模式'a'写入,避免覆盖原有内容,同时验证输入的合法性:

chat_id = update.message.chat_id
if chat_id == admin_id:
    add_id = update.message.text.split(" ")[1]
    # 验证输入是否为有效数字ID
    if add_id.isdigit():
        with open("whitelist.txt", 'a') as f:
            f.write(f'{add_id}\n')  # 换行存储,方便后续读取
        update.message.reply_text(f'ChatID `{add_id}` has been added!')
    else:
        update.message.reply_text('无效的ChatID!必须是数字格式。')

3. 补充移除ID功能

如果需要支持移除用户,可添加以下逻辑:

chat_id = update.message.chat_id
if chat_id == admin_id:
    remove_id = update.message.text.split(" ")[1]
    if remove_id.isdigit():
        remove_id_int = int(remove_id)
        # 先读取现有白名单
        with open("whitelist.txt", 'r') as f:
            whitelist = [int(line.strip()) for line in f if line.strip().isdigit()]
        
        if remove_id_int in whitelist:
            whitelist.remove(remove_id_int)
            # 重新写入更新后的白名单
            with open("whitelist.txt", 'w') as f:
                for id_num in whitelist:
                    f.write(f'{id_num}\n')
            update.message.reply_text(f'ChatID `{remove_id}` 已成功移除!')
        else:
            update.message.reply_text('该ChatID不在白名单中!')
    else:
        update.message.reply_text('无效的ChatID!必须是数字格式。')

内容的提问来源于stack exchange,提问作者Basil Gakami

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 05:50:26