如何在discord.py中编写无需cogs的斜杠命令更新与新增命令
不用Cogs实现Discord.py斜杠命令批量同步
核心思路
把所有斜杠命令集中定义,然后做一个仅管理员可用的同步命令,一键完成**新增、更新、删除(可选)**所有应用命令,彻底告别逐个修改重复操作的麻烦。
完整代码示例
import discord from discord import app_commands # 初始化客户端 intents = discord.Intents.default() client = discord.Client(intents=intents) tree = app_commands.CommandTree(client) # -------------------------- # 集中定义所有斜杠命令 # -------------------------- @tree.command(name="hello", description="发送问候消息") async def hello(interaction: discord.Interaction): await interaction.response.send_message(f"你好 {interaction.user.mention}!") @tree.command(name="calc", description="计算两个数的和") @app_commands.describe(num1="第一个数字", num2="第二个数字") async def calculate(interaction: discord.Interaction, num1: float, num2: float): await interaction.response.send_message(f"{num1} + {num2} = {num1 + num2}") @tree.command(name="userinfo", description="查看用户信息") async def user_info(interaction: discord.Interaction, user: discord.User = None): target = user or interaction.user embed = discord.Embed(title=f"{target.name} 的信息", color=discord.Color.blue()) embed.add_field(name="ID", value=target.id, inline=False) embed.add_field(name="创建时间", value=target.created_at.strftime("%Y-%m-%d %H:%M:%S"), inline=False) await interaction.response.send_message(embed=embed) # -------------------------- # 管理员专属同步命令 # -------------------------- @tree.command(name="sync_commands", description="同步所有斜杠命令(仅管理员可用)") @app_commands.checks.has_permissions(administrator=True) async def sync_commands(interaction: discord.Interaction, guild_id: str = None): try: if guild_id: # 同步到指定服务器(测试用,立即生效) guild = discord.Object(id=int(guild_id)) await tree.sync(guild=guild) await interaction.response.send_message(f"已同步所有命令到服务器 {guild_id}", ephemeral=True) else: # 全局同步(正式用,生效需1小时左右) await tree.sync() await interaction.response.send_message("已全局同步所有命令,生效可能需要1小时", ephemeral=True) except ValueError: await interaction.response.send_message("无效的服务器ID格式", ephemeral=True) except discord.Forbidden: await interaction.response.send_message("机器人没有同步命令的权限", ephemeral=True) # 客户端就绪事件 @client.event async def on_ready(): print(f"已登录为 {client.user}") # 运行客户端 client.run("你的机器人TOKEN")
关键说明
- 命令集中管理:所有斜杠命令都写在
tree.command装饰器下,修改或新增只需要在这里操作,不用分散到各个cogs。 - 权限控制:用
@app_commands.checks.has_permissions(administrator=True)锁死同步权限,防止普通用户误操作。 - 两种同步模式:
- 指定服务器同步:调试阶段用,修改完命令执行后立即生效,不用等全局推送。
- 全局同步:正式发布用,同步后Discord会逐步推送到所有服务器,大概1小时左右生效。
- 自动处理更新:不管是改命令名、描述,还是增删参数,执行同步命令后,Discord都会自动更新现有命令,不用重复写冗余代码。
使用方法
- 修改或新增斜杠命令后,在Discord里执行
/sync_commands(全局同步),或者/sync_commands guild_id:你的服务器ID(指定服务器同步)。 - 同步完成后,新命令立即(指定服务器)或延迟(全局)生效,旧命令的修改也会同步更新。
注意事项
- 全局同步每天有次数限制,测试阶段优先用指定服务器同步。
- 要删除某个命令,直接删掉对应的
@tree.command函数,再执行同步命令,Discord会自动移除该命令。
内容的提问来源于stack exchange,提问作者howa
相关产品推荐
相关产品推荐

