使用@client.command无法创建Discord斜杠命令问题求助
解决Discord机器人斜杠命令无响应的问题
你的代码里实现的是前缀触发的命令(比如通过-tban调用),并非Discord官方的斜杠命令(/ban),这是核心问题。要实现斜杠命令,需要使用discord.py的app_commands模块,以下是修改方案:
关键修改点
- 导入
discord.app_commands模块,用于定义斜杠命令 - 添加命令同步逻辑,将本地定义的斜杠命令同步到Discord服务器
- 用
@client.tree.command()替换@client.command()来定义斜杠命令 - 权限检查改用
app_commands.checks.has_permissions
修改后的完整代码
import discord from discord.ext import commands from discord import app_commands # 初始化Bot,intents需要包含成员相关权限 intents = discord.Intents.default() intents.members = True client = commands.Bot(command_prefix='-t', intents=intents) token = "[你的机器人Token]" # 前缀命令的错误处理 @client.event async def on_command_error(ctx, error): if isinstance(error, commands.MissingRequiredArgument): await ctx.send('请传入所有必填参数 :rolling_eyes:.') if isinstance(error, commands.MissingPermissions): await ctx.send("你没有足够的权限 :angry:") # 斜杠命令的错误处理 @client.tree.error async def on_app_command_error(interaction: discord.Interaction, error: app_commands.AppCommandError): if isinstance(error, app_commands.MissingPermissions): await interaction.response.send_message("你没有足够的权限执行此命令", ephemeral=True) elif isinstance(error, app_commands.MissingRequiredArgument): await interaction.response.send_message("请传入所有必填参数", ephemeral=True) else: await interaction.response.send_message("命令执行出错", ephemeral=True) # 斜杠命令:封禁成员 @client.tree.command(name="ban", description="封禁指定成员") @app_commands.checks.has_permissions(ban_members=True) async def ban(interaction: discord.Interaction, member: discord.Member, reason: str = "无"): await member.ban(reason=reason) await interaction.response.send_message(f"已封禁 {member.mention},原因:{reason}") # 斜杠命令:解封成员 @client.tree.command(name="unban", description="解封指定成员(格式:用户名#标签)") @app_commands.checks.has_permissions(administrator=True) async def unban(interaction: discord.Interaction, member: str): try: member_name, member_discriminator = member.split("#") except ValueError: await interaction.response.send_message("请输入正确的格式:用户名#标签", ephemeral=True) return banned_users = await interaction.guild.bans() for ban_entry in banned_users: user = ban_entry.user if (user.name, user.discriminator) == (member_name, member_discriminator): await interaction.guild.unban(user) await interaction.response.send_message(f"已解封 {user.mention}") return await interaction.response.send_message("未找到该封禁用户", ephemeral=True) # 启动时同步斜杠命令到服务器 @client.event async def on_ready(): print(f"已登录为 {client.user}") # 全局同步(所有服务器生效,需等待约1小时Discord审核) await client.tree.sync() # 调试用:单服务器即时同步(替换为你的服务器ID) # guild = discord.Object(id=1234567890) # client.tree.copy_global_to(guild=guild) # await client.tree.sync(guild=guild) print("斜杠命令已同步") client.run(token)
额外说明
- 斜杠命令必须同步到Discord才能被用户看到:
- 全局同步适合正式部署,生效时间约1小时
- 单服务器同步仅对指定服务器生效,即时生效,适合开发调试
- 斜杠命令的交互对象是
discord.Interaction,回复方式与前缀命令不同,使用interaction.response.send_message - 代码保留了原有的前缀命令体系,你可以同时使用
-tban和/ban两种触发方式
内容的提问来源于stack exchange,提问作者bogdanel2011 Sandu
相关产品推荐
相关产品推荐

