#Basic Pycord Help (Quick Questions Only)
1 messages · Page 61 of 1
Quick question (again, hope this time it's really a quick one lmao), is default_member_permissions = discord.Permissions(administrator=True) supposed to make the command visible only by admins ?
Because a non-admin can see it and execute it
How would I remove other roles if they hadd them?
user.remove_roles(role)```
Alright
📠
why is it "remove_roles" in plural if you only remove one?
Slash commands are visible to all, you can only restrict the execution of them.
It really doesnt make sense since you can only remove 1 role each (command) I think
You must pass the role you want to remove.
hmm ok thanks weird, but then why non admin can execute it even if i specified default_member_permissions ?
I always use this above the function
@commands.has_permissions(administrator=True)```
Thanks I'll try it 😄
which commands do you use ? discord.commands or discord.ext.commands ?
ok it's discord.ext.commands, but if the user doesn't have the permission it outputs an error on the console (not to the user, he just sees that the app doesn't respond)
In my class commands.Cog
And @slash_command
I'll just handle it inside the function via ctx.author.guild_permissions.administrator it'll be easier
like this but in bots?
Thank you
Why
Traceback (most recent call last):
File "e:\Einar\Programming\Testing\chiz\Cheeese\src\main.py", line 9, in <module>
from discord.ext import commands
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)
How can I disable a button? I am trying self.children[-1].disabled = True but idk
Learn all about implementing buttons in your Discord Bot using Pycord.
I send my Paginator to another channel, that works so far. But why do the buttons not work and I always get "interaction failed"?
async def callback(self, interaction: discord.Interaction):
Channel_ID = 1079779225847992411
channel = self.bot.get_channel(Channel_ID)
context = await self.bot.get_context(interaction.message, cls=commands.Context)
context.channel = channel
SPOTS_PER_PAGE = 6
data = await dab.get_all_spots()
pages = []
# Erstelle für jedes sechste Element eine neue Seite
for i in range(0, len(data), SPOTS_PER_PAGE):
page_data = data[i:i+SPOTS_PER_PAGE]
embed = discord.Embed(title="Spotübersicht")
for entry in page_data:
name, fish, spot = entry
if fish is None and spot is None:
fish_text = "Keine Einträge vorhanden"
spot_text = ""
else:
fish_list = []
spot_list = []
fish_text = ""
spot_text = ""
if fish:
fish_list = fish.split(",")
if spot:
spot_list = spot.split(",")
if len(fish_list) == len(spot_list):
for i in range(len(fish_list)):
fish_text += f"{fish_list[i]} - Spot: {spot_list[i]}\n"
else:
fish_text = fish
spot_text = f" - Spot: {spot}"
embed.add_field(name=name, value=fish_text + spot_text, inline=False)
pages.append(embed)
# Erstelle den Paginator und füge den neuen Button hinzu
view = discord.ui.View(SpotDownvote(self.bot))
view.add_item(SpotUpvote(self.bot))
paginator = Paginator(pages=pages, timeout=None, custom_view=view)
await paginator.send(context)```
How to silently respond to an interaction? Without any message displaying
You can only bypass it if you use defer. Even though it is not really intended for that.
response.defer()```
Thanks, works
How do I enable application slash commands on other servers. I have application slash commands on one of my servers but the other two servers don’t show application slash commands. The bot has been active on the server for 15 hours.
Have you activated it in the DEV portal ?
Mmm i think application slash commands are on by default, are you sure the bot is connected to those servers? have you tried restarting discord or doing Ctrl+R?
enabling 'slash commands' in the dev portal permissions is to allow bots to USE slash commands i believe
Now for my question: Isn't there a way to hide application slash commands from showing up on the autocomplete if they dont meet checks? I thought I saw that in the documentation but cant find it now =T
do you have debug_guilds or guild_ids set anywhere? If you do, the command(s) will be guild only
I do! When I am home I’ll try this change
Removing these parameters should work.
How do I make bot owner only commands
The following section outlines the API of Pycord’s prefixed command extension module. Bots: Bot: Attributes activity, allowed_mentions, application_flags, application_id, cached_messages, case_inse...
I will take a look at it
I tried it and gotten this error
Ignoring exception in command ctl:
Traceback (most recent call last):
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\bot.py", line 347, in invoke
await ctx.command.invoke(ctx)
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\core.py", line 942, in invoke
await self.prepare(ctx)
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\core.py", line 858, in prepare
raise CheckFailure(
discord.ext.commands.errors.CheckFailure: The check functions for command ctl failed.
Is there still no way to set a custom bot status/presence ?
If you mean fully custom, no
a simple status, yes. Not rich presence, though.
How do you do the simple one? I want to keep a count of something in plaintext
.rtfm bot.change
those
Yeah so, Im doing that
activity = discord.Activity(type=discord.ActivityType.custom, state=f"{numBolts}/{totalBolts} bolts collected")
bot = discord.Bot(intent=intents, activity=activity, status=discord.Status.online)
Bots can't use the custom activity type
Thats what I was asking about originally
I dont want "Listening to" or "Watching"
etc
You can use Playing
That was included in the etc but it might be my best bet I guess

🤣
I am trying to make code that prints out the user's name that uses the owner-only commands but I get this error instead
Ignoring exception in command restart:
Traceback (most recent call last):
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\bot.py", line 347, in invoke
await ctx.command.invoke(ctx)
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\core.py", line 942, in invoke
await self.prepare(ctx)
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\core.py", line 858, in prepare
raise CheckFailure(
discord.ext.commands.errors.CheckFailure: The check functions for command restart failed.
My code is in the txt
- return await bot.is_owner(ctx.author)
+ return bot.is_owner(ctx.author)
The await isn't necessary
Oh ok
wait nvm I'm dumb
So I still need it
what's wrong with just using ```py
@commands.is_owner()
I had no clue why my code did not work so I did not try that
it works now!
But you know basic python?
Yes
why do you have a member event without member intents?
🤦
Those are guild-intent events, not member-intent events
ok

hi lala!
Could I change the code to @commands.is_bot_owner() because it was already defined as is_bot_owner
on_guild_member_remove that is not an event? I cannot see anything like that at the docs
no, because that is not defined
Just try and see lol
^
I just now found this it has to be defined in the module, not the code it self
if you use "is_owner" it will be already an owner command...
if you want to just keep it simple, then just hardcode your ID in.
Does it work under
bot = bridge.Bot(command_prefix='*', intents=intents, help_command=commands.DefaultHelpCommand(), owner_id=668445956001234944)
if you use commands.is_owner yes
Ok

I did but I think I read the wrong part
I think I miss looked at this part in the docs
def is_owner():
async def predicate(ctx):
return ctx.author.id == 316026178463072268
return commands.check(predicate)
@bot.command(name='eval')
@is_owner()
async def _eval(ctx, *, code):
"""A bad example of an eval command"""
await ctx.send(eval(code))
Thinking I could change the is_owner part
If you look at 10 messages above, that is exactly what they tried to use
Is there a way to make it use the print function to say who used the command instead of
Ignoring exception in command restart:
Traceback (most recent call last):
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\bot.py", line 347, in invoke
await ctx.command.invoke(ctx)
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\core.py", line 942, in invoke
await self.prepare(ctx)
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\core.py", line 857, in prepare
if not await self.can_run(ctx):
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\core.py", line 1198, in can_run
return await discord.utils.async_all(predicate(ctx) for predicate in predicates) # type: ignore
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\utils.py", line 701, in async_all
elem = await elem
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\core.py", line 2285, in predicate
raise NotOwner("You do not own this bot.")
discord.ext.commands.errors.NotOwner: You do not own this bot.
just add the print func in the check.
Will that stop it from showing the whole error
If you want to not show the full error, you can use error handling: https://docs.pycord.dev/en/master/ext/commands/commands.html#error-handling
hey im getting 404 errors for 3 - 5 seconds of command send to reply sent time, is this just because the interaction times out?
defer
i should have specified, its a response, not a reply. i defer with all my commands first, sometimes my pc just lags
so it is the defer that is the initial response and therefore the source of the error
ah so it's taking you 3+ seconds to defer?
defer is the 6th line of code for every command
first others are for logging purposes, local only
they access an SQL database so i seriously doubt it takes so long to defer, thats why i think its just my pc lagging
just in case, could you make the defer first anyway?
but i just want to know if an interaction actually times out in 3 - 5 seconds
yeah, already tried that; same output
can't do much else then, unless you're running blocking code/libraries elsewhere in the bot
darn alright, my pc has one of those plugin-recivers for wifi so ill try to figure something out for that
thanks for your help kind fellow
is your SQL database in any chance non-async?
If you're hosting your database on your local machine, WiFi has nothing to do with that.
See the partial channel example 2 message above your message.
You would do paginator.send(bot.get_partial_messageable(id))
get_channel works too
Uninstall py-cord dpy and any other Discord related library. Then reinstall py-cord
Hi I have a question, does the persistent view works if I add buttons dynamically? (they're not defined using @ syntax)
If not, how can I make it work?
as long as they have a custom_id.
Thanks
uh but it says I have to add it on on_ready: bot.add_view(MyView()) and I can't do that, because my view needs arguments passed to its constructor, what to do?
Pass the arguments to the constructor then
But I can't do that on bot initialization, they are arguments that have input from the player, when he uses the command
How are you going to have a persistent view if the view requires user input??
Then read it from the database?
Gah. How can I work around "circular references"? I have a Cog that calls a View and want to split out my related View classes into another file.
So the Cog has
# commands/mycog.py
from views.MyView import TransactionConfirmationView
And I'm typehinting my referenced cog passed into the View constructor so it can access other parts of the bot
# views/MyView.py
from commands.mycog import MyCog
.... python does not like this. How should I structure my imports so that everything plays nice ?
if it is only for the sake of typehinting, import it like so
from typing import TYPE_CHECKING
if TYPE_CHECKING:
import XYZ
The thing with TYPE_CHECKING is that it is False at runtime, but True otherwise
this is the standard way to avoid circular imports arising from type hinting
even py-cord does it in almost every file
When I try like this:
await paginator.send(self.bot.get_partial_messageable(Channel_ID))```
I receive this error message:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/ui/view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "/home/Bot/Bot/cogs/showspot.py", line 266, in callback
await paginator.send(self.bot.get_partial_messageable(Channel_ID))
File "/usr/local/lib/python3.8/dist-packages/discord/ext/pages/pagination.py", line 973, in send
raise TypeError(f"expected Context not {ctx.class!r}")
TypeError: expected Context not <class 'discord.channel.PartialMessageable'>
i just checked the source code and found that it is a bad implementation
i think i can make a fix
oh well not sure now
as for now, you need to pass context and a target
And how do I make the buttons work in the other channel?
I have tried it this way, the paginator is also sent to the channel but the buttons do not work then.
async def callback(self, interaction: discord.Interaction):
Channel_ID = 1079779225847992411
channel = self.bot.get_channel(Channel_ID)
context = await self.bot.get_context(interaction.message, cls=commands.Context)
context.channel = channel
SPOTS_PER_PAGE = 6
data = await dab.get_all_spots()
pages = []
# Erstelle für jedes sechste Element eine neue Seite
for i in range(0, len(data), SPOTS_PER_PAGE):
page_data = data[i:i+SPOTS_PER_PAGE]
embed = discord.Embed(title="Spotübersicht")
for entry in page_data:
name, fish, spot = entry
if fish is None and spot is None:
fish_text = "Keine Einträge vorhanden"
spot_text = ""
else:
fish_list = []
spot_list = []
fish_text = ""
spot_text = ""
if fish:
fish_list = fish.split(",")
if spot:
spot_list = spot.split(",")
if len(fish_list) == len(spot_list):
for i in range(len(fish_list)):
fish_text += f"{fish_list[i]} - Spot: {spot_list[i]}\n"
else:
fish_text = fish
spot_text = f" - Spot: {spot}"
embed.add_field(name=name, value=fish_text + spot_text, inline=False)
pages.append(embed)
# Erstelle den Paginator und füge den neuen Button hinzu
view = discord.ui.View(SpotDownvote(self.bot))
view.add_item(SpotUpvote(self.bot))
paginator = Paginator(pages=pages, timeout=None, custom_view=view)
await paginator.send(context)```
you need to set ctx.author to you (interaction.user ig)
rather than setting ctx.channel , pass it to target
But then can every user use the Paginator or only me?
only you (interaction.user)
Can't I make it so that everyone can use the Paginator?
unless you set author_check to False
yes do this ^
How can I do that?
Okay that solved my problem
author_check=False```
Can I also put the whole thing in a class so I can edit it via edit_original_response(view=view)?
async def callback(self, interaction: discord.Interaction):
SPOTS_PER_PAGE = 6
data = await dab.get_all_spots()
pages = []
# Erstelle für jedes sechste Element eine neue Seite
for i in range(0, len(data), SPOTS_PER_PAGE):
page_data = data[i:i+SPOTS_PER_PAGE]
embed = discord.Embed(title="Spotübersicht")
for entry in page_data:
name, fish, spot = entry
if fish is None and spot is None:
fish_text = "Keine Einträge vorhanden"
spot_text = ""
else:
fish_list = []
spot_list = []
fish_text = ""
spot_text = ""
if fish:
fish_list = fish.split(",")
if spot:
spot_list = spot.split(",")
if len(fish_list) == len(spot_list):
for i in range(len(fish_list)):
fish_text += f"{fish_list[i]} - Spot: {spot_list[i]}\n"
else:
fish_text = fish
spot_text = f" - Spot: {spot}"
embed.add_field(name=name, value=fish_text + spot_text, inline=False)
pages.append(embed)
# Erstelle den Paginator und füge den neuen Button hinzu
new_view = SpotVoteButtonsView(self.bot, self.message_details)
paginator = Paginator(pages=pages, timeout=899 ,custom_view=new_view, author_check=False)
await paginator.respond(interaction, ephemeral=True)```
wdym?
I have a Custom_View with 2 buttons.
When I click one of these two buttons, both buttons should deactivate.
For this I wanted to edit the Respons and decide with the if query accordingly whether the buttons are enabled or disabled.
class SpotVoteButtonsView(discord.ui.View):
def __init__(self, bot: discord.Bot, message_details):
self.bot = bot
self.message_details = message_details
super().__init__(timeout=None)
if self.message_details[0]['votebuttoncheck'] == 'False':
self.add_item(SpotUpvoteButton(self.bot, self.message_details, disabled=False))
else:
self.add_item(SpotUpvoteButton(self.bot, self.message_details, disabled=True))
if self.message_details[0]['votebuttoncheck'] == 'False':
self.add_item(SpotDownvoteButton(self.bot, self.message_details, disabled=False))
else:
self.add_item(SpotDownvoteButton(self.bot, self.message_details, disabled=True)) ```
So the two buttons and the Custom_View have been added to the Paginator:
new_view = SpotVoteButtonsView(self.bot, self.message_details)
paginator = Paginator(pages=pages, timeout=899 ,custom_view=new_view, author_check=False)```
Can I edit only the view of the 2 buttons or do I have to edit the whole respons with the whole paginator?
Count the number of members
ctx.guild.members```
Try and see
Okay just edit the view from the buttons doesn't work so I have to edit the whole message with the paginator .
How can I write the paginator now in a subclass, so that I can call and create it in the callback function and edit it in the callback function via edit_original_response?
I have imagined a class like the buttons only for the Paginator
class Button(discord.ui.Button):```
Paginator is already a subclass of View, the items from your custom_view are just moved to it. You can subclass Paginator the same as any other view, to some extent
So can I make a class "PaginatorView" and then put the code from the Paginator in there?
more or less yeah
If I create the class like this, how can I put my paginator in there?
class PaginatorView(discord.ui.View):
def __init__(self, bot: discord.Bot):
self.bot = bot
super().__init__()```
wdym
wait no
don't inherit from View, inherit from Paginator
How do I do it?
class Paginator():
def __init__(self, bot: discord.Bot):
self.bot = bot
super().__init__()
#Code for Pages
view = discord.ui.View(TestView(self.bot))
paginator = Paginator(pages=pages, timeout=None, custom_view=view, author_check=False)
await paginator.send(ctx)
no...
Paginator is already a view, so you inherit from Paginator instead of discord.ui.View
when you do that, self would be your paginator variable and you would put your arguments like pages, custom_view etc. into super().init__(...)
Okay but I can't just paste the whole thing into the super().init__(...)?
SPOTS_PER_PAGE = 6
data = await dab.get_all_spots()
pages = []
# Erstelle für jedes sechste Element eine neue Seite
for i in range(0, len(data), SPOTS_PER_PAGE):
page_data = data[i:i+SPOTS_PER_PAGE]
embed = discord.Embed(title="Spotübersicht")
for entry in page_data:
name, fish, spot = entry
if fish is None and spot is None:
fish_text = "Keine Einträge vorhanden"
spot_text = ""
else:
fish_list = []
spot_list = []
fish_text = ""
spot_text = ""
if fish:
fish_list = fish.split(",")
if spot:
spot_list = spot.split(",")
if len(fish_list) == len(spot_list):
for i in range(len(fish_list)):
fish_text += f"{fish_list[i]} - Spot: {spot_list[i]}\n"
else:
fish_text = fish
spot_text = f" - Spot: {spot}"
embed.add_field(name=name, value=fish_text + spot_text, inline=False)
pages.append(embed)
# Erstelle den Paginator und füge den neuen Button hinzu
view = discord.ui.View(SpotDetails(self.bot))
paginator = Paginator(pages=pages, timeout=None, custom_view=view, author_check=False)```
man...
think about it like this
paginator = Paginator(pages=pages, timeout=None, custom_view=view, author_check=False)```would be the same as```py
class PaginatorView(discord.ui.View):
def __init__(self):
super().__init__(pages=pages, timeout=None, custom_view=view, author_check=False)
paginator = PaginatorView()
but the 2nd example is incomplete; pages and view aren't actually defined yet
there are two ways to approach this:
-
define them inside
__init__using some functions to create them```py
class PaginatorView(discord.ui.View):
def init(self):
pages = self.generate_pages()
view = discord.ui.View(...)
super().init(pages=pages, timeout=None, custom_view=view, author_check=False)def generate_pages(self):
pages = [...]
return pages
paginator = PaginatorView()
- add arguments to `__init__` and pass them in```py
class PaginatorView(discord.ui.View):
def __init__(self, pages, custom_view):
super().__init__(pages=pages, timeout=None, custom_view=view, author_check=False)
pages = [...]
view = discord.ui.View(...)
paginator = PaginatorView(pages, view)
Okay I try to understand
Did I understand that correctly?
class PaginatorView(discord.ui.View):
def __init__(self):
pages = self.generate_pages()
view = discord.ui.View(...)
super().__init__(pages=pages, timeout=None, custom_view=view, author_check=False)
async def generate_pages(self):
SPOTS_PER_PAGE = 6
data = await dab.get_all_spots()
pages = []
for i in range(0, len(data), SPOTS_PER_PAGE):
page_data = data[i:i+SPOTS_PER_PAGE]
embed = discord.Embed(title="Spotübersicht")
for entry in page_data:
name, fish, spot = entry
if fish is None and spot is None:
fish_text = "Keine Einträge vorhanden"
spot_text = ""
else:
fish_list = []
spot_list = []
fish_text = ""
spot_text = ""
if fish:
fish_list = fish.split(",")
if spot:
spot_list = spot.split(",")
if len(fish_list) == len(spot_list):
for i in range(len(fish_list)):
fish_text += f"{fish_list[i]} - Spot: {spot_list[i]}\n"
else:
fish_text = fish
spot_text = f" - Spot: {spot}"
embed.add_field(name=name, value=fish_text + spot_text, inline=False)
pages.append(embed)
return pages
async def generate_view(self):
view = SpotVoteButtonsView(self.bot, self.message_details)
return view```
And so I can then call it up somewhere else?
```py
paginator = PaginatorView()
await paginator.respond(interaction, ephemeral=True)```
you're basically there yeah
the discord.ui.View(...) in my example is just a placeholder, do make sure it's the actual code for your view
also, where is dab defined?
dab is defined in another file this is simply a database query.
I have replaced your placeholder here with the view with the extra buttons, was that correct?
async def generate_view(self):
view = SpotVoteButtonsView(self.bot, self.message_details)
return view```
yeah that'd be fine
oh though
if you want self.bot, you need to add the bot argument to your Paginator class and define it
just like you have in any other classes with bot
How does the bot emoji reacts with a custom emoji?
Do I need to make the init async so I can use await there right?
pages = self.generate_pages()```
TypeError: init() got an unexpected keyword argument 'pages'
/usr/local/lib/python3.8/dist-packages/discord/ui/view.py:416: RuntimeWarning: coroutine 'PaginatorView.generate_pages' was never awaited
return await self.on_error(e, item, interaction)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
/usr/local/lib/python3.8/dist-packages/discord/ui/view.py:416: RuntimeWarning: coroutine 'PaginatorView.generate_view' was never awaited
return await self.on_error(e, item, interaction)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
like does it need the name of the emoji (with id)? or just the emoji id
- change the
async defs to justdef - change
pages=pagesto justpages
i think there are different ways to do it, but you can use "<name:id>"
But I need an await here then I must have async function 🤔
data = await dab.get_all_spots()```
Why?
TypeError: init() got an unexpected keyword argument 'custom_view'
class PaginatorView(discord.ui.View):
async def __new__(cls, *args, **kwargs):
obj = super().__new__(cls)
await obj.__init__(*args, **kwargs)
return obj
async def __init__(self, bot: discord.Bot, message_details):
self.bot = bot
self.message_details = message_details
pages = await self.generate_pages()
view = await self.generate_view()
super().__init__(pages, custom_view=view, timeout=None, author_check=False)```
tried that
wait.... you still haven't inherited from Paginator
seems to be working fine for me, are you sure the bot has access to the emoji and that's the exact name?
How can I do that?
from discord.ext.pages import Paginator
class PaginatorView(Paginator):
yeah, i will try something
Hii, persistent views are sometimes randomly not working for me. Is it possible to just manually create the views and reattach them to messages?
Oh awesome works! Huge thanks to you!!
the bot is in the server with the emoji yes
that's how persistent views already work no?
what's your issue
They work a few times but then stop working, after nth bot restart
sometimes after 5th restart, sometimes after 1st etc
are you sure you're re-adding it correctly on startup
I think so, but I'll check
what things need to match so the view gets reactivated? only buttons, or something else too?
Now if I want to cache the paginator and then edit it. How can I do that?
paginator = await PaginatorView(self.bot, self.message_details)
spotdetails = await paginator.respond(interaction, ephemeral=True)
self.message_details[1]['spotdetails'] = spotdetails```
Is that how it works?
```py
await self.message_details[1]['spotdetails'].edit_original_response(view=await PaginatorView(self.bot, self.message_details))```
custom_id mainly
give it a go i guess?
Hmm
File "/usr/local/lib/python3.8/dist-packages/discord/ui/view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "/home/Bot/Bot/cogs/showspot.py", line 94, in callback
await self.message_details[1]['spotdetails'].edit_original_response(view=await PaginatorView(self.bot, self.message_details))
AttributeError: 'InteractionMessage' object has no attribute 'edit_original_response'```
then change it to just edit
Okay so the paginator is edited but the buttons disappear completely 😄
Like this?
await paginator.edit(view=await PaginatorView(self.bot, self.message_details))```
worked for me now when I used like this.
strange
wait, so persistent views edit all messages with views on bot startup? even if there are thousands of them?
no, you just have to run add_view
but how does it work internally?
and you can optionally pass in a message object (which could be a PartialMessage to limit it there)
recieve interaction > find matching custom id > run
hm I see, thanks
now I know how to replicate it (since the builtin doesn't work for me)
If I try it this way then the embed from the paginator is still shown, the two extra buttons (vote buttons) are also edited and disabled but the buttons from the paginator itself to browse are still gone 🤔
await self.message_details[1]['spotdetails'].edit(view=SpotVoteButtonsView(self.bot, self.message_details))```
what specifically are you trying to edit on the message
I have the Paginator. This has yes the 5 standard buttons to change page etc..
Below that I have 2 extra buttons that I add via the custom_view.
If I now press one of these two buttons I want the custom buttons to disable themselves.
So only the buttons have to be edited or updated.
Yes
class SpotUpvoteButton(discord.ui.Button):
def __init__(self, bot: discord.Bot, message_details, disabled):
self.bot = bot
self.message_details = message_details
super().__init__(
label='Spot Upvote',
style=discord.ButtonStyle.green,
custom_id='spotupvote',
disabled=disabled,
)
async def callback(self, interaction: discord.Interaction):
self.message_details[0]['votebuttoncheck'] = 'True'
await interaction.response.send_message('Super', ephemeral=True)
await self.message_details[1]['spotdetails'].edit(view=SpotVoteButtonsView(self.bot, self.message_details))```
This is the view of the buttons
class SpotVoteButtonsView(discord.ui.View):
def __init__(self, bot: discord.Bot, message_details):
self.bot = bot
self.message_details = message_details
super().__init__(timeout=None)
if self.message_details[0]['votebuttoncheck'] == 'False':
self.add_item(SpotUpvoteButton(self.bot, self.message_details, disabled=False))
else:
self.add_item(SpotUpvoteButton(self.bot, self.message_details, disabled=True))
if self.message_details[0]['votebuttoncheck'] == 'False':
self.add_item(SpotDownvoteButton(self.bot, self.message_details, disabled=False))
else:
self.add_item(SpotDownvoteButton(self.bot, self.message_details, disabled=True)) ```
so the moment you use custom_view, the original view is more or less irrelevant because the items from custom_view are transferred to the Paginator
honestly
hmmmm
wait
ehhhhh
what if you ditched this view and just moved it to paginator?
For what do you need the bot?
It wouldn't make any difference to me, I just need this view under the paginator.
I create a paginator that should have 2 vote buttons. When I click on a vote button I want to vote the page of the paginator.
The buttons should be disabled after they have been pressed so that you can not vote 5x.
this is incredibly scuffed, but you could assign paginator inside SpotUpvoteButton and go through that
What do you mean with incredibly scuffed?
well it just looks stupid
let's see
actually it isn't that bad
inside Paginator we have generate_view; first, we assign the attribute herepy async def generate_view(self): view = SpotVoteButtonsView(self.bot, self.message_details) view.paginator = self return view
now every Item, including Button, has a view attribute to access the parent view
so inside your button callback you can access self.view.paginator
so to disable, you would go self.view.paginator.custom_view.disable_all_items()
and THEN await self.view.paginator.update()
probably
idfk paginator is so cursed
@cyan quail I'm a complete dumbass
nice
I was getting the MESSAGE ID
LOL
instead of the emoji
you can always get the full emoji <name:id> with a backslash \
yeah I forgot about that and I was getting with right click in the emoji
rip

File "/home/Bot/Bot/cogs/showspot.py", line 93, in callback
self.view.paginator.custom_view.disable_all_items()
AttributeError: 'PaginatorView' object has no attribute 'paginator'```
well i meant from the button callback
if you're doing it inside paginator then it's just self.custom_view.disable_all_items()
If I use it like this in the button callback, the buttons are taken out completely and the paginator still works.
self.view.custom_view.disable_all_items()
await self.view.update()```
I think this is good, the important thing is that the buttons can no longer be pressed. Whether they are now gone or only disabled is not so important
is there a way to set a eternal interaction button?
Here's the persistent example.
thx
Thanks for your help!
How do I check if the message has been flagged my automod?
msg = discord.utils.get(history, id=1080135333842272298)
button1 = discord.utils.get(msg.components[0].children, label="Claim Invite Rewards")
button1.callback = callbackfunction
says button does not have the attribute callback
...
where is the async function?
Hey if you are around, I implemented the producer / consumer queue and it broke still :/
ohh
how long did you wait for?
0.5 second
I am still getting the unknown interaction on the interaction.response.defer() call because the traffic is so high
we get like probably 200 people clicking the button in the span of 2 seconds and probably 400-1000 over the first 20 seconds
and then getting rate limited agian trying to send follow up messages
I even tried to rate limit my own button by using a counter that increments when an interaction happens, then respond and say traffic high wait 10 seconds, but even the response message is getting blocked for some reason too
It says the attribut of button class.
is the callback above or under it?
Above
you have to set the button.callback under the async func
Are you putting defer and response through this queue? Don't do that. Use the queue for followup only. Responses don't have ratelimits, only followups do
Will PyCharm be able to inspect? I say typehinting but I really mean inspection so the ide works smoothly
uh i dont use pycharm, but it should work. what exactly do you mean by inspect?
do you use those things at runtime? like create objects using the class? or it is only for ide typehinting?
For this View thing it was just for ide use so I can get autocomplete of available methods during development. But I do have functional imports otherwise.
Thanks for the note on TYPE_CHECKING
can I use one SlashCommandGroup in different files (cogs)?
try #1015563296784515082
you mentioned a deleted channel ;-;
discord cache sucks
Which is the latest Python Version which works with Pycord?
3.11 iirc
@fervent cradle
Yes but you can not have must customization so it is not recommended.
ok!
thank you
Hello guys, is there anyway to run a command as the bot?
what?
and prefixed?
How can I make my Paginator persistent?
Does it work the same way with Paginator?
class Base(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.persistent_views_added = False
@commands.Cog.listener()
async def on_ready(self):
if not self.persistent_views_added:
self.bot.add_view(PaginatorInfoView())
self.persistent_views_added = True
@commands.command(name="showspot", help="Zeigt alle Spots an")
async def page(self, ctx):
paginator = await PaginatorInfoView(self.bot)
await paginator.send(ctx)
class PaginatorInfoView(Paginator):
async def __new__(cls, *args, **kwargs):
obj = super().__new__(cls)
await obj.__init__(*args, **kwargs)
return obj
async def __init__(self, bot: discord.Bot):
self.bot = bot
pages = await self.generate_pages()
view = await self.generate_view()
super().__init__(pages=pages, custom_view=view, timeout=899, author_check=False)
async def generate_pages(self):
SPOTS_PER_PAGE = 6
data = await dab.get_all_spots()
pages = []
.
.
.
embed.add_field(name=name, value=fish_text + spot_text, inline=False)
pages.append(embed)
return pages
async def generate_view(self):
view = SpotDetails(self.bot)
return view```
Hello, I have the problem that when I want to get the top_role of a member, there are unnecessary roles in the way. How can I exclude these roles from top_role?
That depends on the other bot, not yours
Top role is only one
wdym
i know, but there are roles, which have to be listet higher, but they shouldn't be handled as a top role
If the other bot ignores or doesn't ignore bots
No idea what you mean
Show code
that wouldn't make it easier to understand, i try to explain it better
Roles of user "hello":
- admin-perms
- owner
Now I want to get the top role of the user, but the role called admin perms is his highest role. The role admin perms shouldn't be used in my code, because I only need a "list role" as the top role
I am not putting the defer through the queue but I am follow up in the queue… I have the no response until the follow up… so how does this work without putting the follow up in the queue
Check if the role is hoisted and if it isn't index the next one?
How can I check the interaction message if it is still available and if not an error should be displayed?
Unfortunately it does not work like this...
paginator_message = await paginator.respond(interaction, ephemeral=True)
try:
await paginator_message.delete()
except Exception as e:
print(e)```
Damn. I'm still having some trouble with this, if you don't mind me picking your brain more..
Failed to load extension commands.gnosis. Extension 'commands.gnosis' raised an error: NameError: name 'Gnosis' is not defined
# cogs/Gnosis.py
from views.Multisig import TransactionConfirmationView
class Gnosis(commands.Cog):
...
# views/Multisig.py
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from commands.gnosis import Gnosis
class TransactionConfirmationView(discord.ui.View):
def __init__(self, cog: Gnosis, callback: callable, txn_data: BeefyTransferProposal, nonce_list: list[PendingTransaction]):
...
NameError: name 'Gnosis' is not defined
I don't get why the Cog was throwing the first error; it shouldn't need to care.
why do you do that?
Because that was recommended to me to avoid circular references.
The View constructor accepts the Cog, and want to be able to autocomplete from within my view classes. But because the Cog references the View and the View references the Cog, python gets angry
My cog sends a View. I was hoping to have my View in a separate file
But as stated, my View accepts the Cog as a constructor argument so I can reference methods within (including the bot instance itself)
So the question is how to allow them to both reference each other for development purposes so that I can separate the view from the cog
Is this where you would use a string as the type? e.g.
def __init__(self, cog: "Gnosis"...)
There was such a problem. I wrote a modal window, everything works, but I really don't like one thing. When I press the send button, the window should close, well, it doesn’t close, it says something happened, but everything works. Needed when clicking the submit button, the modal window was closing
Please help
anyone having problems with Pycord?
no?
my bot wont start, package discord not found
can you show the pip list
tried uninstalling, reinstalling pycord
can you open a thread?
py-cord 2.4.0 is on there
show the full pip list pls
it just started working again 
no idea what is going on
maybe a visual studio issue
sorry for the trouble
How do I make it where in bridge some commands are slash commands and others not
do you mean only a slash command or prefix command?
Prefix command
with that it would be bot.command
So would that make it into a prefix command
yes
Ok
basic prefix command
Will it mess with the bridge.Bot for setting up the bot settings
try and see
Saved a ton of grinding!
Wrong server
I started developing on my old bot and used has_role() but it doesnt exists anymore. What can i use instead?
? it still exists
i get this
can you show the code?
oh alr. thx
How do I use add_role in buttons, I'm making a verification system with button
interaction.user
^
Is there a way to put a event cooldown something like that?
e.g.: Whenever the people say a keyword my bot sends a message, but I dont want to people spam the keyword and the bot spam the response for the keyword, so I thought on creating an event function to have a certain cooldown, and only activates inside the on_message event if the keyword is said and the cooldown is gone.
Is there a way to make a custom help command or to over write the help command for making a custom one
yes
Pycord's commands extension comes with a built-in help command. In this guide, we will take a look at them as well as learn how to create your own. Let's dive in!
alright thanks
isn't that what commands are for?
I think bot.remove_command(help)
but is it fine to use commands.cooldown in a function that's not even a command?
then just create a custom help command
@commands.cooldown only works on commands.
its easier to use help_command=None where you define the bot
No, there is a native way to do it
There is a native and easier way to do it
I was looking for one that works on events
oh alright
You can use
bot.cd_mapping = commands.CooldownMapping.from_cooldown(10, 10, commands.BucketType.member)
or something similar
This would go somewhere in your event
bucket = bot.cd_mapping.get_bucket(message)
retry_after = bucket.update_rate_limit()
if retry_after:
# ratelimited
else:
# not ratelimited
I made an argument for a command to add a second part but how do I make it where it's not needed for every use
The native version already handles that
It gave me an error for not using the second argument
=None?
show current code.
The whole code or the code with the problem
whatever code is related to this
For action when using the start command it's not used
you can remove the line "file.close()"
no you cannot that can cause a memory leak
Also removing it there would make problems with python overwriting the file with Write+ permissions and Read permissions would not have anything to read
Here is the error it's giving me
Ignoring exception in command games:
Traceback (most recent call last):
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\bot.py", line 347, in invoke
await ctx.command.invoke(ctx)
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\core.py", line 942, in invoke
await self.prepare(ctx)
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\core.py", line 872, in prepare
await self._parse_arguments(ctx)
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\core.py", line 774, in _parse_arguments
transformed = await self.transform(ctx, param)
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\bridge\core.py", line 94, in transform
return await super().transform(ctx, param)
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\core.py", line 601, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: action is a required argument that is missing.
add another action: str = None
Ok
Like this?
async def games(ctx, startorplay : str, game : str, action : str = None):
"with open" is already doing that for you
file = open("file.txt", "r")
file.read()
file.close()
or
with open("file.txt", "r") as f:
data = f.read()
Is there a way if the guessing game is played on different servers at the same time to have it were that server has it's own game running
Either with txt or databases
I did not see with.
Hmm are you deferring at the first line of callback?
Full error?
Yes
Then it could be network issues?
Pretty much the full error. But typehinting it as a literal seems to have helped; no more circular import at runtime and the IDE knows what class it is 🎉
This might be silly. But what on earth is "speedup"? I saw it on the install and have tried to look for what it is but no dice.
it installs packages for aiohttp speedup
It doesn't actually do anything just by installing it
Ah! I see, well thank ya. I'll have to burn that async bridge when I come to it then, lol.
No? aiohttp only you to install them. It automatically uses them if installed
I am using a bunch of persistent components. Eventually there IDs will start overlapping. How do you all overcome this. Do you add a prefix like moderate? moderate_d9fdgns7
Can't you just use a custom id that is unique?
what is the max length of a custom_id property?
100
ok thanks
Yeah, I was assuming I could only use autoincrement in my db but I could just let pycord generate the key and insert it.
I don’t see why it would be so not sure. Running the bot on a dedicated server
wait does that means you can have 16^100 combinations of custom ids using only hexadecimal characters? 💀
wait even more because "0a" and "a" are different custom ids 💀
Quick question how do I fix this
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: View.to_components() missing 1 required positional argument: 'self'
even youtube doesnt have so many combinations 💀
@command()
@has_permissions(administrator = True)
async def releaseverification(self, ctx: ApplicationContext):
n_b = Button(label = "verify", style = ButtonStyle.green, disabled = False)
async def cb(interaction):
role = discord.utils.get(msg.guild.roles, id=roleid)
await interaction.user.add_roles(role)
n_b.callback = cb
view = View()
view.add_item(n_b)
e = Embed(description = "Welcome to Republic of Dreamers a group project jumpers!\nClick the verify button below to get verified.", color = con.clr)
await ctx.send(embed = e, view = View)```
did you pass the view class instead of view object?
yes you did
pass view V small
np
hmm. how frequently does it happen?
Every time there is a high traffic to the button, which is every time. It’s used as an unlock tool to unlock content and then personalized content is sent to the member
interaction.response getting blocked is a very unlikely scenario. if that happens you might want to ask in discord devs server
hmm
Yeah I’m kind of stuck and don’t know where to go from here lol
if you have such high traffic, you could try and use http based interactions on a webserver instead of gateway, as they are much more scalable
Although it usually not very favourable to not use gateway
those event are quite useful many times
unless you made a complicated system where you use gateway for events and http for interactions and somehow communicate between the two
ouu alr
How do i give a slash command a description?
pass it into the decorator
btw can you do a test? since interaction ids are snowflakes, they have a time of creation. can you compare this time to current time? https://docs.pycord.dev/en/stable/api/utils.html#discord.utils.snowflake_time
Well it's a string so 100 characters max, not sure about hexadecimals, but yeah you can have a crazy amount of combinations. Which is why I was confused when they said their IDs will start overlapping because they would need an astronomical amount of components for that to even happen.
But it'd be something like 95^100, I don't know which characters they support
randomly started getting discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access on on_connect error. the code hasn't changed and has all the nesseccary permissions: Bot, applications.commands, administrator. any ideas?
How do you know your bot has administrator in all servers it is in?
I was being dumb. My db had auto increment values and they all started at 1 and I was useing that for ID.
beacuse its only in 1 as its a test bot for development
And is your debug_guilds list also only that server ID?
Send your full stack trace
Ignoring exception in on_connect
Traceback (most recent call last):
File "C:\Users\philc\Desktop\venvs\BotDev\Lib\site-packages\discord\client.py", line 377, in _run_event
await coro(*args, **kwargs)
File "C:\Users\philc\Desktop\venvs\BotDev\Lib\site-packages\discord\bot.py", line 1164, in on_connect
await self.sync_commands()
File "C:\Users\philc\Desktop\venvs\BotDev\Lib\site-packages\discord\bot.py", line 738, in sync_commands
app_cmds = await self.register_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\philc\Desktop\venvs\BotDev\Lib\site-packages\discord\bot.py", line 531, in register_commands
prefetched_commands = await self._bot.http.get_guild_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\philc\Desktop\venvs\BotDev\Lib\site-packages\discord\http.py", line 360, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
was fine last week when i was working on it, nothing had changed
That means your bot is trying to register commands in a guild it isn't in. So somewhere you have a guild id in a command that your bot is not in.
okie, thank you
how do I create <t:0> in pycord?
If you have a datetime object, use discord.utils.format_dt
can a ephemeral message be deleted in some way?
yes
how?
zamn
just delete it like any other message
this is what I get then
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'Interaction' object has no attribute 'delete'
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
a ok, so I have to do it on the context 👍
how do I "clense" a message off @ everyone, @ here and any role pings the command caster isn't supposed to ping?
allowed_mentions
Some classes are just there to be data containers, this lists them. Unlike models you are allowed to create most of these yourself, even if they can also be used to hold attributes. Nearly all clas...
hm, that one only works on send if I understand correct?
I want to filter out any that were handed in and add that to a message that does need to still be able to do that though
it also works on edit if that's what you're asking
what I need:
- user uses command and inserts text
- remove all unallowed mentions from that
- add this processed text to a text that is allowed to have these mentions
- send that composition
why is it saying that? 😦
Why not using a Error Handler?
I think your IDE is just confused.
^
aight
also what do you mean by that?
how can i register my default help command as a slash command?
I did Bot(help_command=MyHelp()) but that doesnt make it a slash command only a prefixed command
well its not very simple to make help cmd a slash cmd
you dont really need a help cmd in slash cmds because you have descriptions on the cmds and options. even discord says you dont need a help cmd for slash
Getting these errors while hosting the bot. Code:
bot.event
async def on_message(ctx, message):
ctn = message.content.lower()
if „discord.gg“ in ctn:
await message.delete
message doesnt have a send method iirc
there is message.reply
and message.channel.send
Oh alr

what’s tracemalloc
Regarding 1st error, is the codeblock you sent the code?
it usually is associated with the error when you didnt await
btw you can an ss on your macbook with cmd + shift + 5

Ik i can but I’m to lazy to open discord

But does message.delete exists?
If you imported the message module
yes
wdym?
But this is my code, and it doesn't work
Do you know basic python?
As a teacher or Student?
.
is there a list of all available datatypes that can be received from a slash command?
yh the intens are intents = discord.Intents().all()
Any error?
No it’s just not responding
Can the bot see the channel?
not the () after Intents. only after all
discord.Intents.all()
and do you pass it to the bot constructor?
i just pasted it in the bot fiel
file*
ok it worked
How can i do it like if cnt == "lol" it will only block "lol" but it will allow "hi lol". How can i allow it for the whole msg ?
@proud mason
if lol in message.content
but this blocks dcgfhsdfhdfloljdzsgfusdzfg too
ok nice ty
Yes every perms
dont ping people to get help 

using regex would be a good way
or you can split the content at space
and check if "lol" is in the list of words
honestly if you want regex just use built in automod
Not a Pycord question, but is anyone relatively advanced with PyYAML? Want to run an approach by someone
How do you make a task loop in a random period of time inside a range?
I mean to use like
@tasks.loop(seconds=randomSecond)
async def send_message(self):
# do something
randomSecond = random.randint(500, 50000) # New random second between 500 and 50k
but randomSecond is not accessible cuz it is out of the class
nvm it is accessible

but i dunno if it will work, i will try with short periods of time
ok its not even working with a persistent value
Am I using it wrong?
do you even start the task?
and yes I made self.falas[word] a string cuz I was testing
fetch_channel is a coroutine
so I should use get_channel instead?
changed to get_channel and:
.
.
do you know what we are talking about?
I used fetch_channel
but it said I can't send non-None value to a just-started coroutine, so how could I handle that?
Bots: Attributes activity, allowed_mentions, application_flags, application_id, auto_sync_commands, cached_messages, cogs, debug_guilds, description, emojis, extensions, get_command, guilds, intent...
tried to figure out but I give up, I will try something later
what would be the best way to store variable values? e.g. if the bot needs to be restarted so the values are kept
databases
fair
I'll have the same question, storing simple settings values (like booleans but also maybe my tokens (for now it's in a .env file)), I was thinking of using a file.ini, is making a db a better choice (little bit overkill for just few values no ?)
databases are for more dynamic values like coins and things.
Oh yes I see, totally, but for my settings that'll change not so often (just some flags to disable specific commands in case of problem etc) a config file is a good choice ?
yup
ok thanks 😄
usually when I want to load a preset data when starting the bot and plan to change it while the code (or bot) is being I just use json files to do it
or a dictionary for example
is there a way to quit (not reopen just quit) the bot's process with a command?
like make him shutdown with a command?
mhm
finally solved with this.
since I couldnt await it inside the init
with the audio recording features, is there any way to record all of the audio in the channel to a single file instead of every separate user?
I know i can use other libraries to merge the audio streams i was just wondering if there was a built-in way to do this
yes
do you plan on reactivating it thru a command too?
or just a complete stop and a manual restart
no because thats not possible
yeh
@bot.command()
@commands.is_owner()
async def shutdown(context):
exit()```
found that in Stackoverflow
never tried out but might work
when I call bot.close() does it shut down the bot, or only close the connection to discord?
keep in mind that this is a slash command so use it like /shutdown
Close the connection
?tag restartcmd
Tag Credit: discord.py server
The only good way to restart your bot is to shut it down and have your process manager handle it. You can shutdown your bot by running Bot.close().
Do use:
- run your bot in a process manager such as:
- systemd
- openrc (gentoo, devuan)
- runit (void linux)
- supervisord
- upstart (old ubuntu)
- docker
- manually reboot it
Do not use:
- a bash loop (it can eat your C-c by rapidly spawning python and if your bot fails it won't stop it from constantly failing)
- subprocess.call (you will eat your memory up by not letting your old processes die)
- os.exec*
thanks!
it seems the process is exiting as well
idk what could be wrong here, when I send the message with the prefix, doesnt work but the command is registered as a slash_command, code:
bot = discord.Bot(command_prefix="$", intents=Intents.default())
@bot.event
async def on_ready():
print(f"{bot.user} is ready and online!")
@bot.command()
async def ping(ctx):
await ctx.send("Pong")
bot.run(BOT_TOKEN)```
could anyone help?
remove the prefix and use ctx.respond
you can check for permissions?
you can even hide the slash commands
it isnt possible to use command_prefix AND slash commands then?
Here's the bridge commands example.
oh thats very useful, ty
about that, do you mean make it visible only to the one that sent? if so, how do I do it?
it is an even solution for what I want
Here's the slash perms example.
still ctx.respond
yeah but might need a specific parameter, I could see your /example for example
?tag ephemeral
An 'ephemeral' message is one that's only visible to the person who invoked a command. If you ever got a command error with a blue background, this is an example of one.
To do this, set ephemeral=True when you first use an ApplicationContext. (This includes .defer()ing it; the choice of whether a message is ephemeral or not must be made up front. If you .respond() to a deferred message, setting the ephemeral flag at that time will have no effect.)
This is the equivalent of hidden=True if you're coming from interactions.py
"setting the ephemeral flag at that time will have no effect"
I'll delete it after running the command
this way wont show the slash command used
but ty all for the help!
neverming I just realized that I was using .defer() and so it wouldn't work
just fixed it, ty!
I was following this example and worked very well
https://github.com/Pycord-Development/pycord/blob/master/examples/views/button_roles.py
But I noticed that if I restart the bot, the buttons stop working, is this intended?
even after the bot is fully up, no response at all
If you want them to work after a restart you need to use persistent views
The bot isn't just magically going to remember every view created
Here's the persistent example.
ah I was doing the timeout=None and thought it was enough
No, that will just remove the timeout of the view
Can a message be edited multiple times in one interaction?
I attempted to use
message = await interaction.response.edit_message(embed=embed)
await asyncio.sleep(1.5)
await interaction.message.edit(message.id, embed=new_embed)```
This didn't work because `message` returns NoneType
use interaction.edit_original_response
also your method could work, but dont pass message.id to it
Although this is more reliable
Is there a way to deselect the option after clicking at the Select menu (dropdown options)?
I've tried doing something like this at the callback:
select.row = None
select.refresh_state(interaction)
I've also seen this message:
#general message
idk if it is already implemented
This won't work because it has already been edited.
It returns discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
that was regarding this <#general message>....
hmm
ah I just searched for "deselect" on the server haahahah
then what about interaction.message.edit(embed=embed)
i think you would need to edit the message with the view again
same error :/
It's because I'm editing an ephemeral message in the original interaction response, so there is no ID to be traced I guess?
you can delete an ephemeral message, so you should be able to edit it too
at least thats what i think
try interaction.delete_original_response and see if that works
This is true. My problem is not having a good way to fetch it after the first edit I guess. :/
will do sec
ehh..AttributeError: 'Webhook' object has no attribute 'delete_original_response'
what did you do? are you reassigning interaction somewhere?
that is meant to work
But is it meant to work in the context of already having edited the original response?
yes
mmm, no
hmm
Will send this:
if select.values[0] == "Pokeflute":
for interaction_name, interaction_coord in interactions.items():
if interaction_coord["x"][0] <= select.profiles[interaction.user.id]["user_position"][0] <= interaction_coord["x"][1] and interaction_coord["y"][0] <= select.profiles[interaction.user.id]["user_position"][1] <= interaction_coord["y"][1]:
if interaction_name == "snorlax":
embed = discord.Embed(description="*ZZZ... Snoring* \n**The Snorlax woke up!**")
file = discord.File(encounter_animation(select.profiles[interaction.user.id]), filename="encounter.gif")
embed.set_image(url="attachment://encounter.gif")
message = await interaction.response.edit_message(embed=embed, file=file)
await asyncio.sleep(1.5)
new_embed = discord.Embed(description="")
snorlaxencounter = discord.File("Media\snorlaxencounter.jpg", filename="snorlaxencounter.jpg")
new_embed.set_image(url="attachment://snorlaxencounter.jpg")
await interaction.message.edit(embed=embed)
return
.idw
Saying it doesn't work or asking what's wrong with this code is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
Partial Objects
These can be used to make API calls when you have channel id and/or message id, and you don't want to rely on the cache to have their objects.
Methods which can be used on them are -
- Partial Messageable (analogus to a Channel) : https://docs.pycord.dev/en/stable/api/models.html#discord.PartialMessageable
- Partial Message (analogous to a Message): https://docs.pycord.dev/en/stable/api/data_classes.html#discord.PartialMessage
Example Usage:
async def star_message(channel_id: int, message_id: int):
# Get Partial Messageable object. Docs-
# https://docs.pycord.dev/en/stable/ext/commands/api.html#discord.ext.commands.Bot.get_partial_messageable
partial_channel = bot.get_partial_messageable(channel_id)
# Get Partial Message. Docs-
# https://docs.pycord.dev/en/stable/api/models.html#discord.PartialMessageable.get_partial_message
partial_message = partial_channel.get_partial_message(message_id)
# Add a reaction
await partial_message.add_reaction(":star:")
yeah interaction.edit_original_response is exactly what you want there
only after using interaction.response.edit_message
show your code
don't await
and where's channel_id defined
errr..idk why I'm getting an attribute error then >.<
AttributeError: 'Webhook' object has no attribute 'edit_original_response'
you definitely reassigned it
what's your full callback
async def callback(select, interaction):
if select.values[0] == "Pokeflute":
for interaction_name, interaction_coord in interactions.items():
if interaction_coord["x"][0] <= select.profiles[interaction.user.id]["user_position"][0] <= interaction_coord["x"][1] and interaction_coord["y"][0] <= select.profiles[interaction.user.id]["user_position"][1] <= interaction_coord["y"][1]:
if interaction_name == "snorlax":
embed = discord.Embed(description="*ZZZ... Snoring* \n**The Snorlax woke up!**")
file = discord.File(encounter_animation(select.profiles[interaction.user.id]), filename="encounter.gif")
embed.set_image(url="attachment://encounter.gif")
message = await interaction.response.edit_message(embed=embed, file=file)
await asyncio.sleep(1.5)
new_embed = discord.Embed(description="")
snorlaxencounter = discord.File("Media\snorlaxencounter.jpg", filename="snorlaxencounter.jpg")
new_embed.set_image(url="attachment://snorlaxencounter.jpg")
await interaction.followup.edit_original_response(embed=embed)
return
else:
embed = discord.Embed(title = "Nothing happened...")
file = discord.File(update_map_image(select.profiles[interaction.user.id]), filename="map_image.jpeg")
embed.set_image(url="attachment://map_image.jpeg")
await interaction.response.edit_message(embed=embed, file=file)
.
?tag intents
https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents
import discord
from discord.ext import commands
# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content
intents = discord.Intents.default()
# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True # Required for prefix commands >= 2.0.0b5
# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()
# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
Right, but that yields:
AttributeError: 'Interaction' object has no attribute 'edit_original_response'
upgrade
update
wth version are you on
well are you not on v2 💀
No xD
interactions were added in v2

so if you aren't on v2 already then this is the wrong server
whhhaaaa
dont use 3rd party libs. they are really messy
Okay I must be confused lol
i mean you can, but if you are then we can't really help since the code's different
I'm not using a third party lib
wait what
I think I'm confused lol
I'll update
are you using the component extension lib or something
noooo
eh...
I'm using Pycord
print discord.__version__
2.0.1
oh wait i think you are on an old dpy version where interactions were added but other breaking changes werent
Yea, I'm trippin
aah
Okay, lemme fix that ahahahha
GGz <3
Holy shit I have to change all kinds of stuff to migrate to 2.4 0-0
there shouldn't be that much? a lot of additions but i can't recall us removing anything major
It looks like import options from discord changed alongside slash_commands too? I might need to go read up on the changelog or something to figure out how to adjust my code for this.
After updating, I get this
Traceback (most recent call last):
File "d:\!coding\EtherGame\ethergame copy 4.py", line 7, in <module>
from discord import option
ImportError: cannot import name 'option' from 'discord' (C:\Users\Drew\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\__init__.py)
PS D:\!coding\EtherGame>
And if I remove that line I get even more wacky errors
works fine on my end... this seems more like an venv error
what did you install
pip install --upgrade discord
God, thank you 🥹
Sorry, I'm still so new to this development journey. Doing my best to take it all as it comes
But man, I appreciate this place so fucking much
Yeah I see but I assume there's a module that makes the transformation ini -> dict and dict -> ini as well (I can't use "hardcoded" dicts as I want the changes to be persistent if the bot is stopped)
depends on where you are hosting it, you can just export the json with json.dump with the same name of the file you are loading it from, but since I started using MongoDB this turned out deprecated to me, and I had trouble cuz I was using this method when hosting with a github repo, since the host loaded the info from github I would have to make a backup from the host and commit manually to github if I wanted to persist the information in the next execution
not built in
its complicated
you would need to start some sort of a buffer when you start recording, and write each users data to it as you receive it
ig smth like pydub can make this work
Discord does not send silent frames of audio. So the timings of people talking would be off.
Unless you fill them in yourself, by having a timer between frames and if it is over X amount of time add X amount of silence.
pycord does that for you iirc
Ah ok.
can i ignore this
you could face some issues in replit but pycord should work
alr thanks
I want to add an image from my PC to my embed in Paginator instead of from a URL.
How can I pass the file of the page so that the image is displayed?
embed = discord.Embed(title=f"Informationen für {self.message_details[2]['spot']} ({self.message_details[2]['gewaesser']})", color=0x00ff00)
file = discord.File("./Fische/Rotauge.png",filename="Rotauge.png") embed.set_image(url='attachment://Rotauge.png')
for key, value in info.items():
if key not in ['ID', 'GuildID', 'UserID']:
new_key = word_dict.get(key, key)
embed.add_field(name=new_key, value=value, inline=True)
pages.append(embed)
return pages```
Paginator call:
```py
paginator = await PaginatorDetailsView(self.bot, self.message_details)
await paginator.respond(interaction, ephemeral=True)```
I was trying to use pydub, but my eventual overlays were always silent
uses a list of Pages instead of embeds
So I have to change the whole thing to pages and then returne them?
yes
if you read the docs page i linked, Page can contain both embeds and files
Is there an example somewhere how to create the page?
it'll be at the top of the docs i linked
...eh those are confusing actually
literally just call it normally py from discord.ext.pages import Page page = Page(embeds=[discord.Embed(...)], files=[discord.File(...)])
and then pass a list of these Pages into Paginator instead of using embeds directly
Like this?
page = Page(embeds=[embed], files=[file])
pages.append(page)
return pages```
mhm
Okay I have tested it and it works
Yeah it'd just return almost empty objects
this isn't working for me, the first one is working but the elifs aren't:
@bot.event
async def on_message(message):
msg = message.content.lower()
if "word" in msg:
await message.reply("Hi")
elif "anotherword" in msg:
await message.reply("How's it going")
dang
i did once try to theorise how it could work but never came up with a concrete solution
you could do smth like create a dict of timestamp and packet and then try to do some magic on it
2nd one wont ever execute
but also if i do it like this:
@bot.event
async def on_message(message):
msg = message.content.lower()
if "word" in msg:
await message.reply("Hi")
@bot.event
async def on_message(message):
msg = message.content.lower()
if "anotherword" in msg:
await message.reply("How's it going")
it's not working
because if anotherword is part of msg, that means word is also part of msg, because word is part of anotherword. so "word" in msg would resolve to True, and will skip thee 2nd check
unless "word" and "anotherword" are replaced by some real words 💀
use a listener
can't i do it like that?
just replace @bot.event with @bot.listen()
oh easy
yea
tysm
does someone know why it dont work ?
- Uninstall discord.py or any other forks of discord.py you might have with the namespace
discord.
python -m pip uninstall discord.py discord -y
2a. Install py-cord
python -m pip install py-cord
2b. Update py-cord
python pip install -U py-cord
Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.
Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
also dont expose your bots token. reset it 
i reset it
read
i dont now what do you mean with environment
do you know basic python?
i dont use pycharm but check this https://www.youtube.com/watch?v=2P30W3TN4nI
Learn to use virtual environments in PyCharm within 10 Minutes!
🔍 PyCharm Tutorial Playlist: https://www.youtube.com/playlist?list=PL30AETbxgR-dKTR0wBfkQw9mywvkCi3q_
⌚ Timestamps ⌚
00:00 | Two Methods of Creating a Virtual Environment (venv)
00:16 | Method 1: New Project with a Virtual Environment
01:34 | Method 2: Adding a Virtual Environmen...
thanks
hello, is there a way to send multiple message to a member without referencing the original message ?
await ctx.send() is that what you want?
replit moment, it works on my ide (but code stops when i close computer ofc)
any way to fix? basically i cant download the pycord package
Hey guys!
Do you guys know if there is any way to respond to a ctx without responding to it? (so that you don't have to send a message)
You must respond to interactions
but is there a way to respond without a message?
Can you speak without saying any word?
sign language xD
That was not the point but ok
ok, but thanks anyway
What's the point of not sending any message?
if channel.category == model and channel.name == REMINDER_CHANNEL:```
is this a good way to check for the existence of a channel in a particular category?
But is there a way to delete a message, which was responded? When i tried to delete a message which was sent via msg = ctx.send i can delete it via msg.delete, but it doesn't work with a msg = ctx.respond message.
i found it
what is ctx.respond returning?
I have a view with select I'm trying to update the options dynamically, how do I reload the View?
The code that generates it is already getting the options when run but it happens only when the bot is run
(it is a persistent view)
Currently I dont need to that message to update, I dont have any problem at re-sending it, I just want it to reload
you could edit it
How could I do that? The only moment that it is currently "generating" is when self.bot.add_view() run at on_ready()
I'm doing something like this on the add_option command:
FactionsSelectView().children[0].options.append(SelectOption(**new_option))
new_option is a dict with label, description, value and emoji
When debugging seems correct but I might have missed something
Embed
no
How can I disable the Select menu after the selection?
class MontageartPosenangel(discord.ui.Select):
def __init__(self, bot: discord.Bot):
self.bot = bot
options = [discord.SelectOption(label=art) for art in montageart]
super().__init__(
placeholder="Wähle deine Montageart aus",
min_values=1,
max_values=1,
options=options,
)
async def callback(self, interaction: discord.Interaction):
self.disabled = True```
Edit the message with the new view
Can I also display the selected variant there when I have the menu disabled?
.tag tias ?
Tag not found.
Did you mean...
tias
.tag tias
?
The placeholder is always displayed and not the selected choice
Did you edit self.values?
I only disable the menu
self.disabled = True
await interaction.message.edit(view=self.view)```
You need to also edit the values
How do I have to do this?
Ah I can solve it like this
self.disabled = True
self.placeholder = self.values[0]
await interaction.message.edit(view=self.view)```
class FactionsSelectView(discord.ui.View):
def generate_options(self):
select = discord.ui.Select(
placeholder="Clique para selecionar",
custom_id="faction_selector",
options=[SelectOption(**x) for x in JsonData.read().get("options")],
)
select.callback = FactionsSelectView.select_callback
return select
@classmethod
async def select_callback(cls, select: discord.ui.Select, interaction: Interaction):
...
def __init__(self):
super().__init__(timeout=None)
self.clear_items()
self.add_item(self.generate_options())
I created the view above trying to dynamically change buttons but I get this error when calling the command to show it:
Invalid Form Body
In components.0.components.0.options.1: The specified option value is already used
nvm figured it out
is their a way for me to wait for the result to arrive in asyncio in my pool ? _get_all_expired_recurrent_roles is a CPU bound method
I would want something like: asyncio.wait(result)
I dont want to use the method asyncio.to_thread, because it is specified in the docs that it is for IO bound methods not CPU bound methods
is there a way to make it so Bot.close() closes with an error code? so like the process exits with error code 1 instead of 0
I think you could overwritre the method close for the bot a bit like this
I meant like sys.exit(1)
but I can't do that since I have to run await Bot.close() first which exits
yeah you could do a sys.exit(1) after bot.close()
like this
I dont know if it woudl really work, but it is work trying
I think Bot.close() closes the bot so it wouldn't reach the sys.exit()
but I can try that!
Use loop.run_in_executor with a process pool?
Instead of a thread pool
Yes. It's hacky, but you can send an empty message and just catch the exception that's thrown.
This is particularly useful with modals where you're updating an Embed, for instance, and don't need to post anything new to the user.
If I have a group of 5+ buttons, is it possible to disable certain ones based on the other buttons pressed?
Or would it be easier to disable all the buttons and just send a new view with the desired buttons available?
yes
no
yes
given that you a button object, you can disable it with
.rtfm button.disable
probably a poorly formatted question. I have the buttons currently set up as children and they disable all others when pressed:
async def second_button_callback(self, button, interaction):
get_user_id(interaction.user)
for child in self.children:
child.disabled = True
await interaction.response.edit_message(view=None, content="You clicked the B2 button!")```
so, changing to something like:
```@discord.ui.button(label="B2", style=discord.ButtonStyle.primary, row=0)
async def second_button_callback(self, button, interaction):
get_user_id(interaction.user)
for child in self.children:
if child.label == "B3":
child.disabled = True
await interaction.response.edit_message(view=None, content="You clicked the B2 button!")```
what is your question?
I guess, am I on the right track? Been trying this for a few hours now and finally came here for a sanity check.
await interaction.response.edit_message(view=None, content="You clicked the B2 button!")
I don't understand why you would want to remove the view
I only want them to be able to select two buttons max so I have that code to remove the view once that happens, though I haven't figured that part out yet... I'll play with that after I have the other bit working.
You can create an instance variable named buttons_selected and increment it as you go.
sounds right. I'll have to test the logic more but this gives me a good jumping point for more testing and experimentation. Thanks Squid, I appreciate the help.
yw
I remember someone telling me that shards can set their own independent status different from other shards and that's how bots get like "Status | Shard X", how do you do this in pycord?
Bots: Attributes activity, allowed_mentions, application_flags, application_id, auto_sync_commands, cached_messages, cogs, debug_guilds, description, emojis, extensions, get_command, guilds, intent...
Does that let you change the status of a specific shard though?
if I just fetch_or_get() a guild, will the members inside be accurate and up to date to the current moment ? or do I also need to fetch_or_get all members of the guild
Try it and see?
well it will be up to date for a tests server for sure
I am more asking for a servers with like 100k members or more
Which I cannot manually verify
get will get it from the cache and the cache is updated on every guild event you receive.
oooh I see, so if the cache is full, there will be members missing ?
There is no limit to the guild cache iirc
oooh perfect, so the RAM is the limit 😅
yeah, the only significant cache limit is messages which is 1000 by default but can be adjusted
thanks you !
And you also obviously need the guild members intent
yesss 💯
I don't think get_or_fetch_guild and get_or_fetch_role exists tho
And it wouldn't make sense to use get_or_fetch on every member of the server, because how would you have every member's ID?
they dont no, custom made to check for network errors
ic
fetch_role doesn't exist because there's no route for it
you have to fetch all roles in the guild and pick from there
yeah I was wondering that to ahaha
but you can use utils.get_or_fetch(bot, "guild", id)
that's why it takes a guild arg?
hm?
Also, we don't need 3 people here.
oooh I see, I used _fetch_role 
which is pretty dumb ahahaha
actually huh
yeah _fetch_role does just call fetch_roles
...maybe it should be public anyway
mhm maybe, but would not change much 😄
well it'd just force it to be documented
and then would be compatible with get_or_fetch
oooh smart ! but In the mean time I just did :
hello, any one knows how to avoid displaying the avatar of the bot if 2 or more consecutive messages are sent to the user ? I would like to avoid the first image situation.
On the second image you can see that 2 messages were sent to the user but the bot profile /name is only visible for the first message.
?tag nojson
Why not to use json files for data storage
JSON files are commonly used to store data that is read by a program, however, they are unsuitable for storing dynamic data due to a number of reasons.
It is recommended to use a DBMS (Database Management System) as they come with optimized technologies for storing and retrieving information.
Advantages of using a database:
- Database tables can be related, making it easy to separate your information into multiple tables and only fetch what you need
- Databases allow you to use a query/data processing language to make complex data operations easier with less code
- One misplaced character will corrupt an entire file. A database very rarely experiences corruptions due to their automatic handling of data integrity
- Transactions in SQL databases allow you to revert unwanted changes and prevent data corruption in the case of an error
- Databases have support for indexes, allowing retrieval of some data to be extremely fast
- It is very easy to update existing data in a database, as opposed to re-writing a file
- Databases are reliable
Popular database management systems:
- SQLite3
- MongoDB
- PostgreSQL
- MySQL
- MariaDB
- Microsoft Access
can anyone help me
im trying tu run a discordcloner selfbot on vscode and the code gives this error! how can i fix it
Is there a way to detect when a new forum post is created?
async def callback(self, interaction: discord.Interaction):
report_channel = bot.get_channel(1044192795440709684)
success = discord.Embed(description="desc", color=discord.Colour.brand_green())
report = discord.Embed(
title = f"hidden",
description = f"hidden",
color = discord.Colour.brand_green()
)
report.set_thumbnail(url=msg.author.avatar)
report.add_field(name="hidden", value=f"[Click to view]({msg.jump_url})")
report.add_field(name="hidden", value=self.children[0].value)
report.set_footer(text=f"{hidden}")
await interaction.response.send_message(embed=success, ephemeral=True)
await report_channel.send(embed = report)```
Why am I receiving this error?
- `AttributeError: 'NoneType' object has no attribute 'send'`
(this is a modal callback btw)
The channel is not cached
?tag get_x
Any function that starts with get_ in Py-cord is retrieving the related object from your bots cache. If the object is not in the bots cache the get_ method will return None. Because of this behavior you should check if the get_x method is None and if it is use the fetch_x method.
Why Is Using fetch_ Without Using get_ First Bad?
The fetch_ method makes a call to the discord API. This API call is unneeded if you already have the information. It will also make your command take longer because it will have to send and than wait for a response from the discord API. It will also contribute to the discord APIs global rate limit of 50 requests per second.
What Is Cache?
The cache is a temporary storage inside your bot. It holds many objects from members to messages. When you restart your bot the cache will be empty. When the cache is full it will delete older objects to make space for the new objects.
Is there a way to have different servers play the same game of Guess the Number but with a different preset number
For all of them
Can someone send me a giveaway code for Pycord per dm plsss
Yes why not
.partial
Partial Objects
These can be used to make API calls when you have channel id and/or message id, and you don't want to rely on the cache to have their objects.
Methods which can be used on them are -
- Partial Messageable (analogus to a Channel) : https://docs.pycord.dev/en/stable/api/models.html#discord.PartialMessageable
- Partial Message (analogous to a Message): https://docs.pycord.dev/en/stable/api/data_classes.html#discord.PartialMessage
Example Usage:
async def star_message(channel_id: int, message_id: int):
# Get Partial Messageable object. Docs-
# https://docs.pycord.dev/en/stable/ext/commands/api.html#discord.ext.commands.Bot.get_partial_messageable
partial_channel = bot.get_partial_messageable(channel_id)
# Get Partial Message. Docs-
# https://docs.pycord.dev/en/stable/api/models.html#discord.PartialMessageable.get_partial_message
partial_message = partial_channel.get_partial_message(message_id)
# Add a reaction
await partial_message.add_reaction(":star:")
We do not offer to give you completed code. We will help you fix the code you currently have and answer any questions you might have. You can look at github but remember to give credit according to the licensing if you use code.
Ok Ty
I am stuck trying to get categories and owner only commands show up when only owner is using ;help
Well my categories are not working
wdym?
prefix cmds? use is_owner check. are you not subclassing help command?
The bot works for all commands, when I want to add another command, is it not visible in the slash list, or has it not been created? What is on the screen, why such an error occurred, please help
It's not showing the categories
@bot.bridge_command(description="Just Say Hello To Dia", category='Random')
bot = discord.Bot()
@bot.event
async def on_read():
print(f"{bot.user} is ready and online!")
for guild in bot.guilds:
print(guild.name)
bot.run(token)```
why doesn't this print anything?
what is on_read
k
also, if you could help,
why would that for loop no print anything outside of the async function?
*not
what do you mean
bot = discord.Bot()
for guild in bot.guilds:
print(guild.name)
bot.run()```
something like this
guild data is not populated before ready
oh
well the bot isn’t even connected to gateway
okay
so how does it know
yea lol
so basically python doesn't know when to execute that for?
no it will execute. but there are 0 guilds
