Reputation: 21
from discord.ext import commands
from discord import app_commands
import json
from discord.ui import Button
with open('.\config.json') as f:
data = json.load(f)
class button(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="Button", style=discord.ButtonStyle.success, custom_id="ver")
async def verify(self, interaction: discord.Interaction, button:discord.ui.Button):
user = interaction.user
role = interaction.guild.get_role(data['verify_role'])
await user.add_roles(role)
await interaction.response.send_message(f"success", ephemeral = True)
class verify(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
@commands.Cog.listener()
async def on_interaction(self, interaction: discord.Interaction):
green = await bot.wait_for("button_click", check = lambda k: k.custom_id == "ver")
await green.send(content="Button smashed!", ephemeral=False)
@app_commands.command(name = "ver", description = "ver")
async def verify(self, interaction: discord.Interaction) -> None:
await interaction.response.send_message(view=button())
async def setup(bot: commands.Bot) -> None:
await bot.add_cog(verify(bot))
I made a verify button, but when I reload the bot, I have to command it again. I want to use on_interaction to prevent him, but I don't have enough understanding of it. How do I get the button to work when the bot is reloaded?
Upvotes: 0
Views: 930
Reputation: 140
You need to add the view when the cog gets loaded for it to be a persistent view
class verify(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
bot.add_view(button())
Read more on bot.add_view()
: https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.add_view
Example of persistent views: https://github.com/Rapptz/discord.py/blob/master/examples/views/persistent.py
Upvotes: 1