You need to enable JavaScript to run this app. discord.py 基于自定义用户ID列表控制命令访问权限的问题排查
优惠活动
大模型
产品
解决方案
定价
更多

discord.py 基于自定义用户ID列表控制命令访问权限的问题排查

问题排查与修正方案

核心问题点

  • 权限校验永久失效的直接原因:数据类型不匹配
    校验逻辑中获取的ctx.author.id是Discord接口返回的整数类型用户ID,但AddUser命令直接将用户输入的文本(字符串类型)追加到modlist中。Python中字符串格式的ID和整数格式的ID永远无法判定为相等,导致无论你是否把自己加入列表,校验逻辑永远返回False,最终触发权限错误。
  • 权限控制存在逻辑漏洞
    当前编写的AddUser、ViewModList、ClearModList三个修改、查询授权列表的命令没有任何身份校验,任何服务器成员都能自行调用命令把ID加入授权列表,甚至直接清空整个modlist,你设置的权限限制完全没有实际作用。
  • 授权数据无法持久保存
    现有modlist是存储在bot进程内存中的临时列表,只要bot重启、崩溃重连,所有已授权的用户信息会全部丢失,恢复为初始的空列表状态。

修正后的可运行代码

import json
from discord.ext import commands

# 替换为你自己的Discord用户ID,作为最高权限身份硬编码,不受modlist影响
BOT_OWNER_ID = 替换为你的Discord整数用户ID

# 从本地文件加载授权列表,避免重启丢失数据
def load_modlist():
    try:
        with open("modlist.json", "r", encoding="utf-8") as f:
            return json.load(f)
    except FileNotFoundError:
        return []

# 变更后同步保存授权列表到本地文件
def save_modlist(mod_list):
    with open("modlist.json", "w", encoding="utf-8") as f:
        json.dump(mod_list, f)

modlist = load_modlist()

def ListCheck():
    async def IsInList(ctx):
        # 统一使用整数类型比对,从根源解决类型不匹配问题
        return ctx.author.id in modlist or ctx.author.id == BOT_OWNER_ID
    return commands.check(IsInList)

@commands.command()
async def AddUser(ctx, user_id: int):
    # 仅bot所有者可执行授权操作
    if ctx.author.id != BOT_OWNER_ID:
        await ctx.send("你没有权限执行此操作")
        return
    if user_id in modlist:
        await ctx.send("该用户已在授权列表中")
        return
    modlist.append(user_id)
    save_modlist(modlist)
    await ctx.send(f"已将用户ID {user_id} 加入受限命令授权列表")

@commands.command()
async def ViewModList(ctx):
    if ctx.author.id != BOT_OWNER_ID:
        await ctx.send("你没有权限执行此操作")
        return
    if not modlist:
        await ctx.send("当前授权列表为空")
        return
    await ctx.send("已获得受限命令权限的用户ID:")
    for uid in modlist:
        await ctx.send(f"- {uid}")

@commands.command()
async def ClearModList(ctx):
    if ctx.author.id != BOT_OWNER_ID:
        await ctx.send("你没有权限执行此操作")
        return
    modlist.clear()
    save_modlist(modlist)
    await ctx.send("授权列表已清空")

@commands.command()
@ListCheck()
async def PermTest(ctx):
    await ctx.send("你已成功获得受限命令使用权限")

调整说明

  • 调用AddUser时直接输入纯数字的用户ID即可,代码内置了参数类型转换,自动过滤非数字的无效输入,从根源上避免之前的字符串、整数类型不匹配问题
  • 硬编码的所有者ID拥有所有命令的最高权限,就算modlist被清空也不会影响你自身的操作权限
  • 增加的json文件读写逻辑会把授权列表同步保存到本地,bot重启后自动加载之前的配置,不会丢失已设置的授权用户

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.29 02:45:04