如何在Discord私密频道设置Verified等角色发送消息权限为False
修改后的Discord频道锁定/解锁机器人代码
以下是调整后的代码,保留了仅Leader角色可执行命令的权限验证逻辑,同时将锁定/解锁操作的目标改为你指定的三个角色(Verified、Member TCR、FRZ):
# 定义需要控制消息发送权限的目标角色名称 TARGET_ROLES = ["Verified", "Member TCR", "FRZ"] async def lock(ctx): author = ctx.message.author leader_role = discord.utils.get(ctx.guild.roles, name="Leader") # 验证操作权限:仅Leader角色可执行 if leader_role not in author.roles: await ctx.send("You do not have permission to lock channel") return # 遍历目标角色,设置send_messages为False for role_name in TARGET_ROLES: role = discord.utils.get(ctx.guild.roles, name=role_name) if role: perms = ctx.channel.overwrites_for(role) perms.send_messages = False await ctx.channel.set_permissions(role, overwrite=perms) await ctx.send("Channel Locked") @client.command() async def unlock(ctx): author = ctx.message.author leader_role = discord.utils.get(ctx.guild.roles, name="Leader") # 验证操作权限:仅Leader角色可执行 if leader_role not in author.roles: await ctx.send("You do not have permission to unlock channel") return # 遍历目标角色,设置send_messages为True for role_name in TARGET_ROLES: role = discord.utils.get(ctx.guild.roles, name=role_name) if role: perms = ctx.channel.overwrites_for(role) perms.send_messages = True await ctx.channel.set_permissions(role, overwrite=perms) await ctx.send("Channel Unlocked")
关键修改说明
- 新增
TARGET_ROLES常量统一管理需要控制的角色,便于后续维护 - 将权限验证逻辑提前,不符合权限时直接返回提示,代码结构更清晰
- 循环处理每个目标角色,自动跳过不存在的角色(避免因角色名称错误导致命令执行失败)
- 锁定/解锁操作仅针对指定的三个角色,不再修改默认角色的权限
内容的提问来源于stack exchange,提问作者HendraIqbal
相关产品推荐
相关产品推荐

