Discord.PY Button UI交互重启后失败

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

所以我一直在努力让这个不和谐按钮起作用。它确实,有点... 该按钮按预期工作。但在重新启动后,该按钮失去所有功能并在单击时显示“交互失败”。这意味着我每次重新启动机器人时都必须再次发送按钮。

import discord
import config
import discord.ui
from discord.ext import commands

intents = discord.Intents.all()
client = discord.Client(intents=intents)

bot = commands.Bot(command_prefix=config.PREFIX, intents=intents, help_command=None)

class VerifyButton(discord.ui.View):

    def __init__(self):
        super().__init__(timeout=None)

    @discord.ui.button(label="Click me!", style=discord.ButtonStyle.green, custom_id='verify_button')
    async def click(self, interaction: discord.Interaction, Button: discord.ui.Button):

        role = config.ROLE

        if config.ROLE in [y.id for y in interaction.user.roles]:
            await interaction.user.remove_roles(interaction.user.guild.get_role(role))
            await interaction.response.send_message("You've unverified yourself", ephemeral = True)

        else:
            await interaction.user.add_roles(interaction.user.guild.get_role(role))
            await interaction.response.send_message("You've been verified", ephemeral = True)

class VerifyViewBot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.default()
        intents.message_content = True

        super().__init__(command_prefix=config.PREFIX, intents=intents)

    async def setup_hook(self) -> None:
        self.add_view(VerifyButton())

@client.event
async def on_ready():
    print(f'Successfully logged in as {client.user}')

    bot.add_view(VerifyButton())
    await bot.setup_hook()

@client.event
async def on_message(message):
    if message.content.lower().startswith(f'{config.PREFIX}verify'):
        embed = discord.Embed(title="Verify!", description="Read the rule, and press the button to Verify!")
        await message.channel.send(embed=embed, view=VerifyButton())

在 Windows 中运行代码时,没有任何问题,并且在机器人重新启动后按钮仍然有效。

Linux/Mac 重启后无法正常工作。考虑到它仍然是 python,我个人不明白为什么它的行为会有所不同。

我知道你需要一个 persistent 让它在重启之间持续存在。我有,但只能在 Windows 中使用。

python button discord.py interaction
1个回答
0
投票

你这里有 3 不同类型的客户,你出于某种原因混合了他们。你应该只有1.

  • client = discord.Client(...)
    :这是一个
    Client
    实例,没有
    Bot
    功能
  • bot = commands.Bot(...)
    :这是一个
    Bot
  • 你的
    VerifyViewBot
    :这是你自己的子类,但你永远不会在任何地方使用它

您的

on_ready
已注册到
client
,但由于某种原因,您在其中调用
bot.setup_hook
client
bot
是两个不同的变量,并且是两个不同类的两个不同实例。这没有任何意义。

此外,

bot.setup_hook
不做任何事情,因为这是默认的(空)
setup_hook
方法。

创建您自己子类的实例,并将所有事件监听器注册到that。另外,不要手动调用

setup_hook
,图书馆会为你做。

摆脱

client
bot
。你不需要他们做任何事。你有自己的子类可以使用。

关于持久视图,有一个官方示例可以参考:https://github.com/Rapptz/discord.py/blob/master/examples/views/persistent.py

最后,您使用的是

commands.Bot
,因此您可以访问命令。在
on_message
中手动解析消息内容没有意义,只需使用
commands
框架即可为您完成此操作。

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