#Buttons do not work with my bot
1 messages · Page 1 of 1 (latest)
Any errors in console?
No none
iirc the default timeout for views is 900s
You'll need to make it persistent
No
Its only 180 seconds or 3 minutes
For the IDE error stuff at the discord import you can try to uninstall Pylance and reinstall it
Done but still does not worl
Should the button also work after a restart?
Yes but it does not work even if i just start the bot and then do the command and then click the button it does not work. Am i missing some dependencies?
Do you use discord.Bot or commands.Bot?
In my start.py you mean? This is it:
Do you want to use discord.py or py-cord?
Im asking because you await the cogs and other stuff
pycord
when i dont await cogs i get a error and then they dont work
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
uninstall py-cord, discord.py and discord
and then pip install py-cord again?
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())
Ah oke so i need to remove the async and await and then it should work oke
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))
replace async def update_presence(self): with
async def on_presence_update(self):
This section outlines the different types of events listened by Client. There are 3 ways to register an event, the first way is through the use of Client.event(). The second way is through subclass...
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
No that is an event? That is not what i am trying to do here
well you decorated it with an event listener
Yes because it is on task loop and that is how it works with discord.py
Does it work different with pycord? If so how do i need to do it?
if you want to use a task loop:
from discord.ext import tasks
@tasks.loop
async def some_loop():
pass
some_loop.start()
@hexed idol Do you know why this does not work?
you forgot the ()
at the task
right
@severe fossil still there?
Yes i am still here. I will try it today
do you still need help?
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?
Yes i do
Yes i do
Are you online right know?
No not yet
so you would not learn it if you do just a copy and paste
yep
wait
The error lies in the method init of the Team2 class. There __init__ should be used to define the constructor, not init. Therefore, self.bot is not initialized, resulting in the bot not being able to register the command properly.
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))
Here, init is used correctly to define the constructor of the Team2 class. This will initialize self.bot correctly, which will allow the bot to register the command correctly.
But what is different?
This is how i did it and this is how you did it?
I dont see a difference?
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
De twee zijn identiek
lemme check
Ja dat klopt
oh ok
The piece of code you provide correctly uses the init method to define the constructor of the Team2 class. The bug wasn't in the use of init, but possibly in other parts of the code, or in the configuration of the Discord app itself, which may not have handled the interactions properly.
But I got a different error code, that's why I came up with the init but does the code work now?
add that to the task await self.wait_until_ready() at the first line after the aync def
Use on Blocks
For Python:
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))```
ephermeral is only for interactions
so slash commands with ctx.respond or something like buttons with interaction
Yes i will remember that thanks. How do i make it so the button still works after a bot restart like you said
Here's the persistent example.
hmm
lemme check dogs if this is possible
....
@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))
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))```
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))```
and what is the error?
It just keep repeating it over some time like 2 hours orso and then after the first 2 or 3 times chrashes
Unfortunatly this does not work for persistent.
;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))
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'
But this error is more annoying because my bots dont stay online for more then 30 minutes
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
Because of this i think
Do i need to know this?
dont overwrite the on_connect event
Oke but the warning that is probeply happening to my bots and that is causing them to chrash every time it is called for a second time. Any ideas what to do?
still need help?
Yes and elspecialy with this: #1220715560959213659 message
#1220715560959213659 message
#1220715560959213659 message
But also with the buttons
please send me your code and the errors
@severe fossil
All of the code is above here. So are all of the errors, but with the repeating on_ready there are none
lemme check
if you just use ChatGPT, why bother