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

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')])

关键调整点

  1. 将SurveyModal类独立于Cog类定义,保持模态框逻辑独立性
  2. 将@app_commands.command装饰的box方法移到Box Cog类内部,确保Cog能识别并注册斜杠命令
  3. 修正类型提示写法:commands.bot改为commands.Bot

验证步骤

  1. 确保机器人在目标服务器拥有应用程序命令权限
  2. 重启机器人,等待Cog加载完成
  3. 在服务器输入/input,检查是否正常触发模态框

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 13:10:34