Discord.py 按钮持久性混乱

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

我希望使信息发布上的按钮保持不变,以便即使在我的机器人重新启动后它们仍然可以交互,但我不完全确定它将如何工作以及它将如何应用于我的代码。我目前正在为我的不和谐机器人使用齿轮。我研究了持久性,甚至检查了示例,但正在努力将其实现到我的代码中

main.py

import discord
from discord.ext import commands
from discord import app_commands
import asyncio
from variables import cogs, success, failed, check_is_it_us, MY_GUILD, TOKEN, status

bot = commands.Bot(command_prefix=">", intents=discord.Intents.all())

@bot.event
async def on_ready():
    synced = await bot.tree.sync()
    print(f"Logged in as {bot.user} (ID: {bot.user.id})")
    print(f"Loaded {success}") if failed == [] else print(f"Loaded {success}\nFailed to load {failed}")
    print(f"Synced {len(synced)} commands.")  
    await bot.change_presence(activity = discord.Game(name=status))

@bot.tree.command(name="sync")
@app_commands.check(check_is_it_us)
async def sync(interaction: discord.Interaction):
    bot.tree.copy_global_to(guild=MY_GUILD)
    synced = await bot.tree.sync()
    print(f"Synced {len(synced)} commands.")  
    await interaction.response.send_message(f"Synced {len(synced)} commands.", ephemeral=True)
        
async def loadCogs():
    for cog in cogs:
        try:
            await bot.load_extension(f"Cogs.{cog}")
            success.append(cog)
        except Exception as e:
            print(e)
            failed.append(cog)

async def main():
    await loadCogs()

asyncio.run(main())
bot.run(TOKEN)

我想要永久按钮的齿轮称为

info.py
,命令称为
/sendinfo
,基本上我只是希望机器人发送一条消息,用户可以单击按钮来查看规则的临时消息,并能够获得 Member 角色。

info.py

import discord
from discord.ext import commands
from discord import app_commands
from typing import Literal
import platform
from variables import suggestionChannel, pollChannel, pollRole, timeformat, stats, convertTime, check_is_it_us, rules
import asyncio
import random
from discord.utils import get

class info(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
    
    

    createGroup = app_commands.Group(name="create", description="Allows you to create suggestions and polls")
    infoGroup = app_commands.Group(name="info", description="Shows you info")

    @app_commands.command(name="sendinfo", description="Sends the information message")
    @app_commands.check(check_is_it_us)
    async def sendinfo(self, interaction:discord.Interaction):
        view=discord.ui.View(timeout=None)

        async def rulesButtoncallback(interaction:discord.Interaction):
            rulesEmbed = discord.Embed(title="Official Rules for DRags Club", description="Please agree to our guidelines.")
            for item in rules:
                rule = item.split("|")
                rulesEmbed.add_field(name=rule[0], value=rule[1], inline=False)
            await interaction.response.send_message(embed=rulesEmbed, ephemeral=True)
        
        rulesButton = discord.ui.Button(style = discord.ButtonStyle.blurple, label = "Rules")
        rulesButton.callback = rulesButtoncallback
        
        view.add_item(rulesButton)
        async def verifyButtoncallback(interaction:discord.Interaction):
            role = get(interaction.guild.roles, name = "Member")
            await interaction.user.add_roles(role)
            await interaction.response.send_message("You have been verified!", ephemeral=True)

        verifyButton = discord.ui.Button(style = discord.ButtonStyle.blurple, label = "Verify")
        verifyButton.callback = verifyButtoncallback
        view.add_item(verifyButton)
        embed=discord.Embed(colour= 000, title = "DRags' Club", description = "Welcome to the home of [DRags](https://www.youtube.com/@_DRags). Explore the **2 year old** server and see what we have to offer!")
        await interaction.channel.send(embed=embed, view=view)
        await interaction.response.send_message(f"The information message has been sent in {interaction.channel}!", ephemeral=True)
        
async def setup(bot):
    await bot.add_cog(info(bot))

请注意,为了简单起见,我删除了此齿轮中的更多命令。

rules
variables.py

的结构
rules = ["rule name|rule description","rule name|rule description"]

所以基本上我想知道如何使该命令上的按钮持久存在,我也在这里链接了该命令的屏幕截图。

python discord.py persistent
1个回答
1
投票

将你的视图改为基于类的,它会更容易管理。

class MyPersistentView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)

    @discord.ui.button(label="Rules", custom_id="rules-button", style=discord.ButtonStyle.blurple)
    async def rules_callback(self, interaction, button):
        rulesEmbed = discord.Embed(title="Official Rules for DRags Club", description="Please agree to our guidelines.")
        for item in rules:
            rule = item.split("|")
            rulesEmbed.add_field(name=rule[0], value=rule[1], inline=False)
        await interaction.response.send_message(embed=rulesEmbed, ephemeral=True)

    @discord.ui.button(label="Verify", custom_id="verify_button", style=discord.ButtonStyle.blurple)
    async def verify_callback(self, interaction, button)
        role = get(interaction.guild.roles, name = "Member")
        await interaction.user.add_roles(role)
        await interaction.response.send_message("You have been verified!", ephemeral=True)


class info(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    createGroup = app_commands.Group(name="create", description="Allows you to create suggestions and polls")
    infoGroup = app_commands.Group(name="info", description="Shows you info")

    @app_commands.command(name="sendinfo", description="Sends the information message")
    @app_commands.check(check_is_it_us)
    async def sendinfo(self, interaction:discord.Interaction):
        view = MyPersistentView(timeout=None)
        await interaction.response.send_message(view=view)

现在创建持久视图非常简单。在

setup_hook
方法内部调用
bot.add_view
并传递
MESSAGE_ID
(您可以通过在发送初始消息后复制不和谐中的消息 ID 来完成此操作)

from cogs.info import MyPersistentView  # or wherever you defined your view class

bot = commands.Bot(command_prefix=">", intents=discord.Intents.all())

MESSAGE_ID = 0

async def setup_hook():
    bot.add_view(MyPersistentView(), message_id=MESSAGE_ID)

bot.setup_hook = setup_hook
© www.soinside.com 2019 - 2024. All rights reserved.