如何简化discord.py关闭机器人代码并限制仅3个指定UUID用户可用
Discord.py 机器人关闭命令简化方案(仅指定UUID用户可执行)
简化思路
把允许执行命令的用户UUID放到一个集合里,通过in操作符快速判断权限,替代冗余的多分支if判断。你之前用括号分隔多个UUID无效,是因为错误地用了==和元组做比较(比如ctx.author.id == (uuid1, uuid2)),这种写法逻辑不成立,而集合的in操作才是正确的多值判断方式。
简化后的代码示例
方式一:使用权限检查装饰器(符合discord.py规范)
from discord.ext import commands import discord # 初始化机器人(根据你的实际需求配置intents) bot = commands.Bot(command_prefix="!", intents=discord.Intents.all()) # 定义允许执行关闭命令的用户UUID集合(替换成你的三个UUID) ALLOWED_SHUTDOWN_USERS = {"123456789012345678", "987654321098765432", "111222333444555666"} # 权限检查函数 def can_shutdown(ctx): return str(ctx.author.id) in ALLOWED_SHUTDOWN_USERS # 关闭命令 @bot.command(name="shutdown") @commands.check(can_shutdown) async def shutdown_bot(ctx): await ctx.send("机器人正在关闭,请稍等...") await bot.close() # 运行机器人 bot.run("你的机器人令牌")
方式二:直接在命令内判断(直观易修改)
from discord.ext import commands import discord bot = commands.Bot(command_prefix="!", intents=discord.Intents.all()) ALLOWED_SHUTDOWN_USERS = {"123456789012345678", "987654321098765432", "111222333444555666"} @bot.command(name="shutdown") async def shutdown_bot(ctx): # 检查用户权限 if str(ctx.author.id) not in ALLOWED_SHUTDOWN_USERS: await ctx.send("抱歉,你没有权限执行这个命令!") return # 执行关闭逻辑 await ctx.send("机器人即将关闭,再见!") await bot.close() bot.run("你的机器人令牌")
注意事项
- UUID可以用字符串或整数类型:如果集合里存整数,直接用
ctx.author.id in ALLOWED_SHUTDOWN_USERS即可,无需转字符串 - 使用装饰器的方式,无权限用户执行命令时,机器人会返回默认的权限不足错误;直接判断的方式可自由定制提示语
内容的提问来源于stack exchange,提问作者Tiemango
相关产品推荐
相关产品推荐

