這是一篇 Discord Bot 的進階教學,會使用 [Python Cog 架構](https://hackmd.io/@smallshawn95/python_discord_bot_cog)撰寫。 彈出對話框在許多 UI 程式開發中扮演了重要的角色,這些對話框提供一個全新的互動方式,它們不僅可以彈出提醒訊息或者確認對話框,還能彈出讓使用者輸入資料的對話框來收集資料。 在 Discord 中,開發者可以使用 Modal 工具來實現這樣的彈出對話框,為 Discord Bot 帶來更強大的互動性,以下將來學習如何在 Discord 使用 Modal 工具。 :::success :book: **更多 Python Discord Bot 教學系列和程式範例** https://github.com/smallshawn95/Python-Discord-Bot-Course ::: --- [TOC] --- ## 一、Modal 簡介: Discord Modal 是 Discord 中用來製作彈出對話框的工具,讓使用者利用更直觀的介面,與能夠換行的性質,可以用於處理複雜的互動,來輸入需要較多文字的資料。 Discord Modal 是由「discord.ui.TextInput 文字輸入」這個 Item 元素組成,一個 Modal 中最多只能添加五個 Item 元素。 更多資訊可參考 [Discord.py Modal 官方文檔](https://discordpy.readthedocs.io/en/stable/interactions/api.html?#discord.ui.Modal)。 ## 二、Modal 撰寫: ```python= # 繼承 discord.ui.Modal 類別,並傳入 title 參數 class ModalClass(discord.ui.Modal, title = "設定名稱"): # 宣告一個 TextInput Item 元素 name = discord.ui.TextInput(label = "Name") # Modal 提交後接著要執行的程式碼 async def on_submit(self, interaction: discord.Interaction): await interaction.response.send_message(f"Hello, {self.name.value}!") ``` ```python= @app_commands.command(name = "modal_base", description = "Modal 基本範例") async def modal_base(self, interaction: discord.Interaction): # 回覆 Modal 給使用者 await interaction.response.send_modal(ModalClass()) ```   ## 三、TextInput 參數: ```python discord.ui.TextInput(label: str, style: discord.TextStyle, placeholder: str, default: str, required: bool, min_length: int, max_length: int, custom_id: str, row: int) ``` * **label 標籤** TextInput 的標題。 * **style 風格** TextInput 的風格分成兩種,short 和 paragraph(long)。 * **placeholder 提示文字** TextInput 輸入為空時,顯示提示文字。 * **required 必填** TextInput 是否必填。 * **default 預設值** TextInput 的預設內容。 * **min_length 最小長度** TextInput 最小的輸入內容長度。 * **max_length 最大長度** TextInput 最大的輸入內容長度。 * **custom_id 交互 ID** 交互期間收到的 TextInput ID。 * **row 相對行號** Discord Modal 允許 TextInput 最多 5 個,預設情況會自動排序,如果要控制相對位置,則行號 row = 1 會在 row = 3 之前,行號必須介於 0 到 4 之間。 ## 四、Modal 重點整理: 1. 一個 Modal 最多有 5 個 TextInput。 2. 傳送 Modal 的程式碼更改成 `send_modal()`。 3. TextInput 兩種 style 的差異,short 只能單行輸入,而 paragraph(long) 允許多行輸入。 4. TextInput 預設 required 為 True 值,當使用者未輸入內容就提交時,會提醒使用者需將必填的內容補齊。 5. TextInput 額外設置最大最小長度,當使用者輸入內容不符合格式就提交時,會提醒使用者需改為正確的輸入格式。 --- :::info 📢 **歡迎加入我的 Discord 伺服器** https://discord.gg/Jtd3eVrFJs ::: *Copyright © 2024 SmallShawn95. All rights reserved.*
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.