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

如何使用discord.py结合JSON文件实现用户ID黑名单功能

Discord机器人黑名单命令(通过用户ID添加)

先给你修正并补全完整的实现代码,解决你需要用用户ID拉黑的需求:

import json
from discord.ext import commands
from typing import Optional

@bot.command()
@commands.is_owner()  # 这里必须加括号,否则装饰器无法生效
async def blacklist(ctx, user_id: Optional[int] = None):
    # 检查是否提供了用户ID
    if not user_id:
        await ctx.send("请提供要拉黑的用户ID!")
        print("执行blacklist命令时未提供用户ID")
        return
    
    # 处理黑名单文件
    try:
        # 读取现有黑名单数据
        with open('blacklist.json', 'r') as f:
            blacklisted_users = json.load(f)
    except FileNotFoundError:
        # 如果文件不存在,初始化空列表
        blacklisted_users = []
    
    # 检查用户是否已在黑名单中
    if user_id in blacklisted_users:
        await ctx.send(f"用户ID {user_id} 已经在黑名单里了!")
        return
    
    # 添加用户到黑名单并保存
    blacklisted_users.append(user_id)
    with open('blacklist.json', 'w') as f:
        json.dump(blacklisted_users, f, indent=4)
    
    await ctx.send(f"已成功将用户ID {user_id} 添加到黑名单!")
    print(f"用户ID {user_id} 被添加到黑名单")

额外补充:黑名单校验逻辑

你可以给机器人的其他命令加个前置检查,让黑名单用户无法使用任何命令:

def is_not_blacklisted():
    async def predicate(ctx):
        try:
            with open('blacklist.json', 'r') as f:
                blacklisted_users = json.load(f)
        except FileNotFoundError:
            blacklisted_users = []
        
        return ctx.author.id not in blacklisted_users
    return commands.check(predicate)

# 示例:给需要保护的命令添加这个装饰器
@bot.command()
@is_not_blacklisted()
async def test(ctx):
    await ctx.send("你不在黑名单里,可以正常使用命令!")

代码说明

  • 修复了@commands.is_owner的语法错误,必须加括号才能验证机器人所有者身份
  • 用Optional[int]处理未传ID的情况,避免命令直接报错崩溃
  • 兼容黑名单文件不存在的场景,自动初始化空列表
  • 增加了重复拉黑的判断,避免无效操作
  • 补全了将用户ID写入JSON文件的核心逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 12:33:21