如何为Discord Bot的!live命令添加用户权限校验?
Discord Bot !live命令权限校验方案
要限制只有特定用户/角色能使用!live命令,核心是在触发命令回复前,先校验用户的身份或权限,以下是几种常见实现方式(以discord.py框架为例):
1. 校验用户是否拥有指定角色
通过检查用户的角色列表,判断是否包含你预先设定的权限角色(比如“主播”“直播管理员”),角色ID比名称更可靠(避免重名问题):
if p_message == "!live": # 获取发送消息的用户对象 author = message.author # 方式1:通过角色名称判断 has_permission = any(role.name == "Streamer" for role in author.roles) # 方式2:通过角色ID判断(推荐) # has_permission = any(role.id == 123456789012345678 for role in author.roles) if has_permission: return "@here I'm live right now - urlhere" else: return "你没有权限使用该命令!"
2. 校验用户是否为服务器管理员
直接利用Discord自带的管理员权限判断,适合让服务器管理员专属使用:
if p_message == "!live": author = message.author if author.guild_permissions.administrator: return "@here I'm live right now - urlhere" else: return "你没有权限使用该命令!"
3. 用户ID白名单
只允许特定几个用户使用,适合私人或小型Bot场景:
# 预先配置允许使用的用户ID列表 ALLOWED_USERS = [111222333444555666, 777888999000111222] if p_message == "!live": author_id = message.author.id if author_id in ALLOWED_USERS: return "@here I'm live right now - urlhere" else: return "你没有权限使用该命令!"
注意事项
如果你的Bot使用的是其他框架(如discord.js),逻辑完全一致,仅语法细节不同——核心都是先获取用户的权限/身份信息,再执行校验判断。
内容的提问来源于stack exchange,提问作者axelkoto
相关产品推荐
相关产品推荐

