首页 > 解决方案 > 当我将命令放入单独的文件时,找不到命令错误

问题描述

我最近刚刚尝试清理我的 main.py 文件,因为其中有很多代码。我想将每个命令存储到一个文件中。我从清除/清除命令开始。每当我键入>clean时,我都会收到错误消息“找不到命令”。我该如何解决?一些 main.py 和 clear.py 的代码如下。任何帮助,将不胜感激!:D

主文件

import discord
from discord import User
import os
from keep_alive import keep_alive
from discord.ext import commands
import random
import requests
import json
import asyncio
from discord.ext.commands import MissingPermissions
from discord.ext.commands import Bot, Greedy
from discord.ext.commands import CommandNotFound
bot=commands.Bot(command_prefix = '>')
bot.remove_command("help")

@bot.event
async def on_ready():
 print('The bot is online')
 await bot.change_presence(activity=discord.Game('>help | Bot made by ColeTMK'))

清除.PY

from discord.ext import commands
import asyncio
from discord.ext.commands import MissingPermissions
bot=commands.Bot(command_prefix = '>')

class Clear():
    def __init__(self, bot):
        self.bot = bot

@bot.command()
@commands.has_permissions(manage_messages=True)
async def clear(ctx, amount=5):
 await ctx.channel.purge(limit=amount+1)
 embed=discord.Embed(title="Clear Messages", description=f'{amount} messages were deleted!', color=0x00FFFF)
 await ctx.send(embed=embed)
 await asyncio.sleep(3)
 await ctx.channel.purge(limit=1)

@clear.error
async def clear_error(ctx, error):
   if isinstance(error, MissingPermissions):
       await ctx.send(f"{ctx.author.mention}, Sorry, you do not have permission to do that!")

def setup(bot):
  bot.add_cog(Clear(bot))

标签: pythondiscorddiscord.py

解决方案


编辑:使用 COGS 的更好解决方案

实际上 discord.py 允许“cogs”,请参阅此处的文档:https ://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html

这里也是一个例子:https ://gist.github.com/leovoel/46cd89ed6a8f41fd09c5


推荐阅读