discord.py 2.0中Cog内模态框关联斜杠命令未在服务器同步
问题:带模态框的斜杠命令无法在Discord服务器同步
尝试创建关联文本输入框的斜杠命令,但该命令无法同步到目标Discord服务器;移除模态框相关代码后命令可正常同步,代码运行在Cog中且无报错信息。
错误代码示例:
import discord from discord import app_commands,ui from discord.ext import commands import interactions class Box(commands.Cog): def __init__(self, bot: commands.bot): self.bot = bot @commands.Cog.listener() async def on_ready(self): print('input text') class SurveyModal(ui.Modal, title='Survey'): name= ui.TextInput(label='Name') answer = ui.TextInput(label='q1', style= discord.TextStyle.short) async def on_submit(self,interaction: discord.Interaction): await interaction.response.send_message('thanks') @app_commands.command(name="input", description="test input") async def box(self, interaction: discord.Interaction): await interaction.response.send_modal(SurveyModal()) async def setup(bot): await bot.add_cog(Box(bot), guilds=[discord.Object(id='975632483750137878')])
问题原因
@app_commands.command装饰器被错误放置在SurveyModal模态框类内部,而非Box这个Cog类中。Discord.py的Cog只会扫描自身类内部的命令装饰器来注册斜杠命令,模态框类不属于Cog的一部分,因此该命令无法被识别和同步。
修正后的代码
import discord from discord import app_commands, ui from discord.ext import commands import interactions class SurveyModal(ui.Modal, title='Survey'): name = ui.TextInput(label='Name') answer = ui.TextInput(label='q1', style=discord.TextStyle.short) async def on_submit(self, interaction: discord.Interaction): await interaction.response.send_message('thanks') class Box(commands.Cog): def __init__(self, bot: commands.Bot): self.bot = bot @commands.Cog.listener() async def on_ready(self): print('input text') @app_commands.command(name="input", description="test input") async def box(self, interaction: discord.Interaction): await interaction.response.send_modal(SurveyModal()) async def setup(bot): await bot.add_cog(Box(bot), guilds=[discord.Object(id='975632483750137878')])
关键调整点
- 将
SurveyModal类独立于Cog类定义,保持模态框逻辑独立性 - 将
@app_commands.command装饰的box方法移到BoxCog类内部,确保Cog能识别并注册斜杠命令 - 修正类型提示写法:
commands.bot改为commands.Bot
验证步骤
- 确保机器人在目标服务器拥有应用程序命令权限
- 重启机器人,等待Cog加载完成
- 在服务器输入
/input,检查是否正常触发模态框
内容的提问来源于stack exchange,提问作者needyou
相关产品推荐
相关产品推荐

