Discord Bot如何设置仅管理员角色用户可访问管理员命令
解决方案
现有代码问题
- 所有管理员权限命令未添加权限校验装饰器,任意用户均可调用
- Mute类中的mute方法未添加
@commands.command()装饰器,命令注册逻辑失效 - Cog内的on_command_error事件监听方法缺少self参数,且错误处理仅做静默返回,未给用户返回无权限提示
- 主文件全局错误处理未覆盖权限缺失的报错场景
具体修改步骤
1. 主文件修改
给load、unload管理员命令添加权限校验装饰器,同时完善全局错误处理逻辑,新增权限不足的提示:
#Import import discord import os from discord.ext import commands #Client client = commands.Bot(command_prefix='?') client.remove_command('help') #Activity @client.event async def on_ready(): print('Emog9 is running') await client.change_presence(activity=discord.Activity(type=discord.ActivityType.playing, name="?help")) #Error @client.event async def on_command_error(ctx, error): if isinstance(error, commands.CommandNotFound): await ctx.reply('Command does not exist. Please use a valid command') # 新增权限不足的错误处理 elif isinstance(error, (commands.MissingRole, commands.MissingPermissions)): await ctx.reply('你没有权限使用该命令') #Cogs # 如果要校验Admin角色权限可以用 @commands.has_role("Admin") # 直接校验账户管理员权限不受角色名修改影响,更稳妥 @commands.has_permissions(administrator=True) @client.command() async def load(ctx, extension): client.load_extension(f'cogs.{extension}') # 同样添加权限校验 @commands.has_permissions(administrator=True) @client.command() async def unload(ctx, extension): client.unload_extension(f'cogs.{extension}') for filename in os.listdir('./cogs'): if filename.endswith('.py'): client.load_extension(f'cogs.{filename[:-3]}')
2. Mute.py文件修改
修正命令注册逻辑、添加权限校验、修复错误监听方法的语法问题:
import discord from discord.ext import commands class mute(commands.Cog): def __init__(self, client): self.client = client @commands.Cog.listener() async def on_command_error(self, ctx, error): if isinstance(error, commands.MissingPermissions): await ctx.reply('你没有权限使用该命令') return # 新增命令注册装饰器和权限校验装饰器 @commands.command() @commands.has_permissions(administrator=True) async def mute(self, ctx, member: discord.Member, *, reason=None): guild = ctx.guild mutedRole = discord.utils.get(guild.roles, name='Muted') if not mutedRole: mutedRole = await guild.create_role(name='Muted') for channel in guild.channels: await channel.set_permissions(mutedRole, speak=False, send_messages=False, read_message_history=True, read_messages=True) await member.add_roles(mutedRole, reason=reason) await ctx.send(f'Muted {member.mention} for reason: {reason}') await member.send(f"You were muted in the server {guild.name} for reason: {reason}") def setup(client): client.add_cog(mute(client))
补充说明
如果你的服务器管理员角色名称确实为Admin,可以把所有@commands.has_permissions(administrator=True)替换为@commands.has_role("Admin"),即可实现只有持有该角色的用户可调用对应命令的效果。
内容的提问来源于stack exchange,提问作者Sidhak Singh
相关产品推荐
相关产品推荐

