当我创建一个按钮并处理回调或发送消息并等待与我的python机器人不一致的react 时,这似乎是有限的时间.有时在大约1小时后,机器人不再记录react .当然,一旦我重新启动机器人,连接就会丢失,它将不再注册交互.

然而,我见过discord的机器人总是对按钮做出react ,不管按钮是在多长时间前创建的.有没有办法做到这一点?我是否需要定期将机器人"重新连接"到它创建的按钮上?

简单的例子:

class ButtonView(disnake.ui.View):
    def __init__(self):
        super().__init__(timeout=None)

    @disnake.ui.button(label="Hi", style=ButtonStyle.red)
    async def first_button(
        self, button: disnake.ui.Button, interaction: disnake.MessageInteraction
    ):
        await interaction.response.send_message("Button clicked.")

class Test(commands.Cog):
    def __init__(self, bot: commands.Bot):
        self.bot = bot
       
    @commands.slash_command() 
    async def test(self, inter):
        await inter.send("Button!", view=ButtonView())

->在本例中,经过一段时间或我重新启动机器人后,机器人将不再对按钮单击做出react .

推荐答案

你可以这样做:

import disnake
from disnake.ext import commands


# Define a simple View that persists between bot restarts
# In order a view to persist between restarts it needs to meet the following conditions:
# 1) The timeout of the View has to be set to None
# 2) Every item in the View has to have a custom_id set
# It is recommended that the custom_id be sufficiently unique to
# prevent conflicts with other buttons the bot sends.
# For this example the custom_id is prefixed with the name of the bot.
# Note that custom_ids can only be up to 100 characters long.
class PersistentView(disnake.ui.View):
    def __init__(self):
        super().__init__(timeout=None)

    @disnake.ui.button(
        label="Green", style=disnake.ButtonStyle.green, custom_id="persistent_view:green"
    )
    async def green(self, button: disnake.ui.Button, interaction: disnake.MessageInteraction):
        await interaction.response.send_message("This is green.", ephemeral=True)

    @disnake.ui.button(label="Red", style=disnake.ButtonStyle.red, custom_id="persistent_view:red")
    async def red(self, button: disnake.ui.Button, interaction: disnake.MessageInteraction):
        await interaction.response.send_message("This is red.", ephemeral=True)

    @disnake.ui.button(
        label="Grey", style=disnake.ButtonStyle.grey, custom_id="persistent_view:grey"
    )
    async def grey(self, button: disnake.ui.Button, interaction: disnake.MessageInteraction):
        await interaction.response.send_message("This is grey.", ephemeral=True)


class PersistentViewBot(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix=commands.when_mentioned)
        self.persistent_views_added = False

    async def on_ready(self):
        if not self.persistent_views_added:
            # Register the persistent view for listening here.
            # Note that this does not send the view to any message.
            # In order to do this you need to first send a message with the View, which is shown below.
            # If you have the message_id you can also pass it as a keyword argument, but for this example
            # we don't have one.
            self.add_view(PersistentView())
            self.persistent_views_added = True

        print(f"Logged in as {self.user} (ID: {self.user.id})")
        print("------")


bot = PersistentViewBot()


@bot.command()
@commands.is_owner()
async def prepare(ctx: commands.Context):
    """Starts a persistent view."""
    # In order for a persistent view to be listened to, it needs to be sent to an actual message.
    # Call this method once just to store it somewhere.
    # In a more complicated program you might fetch the message_id from a database for use later.
    # However this is outside of the scope of this simple example.
    await ctx.send("What's your favourite colour?", view=PersistentView())


bot.run("token")

这个代码来自disnake repository

Python相关问答推荐

重命名变量并使用载体中的字符串存储 Select 该变量

使用Python从HTTP打印值

使用Curses for Python保存和恢复终端窗口内容

为什么我的(工作)代码(生成交互式情节)在将其放入函数中时不再工作?

如何在Python中按组应用简单的线性回归?

Python无法在已导入的目录中看到新模块

使用Ubuntu、Python和Weasyprint的Docker文件-venv的问题

如何销毁框架并使其在tkinter中看起来像以前的样子?

具有症状的分段函数:如何仅针对某些输入值定义函数?

如何在Python中使用时区夏令时获取任何给定本地时间的纪元值?

Python中使用时区感知日期时间对象进行时间算术的Incredit

从groupby执行计算后创建新的子框架

如何调整QscrollArea以正确显示内部正在变化的Qgridlayout?

如何根据一列的值有条件地 Select 前N组?

Python逻辑操作作为Pandas中的条件

索引到 torch 张量,沿轴具有可变长度索引

如何在Python中获取`Genericums`超级类型?

为什么if2/if3会提供两种不同的输出?

Python Pandas—时间序列—时间戳缺失时间精确在00:00

合并与拼接并举