如何用discord.py从外部文件导入Command Tree斜杠命令?
解决discord.py斜杠命令拆分到独立文件并导入的问题
1. 你的实现思路是正确的
用load_extension将斜杠命令拆分到单独文件是discord.py官方推荐的模块化方案,能有效优化代码结构,完全可行。
2. 拥有load_extension方法的对象
是discord.ext.commands.Bot(或AutoShardedBot)实例,注意:普通的discord.Client没有这个方法,必须使用Bot类。
3. slash.py的正确写法
核心步骤:
- 导入
discord、discord.app_commands以及discord.ext.commands.Cog - 创建继承自
commands.Cog的类,所有斜杠命令定义在该类内部 - 类的
__init__方法接收bot参数并保存 - 用
@app_commands.command()装饰器定义命令,方法需包含self和interaction参数 - 最后实现
setup函数,负责将Cog添加到Bot实例中
示例代码:
slash.py
import discord from discord import app_commands from discord.ext import commands class SlashCommands(commands.Cog): def __init__(self, bot: commands.Bot): self.bot = bot @app_commands.command(name="hello", description="发送问候消息") async def hello_cmd(self, interaction: discord.Interaction): await interaction.response.send_message(f"你好 {interaction.user.mention}!") @app_commands.command(name="ping", description="查看机器人延迟") async def ping_cmd(self, interaction: discord.Interaction): await interaction.response.send_message(f"延迟: {round(self.bot.latency * 1000)}ms") async def setup(bot: commands.Bot): await bot.add_cog(SlashCommands(bot))
主文件(如main.py)
import discord from discord.ext import commands intents = discord.Intents.default() intents.message_content = True # 根据需求开启对应权限 bot = commands.Bot(command_prefix="!", intents=intents) @bot.event async def on_ready(): print(f"已登录为 {bot.user}") # 同步命令到Discord(全局同步需1小时生效,测试可指定服务器) await bot.tree.sync() # 加载slash.py扩展 await bot.load_extension("slash") bot.run("你的机器人TOKEN")
关键注意事项
- 确保
slash.py和主文件在同一目录,若在子目录(如cogs/slash.py),加载时需写await bot.load_extension("cogs.slash") - 测试阶段可通过
await bot.tree.sync(guild=discord.Object(id=你的服务器ID))快速同步命令到指定服务器 - 命令方法必须包含
self(类方法要求)和interaction(交互对象)参数,顺序不可颠倒
内容的提问来源于stack exchange,提问作者Hi I'm Jony
相关产品推荐
相关产品推荐

