这意味着 discord(pycord) 中的属性 custom_id 并显示具有此属性的示例
我不明白什么在哪里以及为什么需要它。我有一只猫,但我想了解 custom_id 的用途,如果可能的话,将代码添加到机器人中。
通过
custom_id
我假设你的意思是按钮创建的参数。请参阅此处。
custom_id 是:
交互期间收到的按钮的 ID。 如果此按钮用于 URL,则它没有自定义 ID。
您是否遇到过机器人重启后无法访问过去的可交互视图的问题?好吧,
custom_id
对于这个目的很有用。如果我们将 custom_id
设置为任何值,则在机器人重新启动后,它应该保存视图(如果机器人加载视图并且视图没有超时)。
这是一些示例代码:
import os
import discord
from discord.ui import View, Button
# --- Bot Setup ---
bot = discord.Bot()
@bot.listen() # ensures that it doesn't override the event method that syncs the bot
async def on_connect():
bot.add_view(EpicView()) # Add the view to make it persistent
print("Bot is connected!")
class EpicView(View): # The persistent view
def __init__(self, ):
super().__init__(timeout=None) # A timeout of None is required
@discord.ui.button(
label="Hello!",
style=discord.ButtonStyle.blurple,
custom_id="hello_button",
)
async def hello(self, button: discord.Button, interaction: discord.Interaction): # the button that uses the custom_id to make the persistent view
await interaction.respond("This works!")
@bot.slash_command()
async def send_view(ctx): # basic slash command to send the view
view = EpicView()
await ctx.respond("Hi!", view=view)
上面是第一次按下按钮
上面是机器人重新启动后按下的第二个按钮。