#Buttons do not work with my bot

1 messages · Page 1 of 1 (latest)

severe fossil
#

When i use this code on my bot it does not work and i get interaction failed when i click the bot

severe fossil
hexed idol
#

You'll need to make it persistent

grizzled hatch
#

Its only 180 seconds or 3 minutes

grizzled hatch
grizzled hatch
severe fossil
grizzled hatch
#

Do you use discord.Bot or commands.Bot?

severe fossil
grizzled hatch
#

Im asking because you await the cogs and other stuff

severe fossil
severe fossil
grizzled hatch
#

Can you show the pip list pls

severe fossil
# grizzled hatch Can you show the pip list pls

Package Version


aiohttp 3.9.3
aiosignal 1.3.1
asn1crypto 1.5.1
async-timeout 4.0.3
asyncio 3.4.3
attrs 23.2.0
betterproto 2.0.0b6
certifi 2024.2.2
cffi 1.16.0
charset-normalizer 3.3.2
cryptography 42.0.5
discord 2.3.2
discord.py 2.3.2
frozenlist 1.4.1
grpclib 0.4.7
h2 4.1.0
hpack 4.0.0
http-ece 1.2.0
hyperframe 6.0.1
idna 3.6
multidict 6.0.5
numpy 1.26.4
oscrypto 1.3.0
pillow 10.2.0
pip 22.0.2
protobuf 5.26.0
py-cord 2.5.0
pyarrow 15.0.0
pycparser 2.21
pylance 0.10.5
PyNaCl 1.5.0
python-dateutil 2.9.0.post0
python-dotenv 1.0.1
requests 2.31.0
rustplus 5.6.15
rustPlusPushReceiver 0.4.1
scipy 1.12.0
setuptools 59.6.0
six 1.16.0
typing_extensions 4.10.0
urllib3 2.2.1
websockets 12.0
yarl 1.9.4

grizzled hatch
severe fossil
grizzled hatch
#

Yes

#

Only py-cord

severe fossil
# grizzled hatch Only py-cord

But now i get this error and none of my commands work:

/Discord-Bots/PVV-Pycord/bot-env/lib/python3.10/site-packages/discord/cog.py:790: RuntimeWarning: coroutine 'setup' was never awaited
setup(self)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
commands.embed file is met succes geladen
events.ready file is met succes geladen
commands.mod file is met succes geladen
commands.voice file is met succes geladen
events.member_join file is met succes geladen
events.moderation file is met succes geladen
logs.voice file is met succes geladen
logs.messages file is met succes geladen
commands.record file is met succes geladen
commands.roles file is met succes geladen
events.member_leave file is met succes geladen
logs.roles file is met succes geladen
logs.member file is met succes geladen
custom.team2 file is met succes geladen
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "recruit" is not found

start.py:
import discord
from discord.ext import commands
from dotenv import load_dotenv
import os
import asyncio

load_dotenv()

intents = discord.Intents.all()
bot = commands.Bot(command_prefix=".", intents=intents)
TOKEN = os.getenv('DISCORD_TOKEN')

cog_files = ["commands.embed", "events.ready", "commands.mod", "commands.voice", "events.member_join", "events.moderation", "logs.voice", "logs.messages", "commands.record", "commands.roles", "events.member_leave", "logs.roles", "logs.member", "custom.team2"]

async def load_cogs():
for cog_file in cog_files:
try:
bot.load_extension(cog_file)
print(f"{cog_file} file is met succes geladen")
except Exception as e:
print(f"Failed to load extension {cog_file}: {e}")

async def start_bot():
await load_cogs()
await bot.start(TOKEN)

if name == "main":
asyncio.run(start_bot())

grizzled hatch
#

Yea

#

Because pycord is not using all the await at the setup and cogs

severe fossil
#

Ah oke so i need to remove the async and await and then it should work oke

grizzled hatch
#

At the setup functions, load_extension

severe fossil
# grizzled hatch At the setup functions, load_extension

Sorry for all of the questions. I am just starting programming with Discord bots and now i am getting this error with my on_ready.py

Failed to load extension events.on_ready: Extension 'events.on_ready' raised an error: ValueError: The 'name' parameter must start with 'on_'

import discord
from discord.ext import commands
from datetime import datetime
import asyncio

class ready_event(commands.Cog):
def init(self, bot):
self.bot = bot

@commands.Cog.listener()
async def on_ready(self):
    guild = discord.utils.get(self.bot.guilds, id=1214620281633771550)
    formatted_timestamp = datetime.now().strftime('%d-%m-%Y %H:%M:%S')
    servernaam = guild.name
    logscat = discord.utils.get(guild.categories, name=f'📄 | {servernaam} BOT LOGS')
    welcomechannel = discord.utils.get(guild.channels, name='🖐┃welcome')
    welcomecat = discord.utils.get(guild.channels, name=f'🖐 | Welkom bij de {servernaam}')
    logsrol = discord.utils.get(guild.roles, name='*')
    overwrites = {
        guild.default_role: discord.PermissionOverwrite(read_messages=False),
        guild.me: discord.PermissionOverwrite(read_messages=True)
    }
    joinlogschannel = discord.utils.get(guild.channels, name='〡🔧・join-logs')
    leavelogschannel = discord.utils.get(guild.channels, name='〡🔧・leave-logs')
    print("Servers waar de server in zit:")
    for guild in self.bot.guilds:
        print(guild.name)
    if guild is not None:
        members = guild.member_count
        print(f"De {self.bot.user} is met succes gestart")
        self.bot.loop.create_task(self.update_presence())
    else:
        print("De ingestelde guild niet gevonden")
    if logscat is None:
        await guild.create_category(f'📄 | {servernaam} BOT LOGS', reason="Logs Categorie is niet gevonden en word nu aangemaakt", overwrites=overwrites)
        print("logscat is niet gevonden en is dus aangemaakt.")
        return

@commands.Cog.listener()
async def update_presence(self):
    while True:
        guild = discord.utils.get(self.bot.guilds, id=1214620281633771550)
        if guild is not None:
            formatted_timestamp = datetime.now().strftime('%d-%m-%Y %H:%M:%S')
            members = guild.member_count
            await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f"{members} Discord Leden"))
        await asyncio.sleep(180)

def setup(bot):
bot.add_cog(ready_event(bot))

#

And still buttons do not work

import discord
from discord.ext import commands

class MyView(discord.ui.View): # Create a class called MyView that subclasses discord.ui.View
@discord.ui.button(label="Click me!", style=discord.ButtonStyle.primary, emoji="😎") # Create a button with the label "😎 Click me!" with color Blurple
async def button_callback(self, button, interaction):
await interaction.response.send_message("You clicked the button!") # Send a message when the button is clicked

class Team2(commands.Cog):
def init(self, bot):
self.bot = bot

@commands.command()
async def teaminfo(self, ctx:commands.Context):
    await ctx.send("Teaminfo Embed", view=MyView())

def setup(bot):
bot.add_cog(Team2(bot))

hexed idol
#

async def on_presence_update(self):

severe fossil
# severe fossil Sorry for all of the questions. I am just starting programming with Discord bots...

Ignoring exception in view <MyView timeout=180.0 children=1> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='Click me!' emoji=<PartialEmoji animated=False name='😎' id=None> row=None>:
Traceback (most recent call last):
File "/Discord-Bots/PVV-Pycord/bot-env/lib/python3.10/site-packages/discord/ui/view.py", line 426, in _scheduled_task
await item.callback(interaction)
File "/Discord-Bots/PVV-Pycord/custom/team2.py", line 8, in button_callback
await interaction.response.send_message("You clicked the button!") # Send a message when the button is clicked
File "/Discord-Bots/PVV-Pycord/bot-env/lib/python3.10/site-packages/discord/interactions.py", line 918, in send_message
await self._locked_response(
File "/Discord-Bots/PVV-Pycord/bot-env/lib/python3.10/site-packages/discord/interactions.py", line 1243, in locked_response
await coro
File "/Discord-Bots/PVV-Pycord/bot-env/lib/python3.10/site-packages/discord/webhook/async
.py", line 220, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

severe fossil
hexed idol
severe fossil
#

Does it work different with pycord? If so how do i need to do it?

hexed idol
#

if you want to use a task loop:


from discord.ext import tasks

@tasks.loop
async def some_loop():
    pass

some_loop.start()
severe fossil
#

Yes i saw in the docs

#

Thanks anyway

severe fossil
hexed idol
#

probably times out

#

try deferring the interaction

grizzled hatch
#

at the task

hexed idol
#

right

grizzled hatch
#

@severe fossil still there?

severe fossil
#

Yes i am still here. I will try it today

sharp flicker
#

please send me your codes and your error in ```
in this format

#

@severe fossil I made a new code for you:

#

@severe fossil do you use visual studio code?

severe fossil
severe fossil
sharp flicker
severe fossil
#

No not yet

sharp flicker
#

i can help you

severe fossil
#

I am on now

#

@sharp flicker if you could send me the code

grizzled hatch
sharp flicker
sharp flicker
# severe fossil <@688076128857882695> if you could send me the code
import discord
from discord.ext import commands


class MyView(discord.ui.View):
    @discord.ui.button(label="Click me!", style=discord.ButtonStyle.primary, emoji="😎")
    async def button_callback(self, button, interaction):
        await interaction.response.send_message("You clicked the button!", ephemeral=True)


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

    @commands.command()
    async def teaminfo(self, ctx: commands.Context):
        await ctx.send("Teaminfo Embed", view=MyView())


def setup(bot):
    bot.add_cog(Team2(bot))

sharp flicker
severe fossil
severe fossil
# sharp flicker wait

And something else to. This code is not working for me to. The bot repeats the whole task every time and the task.loop does not work:

from discord.ext import tasks, commands
from datetime import datetime
import asyncio

class ready_event(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.update_presence.start()

    @commands.Cog.listener()
    async def on_ready(self):
        guild = discord.utils.get(self.bot.guilds, id=1214620281633771550)
        formatted_timestamp = datetime.now().strftime('%d-%m-%Y %H:%M:%S')
        servernaam = guild.name
        logscat = discord.utils.get(guild.categories, name=f':page_facing_up: | {servernaam} BOT LOGS')
        welcomechannel = discord.utils.get(guild.channels, name=':hand_splayed:┃welcome')
        welcomecat = discord.utils.get(guild.channels, name=f':hand_splayed: | Welkom bij de {servernaam}')
        logsrol = discord.utils.get(guild.roles, name='*')
        overwrites = {
            guild.default_role: discord.PermissionOverwrite(read_messages=False),
            guild.me: discord.PermissionOverwrite(read_messages=True)
        }
        joinlogschannel = discord.utils.get(guild.channels, name='〡:wrench:・join-logs')
        leavelogschannel = discord.utils.get(guild.channels, name='〡:wrench:・leave-logs')
        
        print("Servers waar de server in zit:")
        for guild in self.bot.guilds:
            print(guild.name)
        if guild is not None:
            members = guild.member_count
            print(f"De {self.bot.user} is met succes gestart")
        else:
            print("De ingestelde guild niet gevonden")
        if logscat is None:
            await guild.create_category(f':page_facing_up: | {servernaam} BOT LOGS', reason="Logs Categorie is niet gevonden en word nu aangemaakt", overwrites=overwrites)
            print("logscat is niet gevonden en is dus aangemaakt.")
            return
        
    @tasks.loop()
    async def update_presence(self):
        guild = discord.utils.get(self.bot.guilds, id=1214620281633771550)
        if guild is not None:
            formatted_timestamp = datetime.now().strftime('%d-%m-%Y %H:%M:%S')
            members = guild.member_count
            if members is not None:
                await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f"{members} Discord Leden"))
            elif members is None:
                print(f"members is None en er is een error mee")

def setup(bot):
    bot.add_cog(ready_event(bot))```
#

Never mind i fixed it. I forget that i cant do @tasks.loop()

It needs to be like this: @tasks.loop(seconds=180)

Now i works

severe fossil
grizzled hatch
#

oh

#

for the task you have to wait that the bot is ready

sharp flicker
grizzled hatch
#

add that to the task await self.wait_until_ready() at the first line after the aync def

severe fossil
#

For the button. I fixed it. In my original code i did not add the ephemeral and now i did and it works. Thanks for the help with this. But i have another question. How do i make it so the button still works after a bot restart like you said @grizzled hatch

import discord
from discord.ext import commands


class MyView(discord.ui.View):
    @discord.ui.button(label="Click me!", style=discord.ButtonStyle.primary, emoji="😎")
    async def button_callback(self, button, interaction):
        await interaction.response.send_message("You clicked the button!", ephemeral=False)


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

    @commands.command()
    async def teaminfo(self, ctx: commands.Context):
        await ctx.send("Teaminfo Embed", view=MyView())


def setup(bot):
    bot.add_cog(Team2(bot))```
grizzled hatch
#

ephermeral is only for interactions

#

so slash commands with ctx.respond or something like buttons with interaction

severe fossil
#

Yes i will remember that thanks. How do i make it so the button still works after a bot restart like you said

plush cobaltBOT
#

Here's the persistent example.

sharp flicker
#

lemme check dogs if this is possible

grizzled hatch
severe fossil
#

@grizzled hatch So this is how i make it no it will still work after a restart right? Or am i doing it wrong?

import discord
from discord.ext import commands


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

    @discord.ui.button(label="Farmer", style=discord.ButtonStyle.primary, emoji="🪓", custom_id="farmerinfo")
    async def button_callback(self, button, interaction):
        farmer = "Een farmer farmt constant wat er nodig is."
        await interaction.response.send_message(content=farmer, ephemeral=True)


class Team2Cog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.view = MyView()

    @commands.command()
    async def teaminfo(self, ctx: commands.Context):
        await ctx.send("Teaminfo Embed", view=self.view)


def setup(bot):
    bot.add_cog(Team2Cog(bot))
severe fossil
#

And something else to. This does not work for some reason still it loops the whole on_ready or it shuts down the bot.

import discord
from discord.ext import tasks, commands
from datetime import datetime
import asyncio
import os

class ready_event(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.update_presence_task = None

    @commands.Cog.listener()
    async def on_ready(self):
        if self.update_presence_task is None or self.update_presence_task.done():
            self.update_presence_task = self.update_presence.start()

        guild = discord.utils.get(self.bot.guilds, id=1069735143146799115)
        formatted_timestamp = datetime.now().strftime('%d-%m-%Y %H:%M:%S')
        servernaam = guild.name
        logscat = discord.utils.get(guild.categories, name=f'📄 | {servernaam} BOT LOGS')
        logsrol = discord.utils.get(guild.roles, name='*')
        overwrites = {
            guild.default_role: discord.PermissionOverwrite(read_messages=False),
            guild.me: discord.PermissionOverwrite(read_messages=True)
        }
        joinlogschannel = discord.utils.get(guild.channels, name='〡🔧・join-logs')
        leavelogschannel = discord.utils.get(guild.channels, name='〡🔧・leave-logs')
        
        print("Servers waar de server in zit:")
        for guild in self.bot.guilds:
            print(guild.name)
            print("--------------------------------")
        if guild is not None:
            members = guild.member_count
            print(f"De {self.bot.user} is met succes gestart")
        else:
            print("De ingestelde guild niet gevonden")
        if logscat is None:
            await guild.create_category(f'📄 | {servernaam} BOT LOGS', reason="Logs Categorie is niet gevonden en word nu aangemaakt", overwrites=overwrites)
            print("logscat is niet gevonden en is dus aangemaakt.")
            return
        
    @tasks.loop(seconds=180)
    async def update_presence(self):
        guild = discord.utils.get(self.bot.guilds, id=1069735143146799115)
        if guild is not None:
            formatted_timestamp = datetime.now().strftime('%d-%m-%Y %H:%M:%S')
            members = guild.member_count
            if members is not None:
                await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f"{members} Discord Leden"))
            elif members is None:
                print(f"members is None en er is een error mee")

def setup(bot):
    bot.add_cog(ready_event(bot))```
grizzled hatch
severe fossil
# grizzled hatch You still have to wait for the bot to be ready to start the task

Also with this code over the last 2 hours or so it keeps repeating this and the bot chrashes

import discord
from discord.ext import tasks, commands
from datetime import datetime
import asyncio

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

    @commands.Cog.listener()
    async def on_ready(self):
        guild = discord.utils.get(self.bot.guilds, id=1214620281633771550)
        formatted_timestamp = datetime.now().strftime('%d-%m-%Y %H:%M:%S')
        servernaam = guild.name
        logscat = discord.utils.get(guild.categories, name=f':page_facing_up: | {servernaam} BOT LOGS')
        welcomechannel = discord.utils.get(guild.channels, name=':hand_splayed:┃welcome')
        welcomecat = discord.utils.get(guild.channels, name=f':hand_splayed: | Welkom bij de {servernaam}')
        overwrites = {
            guild.default_role: discord.PermissionOverwrite(read_messages=False),
            guild.me: discord.PermissionOverwrite(read_messages=True)
        }
        joinlogschannel = discord.utils.get(guild.channels, name='〡:wrench:・join-logs')
        leavelogschannel = discord.utils.get(guild.channels, name='〡:wrench:・leave-logs')
        
        print("Servers waar de server in zit:")
        for guild in self.bot.guilds:
            print(guild.name)
        if guild is not None:
            members = guild.member_count
            print(f"De {self.bot.user} is met succes gestart")
            await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f"{guild.name}"))
        else:
            print("De ingestelde guild niet gevonden")
        if logscat is None:
            await guild.create_category(f':page_facing_up: | {servernaam} BOT LOGS', reason="Logs Categorie is niet gevonden en word nu aangemaakt", overwrites=overwrites)
            print("logscat is niet gevonden en is dus aangemaakt.")
            return
        
    #@tasks.loop(seconds=180)
    #async def update_presence(self):
        #guild = discord.utils.get(self.bot.guilds, id=1214620281633771550)
        #if guild is not None:
            #formatted_timestamp = datetime.now().strftime('%d-%m-%Y %H:%M:%S')
            #members = guild.member_count
            #if members is not None:
                #await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f"{members} Discord Leden"))
            #elif members is None:
                #print(f"members is None en er is een error mee")

def setup(bot):
    bot.add_cog(ready_event(bot))```
grizzled hatch
#

and what is the error?

severe fossil
severe fossil
severe fossil
grizzled hatch
severe fossil
# grizzled hatch ;3

Like this?

import discord
from discord.ext import commands


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

    @discord.ui.button(label="Farmer", style=discord.ButtonStyle.primary, emoji="🪓", custom_id="farmerinfo")
    async def button_callback(self, button, interaction):
        farmer = "Een farmer farmt constant wat er nodig is."
        await interaction.response.send_message(content=farmer, ephemeral=True)


class PersistentViewBot(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.persistent_views_added = False
        self.view = MyView()
        
    @commands.command()
    async def teaminfo(self, ctx: commands.Context):
        await ctx.send("Teaminfo Embed", view=self.view)

    @commands.Cog.listener()
    async def on_ready(self):
        if not self.persistent_views_added:
            self.add_view(MyView())
            self.persistent_views_added = True

def setup(bot):
    bot.add_cog(PersistentViewBot(bot))

grizzled hatch
#

remove that self.persistent_views_added = True

severe fossil
# grizzled hatch remove that `self.persistent_views_added = True`

Oke but now with this code:

import discord
from discord.ext import commands


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

    @discord.ui.button(label="Farmer", style=discord.ButtonStyle.primary, emoji="🪓", custom_id="farmerinfo")
    async def button_callback(self, button, interaction):
        farmer = "Een farmer farmt constant wat er nodig is."
        await interaction.response.send_message(content=farmer, ephemeral=True)


class PersistentViewBot(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.persistent_views_added = False
        self.view = PersistentView()
        
    @commands.command()
    async def teaminfo(self, ctx: commands.Context):
        await ctx.send("Teaminfo Embed", view=self.view)

    @commands.Cog.listener()
    async def on_ready(self):
        if not self.persistent_views_added:
            self.add_view(PersistentView())

def setup(bot):
    bot.add_cog(PersistentViewBot(bot))

I get this error

Ignoring exception in on_ready
Traceback (most recent call last):
  File "/Discord-Bots/PVV-Pycord/bot-env/lib/python3.10/site-packages/discord/client.py", line 400, in _run_event
    await coro(*args, **kwargs)
  File "/Discord-Bots/PVV-Pycord/custom/team2.py", line 28, in on_ready
    self.add_view(PersistentView())
AttributeError: 'PersistentViewBot' object has no attribute 'add_view'
severe fossil
# severe fossil

But this error is more annoying because my bots dont stay online for more then 30 minutes

grizzled hatch
#

just do self.add_view(THE VIEW)

severe fossil
# grizzled hatch just do self.add_view(THE VIEW)

The error is that add_view does not exist?

And it seems that the on_ready seems repeating it self. Like it renews or something and then triggers all of the events again and that chrashes the bot

severe fossil
#

Do i need to know this?

grizzled hatch
#

dont overwrite the on_connect event

severe fossil
severe fossil
# sharp flicker still need help?

Yes and elspecialy with this: #1220715560959213659 message

#1220715560959213659 message

#1220715560959213659 message
But also with the buttons

sharp flicker
#

please send me your code and the errors

sharp flicker
severe fossil
sharp flicker
#

lemme check

mellow cove