You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在discord.py中从其他文件导入斜杠命令?

如何在discord.py中拆分斜杠命令到不同文件

方法一:使用Cogs(适配你之前的Extensions使用习惯)

这种方式和你之前用Cogs管理前缀命令的逻辑一致,是官方推荐的模块化方案。

  1. 编写slashcommands.py
    将斜杠命令封装到Cog类中:
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="Says hello to the user.")
    async def hello(self, interaction: discord.Interaction):
        await interaction.response.send_message(f"Hello <@{interaction.user.id}>!")

async def setup(bot: commands.Bot):
    await bot.add_cog(SlashCommands(bot))
  1. 在main.py中加载扩展
    修改主文件,添加扩展加载逻辑并同步斜杠命令:
import discord
from discord.ext import commands

# 配置所需的Intents,根据Bot功能调整
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}")
    # 同步斜杠命令(测试时可指定服务器ID,避免全局同步的1小时延迟)
    try:
        synced = await bot.tree.sync()
        # 若要指定服务器,替换为:synced = await bot.tree.sync(guild=discord.Object(id=你的服务器ID))
        print(f"已同步 {len(synced)} 条斜杠命令")
    except Exception as e:
        print(f"同步命令出错:{e}")

# 加载扩展
async def load_extensions():
    await bot.load_extension("slashcommands")

async def main():
    async with bot:
        await load_extensions()
        await bot.start("你的Bot令牌")

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

方法二:直接传递CommandTree实例(轻量方案)

如果不想用Cogs,可以通过传递bot.tree对象到其他文件来注册命令。

  1. 编写slashcommands.py
    定义一个初始化函数,接收CommandTree实例并注册命令:
import discord
from discord import app_commands

def setup_commands(tree: app_commands.CommandTree):
    @tree.command(name="hello", description="Says hello to the user.")
    async def hello(interaction: discord.Interaction):
        await interaction.response.send_message(f"Hello <@{interaction.user.id}>!")
  1. 在main.py中调用初始化函数
import discord
from discord.ext import commands
import slashcommands

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}")
    # 注册外部文件中的命令
    slashcommands.setup_commands(bot.tree)
    # 同步命令
    try:
        synced = await bot.tree.sync()
        print(f"已同步 {len(synced)} 条斜杠命令")
    except Exception as e:
        print(f"同步命令出错:{e}")

bot.run("你的Bot令牌")

注意事项

  • 不要用self作为命令函数名,这是Python的保留关键字,会导致语法错误
  • 全局斜杠命令同步后需要约1小时生效,测试阶段建议指定服务器ID进行同步
  • 确保main.py和slashcommands.py在同一目录下,否则需要调整导入路径

内容的提问来源于stack exchange,提问作者noelhermans

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 00:35:22