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

Discord.py如何将命令存放在单独文件夹并导入?

拆分Discord.py命令到单独文件夹的实现方法

首先确保你的项目目录结构如下(必须在commands文件夹里创建空的__init__.py文件,让Python识别为包):

项目根目录/
├─ main.py
└─ commands/
   ├─ __init__.py
   └─ ping.py

方法一:使用Cog(推荐,适合多命令管理)

1. 修改命令文件(commands/ping.py)

把原来直接绑定client的代码改成Cog类形式,这样可以通过bot加载扩展:

import discord
from discord.ext import commands

class Ping(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def ping(self, ctx):
        delay = self.bot.latency * 1000
        await ctx.reply(f'Ping is {int(delay)} Milliseconds')
        print(f"Pinged In {ctx.guild} -- {ctx.channel}")

# 必须定义setup函数,供bot加载该Cog
async def setup(bot):
    await bot.add_cog(Ping(bot))

2. 修改主文件(main.py)

添加批量加载commands文件夹下所有命令扩展的代码,同时注意开启Discord所需的intents(否则bot可能无法响应命令):

import discord
from discord.ext import commands
import os

# 开启必要的intents,需在Discord开发者后台对应开启
intents = discord.Intents.default()
intents.message_content = True
intents.guilds = True

client = commands.Bot(command_prefix=">", intents=intents)

@client.event
async def on_connect():
    print(f'Logged In As {client.user}')
    # 遍历commands文件夹,加载所有.py后缀的命令文件
    for filename in os.listdir('./commands'):
        if filename.endswith('.py') and filename != '__init__.py':
            # 按格式加载扩展:commands.文件名(去掉.py后缀)
            await client.load_extension(f'commands.{filename[:-3]}')
            print(f'已加载命令文件: {filename}')

# 替换为你的机器人token
client.run('你的机器人Token')

方法二:直接通过setup函数添加命令(适合简单单命令文件)

如果不想用Cog,也可以直接在命令文件里定义命令函数,再通过setup函数绑定到bot:

1. 修改命令文件(commands/ping.py)

import discord
from discord.ext import commands

async def ping(ctx):
    delay = ctx.bot.latency * 1000
    await ctx.reply(f'Ping is {int(delay)} Milliseconds')
    print(f"Pinged In {ctx.guild} -- {ctx.channel}")

async def setup(bot):
    # 将函数包装成Command对象并添加到bot
    bot.add_command(commands.Command(ping))

2. 主文件修改和方法一的main.py完全一致,同样需要批量加载扩展

注意事项

  • 必须在Discord开发者后台的机器人页面,开启消息内容意图和服务器成员意图,否则bot无法读取消息和响应命令。
  • 确保你的Python版本在3.8以上,Discord.py v2.x版本需要该版本支持。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 03:55:20