我们如何才能将 Pycord 中的一个 Modal 的值(2.x)存储在一个 method/function 然后 return 呢?

How can we store the value of a Modal in Pycord (2.x) in a method/function and then return it?

class title_input_modal(Modal):
    def __init__(self):
        super().__init__("Audio Title Input")

        self.add_item(InputText(label = "Audio Title", style = discord.InputTextStyle.short))

    async def callback(self, interaction: discord.Interaction):
        
        val = self.children[0].value
        await interaction.response.send_message(val)

如何创建一个方法并存储响应值?如果我尝试从另一个 cog 的 class 方法访问 title_input_modal.children[0],则会弹出此错误:-

Ignoring exception in view <View timeout=180.0 children=1> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='Play' emoji=<PartialEmoji animated=False name='▶️' id=None> row=None>:
Traceback (most recent call last):
  File "C:\Users\Chinmay Krishna\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ui\view.py", line 371, in _scheduled_task
    await item.callback(interaction)
  File "d:\Programming\python\intellij\intellij_python\AxC-777-Music\no_upload.py", line 137, in play_button_callback
    print(title_input_modal.children[0].value)
AttributeError: type object 'title_input_modal' has no attribute 'children'
Ignoring exception in view <View timeout=180.0 children=1> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='Play' emoji=<PartialEmoji animated=False name='▶️' id=None> row=None>:
Traceback (most recent call last):
  File "C:\Users\Chinmay Krishna\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ui\view.py", line 371, in _scheduled_task
    await item.callback(interaction)
  File "d:\Programming\python\intellij\intellij_python\AxC-777-Music\no_upload.py", line 137, in play_button_callback
    print(title_input_modal.children[0].value)
AttributeError: type object 'title_input_modal' has no attribute 'children'

您可以将值作为 属性 存储在 class 中,并在模式被关闭后访问它。 为此,您必须像这样修改 class。

class title_input_modal(Modal):
    def __init__(self):
        super().__init__("Audio Title Input")
        
        #
        self.val = None

        self.add_item(InputText(label = "Audio Title", style = discord.InputTextStyle.short))

    async def callback(self, interaction: discord.Interaction):
        
        self.val = self.children[0].value
        await interaction.response.send_message(val)
        self.stop()

然后从你调用模态的地方,你必须像这样初始化它,这样你就可以访问它的属性

title_modal = title_input_modal()
await ...send_modal(title_modal)
await title_modal.wait()
print(title_modal.val)

如果没有 stopwait 方法,您的机器人不会等待模态交互结束,所以您不会无法访问用户的值。