#Basic Pycord Help
1 messages · Page 68 of 1
Looks like only ctx.author and ctx.send
Just have to copy paste and remove author stuff and set it up to accept a channel instead
copy paste the entirety of the paginator class? and modify those ctx parts is what you're saying?
Just .send
and the constructor ofc
oh oh
Subclass paginator and override .send
right i see
I can help more in a couple hours when I am back at my PC if needed
i'd appreciate that. I do have to get normal work work done today, but i will try to sneak in some time for this when i can lol
Paginator2: Electric Boogaloo
Now that I am thinking about it it is probably possible to build this in without a breaking change
like add a new method to the paginator that does what i'm going to do?
We'd have to rewrite the whole shit at some point tho
Otherwise we can't maintain it
I think it should be possible to make context optional and just require context OR target
IMO V3 needs to completely remove ext from the main lib so that it can update independently
just build it from scratch and put it in 3.0 lol
but arent all command things in ext too?
I assume they'd get moved
Pretty sure almost everything for slash is out of ext.commands now
If you want prefix you would then install ext.commands separately
honestly i never understood ext
its not an extension if its literally in the library really

why not keep it in the core lib tho?
making an extra package for such a small addition seems unnecessary
True tbh
I don't think prefix commands are small. Also at this point in time most people don't (or should not) need them
With pycord's user integrated commands, is it possible to fetch channel message history?
For what do you need that?
getting channel transcripts
no
i still think discord should've given user apps the same permissions as the invoking user but nope
sucks, would've been cool ngl
it does have some practical use, i mean i can see how it could be abused if you could just fetch any channel regardless of your permissions 
which is why i said they should just copy the user perms
would also allow for actual automated actions like role creation or whatever
just install the bot to the guild at that point O.o
I think the main concern is people could just come in and run a command that could scrape X amount of messages from every channel that they have access to (I assume discord would implement some sort of history limit)
pretty much yeah
if user apps had regular user permissions, they would literally be selfbots
what did I do wrong this time?
@discord.Option(name="Peak Tier", value=str, choices=TIERS)
async def setpeak(self, ctx, user: discord.Member, peak: str):
@discord.Option(name="Peak Tier", value=str, choices=TIERS)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: 'Option' object is not callable
lowercase o
o
and value is not a kwarg for discord.option
and this time?
@discord.option(str, name="Peak Tier", choices=TIERS)
no
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...
actually that might work but you should just pass the name and type positionally
fixed it
so why is the for loop being called twice, makes no sense to me: ```py
cogs = [
'cogs.helper_commands_cog'
]
for cog in cogs:
print("EEEE")
bot.load_extension(cog)
you can just do bot.load_extensions("cogs")
wait fr? bet
this is what happens when you only use boilerplate code ig
tysm for the help
am i dumb or is pycharm dumb?
This is what I came up with. Untested as of now, if it works I might make a PR to add it offically
ayyy, i'll take a look at this thanks. I literally just wrote the boilerplate for the subclass and was gonna implement the method
i was actually thinking of just creating a new method since i'm not sure there's any real reason for me to override send(). Since i'm not going to do super().send() or something like that. I was gonna make a method called channel_send (feel free to come up with a better name for it) that doesn't even take a context at all, or a target_message, none of the things that are only relevant to responding to a user command basically
true, raw_send contextless_send blind_send none of these seem to be good, It is also possible that I could overload the method but a new method would work as well
send_to_channel? lolw
i thought of that too lol
so if anyone knows off the top of their head, is discord.Message.created_at a datetime (or datetime like) object?
yes
so u can do discord.Message.created_at.year right?
yup
I think it is a bug in the docs that it is not listed
xd if the ide knew the type of message though and im not bothered to typehint in this case
-w-
nah i genuinely don't know how does one typehint this: ```py
for message in channel.history(limit=limit):
...
it should be, because channel.history yields Messages
vscode is not an ide
yea
in my humble opinion
nah its a text editor but i like it for what it is
why do embeds sometimes refuse to show thumbnail urls
is the service you use unreliable maybe? like sometimes doesnt respond to requests?
discord proxies stuff like that (even thumbnails, i think) so a failed request might make it not show
its genuis.com so i suppose thats reliable?
the url is in the message raw data and it has a proxy url aswell which works
but the embed just doesnt display it, even after refreshing the client
can you send the url here
url i passed:
https://images.genius.com/a1f98c981ed9ddcb85629e0835a238d3.1000x1000x1.png
discords proxy url:
https://images-ext-1.discordapp.net/external/9Tn3EMUWGdGMXt9jPJlps__23owCZIeJ0xCzVRzSTU4/https/images.genius.com/a1f98c981ed9ddcb85629e0835a238d3.1000x1000x1.png
hm
if it only fails sometimes i would imagine it is a discord issue
the thing is, when the message gets created, it shows the thumbnail for a split fraction of a section, then just completely erases it from the embed
yes, this happens only sometimes
i have seen that a few times, idk why it happens
really annoying :(
does it work with the same url if you try again?
worked like a charm:
import discord
from discord.ext.pages import Paginator as PycordPaginator
class Paginator(PycordPaginator):
async def channel_send(
self,
channel: discord.abc.Messageable,
delete_after: float | None = None,
) -> discord.Message:
if channel is not None and not isinstance(channel, discord.abc.Messageable):
raise TypeError(f"expected abc.Messageable not {channel.__class__!r}")
self.update_buttons()
page = self.pages[self.current_page]
page_content = self.get_page_content(page)
if page_content.custom_view:
self.update_custom_view(page_content.custom_view)
self.message = await channel.send(
content=page_content.content,
embeds=page_content.embeds,
files=page_content.files,
view=self,
delete_after=delete_after,
)
return self.message
slimmed it down to just what I needed. thanks @lapis dock and @sage tendon for the advice
lol yea, string formatting sugar for repr() basically
also id be careful with naming your custom stuff the exact same as pycord's built in classes lol
why?
namespace conflicts suck
certainly, but i don't believe there's any opportunity for conflicts here
just a tip 
you could open a PR if you want, otherwise I will sometime in the next few days (But dont want to "steal" it from you if you want to do it)
good point i suppose i should if you think they'd want to add this
perhaps i should come up with a better name for the method if i do lol
if you think they'd want to add this
It is a valid usecase that we dont cover so I dont see a reason to not include it.
method name is the easiest thing to change if people who review the PR dont like it
true
Should I submit an issue for this? It shows on stable
nah it's known
how can i type hint a new channel/announcement channel?
there's no direct discord.NewsChannel from what i can see, nor ..AnnouncementChannel
discord.TextChannel
that's what it is already 😭
yea and its the right typehint
typehints dont find anything
right, i get that, but it's not there is what i'm hinting at
so youre just trying to filter by news channels
well, i'm trying to get it to actually be able to select that channel
when giving its ID to it, it doesn't like it
100% i just tried it again
so <#id> works?
it does work yes
can you show your option decorator / typehint
You can pass channel_types to the option
async def setups_scammers_channel(self, interaction: discord.ApplicationContext, channel: discord.TextChannel):
yea but textchannel should show them all
^ that's what i was thinking
btw dont use interaction, use ctx
interactions are something different
got used to it from discord.py not going to lie
i thought typehinting would save me 😭
does it not?
technically it is valid code, just confusing
i am very much used to it now
i'm so not ready to change so many lines of code from interaction to ctx either
future me problem
TextChannel looks like it is only normal text channels
and those get special treatment
it does also get rules, but i'll see if i can get rid of it?
rules is not a special channel type, it just has a different icon
okay wait one second what is the actual issue rn
that the rules channel shows, or that it doesnt work
yeah so can't do nothing about that rules channel
so i basically want to select the announcement/news channel
but it won't let me whatsoever
not via ID or via just ...TextChannel
let me try something, i have a suspicion
go for it
yea no it works on my bot
i will go for the discord.ChannelType.news for now i guess, weird though, i've always had this issue
news channels just never appeared
try adding @discord.option("channel", discord.TextChannel, channel_types=[discord.ChannelType.text]) under the slash command decorator and see if you can select it then
they want news tho so switch the type to news ^
oh bruhh i thought this was your channel list
yea okay
im tired
yea just add all channel types there that you wanna accept
@setups.command(name="scammers-channel", description="Setup the scammers announcement channel.")
@commands.is_owner()
@discord.option(name="channel", channel_types=[discord.ChannelType.news])
async def setups_scammers_channel(self, interaction: discord.ApplicationContext, channel: discord.ChannelType.news):
[00:03:42] [ERROR] [scammerdb] Failed to load cog setups.py: Traceback (most recent call last):
File "C:\Users\tripl\OneDrive\Documents\doorbio\.venv\Lib\site-packages\discord\cog.py", line 784, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib._bootstrap_external>", line 940, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "C:\Users\tripl\OneDrive\Documents\doorbio\cogs\setups.py", line 11, in <module>
class Setups(commands.Cog):
File "C:\Users\tripl\OneDrive\Documents\doorbio\cogs\setups.py", line 51, in Setups
@discord.option(name="channel", channel_types=[discord.ChannelType.news])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\tripl\OneDrive\Documents\doorbio\.venv\Lib\site-packages\discord\commands\options.py", line 438, in decorator
func.__annotations__[resolved_name] = Option(itype, name=name, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\tripl\OneDrive\Documents\doorbio\.venv\Lib\site-packages\discord\commands\options.py", line 238, in __init__
self.input_type = SlashCommandOptionType.from_datatype(input_type)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\tripl\OneDrive\Documents\doorbio\.venv\Lib\site-packages\discord\enums.py", line 795, in from_datatype
datatypes = [cls.from_datatype(op) for op in datatype]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\tripl\OneDrive\Documents\doorbio\.venv\Lib\site-packages\discord\enums.py", line 795, in <listcomp>
datatypes = [cls.from_datatype(op) for op in datatype]
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\tripl\OneDrive\Documents\doorbio\.venv\Lib\site-packages\discord\enums.py", line 815, in from_datatype
datatype_name = datatype.__name__
^^^^^^^^^^^^^^^^^
AttributeError: 'int' object has no attribute '__name__'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\tripl\OneDrive\Documents\doorbio\main.py", line 71, in load_cogs
self.load_extension(f"cogs.{filename[:-3]}")
File "C:\Users\tripl\OneDrive\Documents\doorbio\.venv\Lib\site-packages\discord\cog.py", line 918, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\tripl\OneDrive\Documents\doorbio\.venv\Lib\site-packages\discord\cog.py", line 787, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.setups' raised an error: AttributeError: 'int' object has no attribute '__name__'
this is actually going to make me throw a fit
i mean the typehint in the function header was correct before
i don't understand why it's just that annoucnement channel.
now its wrong
sec
oh right, no i just edited the one that was already tehre, my bad
i'm a little sped
also i think you have to pass discord.TextChannel as the second positional argument to the options decorator else it wont work
yeah
not sure why you removed it :)
in all honesty, didn't see it there 😭
that did work haha, will have to keep that noted for next time honestly, always had the issue with news channels
i have no idea why they are not included by default
yeah... it's literally the only one missing from typehinting
i mean doing options solely via the typehints is also just a crutch
you cant specify anything beyond the broad type, and whether its required or not by setting a default
everything else, like min and max values, stuff like channel types, the description, are only accessible via the decorator (or discord.Option typehint but really i hate it)
Hi, so I did it and the bot crashed again, but I haven't found anything useful. The last log is just a normal message from a user.
2025-02-15 01:42:21,021:DEBUG:discord.gateway: For Shard ID None: WebSocket Event: {'t': 'MESSAGE_CREATE', 's': 50241, 'op': 0, 'd': (MORE STUFF...)
2025-02-15 01:42:21,021:DEBUG:discord.gateway: For Shard ID None: WebSocket Event: {'t': 'MESSAGE_CREATE', 's': 50241, 'op': 0, 'd': (MORE STUFF AGAIN...)
2025-02-15 01:42:21,021:DEBUG:discord.client: Dispatching event socket_event_type
2025-02-15 01:42:21,021:DEBUG:discord.client: Dispatching event socket_event_type
2025-02-15 01:42:21,021:DEBUG:discord.client: Dispatching event message
2025-02-15 01:42:21,021:DEBUG:discord.client: Dispatching event message
How much RAM do you have access to?
can anyone explain this error?
File "/home/bibi/pyenv/lib/python3.11/site-packages/httpx/_client.py", line 1730, in _send_single _request
Feb 15 09:49:06 vmi1910489.contaboserver.net python3[581627]: response = await transport.handle_async_request(request)
Feb 15 09:40:06 vmi1910489.contaboserver.net python3[581627]:
Feb 15 09:40:06 vmil910489.contaboserver.net python3[581627]: File "/home/bibi/pyenv/lib/python3.11/site-packages/httpx/_transports/default.py", line 393, in handle_async_request
Feb 15 09:40:06 vm:1910469.contaboserver.net python3[581627]: with map_httpcore_exceptions():
Feb 15 09:40:06 vmi1910489.contaboserver.net python3[581627]: File "/usr/local/lib/python3.11/contextlib.py", line 155, in __exit__
Feb 15 09:40:06 vmi1910489.contaboserver.net python3[591627]: self.gen. throw(typ, value, traceback)
Feb 15 09:40:06 wmi1910489.contaboserver.net
python3[581627]: File "/home/bibi/pyenv/lib/python3.11/site-packages/httpx, transports/default.py", line 118, in map httocore exceptions
Feb 15 09:40:06 vmi1910489.contaboserver.net python3[581627]: raise mapped_exc(message)
from exc
Feb 15 09:40:06 wmi1910459.contaboserver.net python3[581627]: httpx.ConnectTineout
it stopped my bot
just looks like a fat disconnect to me
by your vps having bad connection lol
it should
What was the actual HTTP Error Code thrown? I would expect that to be an error-code in a protocol response from the remote host, rather than any real error in the transport which represents a network issue.
I don't think that I can revert back and find the error but I do have a screenshot of it
this is what systemd gave me
Sorry, that still doesn't contain the information. I'm most interested in raise mapped_exc(message) from exc -- if I'm right then that message content should contain something like a 50x HTTP Response Status Code.
ill try to get more information
do you perhaps know the command to see the logs of a systemd service?
On a debian-core it should be journalctl with some combination of switches to display more, less, or specific info bits.
I really only know debian, and probably less than I should. journalctl --help should give you enough data for a crash course in usage. If not, then man journalctl
So I'm trying to make a message_command that has a dropdown when you use it.
I then want the original message I click on to be deleted and reposted elsewhere.
I got the dropdown working, but somehow the message it reposts is the message where the bot asks me which channel I want to send it too...
I might be just blind and missing something here, but could someone do a once-over and see if they pinpoint the problem?
@commands.message_command(name="Nudge Message")
async def _Nudge(self, ctx, message: discord.Message):
await ctx.defer(ephemeral=True)
view = ChannelSelectView(message)
await ctx.respond(f"Where do you want to nudge this message to?", view=view)
class ChannelSelectView(discord.ui.View):
def __init__(self, message):
super().__init__()
self.message = message
@discord.ui.channel_select(placeholder="Select a channel...", min_values=1, max_values=1, channel_types=[discord.ChannelType.text])
async def callback(self, select, interaction: discord.Interaction) -> None:
channel_id = int(select.values[0].id)
target_channel = self.message.guild.get_channel(channel_id)
embed = discord.Embed(description=self.message.content, color=discord.Color.blue())
await target_channel.send(content=self.message.author.mention, embed=embed)
await self.message.delete()
await interaction.response.send_message(f"Message moved to {target_channel.mention}", ephemeral=True)
Did some extra print debugging, print(self.message) under the self.message=message
and one under the callback command, and it indeed changed the message id.
So I'm confused now.
rename self.message
views already have a builtin message attribute and im very surprised that didnt explode everything
i mean im not saying that is it but its very likely, and having name clashes is nuh uh
np
Is there a way to also delete the view after I selected an option in the dropdown here?
try await self.message.delete() but it might not work, ephemeral messages are a bit weird
or you could just edit it to say "Message moved" or whatever
yeah editing the message, and nulling the view worked, thanks again. Much appreciated.
you can response with a delete_original_response() to component interactions to delete the message they are on
i remember one of the regular methods of deleting responses not working with ephemeral responses tho
but im not sure which one didnt work
you can only edit/delete ephemeral messages with the interaction endpoints.
I would like an advice, let's say I make a database in which I keep track of my users (useful to manage xp etc), I saw there was a listener to see if a user updates its profile (useful for profiles changes) my bot would update the database. Now I have two questions:
- would that listener be called if the bot wasn't online (will the bot automatically check for any updates) , or should I make a checker at bot startup ?
- should this chercker be a common python package , or should I make it a discord cog ?
I think discord will send you missed events if you were disconnected for a short amount of time. In general you should not expect this. If the bots code was fully restarted you wont have any "before" reference, just what it is now.
It would probably be best to put a listener in a extension/cog.
The main question is what do you need to store?
thank you for your answer.
I need to store a string unique for some users
I was talking about the function that check at start up if the profile have changed (cause the string is used for a role for the users USERNAME:ROLE-<String from database>)
should 'start up' function be in a cog ?
id make an on_ready listener and the listener for the user update in the same cog
i still dont understand what you even wanna save since user profile access is super limited but
^
hooo I haven't thought about that ! thank you
a simple exemple (I don't use but that illustrate my needs),
Each user has a color that belong tho them, for exemple:
Id | Username | Color
<The Toothy userID> | toothyfernsan | "#FF00FF"
Would result in you having the role
"toothyfernsan color" -> role_color = #FF00FF
let's say you change your username (which is rare but possible) I want you to keep your "color role" up to date with your username ^^
ah its just about the name
yup
What about ✨️ using ids ✨️
The User.ID in Discord stays the same no matter what changes you make to your account, and the Member.ID you have in every Guild is your User.ID. Having an individual Role for each and every user to give them a custom color seems a bit excessive tho, IMO. Same is true of every Role.ID. If it gets renamed it keeps its ID.
Also if you change your username in Discord, I'm almost positive that it does NOT remove you from Roles in servers.
the role in their case contains the user's name
i dont see what about zed's solution is bad here
I didn't say anything was? I just added an annotation. No clue what use it has other than to spend CPU cycles :-)
giving everyone a color role so that the server owner can find anyone's role and change the color instead of having an unnamed mess of color roles?
I would use one Role per Color and something like Reaction Roles to allow users to switch their personal color at will.
and what if everyone wants a slightly different color instead of just one of 10, 20 presets?
Make up a permissions preset for color roles, use a naming scheme to identify color roles as a strict type of role, and use a /command to allow users to create their own color role via RGB input, which other users can then join into via aforementioned automation.
or just do what zed does
The official helper in the automation programming community recommends manual over automated management. I weep.
youre reading into it too much
Hello, I need help with a code from my bot.
Specifically it has to do with a command that shows the status of the mentioned user, or in case the user has not been specified, the author of the message is displayed.
However, it only shows an offline status. Even if I'm not offline, the bot tells me that I am.
I have tried some things, but they have not worked. I leave you the code here:
@commands.command(name="status", aliases=["Status"])
async def status(self, ctx, member: discord.Member = None):
if member is None:
member = ctx.author
try:
estado = member.status
embed = discord.Embed(
title = f"Estado de {member.name}",
description = f"El Estado actual del usuario es `{estado}`",
color = discord.Color.yellow()
)
embed.set_thumbnail(url = member.avatar.url)
await ctx.send(embed=embed)
except Exception as e:
await ctx.send(f"Ocurrio un error: `{e}`")
I must highlight the fact that I am new using pycord, I only have 2 days using this library.
first of all you should do noçt a try except like this in ur command, you have some special event like on_command_error to get all of those
second of all you should not use member.avatar.url since avatar can be none if the user doesnt have any avatar. Instead you can use member.display_avatar. This will always works even if the member doesnty have any profil picture
and last thing, check the intents of your bot, if you dont have the necessary intent like presence it will not work
is that a prefix command
3rd of all, if you want you can make the trigger of command non case sensitive
which mean you can do +status, +StaTus, + STATUS etc and it will work
On subclassing discord.Bot: I have the need to override __init__ to do some preliminary setup like instancing a database connection. Websearches for 'py-cord subclass discord.Bot' turns up a bunch of stuff, but most of it is for discord.py and not py-cord. So in the old way, it appears to have been super.__init__(self, *args, **kwargs)
The py-cord docs I found on guide.pycord.dev don't contain any examples for calling super.__init__ so I tried to figure it out via IntelliSense in PyCharm, which shows super.__init__( self, t, obj ) without any typehints. Then I took a look into the actual discord.Bot source. shows there is no __init__ on there, but also that the discord.Bot class inherits multiple other classes, so rather than try to figure out which of those to look into I thought I should just ask somebody who already knows the library well.
What exactly do I need to require as in-params to my __init__ in order to pass them to super.__init__( t, obj )?
you just put exactly what you usally pass to discord.Bot(THIS) in there
At the present time that is actually nothing. I started out with a raw discord.Bot() in bot.py as found in the basic examples, then I decided to subclass at the point where I determined that the library was actually worth using for my project. What are the potential parameters?
everything discord.Bot takes
check the docs
Bots: Attributes activity, allowed_mentions, application_flags, application_id, auto_sync_commands, cached_messages, cogs, debug_guilds, default_command_contexts, default_command_integration_types,...
Well is guide.pycord.dev the wrong place to look???
no
typically the only things you need are the intents and maybe activity (if you need a custom activity)
Thank you. For some reason I thought I checked this first, I just didn't notice that there's an init signature at the top.
Thank you!
You could just take anything and pass it to the original init instead of specifying the specifics::
def __init__(self, *args: Any, **kwargs: Any):
super().__init__(*args, **kwargs)
... # setup
# before
# discord.Bot(...)
# after
YourClass(...)
Nothing "old" about it
The signature on Toothy's docs page shows class discord.Bot(description=None, *args, **options) so I went with that. I think yours would work too, but does omit the one parameter.
ive never seen description used lol
also, no, what soheab shows would pass literally any parameter on
so if you did CustomBot(description="a") it would pass that to the discord bot too
Doesn't the description parameter to the init routine set the description property on the bot instance?
i literally have no idea where the description even shows up
It's used in the prefix help command lol
i think its the bot's about me but i just set that via the dev page
honestly i dont get why its defined like that its kinda weird
That would be neat but also weird to do that on startup every time for a library
In role.edit, I note the following: "Changed in version 2.0: Edits are no longer in-place, the newly edited role is returned instead. "
I also note that calling role.edit does absolutely nothing to the role.
How do I then apply the edits to the role on the server, after I put the bot into a role which manage its own integration role?
thats not possible unless the bot has another role above its own role
I did figure that finally. In my first test I forgot to put the new test role above the dumb bot role. Sorry. Should have deleted instead of editing, if I'd done it right the first time.
and you're reading that wrong. previously if you had a Role object saved to a variable and ran await role.edit() it would update the role variable. But now it doesn't update the variable, so you'd need to run role2 = await role.edit() to catch the newly edited role
and well, show your code
the edit goes through the API either way, you dont need to do anything extra. its just how it touches the local variables that changed
I disagree that I misread the semantics. I believe the semantics are misleading. It expresses: "Edits are no longer in-place," which I think fairly interprets to, "Edits no longer affect the role on the server." The concept of updating a stored variable to match the edited-in-place role settings is mutually exclusive IMO.
no
in-place, in programming, means editing an object directly instead of creating a copy and applying the changes to that
its just about the object in memory
So there's no problem now. I did discover what you said about putting the bot into another role, with Manage Roles Permission, which must be a higher tier than the Bot Role. Before I edited my post, I had created such a role, but I forgot to move it up above the Bot Role. So the whole thing was my mistake. I should have deleted the question instead of editing it.
dw lol
In single-host programming, sure. In host-client networked programming, many concepts change.
not really lol
its just a fixed concept
In computer science, an in-place algorithm is an algorithm that operates directly on the input data structure without requiring extra space proportional to the input size. In other words, it modifies the input in place, without creating a separate copy of the data structure. An algorithm which is not in-place is sometimes called not-in-place or ...
the await signals you're doing an API request
Generally (there are some exceptions probably but not sure) if you ever await something within pycord, you are sending an API request. And when you DON'T await something, you never make an API request
Also, didn't it give you any error when you sent the request? should've given you something like missing permissions
Exactly my point. The edit method must be awaited, therefore it is a remote callout, in which case I maintain my stance upon the semantics of documentation for it. This is not really worth arguing though, I'm sorry for starting it. Agree to Disagree is functional :-)
Nothing in Traceback. Just no effect on the server-side.
youre really just reading into it too much lol
in-place always refers to whether something directly affects the object in memory or not
it has nothing to do with network-anything
hm, either weird handling from pycord / discord or your error handler is eating it then
No error handler in dev mode. Not even a try/catch in the function. I'm a big fan of Python's traceback. I've implemented a similar mechanic in several variants of VB, C# on DotNET, and PHP error logging. I'm to a point where the lack of stack-trace just annoys me XD
Now I'm rethinking this code entirely.
It has several purposes, but this one in particular is just to give the bot's integration role a hoist=True and a color=<Greenish Hex Value> by default. I did look in the Discord Application Configuration first and can't find such settings, for the Integration Role. If this can't be accomplished on_guild_join since the bot needs a separately/manually configured role/permission/position, then it's just fairly pointless yes?
yea you can only adjust the permissions
That seems a bit backward to me. I would think that adjusting permissions should be verboten but aesthetic tweaking fundamental.
I just realized you meant in the configuration utility online. I was meaning at runtime.
yea Discord's entire role and permissions system is busted in general
hey, anyone have any idea why when i select from a dropdown menu, it gives me a this interaction failed error even tho the message edits itself correctly? no idea what piece of code would be causing this
class DropdownView(discord.ui.View):
def __init__(self, bot_: discord.Bot, paginator, btns, id, cmds):
super().__init__()
self.bot = bot_
options = [discord.SelectOption(label=cmd) for cmd in cmds.keys()]
self.add_item(Dropdown(self.bot, paginator, btns, self, cmds, options))``` this is the dropdown view
```py
async def callback(self, interaction: discord.Interaction):
if interaction.user.id != self.paginator.user.id:
embed = discord.Embed(
title="Error",
description="This menu isn't for you",
color=discord.Color.red()
)
await interaction.response.send_message(embed=embed, ephemeral=True)
return
``` and my callback function
is your callback actually running
yep, i was playing around with it a bit more, turns out i have to defer it..
if you have to defer then you're taking too long
but that code itself doesn't look particularly intensive
do you have some other code running on that?
i mean this code was fully functional in the previous version of pycord, no idea what changed, but now im having the trouble of the paginator disappearing:
await self.paginator.update(
pages=self.pages,
show_disabled=True,
show_indicator=False,
use_default_buttons=False,
custom_buttons=self.btns,
loop_pages=False,
timeout=30,
custom_view=self.dropview,
author_check=True,
)
await interaction.message.edit(view=self.dropview)
``` this interaction.message.edit is probably messing it up the paginator appears, then quickly disappears lol
when the message times out the paginators back??
no idea what im missing
The edit is messing with the view
You're overriding the paginator
Why are you adding that? You're already passing the custom_view kwarg with the dropdown
yeah paginator.update already responds too
so there's no reason for that final edit
ah ok
what about this error lol
@gaw_commands.command(description="Rerolls a giveaway")
@discord.guild_only()
@discord.option('id', description='The id of the giveaway / message', required=True)
async def reroll(self, ctx, id: int):
result, ephemeral = await self.bot.rerollGaw(id)
await ctx.respond(result, ephemeral=ephemeral)
``` i dont see anything wrong with this either
make it a string option
also you dont have to pass required=True, thats the default
and you shouldnt use guild_only anymore, its deprecated and it should instead be handled via contexts
Thanks, I'll take into account what you told me 👍
appreciate it
fwiw if you change it to type discord.Message it'll automatically convert the ID (assuming the channel matches)
wait that works?
like as an option type?
no, it resolves to MessageConverter
It's probably a lib conversion
no but where are you saying to change it to discord.Message
the option type
all the internal converters are pretty robust because they were made to deal with prefix commands
they still work fine with slash
2GB
About 400MB was used at the time.
I wonder if 400MB RAM a lot for a bot?
As a Python oldbie but a Py-Cord newbie I think it is, but several others who are both Python and Py-Cord oldbies assure me that I am mistaken.
it just depends on how much server, what intents, what event etc
400mb for a bot in 10k guilds is not a lot
but for one with 1 member it is
For user/message commands, can you also use predicates for access to the commands? Like the @commands.guild_only() but for let's say roles?
So it won't even show up for people who don't have X role for instance?
You can set that up in the integrations menu of server settings. The backend check will still work the same though
Also guild only can be controlled through command contexts now
You can do it for specific PERMISSIONS but depending on what you want to do, then in the code itself you also have to account for the Role which holds that permission and also that Role's Position in the hierarchy as compared to other Roles or specific Channel grants per Role.
@discord.commands.default_permissions( administrator = True )
@discord.commands.default_permissions( manage_roles = True )
Etc
Ok ok, so I can't do it role-based in the code. It has to go through the server?
Not sure what you mean.
I don't want them to be hidden based on permissions, but based on roles.
And as far as I gather from both your and Ice's messages, that's not possible.
Server Owners, Administrators, and anyone with Manage Roles in an appropriate heirarchy position can change the names of any Role they can control, and also I believe that every role you create in a different Guild, even using the same name universally, would have a different Role ID via the API, so you'd have no way of knowing which Role to select anyway.
So the best you could do is to check for a Permission you expect to find in that specific Role, to hide the command from auto-complete via decorators, and if it exists for the User in the Guild then scan that User's Roles to find out the Role Name, and hope that somebody didn't change it after you auto-created it.
You can't hide commands via the code. Server managers (don't know exact perm) can change the integration settings to hide commands for roles/users. When you give default_permissions it is a default that is overridden when integration settings are set
Thanks, thought as much.
You can add runtime checks to make it fail though.
A shame, but I guess I'll have to keep running role checks inside the commands then.
Yes, and it is good to do this as well
Makes it weird for users to see staff only commands show up, but they'll have to deal with that 😛
I am saying that it is possible tho
Yes, but only permission based?
The staff of the server just have to set it up, not you as the dev
I don't need/want permission based.
Don't "staff roles" have specific permissions that you can account for using the default_permissions decorator I already mentioned? That DOES hide the command.
There a few commands that are considered staff, but also volunteer staff. Which have 0 extra permissions over everyone, and are marked by a role instead.
So permission based is out of scope, as they are, on a permission level, no more than a regular user.
Then I think Ice's advice is the best. Include documentation such as in your help files which describe to server owners how to configure command-hiding from randos.
So the admins of that guild can go to Server Settings -> Integrations -> Your volunteer command -> Set everyone permisison to false and add the volunteer role as an override
yeah, that's what I have now 
and if a server owner forgets that, there is always the incommand role check.
👍
A shame I can't attribute it, but alas, that's the system we are working with.
Thanks for the brain capacity 🙂
Is it possible to automate that once the bot's Integration Role is positioned appropriately with a Manage Roles permission for itself?
Its also important to remember that the default permissions can be overridden, it will not always require that permission if a server admin sets it up differently
Not through the bot. You can do it through OAuth and the applications.commands.permissions.update scope
Now that we are talking integration overrides.
can you override subcommands? or only the root command?
Only root commands, for some reason discord does not treat sub commands as commands but rather options (that are prefilled) to the root command
Ugh, again the system we are dealing with 😛
Guess I'll have to throw around some commands then.
how should i edit interaction to add some thing on it ?
the class of the interaction
You cannot subclass Interaction like Context
i dont think so, my goal will more to like edit it, maybe wiht a discord.interaction = ...
where there is my thing
mmmm
i guess you can...?
idk no guarantees
import Interaction -> subclass it -> discord.Interaction = ...
Monkeypatching? Nahh
we technically already do that in bridge
im gonna try then
also
do you have an idea of how can i do for my context, i have 2 differents context and i would like to put them together:
class DatabaseContext:
def __init__(
self, cache: aiocache.BaseCache | None = None, *args, **kwargs
) -> None:
super().__init__(*args, **kwargs)
self.cache = aiocache.SimpleMemoryCache() if cache is None else cache
self.user_db: User | None = None
self.guild_db: Guild | None = None
class TranslatorContext:
@property
@lru_cache(maxsize=1)
def translator(self) -> Translator:
return Translator.get_translator(ctx=self)
you can subclass multiple classes
class LumabotPrefixContext(DatabaseContext, TranslatorContext, bridge.BridgeExtContext):
pass
class LumabotAppContext(
DatabaseContext, TranslatorContext, bridge.BridgeApplicationContext
):
pass
class LumabotContext(LumabotAppContext): ...
i was trying something like so, however i get some error by doing that, all my slash command stop working for exemple
what error
TypeError: ApplicationContext.__init__() missing 1 required positional argument: 'interaction'
which is a bit strange since i didnt edit that part of my code, only change was to slipt up the different context
you should define __init__ and super it
how and were ?
should i do for each subcontext or to the main one appcontext and prefixcontext ,
we went with paillat with the order and the only time it was working without error were when we put it last
I'll take a look later if you want
for reference
thanks
but since i dont subclass anything for the first 2, what init should i add ?
because in my database context i dont have super().init(*args, **kwargs)
maybe its what is erasing everything ?
but why would i do that only fro the slash ?
doing like tsol :
class LumabotAppContext(
DatabaseContext, TranslatorContext, bridge.BridgeApplicationContext
):
def __init__(self, bot, interaction: discord.Interaction, **kwargs):
super().__init__(bot, interaction, **kwargs)
didnt change anything
lemme check how i did it
thanks
ok context last is correct
hmmm
how about in database, you only super Interaction?
Let me try that
how should i super interaction here ?
class DatabaseContext:
def __init__(
self, cache: aiocache.BaseCache | None = None, *args, **kwargs
) -> None:
super().__init__(*args, **kwargs)
self.cache = aiocache.SimpleMemoryCache() if cache is None else cache
self.user_db: User | None = None
self.guild_db: Guild | None = None
i guess your existing code technically may have covered that already.. args is just a regular list
my guess is for some reason translate is eating an arg?
Yeah I’m a bit lost too
does it work if you take out translate
it doesnt change anything
so from my taste it shows that it come from the database context
i fixed it by doing like so:
class LumabotPrefixContext(TranslatorContext, DatabaseContext, bridge.BridgeExtContext):
def __init__(self, interaction: discord.Interaction, *args, **kwargs):
super().__init__(interaction, *args, **kwargs)
DatabaseContext.__init__(self)
class LumabotAppContext(
bridge.BridgeApplicationContext, TranslatorContext, DatabaseContext
):
def __init__(self, interaction: discord.Interaction, *args, **kwargs):
super().__init__(interaction, *args, **kwargs)
DatabaseContext.__init__(self)
class LumabotContext(LumabotAppContext): ...
and removing the super form the databasecontext
nothing to be found I think it has been cleaned
By the way people for some reason discord decided to quarantaine my application (that was like 2 weeks ago)
how could that possibly happen? My bot hasn't been doing anything wrong but fortunately discord removed the quarantaine from my bot but didn't give a reason for the quarantaine
Does it send dms ?
nope it never had
it's really just a bot that's used for only one server
probably
just scared that discord will falsely quarantaine my bot again
just dont do weird shit lol
easier said than done if I don't know what I am doing wrong
it's not scamming or sending any weird stuff to people in private
Hello, I'm trying to send "big text" (a header) inside an embed, but instead of getting a formatted text
Example
i get simply
"# Example"
in the formatted text, here's the code
embed.add_field(name="Lyrics:", value="Lyrics first Line\n# **Lyrics big Line**\n-# Lyrics mini line\n-Lyrics third line", inline=False)
while -# lyrics mini line works fine
Example of what i mean
i dont think big text is supported in fields
Only the description supports headers
I've seen it done in other bots tho, do you mean not supported by pycord or am I just wrong and i am not remembering correctly?
didn't mean to tag on reply i hate discord mobile
Those bots were using it on the description
Fields don't support headers, ask discord why
If you wanna know why they're supported: https://github.com/discord/discord-api-docs/issues/7167#issuecomment-2369258696
Wait if a message gets deleted, that fires an audit log entry event, but if another message fromt he same person gets deleted by the same othe rperson, it doesn't fire an event again ?
if it updates the existing audit log entry, then no
because there's only an event for entry creation
Shoot whatever
user.id is identical to guild.member.id for the same person, regardless of what Guild they're in, right?
Yes
Thank you.
Hey guys I'm having problems fetching a message in another channel but in the same server through a command am I missing something?
Following error: 404 Not Found (error code: 10008): Unknown Message
This is the code:
channel=bot.get_channel(info["channelID"])
message = await channel.fetch_message(info["messageID"])
I'm 100% sure channelID and messageID are correct
How are you getting this message and channel IDs ?
I have them stored in a database as ints
strings
check if the channel ID you get from the DB is correct
actually wait the channel is right from what i can see so ig your ints are 64 bit
if i run this code:
chhannel = bot.get_channel(info["channelID"])
print(chhannel.id, ctx.channel.id)
I get this as Output:
1341058807022878750 1341058807022878750
wich means it is detecting and getting the same channel no? (added an extra h for differenciating)
and if you do https://discord.com/channels/SERVERID/CHANNELID/MESSAGEID it works?
with the data you get from the db?
trying rn
it works
sorry it took a long time i was doing various tests
Are you sure the bot is in the server?
yes im talking to him, below the full code
import discord
import os # default module
from dotenv import load_dotenv
import youtube_dl
import yt_dlp
import asyncio
from discord.ext import commands
from handlers import *
import datetime
load_dotenv() # load all the variables from the env file
intents = discord.Intents.default()
intents.message_content = True # Enable message content intent
bot = commands.Bot(intents=intents)
@bot.slash_command(name="testplay", description="test the player", guild_ids=[ID])
async def hello(ctx: discord.ApplicationContext):
if checkSession(ctx.guild.id) == 0:
message = await ctx.respond("This is the main message that will be edited evrytime there is an update, even if restarted")
updateSession(ctx.guild.id, ctx.channel.id, message.id)
else:
info = getGuildInfos(ctx.guild.id)
try:
playerChannel = bot.get_channel(info["channelID"])
message = await playerChannel.fetch_message(info["messageID"])
await ctx.respond("Updated main command", ephemeral=True)
await message.edit(content=now.strftime("%Y-%m-%d %H:%M:%S"))
except Exception as e:
print(e)
message = await ctx.respond(f'https://discord.com/channels/{info["guildID"]}/{info["channelID"]}/{info["messageID"]}')
await ctx.send("messagge id now: "+str(info["messageID"]))
await ctx.send("new nessage id: "+ str(message.id))
updateSession(ctx.guild.id, ctx.channel.id, message.id)
session = Session(ctx.guild.id)
bot.run(os.getenv('BOT_TOKEN')) # run the bot with the token
has to be else they wouldnt have a valid channel
the code is a bit messy rn since im testing stuff
ERROR is still 404 Not Found (error code: 10008): Unknown Message
are you very sure the bot can see the message
as per pycord docs:"
Raises:
NotFound – The specified message was not found.
Forbidden – You do not have the permissions required to get a message.
HTTPException – Retrieving the message failed.
so it should say forbidden no?
unknown message means the message ID is wrong for whatever reason
they say its right tho, they tested by building a message link with their saved ID
I know that get_* which are non-awaited are never API calls. Not sure if or which intent you need enabled to use get_channel rather than fetch_channel, but I see you use fetch_ for everything else.
discord disagrees 
message cache is limited to 1000 so fetching messages is relatively common
guilds and their channels are cached limitlessly afaik
i mean you can raise it, but yeah
Did you try removing the try/except to identify which codeline is actually raising the error?
I'll try now, I've debbuged so much i don't even remember what I did anymore
Been debugging since 16
Anyway, any other way to edit a message that was sent previously even if the bot was restarted?
Since that's what I need
Well, your first message said something like "getting a message from another channel on the same server" meaning another channel from whence the command was executed, right? So if there's nothing wrong with your ID storage types or values, there's something wrong either with your channel retrieval (ie lack of intent for caching, which they say isn't an issue) or perhaps with your db insertion in the first place. I think the issue is simply that you're querying the wrong channel for the message ID, somehow.
Literally stabbing in the dark.
they did say the message link they build from their saved DB data works tho
no i've tried using stuff as channel.id with the retrived channel and it works fine
And that's what prompted me to ask about caching since the use of get_channel over fetch_channel. :-/
I'm a little curious why both exist for that particular purpose when in every other use-case it requires caching.
more detailed error without try except:
File "/home/samuele/home/python_env/musicbottest/lib/python3.12/site-packages/discord/abc.py", line 1748, in fetch_message
data = await self._state.http.get_message(channel.id, id)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/samuele/home/python_env/musicbottest/lib/python3.12/site-packages/discord/http.py", line 370, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/samuele/home/python_env/musicbottest/lib/python3.12/site-packages/discord/bot.py", line 1137, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/samuele/home/python_env/musicbottest/lib/python3.12/site-packages/discord/commands/core.py", line 435, in invoke
await injected(ctx)
File "/home/samuele/home/python_env/musicbottest/lib/python3.12/site-packages/discord/commands/core.py", line 146, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10008): Unknown Message
For shiz and gigz can you target that particular Message in that particular Channel manually, such as by copy/pasting the IDs directly into the codeblock and testing it that way?
Make sure it's not just a weird issue with that one message.
sure
So that works fine. If you then take the values you copy/pasted from Discord and compare them against the values stored in those info[] vars, are they identical?
so hardcoding the IDs of the message you want works, or no?
Did you ever post the code behind that getGuildInfos func?
try casting to int who knows at this point
i thought that was clear lol
if I use infos["channelID"] and type the message id in the code is fine, if i do the opposite it doesent work
for the opposite i mean infos["messageID"] while typing the int of channel id in the code
So SelectOptions only accept emojis (vs remote URLs, like you can do in embeds). I'm assuming this will capture the bot's emoji list in versions of pycord that support this?
But if I want to have my dropdown use icons that don't appear in the server, I would have to upload them as emojis first?
So like Paillat said, try casting to int(infos["messageID"])
Yes
Select options use emojis
You did verify for me that the copy/pasted ID value was identical to the database-stored value, in infos, yah?
Components can use any emoji
updateSession(ctx.guild.id, ctx.channel.id, message.id)
Am I storing the right message ID?
wen Doru 2.7; need those bot-level emojis
ctx.respond returns an Interaction
b r u h
but didnt you say building the message link with the data from the database worked?
Because the LINK aka URL is expecting an str anyway XD
It literally worked
not what im going for.
I did convert into str i posted the code above if u wanna try
Are you deferring the interaction
But did you try casting infos["messageID"] as an int when you put it through fetch_message?
@lofty parcel
Yeah they're storing the interaction id lol
I don't know what we're talking about right now, but I see if checkSession(int)... is checkSession comparing the right types?
So if i change that to send it should work?
yea but they said if they use the data in the DB to build a message link it works... how
interaction = ctx.respond...
interaction.message.id
Nope it just checks if a db entry was created already for that server
Have they tried ✨ printing the hecking value ✨ and comparing
think so
Yes many times
Both console and text message
And the values match?..
this is the problem
didnt you just say the message IDs are correct
im p sure you said earlier you compared what you saved to the actual message ID..
i'm getting crazy, i assumed that since the link i generated worked
bruh i figured youd actually click it lmfao
this is not a thing AttributeError: 'NoneType' object has no attribute 'id'
nono i clicked them and they did bring me to th messages
even tried generating from different channels to channels i sent the message before
wtf
this is me lorem ipsuing the message in order to see if the click of the link i generated would scroll to the right message
Did you await it?
bruh moment
thats why i write codeblocks that you cant copy easily.. and yet.. they still get copy..
i'll take a break from coding today, thanks everyone for the help im just doing random stuff at this point 
gonna go for a beer now i think
It would help if you wrote out exactly what you want the code to do. The things you expect to collect and how it'll be used.
except the dotenv and bot.run(os.getenv('BOT_TOKEN')) i actually did not copy anyhing, i had the docs with me the whole time
no i mean the not awaiting ctx.respond
thought that reaction meant you didnt lol
and i didnt type the await
my head hurts
await head_better()
At one point I thought your issue was totally resolved now. So the question I have now, if the problem is still ongoing, is just a repeat: Did you EVER cast infos["messageID"] as an int when calling fetch_message? And for that matter, did you do anything to verify that "messageID" is in fact the properly spelled case-sensitive key you think it is?
.... await better_head()
been debugging since 16:00 i feel you. I'm used to coding in python for my job and im a cs major, coded many telegram bots as a kid but this is my first time coding a discord one
i did and it is coherent with the code but turns out it was the interaction id all along
and the link workd because it brought to the interaction
im p sure fetch message would convert it either way
plus its stored as int in their db
fetch_message doesn't convert, but it technically doesn't need to either because discord parses it the same
we typically recommend int for consistency with the library and its cache
I thought so too, but it seemed like it wasn't. Poppy now knows that the link was being generated with the wrong ID value, which is why it worked while the other usage did not.
So does a message ID factually change whenever the message is edited?
no
So once the value was changed from the interaction.id to the database-stored message.id, did the link quit working too?
man idk im lost in the sauce
why would it change
New info outdated the Q you replied to.
#1132206148309749830 message
what is your point
I read this whole conversation. Been trying to help troubleshoot for awhile. You just started asking questions and I don't know why you're coming at me instead of the OP.
guys sssh, OP stopped trying anyway
I asked the OP a Q and then you replied to me with another Q. You've been doing nothing but making challenges directly to me ever since. No clue what's going on right now. Cyberbully much?
dawg you're looking into it too much
wtf what
man void chill out its not that deep lol
youre lucky I didnt feel in "ask rhetoric questions to make them feel dumb" mood then lmfao
I have an animated gif I like to use when I just make like a baby and head out. Haven' t seen anybody else posting such media here, so I'll refrain. All it is is some kind of mountain sheep with a badunka-butt walking away from the camera. I am the butt.
Hey >:( i made it to where I wanted to get
hey guys planning to create a discord bot that hosts its own websocket server
if I just get a role with guild.get_role will it also get refreshed?
refreshed how
as in:
async def serve(ws: ...):
guild: discord.Guild
role = guild.get_role(...)
while True:
... # When the role has been manually changed/the state has changed such as the name of the role has been manually changed by for example me, will it also be directly updated?
can barely describe it
get_role just queries the cache
the role will be updated in cache by the events discord sends your bot
and yes, the object stays the same
lol
you just predicted the future i just waned to ask that
alright thanks
by the way to run the ws server I just have to create a new task by doing asyncio.create_task?
no clue, i never do stuff like that
alright thank you!
just updated my python version and it cant find the discord module
Eh, that is pretty normal if you do an update of Python..
i did the uninstalls and reinstalls but it aint working
Can you show the pip list pls
Is discordLevelingSystem installing discord.py or other stuff?
Also did you add the right interpreter at your code?
yeah
Yes that Library sucks don't use it
Worst design choice after using JavaScript on the server
yeah i just uninstalled it
people still use requests without a runner xd
Really it won't help you that much, in the end you're better off doing it yourself, and you'll learn how to do things too
Help
Hello,
is there a possibility if I use a user mention in an embed message to prevent that the user is not resolved correctly and then the user ID is displayed?
So if it should actually be @UserXY sometimes @torn ermine is displayed
Not in titles
It's not in the title. It's in the description.
For one user the mention is displayed, for the other user the whole thing is displayed with the ID.
you need to mention them in the message content as well to force the client to resolve it
Does that mean I have to mention the user in the message and then it will be displayed correctly in the embed? Otherwise I have no other option?
Okay, that's really not a cool solution 😄
is the issue with the duplication of bridge command has been fix on the master ?
In the default help thing ?
If that Yes I made a PR that is on master now
I have no idea I don't think it was
I can take a look if you give me a mrc
If you want, it’s been a while but bridge is completely broken
Did you sync the commands?
This is with prefix commands
The slash commands seems to be removed and update
Are they bridge commands?
Yeah
But the prefix part is the issue
The client. prefixed_commands doesn’t seems to be reset after unload cog
Even if it should
And you unload, sync, load and sync again?
Yes, but I don’t really see how the sync will be related to the prefix part
I also have my own implementation of bridge but I don’t really think it will be the cause of the issue
Because I’m mainly just :
def add_command(self, command: commands.Command):
group_name = self.multicog_metadata.get(str(command.callback))
if not group_name:
command = Lumabot._translator.add_aliases_command(command)
return super().add_command(command)
group = self.find_prefix_group(group_name)
if group:
self.add_prefix_to_group(command, group)
else:
logger.critical(
f"Failed to add command {command.name}: Group '{group_name}' not found."
)
since im then using the super it should also do the same as with a normal implementation
something that i even dont understand is since i do add the prefix command normally it should also unlink it normally no ?
and this is my decorator:
@classmethod
def command(cls, **kwargs):
def decorator(func) -> bridge.BridgeCommand:
result = bridge.bridge_command(**kwargs)(func)
cls._instance.bridge_commands.append(result)
return result
return decorator
and i can fix it if before loading again the cog i do self.bot.prefixed_commands = {}
For those that have built wizard-like interactions (multiple steps), do you put the logic under a single View, or do you have multiple Views that you pass data to? 🤔
Mine will have different components, so I'm guessing it might actually be easier to use separate Views?
or maybe three (for a two-panel wizard) where the first manages state.
dame
how you did that?
?
colors
Does pycord support app_commands
I am trying from discord import app_commands
and it gives me error
First, can you show the pip list pls?
Microsoft Windows [Version 10.0.26100.3194]
(c) Microsoft Corporation. All rights reserved.
(pycord-bot-py3.12) D:\Pycord>poetry show
aiohappyeyeballs 2.4.6 Happy Eyeballs for asyncio
aiohttp 3.11.12 Async http client/server framework (asyncio)
aiosignal 1.3.2 aiosignal: a list of registered asynchronous callbacks
attrs 25.1.0 Classes Without Boilerplate
frozenlist 1.5.0 A list-like structure which implements collections.abc.MutableSequence
idna 3.10 Internationalized Domain Names in Applications (IDNA)
multidict 6.1.0 multidict implementation
propcache 0.3.0 Accelerated property cache
py-cord 2.6.1.dev206+gfca91f750 fca91f7 A Python wrapper for the Discord API
typing-extensions 4.12.2 Backported and Experimental Type Hints for Python 3.8+
yarl 1.18.3 Yet another URL library
(pycord-bot-py3.12) D:\Pycord>
Sended
I see no discord.py, good
In py-cord its called slash commands
And Not App commands
ok thank you
How can i disable a button after a click on it and enable it after about 5 seconds?
# View
# callback
button.disabled = True
await interaction.response.edit_message(view=self)
await asyncio.sleep(5)
button.disabled = False
await interaction.edit_original_response(view=self)
I guess
This will not guarantee that you only get one button click per 5 second though. If multiple users are spamming the button 2 users might be able to press the button before it is disabled. A safer option would be to store the time that the button was pressed and and check that on every button press. You also might need to use an async lock but idk how those work.
That's no problem. The button is sent ephemeral.
👍 then just be aware that the button will only be able to be edited for ~15 minutes
For AudioSinks, I was trying to find what the default filter for audio snippet lengths is. I got a number of 20 ms from somewhere but I can't find confirmation on that number and can't find it again
Hello !!
Do we have the approximate user install and approximate guild count from library ?
guilds i think you can access with bot.guilds
user install, not yet at least
maybe in 2.7
okay thanks.
Any ETA about the 2.7 ? I know everybody is busy but any idea of release date ?
no
okay
i want it too, but its just... idk man
they aint releasing it
they said when bob was kinda "dethroned" lmfao that they'd have a faster release schedule but since then.. nothing
maybe it needs more new features / fix before release ?
there is no reason to hold it back for more features IMHO
they can just do 2.8 or 2.9 later on
true
they need to release something, especially since 3.13 is getting more common and 2.6 doesnt support it natively
I've followed the instructions on setting up a venv on this site https://guide.pycord.dev/More/virtual-environments
After that I've created a main.py file and just wrote "import discord" and it throws me this error message
The following commands are the only one I've run:
mkdir DiscordBot && cd DiscordBot
python3 -m venv venv
source venv/bin/activate
pip install -U py-cord
echo "import discord" > main.py
python main.py
.tag audioop
Pycord 2.6.1 may work with Python 3.13, but it is not officially supported and can cause various issues. Until Pycord 2.7 includes official support for Python 3.13, it is recommended to use a previous version.
For voice features in Pycord versions before 2.7, you might need to run pip install audioop-lts. Some users have reported issues with voice features when using Python 3.13, so ensure that you clear the __pycache__ and .pyc files before running your bot.
oh, so just use an earlier python version?
yeah
3.9 to 3.12 or install audioop
:) very relevant immediately after I said it
it doesn't throw me the error anymore, tysm
Hey guys - working on my first public bot, super noob question here... why isnt my slash command showing up? previously i just hardcoded the guild id into the slash command arg, not sure the propoer way to do it though so it an work on any server
class RPS(commands.Cog):
def __init__(self, bot):
self.bot = bot
@discord.slash_command(name="rps")
async def rps(self, ctx):
"""Start a new Rock-Paper-Scissors game."""
view = RPSGameView() # No game_id needed for now
await ctx.respond("Choose your move:", view=view)
***********
if __name__ == "__main__":
cogs_list = ["rps"]
for cog in cogs_list:
bot.load_extension(f"cogs.{cog}")
bot.run(DISCORD_TOKEN)
.tag slashnoshow
Application Commands Not Showing Up?
- Refresh Discord by restarting or pressing
Ctrl+R(orCommand ⌘ + R) - Uninstall libraries that conflict with the
discordnamespace (e.g.discord.py). - Invite your bot with the
application.commandsscope. - Load cogs before
bot.run()(e.g. not inon_ready). - Do not override
on_connect. - Update to the newest version of
py-cord(see?tag install). - Turn off
User Settings > Accessibility > Chat Input > Use legacy chat input. - Share your code and errors.
i dont think its any of that, i think my code is bad 😅
You are missing the self parameter and slash commands do not take interactions.
please read the guide.
ahhh
wait yes
async def setup(bot):
await bot.add_cog(RPS(bot))
and
if __name__ == "__main__":
cogs_list = ["rps"]
for cog in cogs_list:
bot.load_extension(f"cogs.{cog}")
bot.run(DISCORD_TOKEN)
.
is that the wrong way of loading it?
just tried adding this and seems to not be printing :/
class RPS(commands.Cog):
def __init__(self, bot):
print('LOADED')
self.bot = bot
oh wait just seeing this now...
/Users/ethan/PythonProjects/RPS/venv/lib/python3.12/site-packages/discord/cog.py:796: RuntimeWarning: coroutine 'setup' was never awaited
setup(self)
yes
oh yea the setup isnt async
def setup
should not be async
ohh wow hang on
this was it thanks! thats crazy my other bot has those all async guess i gotta go update that 😄
yeah ig
discord.py does it like that i think
Just realized active support for 3.12 ends on April 2!
3.9 is still supported..
python doesnt deprecate versions that aggressively
3.12 will receive bugfix updates approximately every 2 months for approximately 18 months. Some time after the release of 3.13.0 final, the ninth and final 3.12 bugfix update will be released. After that, it is expected that security updates (source only) will be released until 5 years after the release of 3.12.0 final, so until approximately October 2028.
I’m talking about active development on Python
Going into security support in April
i dont see why that matters lol
yeah
It’s just surprising to not actually support the current version of Python
the software world in general moves slower than you think
look at cobol
look at java 8 still being used all around the world
public stuff running python 3.8 and 3.9 still
many linux distros dont even use 3.13 yet
Yeah and tbh no one pushes with the latest version in production ever
There’s a difference between “this application is old” and “my current-day library doesn’t support the current version”
That’s very definitely not true
Ok sure
absolutely true
Try installing a random ml project that is more than 1 year old and actively maintained
I guess my company doesn’t exist? We were shipping node 22 shortly after release
That's dumb honestly but ok
“No one” is trivially falsifiable
Either Way
Yep
lol, you’re the one who made the claim, but okay
Nuance is needed. Major software development houses generally don’t use bleeding edge because of inertia and the risk of unknown bugs.
More agile companies can and certainly do.
hey, I'm looking to user pycord to create some app-scoped (as opposed to added to a server) message commands, and it seems to take AGES for discord to update the app commands my bot offers. this is making it hard for me to tell if I'm making a mistake with my approach or if discord is just being discord. is this to be expected, or am I doing something wrong, and there is a way to force them to refresh?
I've found this discord API discussion which suggests that discord has added some sort of update-on-interaction-fail system in 2021, but my app still has "old" interactions that I have removed from my files already, and trying to use them isn't updating the list
https://github.com/discord/discord-api-docs/issues/2372
hm, seems like I was not properly loading the cogs, and they are updating in a reasonable timeframe. or I am doing something else wrong? who knows. I am using cogwatch I guess its preload setting doesn't actually get them in early enough. directly loading each cog via bot.load_extension seems to work now
just reload discord
also all bots are apps
what you mean is probably message commands for a user apps
reloading discord was making no difference until I fixed the mistake I mentioned above
"user-scoped" is probably the right term yeah
oh yea i missed this message
Hey guys is there an easy way to prompt the user to allow DMs directly from a bot and not necessarily the entire server they are in?
Probably installing the bit as a user app
yeah is there a way to message them back with the link for that in the settings?
feels like a lot of steps to ping them the link in the server they are in, so they see this then they have to click view, then click the 3 dots, and then click add app
why tho?
I am trying to build a bot that people can play games with across servers, so the only way to message both users that are in a game is with DMs
server 1, player one starts a game and enters some info
3 hours later server X player 2 enters more info, winner is established, message both users the outcome
cant use the ctx since different servers, db saves discord member ids from the interaction, but then need to dm both
or i guess i could save the guild / channel from each server and post the same thing in both
dm feels cleaner tho
Is it possible for a Discord bot to add a button to a member's message? It is to do for example:
If I write "Hello World" the Discord bot will add a button to display the message translated into French in ephemeral mode
Ping me please
Message commands ?
Learn all about Context Menus (User Commands & Message Commands) and how to implement them into your Discord Bot with Pycord!
How does it work?
its just a regular button lol
Hmm
It might be a webhook that embed generator created ?
Yes
oh wait i misunderstood
but yea
you just cant add buttons onto user messages
regardless it'd probably clutter chat hard for your use case
Hm okay
Hey guys - is there a best practice on how to call a function from within a cog as a callback when using a view? ...do you just pass the cog to the view every time?
show what you mean
why just not Mycog.function ?
cant if its not static
you do can
no self if you call it from a class context
# Main RPS game cog
class RPS(commands.Cog):
def __init__(self, bot):
self.bot = bot
# Slash command to start a new game
@rps.command(name="new")
async def rps_new(self, ctx):
"""Starts a new Rock-Paper-Scissors game."""
view = RPSGameView(self, game_id=None) # PASSING THE ENTIRE COG HERE TO VIEW EVERY TIME
await ctx.respond("Choose your move:", view=view, ephemeral=True)
class RPSGameView(discord.ui.View):
def __init__(self, rps_cog: RPS, game_id: int = None):
super().__init__(timeout=None)
self.rps_cog = rps_cog
self.game_id = game_id
choices = [("🪨 Rock", "rock"), ("📄 Paper", "paper"), ("✂️ Scissors", "scissors")]
# Dynamically create buttons with callback
for label, choice in choices:
button = discord.ui.Button(label=label, style=discord.ButtonStyle.primary, custom_id=choice)
button.callback = lambda interaction, choice=choice: self.handle_choice(interaction, choice)
self.add_item(button)
async def handle_choice(self, interaction: discord.Interaction, choice: str):
"""Handles user's game move choice."""
if self.game_id:
await self.rps_cog.join_game(interaction, self.game_id, choice)
else:
await self.rps_cog.create_game(interaction, choice)
you can use the self from the view
just make join_game static
i initially had that, but i wanted to in the join_game and create_game then be able to DM the user
and to do that i need to access the bot to query discord utils
so figured passing it so in self i cuold juse self.bot
yeah thats essentially what i am doing, i am just passing the entire cog (self)
the above works. i am just trying to see if its most efficient way
and then call it and use the view as self if you only need the bot
view = RPSGameView(self, game_id=None) # Pass the cog instance to the view
this is an exemple of what im doing
async def button_reset_callback(self, interaction: discord.Interaction):
if interaction.user.id != self.author_id:
return await interaction.response.send_message(
self.translator.error.no_author, ephemeral=True
)
for field_name, field in StatsCounter._meta.fields_map.items():
if not field.required or not field.pk:
setattr(self.counter, field_name, field.default)
await self.counter.save()
await StatsCounterCog.dropdown_callback(self, interaction, self.counter.id)
because my self.bot is always pass inside my viw
but there is no most efficient, is almost the same to pass the cog or the bot, even if you only need to bot the most logical way would be to pass it inside ur view and in ur function
okay it sounds like my approach above is okay then?
then just pass it the bot lol
yeah true i guess thats a little less heavy
just out of curosity what would go as the hint?
bot: RPS
discord.Bot..?
actually nvm, think i need to pass the cog anyway
because the callback is using some of its functions
i.e.
await self.rps_cog.join_game(interaction, self.game_id, choice)
just make them static
Can’t because those static commands then would not be able to access the self.bot
Not following how I could just pass the bot to the view, the view needs the function which is part of the cog which then needs the bot
if you make the method you need static you can just import it because it doesnt need a self parameter anymore
Hmm I can play around with it some more but from performance standpoint you think it would make any difference?
Is guild.create_test_entitlement() not working in v2.6.1 or is my code wrong:
guild = await self.get_or_fetch_guild(guild_id)
sku_obj = await self.get_sku_from_id(sku_id)
await guild.create_test_entitlement(sku_obj)
Both guild and sku_obj are valid objects and not None
Yes this is broken in 2.6.1, fix is already in next release
Any workaround until it goes live aside from switching to master?
mmmm probably just running it manually
something like ```py
async def create_test_entitlement(guild, sku):
payload = {
"sku_id": sku.id,
"owner_id": guild.id,
"owner_type": discord.EntitlementOwnerType.guild.value,
}
data = await bot.http.create_test_entitlement(
bot.user.id, payload
)
return discord.Entitlement(data=data, state=guild._state)
Test and adjust as you see fit
Thanks. Any idea when .2 will be released?
Soon™ hopefully
Is there a way to remove the test entitlement?
Entitlement.delete
is there a way to get/fetch a discord.Message given just its id? it's in a task processing database data so I don't already have a context. I have seen utils.get_or_fetch but it fails because bot (discord.Client) does not have a get function for messages
message = await utils.get_or_fetch(
self.bot,
"message",
thisReminder.discord_message_id,
default=None,
)
I think I could just store the message's guild id, channel id, and message id in the database but that feels like a complication and waste of storage, especially because the message could be in a dm
discord.Bot.get_message returns none (presumably that only hits cached)?
I am in a cog so self.bot is my client
i know
I don't have the channel I got the message from, unless I also store it and the guild id as described here #1132206148309749830 message
do I just have to suck it up and store the extra data or is there a smarter way
its just one extra number lol
its not like its gigabytes of data
and well, only messageable objects have .fetch_message
so you kinda need whatever messageable the message was sent from to fetch it
alright, just seemed like something there should have been a better way for. I thought message ids were unique across all of discord? or are they only unique within their guild/channel
IDs are unique, but message routes are per channel and message 
message ids should be unique, but they're useless if you don't know what channel they're in
minimum you need is channel and message ids
ID of any messageable* i think, since DMs etc also work
dms are channels

hm
Out of curiosity, what guild do they belong to, then? 🤔
none
They don't
So channels don’t belong to a guild in the same way messages belong to channels
guilds are optional yes
(notice how most channel/message related endpoints don't require the guild id)
Why doesn't BridgeCommand generate slash commands for aliases?
name="wallet",
description=f"Your {BOT_SETTINGS['name']} Wallet address and QR code.",
aliases=["deposit"]
)```
Slash commands does not have aliases
ok thx
How can I give away free entitlements? I see EntitlementType has a developer_gift attribute
don't think this is on the api, but if you have a store page you can set it as Beta
oh hm
try user.create_test_entitlement
idk if that's actually what you want though
glancing around dev server i don't think it exists yet
Does a test entitlement have any differences from a real one?
It's a type of entitlement meant for testing, so no, it shouldn't
But it will not be free entitlement
Like the user will not get any value from that?
it's free and you can revoke it
That’s perfect lol. I can delete so much code now
Will that reflect on discord too ? Like the user will get th perks ?
Or it’s only inside the code ?
the entitlement will show when recieved from discord, but because there is no subscription the user won't get roles or anything automatically
Thanks
I’m only using guild entitlements so far, does it have anything like that tied to the subscription status?
no, test entitlements will not have a subscription, since they're permanent until removed
and have no billing flow
Did discord ever suggest how to name sure a user doesn't subscribe through discord after subscribing e.g. form a bots website?
not particularly, that's up to the dev
(and realistically all it entails is checking the user ID)
Hey guys quick question about Views... Trying to leverage the same view and pass diff args to it. the args i am passing to it (i.e. league) seem to get overwritten when i have 2 views showing at the same time, it just takes the args of whatever the msot recent one is. Why would this not be creating a new instance every time?
@rps.command(name="unranked")
async def rps_new(self, ctx):
"""Start a new unranked Rock-Paper-Scissors game."""
view = RPSGameView(self, game_id=None, league="unranked", tip=None)
await ctx.respond(view=view, embed=view.get_embed(), ephemeral=True)
@rps.command(name="ranked")
async def rps_new(self, ctx, league: str, tip: float):
"""Start a new Ranked Rock-Paper-Scissors game."""
view = RPSGameView(self, game_id=None, league=league, tip=tip)
await ctx.respond(view=view, embed=view.get_embed(), ephemeral=True)
class RPSGameView(View):
def __init__(self, rps_cog: RPS, game_id: int, league: str = None, tip: float = None):
super().__init__(timeout=None)
self.rps_cog = rps_cog
self.game_id = game_id
self.league = league
self.tip = tip
choices = [("🪨", "rock"), ("📄", "paper"), ("✂️", "scissors")]
for emoji, choice in choices:
button = Button(label=choice.capitalize(), style=discord.ButtonStyle.primary, emoji=emoji, custom_id=f"choice_{choice}")
button.callback = partial(self.handle_choice, choice=choice)
self.add_item(button)
async def handle_choice(self, interaction: discord.Interaction, choice: str):
"""Handles user's game move choice."""
if self.game_id:
await self.rps_cog.join_game(interaction, self.game_id, choice)
else:
await self.rps_cog.create_game(interaction, choice, self.league, self.tip)
def get_embed(self):
return self.embed
your custom_id needs to be more unique
(probably, idk the full details of your issue)
when i do this i get a diff id, and the button values seem to be changing.. its just the self.tip and self.legue type values that i am passing to the view htat seem to be getting overwritten
class RPSGameView(View):
def __init__(self, rps_cog: RPS, game_id: int, league: str = None, tip: float = None):
print(id(self), league, tip)
ah wow yep this was it! ..what is supposed to go there then... just like a random.ranint(1,9999) ?
well they do have a unique id, the problem is it doesnt get specified until after the selection in this view is made
because the selection is what triggeers the db insert, and game_id is the auto generated primary key
...wonder if i jsut dont specify a custom_id?
hah everything seems to be working by just removing all the custom_ids 😕
well
how do you make a command take multiple options, and when no option is given it defaults to all of the options?
that's because it generates a random custom_id
in your implementation this is technically fine so sure why not
ah perfect okay
elaborate
I wanna make a command which just grabs my current CPU, GPU etc. info and spits it out, and lets me choose if I wanna just share CPU usage or anything else
is there a way after a button is selected to then delete the view? right now you can keep clicking the button and it keeps running the callback
just the view? or entire message
well the view is the entire message really its an embed
a single arg can't take multiple options
hmm im not sure what it would look like if we remove the view and keep the message it would just be blank?
so you'd just make several bool options
doesn't it have an embed attached?
ah, can you link that part of the docs? I still have trouble navigating them
so do you want to get rid of JUST the view, or also the embed
are you familiar with the Option class or option decorator?
ah i see what youre saying, yeah I guess remove the view (Buttons) and then update the embed too
