discord.py v2.0中使用Cogs与斜杠命令遇RuntimeWarning问题求助
Discord.py v2.0 整合Cogs与斜杠命令的问题解决
问题描述
学习discord.py v2.0时,无法实现Cogs(齿轮模块)与斜杠命令的同时使用,尝试整合官方斜杠命令示例后失败,出现RuntimeWarning: coroutine "main" was never awaited错误。
错误原因分析
- 代码中同时创建了
commands.Bot实例和自定义的abot类(继承自discord.Client),两者功能重叠导致冲突。commands.Bot本身就是discord.Client的子类,无需额外定义客户端类。 - 错误手动实例化了
app_commands.CommandTree,正确的做法是直接使用bot.tree(commands.Bot自带的命令树)。
修正后的代码示例
main.py
import os import asyncio import discord from discord import app_commands from discord.ext import commands MY_GUILD = discord.Object(id=1041079018713260173) # 替换为你的服务器ID TOKEN = "你的机器人令牌" # 初始化Bot,设置命令前缀和所需权限 intents = discord.Intents.default() intents.message_content = True # 如果需要处理消息事件,开启此权限 bot = commands.Bot(command_prefix="!", intents=intents) # Bot就绪事件 @bot.event async def on_ready(): # 同步斜杠命令到指定服务器(全局同步省略guild参数) await bot.tree.sync(guild=MY_GUILD) print(f"已登录为 {bot.user}") print("斜杠命令已同步") # 加载Cogs的函数 async def load_cogs(): for filename in os.listdir("./cogs"): if filename.endswith(".py"): await bot.load_extension(f"cogs.{filename[:-3]}") print(f'已加载Cogs文件:"{filename}"') # 主函数 async def main(): await load_cogs() await bot.start(TOKEN) asyncio.run(main())
在Cogs中添加斜杠命令示例(cogs/slash_commands.py)
import discord from discord import app_commands from discord.ext import commands class SlashCommands(commands.Cog): def __init__(self, bot): self.bot = bot # 定义一个服务器专属斜杠命令 @app_commands.command(name="hello", description="发送问候消息") @app_commands.guilds(discord.Object(id=1041079018713260173)) # 指定服务器 async def hello(self, interaction: discord.Interaction): await interaction.response.send_message(f"你好,{interaction.user.mention}!") # 定义全局斜杠命令(省略guilds装饰器) @app_commands.command(name="ping", description="查看机器人延迟") async def ping(self, interaction: discord.Interaction): await interaction.response.send_message(f"延迟:{round(self.bot.latency * 1000)}ms") async def setup(bot): await bot.add_cog(SlashCommands(bot))
原event.py的修正(保留消息监听)
import discord from discord.ext import commands class Events(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_message(self, message): # 避免机器人响应自己的消息 if message.author == self.bot.user: return print(f"收到消息:{message.content}") async def setup(bot): await bot.add_cog(Events(bot))
关键注意事项
- 确保开启所需的Intents权限(比如
message_content用于处理消息事件),并在Discord开发者门户中启用对应权限。 - 斜杠命令同步:使用
bot.tree.sync(guild=MY_GUILD)进行服务器专属命令同步,全局同步去掉guild参数(全局同步可能需要1小时左右生效)。 - Cogs中的斜杠命令需要使用
@app_commands.command()装饰器,而非传统的@commands.command()。
内容的提问来源于stack exchange,提问作者Snabba_Snigeln
相关产品推荐
相关产品推荐

