这意味着discord(pycord)中的属性custom_id

问题描述 投票:0回答:1

这意味着 discord(pycord) 中的属性 custom_id 并显示具有此属性的示例

我不明白什么在哪里以及为什么需要它。我有一只猫,但我想了解 custom_id 的用途,如果可能的话,将代码添加到机器人中。

python pycord
1个回答
0
投票

文档

通过

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)

这会产生:

First button press

上面是第一次按下按钮

Second button press

上面是机器人重新启动后按下的第二个按钮。

© www.soinside.com 2019 - 2024. All rights reserved.