如何在独立Cog文件中混用前缀命令与Slash命令?解决属性报错
解决Discord.py中Cog加载报错:AttributeError: 'MeuCliente' object has no attribute 'load_extension'
你遇到的报错核心原因是:自定义的MeuCliente类继承的是discord.Client,但load_extension是commands.Bot类独有的方法,discord.Client并没有这个属性。
要同时支持前缀命令、Slash命令和Cog扩展加载,正确的做法是让客户端类继承commands.Bot(它是discord.Client的子类,天然兼容所有Client功能,还额外提供前缀命令和扩展管理能力)。
修改后的main.py代码
import os import datetime import asyncio import random from discord.ext import commands from discord import app_commands, Object from dotenv import load_dotenv import discloud server_id = Object(id=717615951113093130) app_id = 1068876103009194025 hoje = datetime.datetime.today() dia, mes, ano = hoje.day, hoje.month, hoje.year hh, mm, ss = hoje.hour, hoje.minute, hoje.second class MeuCliente(commands.Bot): def __init__(self,*,intents:discord.Intents): super().__init__( command_prefix="!", application_id=app_id, intents=intents, ) # 无需手动创建CommandTree,commands.Bot已经自带self.tree属性 async def setup_hook(self): await self.load_extension("cogs.dashboard") await self.load_extension("cogs.embedcreator") self.tree.copy_global_to(guild=server_id) await self.tree.sync(guild=server_id) bot = MeuCliente(intents=discord.Intents.default()) @bot.event async def on_ready(): print(f"{bot.user.name} está online!") load_dotenv() TOKEN = os.getenv("DISCORD_TOKEN") bot.run(TOKEN)
关键改动说明
- 继承类从
discord.Client改为commands.Bot,直接获得前缀命令管理和扩展加载能力 - 删除手动初始化
self.tree的代码,commands.Bot已经内置了app_commands.CommandTree实例,直接用self.tree即可 - 保留
setup_hook中的扩展加载和命令同步逻辑,这部分无需修改
Cog中同时使用前缀命令和Slash命令示例
在你的Cog文件(比如cogs/dashboard.py)中,可以同时定义两种命令:
from discord.ext import commands from discord import app_commands class Dashboard(commands.Cog): def __init__(self, bot): self.bot = bot # 前缀命令(使用!触发) @commands.command(name="ping") async def ping_prefix(self, ctx): await ctx.send(f"前缀命令Pong!延迟:{round(self.bot.latency*1000)}ms") # Slash命令(通过/触发) @app_commands.command(name="ping", description="Slash命令:查看机器人延迟") async def ping_slash(self, interaction): await interaction.response.send_message(f"Slash命令Pong!延迟:{round(self.bot.latency*1000)}ms") async def setup(bot): await bot.add_cog(Dashboard(bot))
这样修改后,机器人就能正常加载Cog,同时支持前缀命令和Slash命令了。
内容的提问来源于stack exchange,提问作者Eduardo Viana
相关产品推荐
相关产品推荐

