簡體   English   中英

Disnake/discord.py 無限期等待響應

[英]Disnake/discord.py indefinitely await reponse

當我使用我的 python 機器人創建按鈕並處理回調或發送消息並等待 discord 中的反應時,這似乎是時間有限的。 有時大約 1 小時后,機器人不再記錄反應。 當然,一旦我重新啟動機器人,連接就會丟失,它不會再注冊交互了。

但是,我在 discord 中看到機器人總是對按鈕做出反應,無論該按鈕是多久之前創建的。 有沒有辦法做到這一點? 我是否必須定期將機器人“重新連接”到它創建的按鈕?

簡單的例子:

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())

-> 在此示例中,機器人在經過一段時間后不再對按鈕單擊做出反應,或者我重新啟動了機器人。

你可以這樣做:

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 存儲庫

我認為您的互聯網很可能存在連接問題,並且您在沒有注意到的情況下斷開連接。

這發生在我身上,所以我添加了 on_disconnect 和 on_resumed 機器人事件,它們只是簡單的打印語句,以便我能夠檢查這是否是問題的根源。

bot: commands.Bot = commands.Bot(command_prefix='.', intents=intents)
bot.time = time.time()

@bot.event
async def on_ready():
    print(f"Logged in as {bot.user} (ID: {bot.user.id})")
    print('TesterBot is ready starting at ' + time.ctime(bot.time))

@bot.event
async def on_disconnect():
    uptimedelta = time.time() - bot.time
    print('TesterBot is disconnected at ' + time.ctime(bot.time) + '. Testerbot has been up for ' + str(datetime.timedelta(seconds=uptimedelta)))

@bot.event
async def on_resumed():
    uptimedelta = time.time() - bot.time
    print("TesterBot reconnected " + time.ctime(bot.time) + '. Testerbot has been up for ' + str(datetime.timedelta(seconds=uptimedelta)))

@bot.event
async def on_connect():
    print('TesterBot is connected starting at ' + time.ctime(time.time()))

像這樣的基本東西有助於揭示問題在於我的機器正在斷開連接。 這是我的互聯網的物理問題,而不是編碼錯誤或對 api 或庫的誤解。

等待 inter.response.defer(在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM