這是一篇 Discord Bot 的進階教學,會使用 [Python Cog 架構](https://hackmd.io/@smallshawn95/python_discord_bot_cog)撰寫。 各位有沒有曾經看過某些 Bot 指令呼叫後,回覆的不只文字和 Embed 訊息,還有按鈕、下拉選單等等功能,本次教學要來簡單介紹以及實作 Discord 中的 View 工具,下次教學則會繼續完成按鈕、下拉選單等等功能。 :::success :book: **更多 Python Discord Bot 教學系列和程式範例** https://github.com/smallshawn95/Python-Discord-Bot-Teach.git ::: --- [TOC] --- ## 一、View 簡介: Discord View 是 Discord 中一個用來製作互動式使用者交互介面的工具,藉由創建按鈕、下拉選單等等元素,讓用戶可以透過點擊按鈕或選擇下拉選單來和 Bot 互動。 Discord View 的基本內容是由 Item 元素組合而成,常見的 Item 元素有「discord.ui.Button 按鈕」、「discord.ui.Select 下拉選單」。 更多資訊可參考 [Discord.py View 官方文檔](https://discordpy.readthedocs.io/en/stable/interactions/api.html#view)。 ## 二、View 基本語法: 創建一個 Discord View 其實非常簡單,只要使用 `discord.ui.View(timeout = 180)` 即可創建出最基本的 View,其中的 `timeout` 參數代表 View 會在規定時間後失效,如果沒傳入參數則預設 `timeout` 為 180 秒,底下是創建 View 的兩種方式,通常都是使用 Class 版本,靈活性會相較函式版本高。 ### 函式版本 ![](https://hackmd.io/_uploads/SkQ8xc8d3.png) ```python= @app_commands.command(name = "view_base", description = "簡單 View 範例") async def view_base(self, interaction: discord.Interaction): # 創建一個 View,並設置 30 秒超時 view = discord.ui.View(timeout = 30) # 添加一個 Button 到 View 中 view.add_item(discord.ui.Button(label = "Button")) await interaction.response.send_message(view = view) ``` ### Class 版本 ![](https://hackmd.io/_uploads/rJeuugqUu2.png) ```python= # 宣告一個 ViewClass 類別,繼承 discord.ui.View class ViewClass(discord.ui.View): def __init__(self, timeout: float | None = 180): super().__init__(timeout = timeout) # 添加一個 Button 到 ViewClass 中 self.add_item(discord.ui.Button(label = "Button")) ``` ```python= @app_commands.command(name = "view_class", description = "Class 版本 View 範例") async def view_class(self, interaction: discord.Interaction): # 創建一個 ViewClass 類別,並設置 30 秒超時 view = ViewClass(timeout = 30) await interaction.response.send_message(view = view) ``` ## 三、View 額外語法: ### children 使用串列回傳目前 View 中所有的 Item 元素。 ```python= @app_commands.command(name = "view_children", description = "回傳目前 View 所有 Item 元素") async def view_children(self, interaction: discord.Interaction): view = discord.ui.View() view.add_item(discord.ui.Button(label = "Button")) view.add_item(discord.ui.Button(label = "Hello, world!")) await interaction.response.send_message(view.children, view = view) ``` ![](https://hackmd.io/_uploads/Hk15kX1t3.png) ### add.item() 在 View 中添加一個 Item 元素。 ### remove_item() 在 View 中移除一個 Item 元素。 ### clear_items() 清除所有在 View 中所有的 Item 元素。 ### on_timeout() 在 View 超時時會執行此函式中自定義的動作。 --- 此次 Discord View 教學中,我們簡單實作了最基本的 View,而 View 的重頭戲則是平常看到的按鈕和下拉選單等等元素,筆者下次會詳細介紹按鈕和下拉選單該如何撰寫、使用,敬請期待接下來的教學。 --- :::info 📢 **歡迎加入我的 Discord 伺服器** https://discord.gg/Jtd3eVrFJs ::: *Copyright © 2023 SmallShawn95. All rights reserved.*