我正在为 discord 服务器制作一个机器人,我想出了以下代码解决方案。这段代码的问题是任何人都可以使用任何命令。我需要将管理命令限制为具有 Admin 角色的用户。我试过这个,但无法弄清楚什么是正确的方法。
#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')
#Cogs
@client.command()
async def load(ctx, extension):
client.load_extension(f'cogs.{extension}')
@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]}')
Run Code Online (Sandbox Code Playgroud)
Mute.py
:
import discord
from discord.ext import commands
class mute(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
@commands.Cog.listener()
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRole("Administrator")):
return
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))
Run Code Online (Sandbox Code Playgroud)
小智 6
在@client.command() 之后添加以下装饰器:
@commands.has_permissions(administrator=True)
Run Code Online (Sandbox Code Playgroud)
您也可以指定某些角色来使用该命令,在@client.command() 后添加以下内容
@commands.has_any_role('role_name', 'role_name')
Run Code Online (Sandbox Code Playgroud)
请注意,您可以将角色 ID 用作整数而不是角色名称。