#Basic Pycord Help

1 messages · Page 68 of 1

modern trail
#

this is my fear as well

lapis dock
#

Looks like only ctx.author and ctx.send

sage tendon
#

hm

#

then it might be quite easy even

lapis dock
#

Just have to copy paste and remove author stuff and set it up to accept a channel instead

modern trail
#

copy paste the entirety of the paginator class? and modify those ctx parts is what you're saying?

lapis dock
#

Just .send

sage tendon
#

and the constructor ofc

modern trail
#

oh oh

lapis dock
#

Subclass paginator and override .send

modern trail
#

right i see

lapis dock
#

I can help more in a couple hours when I am back at my PC if needed

modern trail
#

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

round heart
#

Paginator2: Electric Boogaloo

lapis dock
#

Now that I am thinking about it it is probably possible to build this in without a breaking change

modern trail
#

like add a new method to the paginator that does what i'm going to do?

lofty parcel
#

We'd have to rewrite the whole shit at some point tho

#

Otherwise we can't maintain it

lapis dock
#

I think it should be possible to make context optional and just require context OR target

lapis dock
sage tendon
#

just build it from scratch and put it in 3.0 lol

sage tendon
lofty parcel
#

I assume they'd get moved

lapis dock
#

Pretty sure almost everything for slash is out of ext.commands now

#

If you want prefix you would then install ext.commands separately

sage tendon
#

honestly i never understood ext
its not an extension if its literally in the library really

lapis dock
sage tendon
#

making an extra package for such a small addition seems unnecessary

lofty parcel
#

True tbh

lapis dock
#

I don't think prefix commands are small. Also at this point in time most people don't (or should not) need them

sage tendon
#

hm, fair

#

lets go to #discussion

red crypt
#

With pycord's user integrated commands, is it possible to fetch channel message history?

little cobalt
red crypt
sage tendon
#

i still think discord should've given user apps the same permissions as the invoking user but nope

red crypt
sage tendon
#

well, discord says no Shrug_3

#

they did say more is to come for user apps, so maybe one day

red crypt
#

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 yb_shrug

sage tendon
#

which is why i said they should just copy the user perms

#

would also allow for actual automated actions like role creation or whatever

lapis dock
#

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)

errant trout
#

pretty much yeah

#

if user apps had regular user permissions, they would literally be selfbots

sage tendon
#

and that is a problem how? :)

#

youd still be limited to application commands

quartz umbra
#

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
sage tendon
#

lowercase o

quartz umbra
#

o

sage tendon
#

and value is not a kwarg for discord.option

quartz umbra
#

and this time?

    @discord.option(str, name="Peak Tier", choices=TIERS)
sage tendon
#

no

#

actually that might work but you should just pass the name and type positionally

quartz umbra
#

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)

sage tendon
#

you can just do bot.load_extensions("cogs")

quartz umbra
#

wait fr? bet

#

this is what happens when you only use boilerplate code ig

#

tysm for the help

sage tendon
#

am i dumb or is pycharm dumb?

lapis dock
modern trail
#

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

lapis dock
#

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

sage tendon
#

send_to_channel? lolw

modern trail
quartz umbra
#

so if anyone knows off the top of their head, is discord.Message.created_at a datetime (or datetime like) object?

lapis dock
#

yes

quartz umbra
#

so u can do discord.Message.created_at.year right?

lapis dock
#

yup

quartz umbra
#

alr thanks

#

🙂

lapis dock
#

I think it is a bug in the docs that it is not listed

sage tendon
#

using your IDE to its fullest can save a lot of time

quartz umbra
#

xd if the ide knew the type of message though and im not bothered to typehint in this case

sage tendon
#

-w-

quartz umbra
#

nah i genuinely don't know how does one typehint this: ```py
for message in channel.history(limit=limit):
...

sage tendon
#

it should be, because channel.history yields Messages

quartz umbra
#

well vscode isn't detecting it then

#

¯_(ツ)_/¯

sage tendon
#

vscode is not an ide

quartz umbra
#

yea

sage tendon
#

in my humble opinion

quartz umbra
#

nah its a text editor but i like it for what it is

raw beacon
#

why do embeds sometimes refuse to show thumbnail urls

sage tendon
#

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

raw beacon
#

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

sage tendon
#

can you send the url here

raw beacon
#

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

sage tendon
#

hm

lapis dock
#

if it only fails sometimes i would imagine it is a discord issue

raw beacon
#

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

lapis dock
#

i have seen that a few times, idk why it happens

raw beacon
#

really annoying :(

sage tendon
#

does it work with the same url if you try again?

raw beacon
#

yup, it does

#

and sometimes it doesnt

#

appears to be completely random

modern trail
#

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

sage tendon
#

what the fuck is channel.__class__!r

#

ive never seen that syntax

modern trail
#

lol yea, string formatting sugar for repr() basically

sage tendon
#

also id be careful with naming your custom stuff the exact same as pycord's built in classes lol

modern trail
#

why?

sage tendon
#

namespace conflicts suck

modern trail
#

certainly, but i don't believe there's any opportunity for conflicts here

sage tendon
#

just a tip Shrug_3

lapis dock
modern trail
#

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

lapis dock
#

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

modern trail
#

true

maiden bloom
#

Should I submit an issue for this? It shows on stable

echo wraith
red crypt
#

how can i type hint a new channel/announcement channel?

#

there's no direct discord.NewsChannel from what i can see, nor ..AnnouncementChannel

sage tendon
#

discord.TextChannel

red crypt
#

that's what it is already 😭

sage tendon
#

yea and its the right typehint

red crypt
#

it is unfortunatley, not finding the one channel that i need

sage tendon
#

typehints dont find anything

red crypt
#

right, i get that, but it's not there is what i'm hinting at

sage tendon
#

so youre just trying to filter by news channels

red crypt
#

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

sage tendon
#

oh thats what you mean

#

well are you very sure thats the right ID

red crypt
#

100% i just tried it again

sage tendon
#

so <#id> works?

red crypt
#

it does work yes

sage tendon
#

can you show your option decorator / typehint

lapis dock
red crypt
#
async def setups_scammers_channel(self, interaction: discord.ApplicationContext, channel: discord.TextChannel):
sage tendon
#

yea but textchannel should show them all

red crypt
#

^ that's what i was thinking

sage tendon
#

btw dont use interaction, use ctx
interactions are something different

red crypt
#

i thought typehinting would save me 😭

#

does it not?

lapis dock
#

technically it is valid code, just confusing

red crypt
#

i'm so not ready to change so many lines of code from interaction to ctx either

#

future me problem

sage tendon
#

do all other channel IDs work

#

i suspect its because its a defined rules channel

lapis dock
#

TextChannel looks like it is only normal text channels

sage tendon
#

and those get special treatment

red crypt
lapis dock
#

rules is not a special channel type, it just has a different icon

sage tendon
#

okay wait one second what is the actual issue rn
that the rules channel shows, or that it doesnt work

red crypt
#

yeah so can't do nothing about that rules channel

red crypt
#

but it won't let me whatsoever

#

not via ID or via just ...TextChannel

sage tendon
#

let me try something, i have a suspicion

red crypt
#

go for it

sage tendon
#

yea no it works on my bot

red crypt
#

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

sage tendon
#

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

lapis dock
#

they want news tho so switch the type to news ^

red crypt
#

all good

#

i'm not allat silly!

sage tendon
#

i thought the issue was not being able to select the rules channel what

#

im confused

red crypt
#

hahaha

#

no it's the news channel that i cannot do anything with

sage tendon
#

yea okay

#

im tired

sage tendon
red crypt
#
@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

sage tendon
#

i mean the typehint in the function header was correct before

red crypt
#

i don't understand why it's just that annoucnement channel.

sage tendon
#

now its wrong

red crypt
#

sec

#

oh right, no i just edited the one that was already tehre, my bad

#

i'm a little sped

sage tendon
#

also i think you have to pass discord.TextChannel as the second positional argument to the options decorator else it wont work

red crypt
#

yeah

sage tendon
#

not sure why you removed it :)

red crypt
#

that did work haha, will have to keep that noted for next time honestly, always had the issue with news channels

sage tendon
#

i have no idea why they are not included by default

red crypt
#

yeah... it's literally the only one missing from typehinting

sage tendon
#

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)

surreal flicker
#

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
frail basin
#

How much RAM do you have access to?

stray cape
#

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

sage tendon
#

just looks like a fat disconnect to me

stray cape
#

oh my days

#

how can this happen?

sage tendon
#

by your vps having bad connection lol

stray cape
#

damn

#

does that error trigger the on_error bot event then?

fresh sierra
tidal pecan
stray cape
#

this is what systemd gave me

tidal pecan
# stray cape 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.

stray cape
#

ill try to get more information

#

do you perhaps know the command to see the logs of a systemd service?

tidal pecan
#

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

oblique fern
#

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.

sage tendon
#

rename self.message

oblique fern
#

the callback has an internal self.message...

#

ofcourse that would be it 😩

sage tendon
#

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

oblique fern
#

Lets find out 😛

#

Yup that was it.

#

I feel dumb, thanks for the help!

sage tendon
#

np

oblique fern
#

Is there a way to also delete the view after I selected an option in the dropdown here?

sage tendon
#

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

oblique fern
#

yeah editing the message, and nulling the view worked, thanks again. Much appreciated.

lapis dock
#

you can response with a delete_original_response() to component interactions to delete the message they are on

sage tendon
#

i remember one of the regular methods of deleting responses not working with ephemeral responses tho

#

but im not sure which one didnt work

lapis dock
#

you can only edit/delete ephemeral messages with the interaction endpoints.

ebon swift
#

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:

  1. 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 ?
  2. should this chercker be a common python package , or should I make it a discord cog ?
lapis dock
#

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?

ebon swift
#

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 ?

sage tendon
#

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

lapis dock
#

^

ebon swift
ebon swift
# sage tendon i still dont understand what you even wanna save since user profile access is su...

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 ^^

sage tendon
#

ah its just about the name

ebon swift
#

yup

lofty parcel
#

What about ✨️ using ids ✨️

tidal pecan
#

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.

sage tendon
#

the role in their case contains the user's name

#

i dont see what about zed's solution is bad here

tidal pecan
tidal pecan
sage tendon
#

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?

tidal pecan
sage tendon
#

and what if everyone wants a slightly different color instead of just one of 10, 20 presets?

tidal pecan
sage tendon
#

Shrug_3 or just do what zed does

tidal pecan
sage tendon
#

youre reading into it too much

hard heath
#

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.

fresh sierra
#

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

sage tendon
#

is that a prefix command

fresh sierra
#

which mean you can do +status, +StaTus, + STATUS etc and it will work

tidal pecan
#

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 )?

sage tendon
#

you just put exactly what you usally pass to discord.Bot(THIS) in there

tidal pecan
#

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?

sage tendon
#

everything discord.Bot takes

#

check the docs

tidal pecan
#

Well is guide.pycord.dev the wrong place to look???

sage tendon
#

no

#

typically the only things you need are the intents and maybe activity (if you need a custom activity)

tidal pecan
silk spire
#

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

tidal pecan
sage tendon
#

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

tidal pecan
#

Doesn't the description parameter to the init routine set the description property on the bot instance?

sage tendon
#

i literally have no idea where the description even shows up

silk spire
#

It's used in the prefix help command lol

sage tendon
#

i think its the bot's about me but i just set that via the dev page

sage tendon
silk spire
#

That would be neat but also weird to do that on startup every time for a library

tidal pecan
#

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?

sage tendon
#

thats not possible unless the bot has another role above its own role

tidal pecan
#

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.

sage tendon
#

and well, show your code

sage tendon
tidal pecan
sage tendon
#

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

tidal pecan
# sage tendon and well, show your code

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.

sage tendon
#

dw lol

tidal pecan
sage tendon
#

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

tidal pecan
tidal pecan
sage tendon
#

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

sage tendon
tidal pecan
tidal pecan
#

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?

sage tendon
#

yea you can only adjust the permissions

tidal pecan
#

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.

sage tendon
#

yea Discord's entire role and permissions system is busted in general

hexed saddle
#

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
errant trout
hexed saddle
#

yep, i was playing around with it a bit more, turns out i have to defer it..

errant trout
#

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?

echo wraith
#

I think they mean to have an invisible response

#

Like they already edit the message

hexed saddle
#

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

lofty parcel
#

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

errant trout
#

yeah paginator.update already responds too

#

so there's no reason for that final edit

hexed saddle
#

ah ok

hexed saddle
#

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
sage tendon
#

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

hard heath
errant trout
#

fwiw if you change it to type discord.Message it'll automatically convert the ID (assuming the channel matches)

sage tendon
#

wait that works?
like as an option type?

errant trout
lofty parcel
#

It's probably a lib conversion

sage tendon
#

no but where are you saying to change it to discord.Message

errant trout
#

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

surreal flicker
#

About 400MB was used at the time.

little cobalt
#

I wonder if 400MB RAM a lot for a bot?

tidal pecan
fresh sierra
#

400mb for a bot in 10k guilds is not a lot

#

but for one with 1 member it is

oblique fern
#

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?

lapis dock
#

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

tidal pecan
# oblique fern For user/message commands, can you also use predicates for access to the command...

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

oblique fern
#

Ok ok, so I can't do it role-based in the code. It has to go through the server?

tidal pecan
#

Not sure what you mean.

oblique fern
#

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.

tidal pecan
#

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.

lapis dock
#

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

tidal pecan
oblique fern
#

A shame, but I guess I'll have to keep running role checks inside the commands then.

lapis dock
oblique fern
#

Makes it weird for users to see staff only commands show up, but they'll have to deal with that 😛

lapis dock
#

I am saying that it is possible tho

oblique fern
#

Yes, but only permission based?

lapis dock
#

The staff of the server just have to set it up, not you as the dev

oblique fern
#

I don't need/want permission based.

tidal pecan
oblique fern
#

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.

tidal pecan
#

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.

lapis dock
#

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

oblique fern
#

yeah, that's what I have now nodders

#

and if a server owner forgets that, there is always the incommand role check.

lapis dock
#

👍

oblique fern
#

A shame I can't attribute it, but alas, that's the system we are working with.

Thanks for the brain capacity 🙂

tidal pecan
lapis dock
#

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

lapis dock
oblique fern
#

Now that we are talking integration overrides.

#

can you override subcommands? or only the root command?

lapis dock
#

Only root commands, for some reason discord does not treat sub commands as commands but rather options (that are prefilled) to the root command

oblique fern
#

Ugh, again the system we are dealing with 😛

Guess I'll have to throw around some commands then.

fresh sierra
#

how should i edit interaction to add some thing on it ?

#

the class of the interaction

silk spire
#

You cannot subclass Interaction like Context

fresh sierra
#

where there is my thing

errant trout
#

mmmm

#

i guess you can...?

#

idk no guarantees

#

import Interaction -> subclass it -> discord.Interaction = ...

silk spire
#

Monkeypatching? Nahh

errant trout
#

we technically already do that in bridge

fresh sierra
#

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)
errant trout
#

you can subclass multiple classes

fresh sierra
#
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

errant trout
#

what error

fresh sierra
#
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

errant trout
#

you should define __init__ and super it

fresh sierra
#

how and were ?

errant trout
#

in your new class

#

it has to pass through

fresh sierra
#

should i do for each subcontext or to the main one appcontext and prefixcontext ,

errant trout
#

actually i think the order matters

#

move the bridgecontext first

fresh sierra
#

we went with paillat with the order and the only time it was working without error were when we put it last

errant trout
#

ehh

#

idk your best bet is actually implementing init

echo wraith
fresh sierra
#

for reference

fresh sierra
fresh sierra
#

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 ?

errant trout
#

add init to LumabotAppContext that takes Interaction

#

then super interaction

fresh sierra
# errant trout then super interaction

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

errant trout
#

lemme check how i did it

fresh sierra
#

thanks

errant trout
#

ok context last is correct

#

hmmm

#

how about in database, you only super Interaction?

fresh sierra
errant trout
#

and put the super last

#

ah

fresh sierra
#

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
errant trout
#

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?

fresh sierra
#

Yeah I’m a bit lost too

errant trout
#

does it work if you take out translate

fresh sierra
#

Let me try that

#

This is correct right

fresh sierra
#

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

stray cape
#

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

stray cape
#

nope it never had

echo wraith
#

hmm

#

that's weird

#

Idk maybe someone else knows of stuff that might quarantie it

stray cape
#

it's really just a bot that's used for only one server

stray cape
#

just scared that discord will falsely quarantaine my bot again

sage tendon
#

just dont do weird shit lol

stray cape
#

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

fickle frost
#

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

raw beacon
#

i dont think big text is supported in fields

lofty parcel
fickle frost
#

didn't mean to tag on reply i hate discord mobile

lofty parcel
#

Those bots were using it on the description

#

Fields don't support headers, ask discord why

fickle frost
#

Okay thank you

#

Have a great night/day swiftie 🫶

lofty parcel
echo wraith
#

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 ?

errant trout
#

because there's only an event for entry creation

echo wraith
#

Shoot whatever

tidal pecan
lapis dock
#

Yes

tidal pecan
#

Thank you.

fickle frost
#

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

echo wraith
fickle frost
sage tendon
#

thats likely the problem

#

32 bit ints do not fit discord snowflakes

fickle frost
#

how should i store them then to save in a discord compliant way?

#

as simple as this

sage tendon
#

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

fickle frost
sage tendon
#

with the data you get from the db?

fickle frost
#

trying rn

fickle frost
#

sorry it took a long time i was doing various tests

echo wraith
#

Are you sure the bot is in the server?

fickle frost
#

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
sage tendon
#

has to be else they wouldnt have a valid channel

fickle frost
#

the code is a bit messy rn since im testing stuff

#

ERROR is still 404 Not Found (error code: 10008): Unknown Message

sage tendon
#

are you very sure the bot can see the message

fickle frost
#

so it should say forbidden no?

errant trout
#

unknown message means the message ID is wrong for whatever reason

sage tendon
#

they say its right tho, they tested by building a message link with their saved ID

tidal pecan
#

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.

errant trout
#

discord disagrees GuraShrug

sage tendon
#

message cache is limited to 1000 so fetching messages is relatively common

#

guilds and their channels are cached limitlessly afaik

errant trout
#

i mean you can raise it, but yeah

sage tendon
#

and you dont need any special intents

#

just default

tidal pecan
#

Did you try removing the try/except to identify which codeline is actually raising the error?

fickle frost
#

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

tidal pecan
#

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.

sage tendon
#

they did say the message link they build from their saved DB data works tho

fickle frost
sage tendon
#

what about fetching like a very new message in the channel

#

like one you send rn

tidal pecan
sage tendon
#

i dont see what the issue is

#

the channel is clearly in cache for them

fickle frost
#

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
tidal pecan
#

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.

fickle frost
#

sure

tidal pecan
#

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?

fickle frost
#

yes

#

they are identical

sage tendon
#

so hardcoding the IDs of the message you want works, or no?

tidal pecan
#

Did you ever post the code behind that getGuildInfos func?

echo wraith
fickle frost
#

hEY!!!!

#

I've managed to isolate the issue, the problem is in the message ID

sage tendon
#

i thought that was clear lol

fickle frost
#

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

round heart
#

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?

tidal pecan
lofty parcel
#

Select options use emojis

tidal pecan
#

You did verify for me that the copy/pasted ID value was identical to the database-stored value, in infos, yah?

lofty parcel
#

Components can use any emoji

fickle frost
#
  updateSession(ctx.guild.id, ctx.channel.id, message.id)

Am I storing the right message ID?

round heart
lofty parcel
#

ctx.respond returns an Interaction

sage tendon
#

b r u h

#

but didnt you say building the message link with the data from the database worked?

tidal pecan
sage tendon
fickle frost
lofty parcel
#

Are you deferring the interaction

tidal pecan
lofty parcel
#

Yeah they're storing the interaction id lol

round heart
fickle frost
sage tendon
sage tendon
fickle frost
lofty parcel
sage tendon
#

think so

fickle frost
#

Both console and text message

lofty parcel
#

And the values match?..

fickle frost
#

new and now of the subsequent message match

#

so it works like id like to

fickle frost
sage tendon
#

didnt you just say the message IDs are correct

lofty parcel
#

You're storing the interaction ID, yes

sage tendon
#

im p sure you said earlier you compared what you saved to the actual message ID..

fickle frost
lofty parcel
#

You get a "valid" jump url

#

If you click it, nothing happens

sage tendon
#

bruh i figured youd actually click it lmfao

fickle frost
fickle frost
#

even tried generating from different channels to channels i sent the message before

fickle frost
#

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

sage tendon
#

bruh moment

#

thats why i write codeblocks that you cant copy easily.. and yet.. they still get copy..

fickle frost
#

i'll take a break from coding today, thanks everyone for the help im just doing random stuff at this point tfuPride

#

gonna go for a beer now i think

round heart
#

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.

fickle frost
sage tendon
#

no i mean the not awaiting ctx.respond
thought that reaction meant you didnt lol
and i didnt type the await

#

my head hurts

round heart
#

await head_better()

tidal pecan
round heart
#

.... await better_head()

fickle frost
# sage tendon my head hurts

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

fickle frost
#

and the link workd because it brought to the interaction

sage tendon
#

plus its stored as int in their db

errant trout
#

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

tidal pecan
#

So does a message ID factually change whenever the message is edited?

sage tendon
#

no

tidal pecan
sage tendon
#

man idk im lost in the sauce

errant trout
tidal pecan
errant trout
#

what

#

there's no relation

sage tendon
#

lmfaooooooo

#

this shit is too funny

tidal pecan
errant trout
#

what is your point

tidal pecan
#

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.

errant trout
#

????????

#

i replied to a question

sage tendon
#

guys sssh, OP stopped trying anyway

tidal pecan
# errant trout i replied to a question

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?

errant trout
#

dawg you're looking into it too much

sage tendon
#

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

tidal pecan
#

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.

fickle frost
stray cape
#

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?

sage tendon
#

refreshed how

stray cape
#

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

sage tendon
#

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

stray cape
#

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?

sage tendon
#

no clue, i never do stuff like that

stray cape
#

alright thank you!

tardy linden
#

just updated my python version and it cant find the discord module

little cobalt
tardy linden
#

i did the uninstalls and reinstalls but it aint working

little cobalt
#

Can you show the pip list pls

tardy linden
little cobalt
#

Is discordLevelingSystem installing discord.py or other stuff?

#

Also did you add the right interpreter at your code?

tardy linden
#

yeah

echo wraith
#

Worst design choice after using JavaScript on the server

tardy linden
#

yeah i just uninstalled it

little cobalt
echo wraith
hazy turret
#

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

hazy turret
# echo wraith 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.

sage tendon
#

you need to mention them in the message content as well to force the client to resolve it

hazy turret
lofty parcel
#

Correct

#

Blame discord for not making the client resolve mentions in embeds

hazy turret
#

Okay, that's really not a cool solution 😄

fresh sierra
#

is the issue with the duplication of bridge command has been fix on the master ?

echo wraith
#

If that Yes I made a PR that is on master now

fresh sierra
echo wraith
#

I have no idea I don't think it was

echo wraith
fresh sierra
#

If you want, it’s been a while but bridge is completely broken

little cobalt
fresh sierra
#

The slash commands seems to be removed and update

little cobalt
fresh sierra
#

But the prefix part is the issue

#

The client. prefixed_commands doesn’t seems to be reset after unload cog

#

Even if it should

little cobalt
#

And you unload, sync, load and sync again?

fresh sierra
#

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 = {}

round heart
#

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.

lapis dock
#

Seperate

#

Main view
Add questions view
Set settings view
Etc.

buoyant eagle
fresh sierra
buoyant eagle
#

colors

neat hornet
#

Does pycord support app_commands
I am trying from discord import app_commands
and it gives me error

little cobalt
neat hornet
#

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>
neat hornet
little cobalt
#

In py-cord its called slash commands

#

And Not App commands

neat hornet
#

ok thank you

ember ravine
#

How can i disable a button after a click on it and enable it after about 5 seconds?

silk spire
lapis dock
ember ravine
lapis dock
#

👍 then just be aware that the button will only be able to be edited for ~15 minutes

tawny berry
#

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

flat wind
#

Hello !!
Do we have the approximate user install and approximate guild count from library ?

sage tendon
#

guilds i think you can access with bot.guilds

#

user install, not yet at least
maybe in 2.7

flat wind
sage tendon
#

no

flat wind
#

okay

sage tendon
#

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

flat wind
#

maybe it needs more new features / fix before release ?

sage tendon
#

there is no reason to hold it back for more features IMHO
they can just do 2.8 or 2.9 later on

flat wind
#

true

sage tendon
#

they need to release something, especially since 3.13 is getting more common and 2.6 doesnt support it natively

weak sentinel
#

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

sly karmaBOT
# weak sentinel I've followed the instructions on setting up a venv on this site https://guide.p...

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.

weak sentinel
#

oh, so just use an earlier python version?

echo wraith
#

yeah

sage tendon
#

install audioop-lts

#

quicker fix

echo wraith
#

3.9 to 3.12 or install audioop

sage tendon
weak sentinel
#

it doesn't throw me the error anymore, tysm

pulsar ferry
#

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)
sly karmaBOT
# pulsar ferry Hey guys - working on my first public bot, super noob question here... why isnt ...

Application Commands Not Showing Up?

  • Refresh Discord by restarting or pressing Ctrl+R (or Command ⌘ + R)
  • Uninstall libraries that conflict with the discord namespace (e.g. discord.py).
  • Invite your bot with the application.commands scope.
  • Load cogs before bot.run() (e.g. not in on_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.
pulsar ferry
#

i dont think its any of that, i think my code is bad 😅

sage tendon
#

You are missing the self parameter and slash commands do not take interactions.

#

please read the guide.

pulsar ferry
#

yeah i updated it

#

sorry that was wrong code initiialy i pasted

sage tendon
#

are you sure the cog is even loaded

#

and does your cog have a setup function

pulsar ferry
#

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)
sage tendon
pulsar ferry
#

is that the wrong way of loading it?

sage tendon
#

are you sure it loads

#

yes or no

pulsar ferry
#

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)
sage tendon
pulsar ferry
sage tendon
#

oh yea the setup isnt async

echo wraith
#

should not be async

pulsar ferry
#

ohh wow hang on

pulsar ferry
echo wraith
#

yeah ig

slender lantern
echo wraith
#

what

#

oh

sage tendon
#

python doesnt deprecate versions that aggressively

echo wraith
#

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.

slender lantern
#

I’m talking about active development on Python

#

Going into security support in April

sage tendon
#

i dont see why that matters lol

echo wraith
#

yeah

slender lantern
#

It’s just surprising to not actually support the current version of Python

sage tendon
#

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

echo wraith
#

Yeah and tbh no one pushes with the latest version in production ever

slender lantern
#

There’s a difference between “this application is old” and “my current-day library doesn’t support the current version”

slender lantern
echo wraith
#

Ok sure

sage tendon
echo wraith
slender lantern
#

I guess my company doesn’t exist? We were shipping node 22 shortly after release

echo wraith
#

That's dumb honestly but ok

slender lantern
#

“No one” is trivially falsifiable

echo wraith
#

Either Way

sage tendon
#

🤓

#

beyond the scope of this channel.

echo wraith
#

Yep

slender lantern
#

lol, you’re the one who made the claim, but okay

round heart
#

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.

dense latch
#

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

GitHub

Description The propagation period of 1 hour of new or edited slash commands to all servers is too long. It should be lowered or optimized such that changes are available within a minute-scale time...

dense latch
#

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

sage tendon
#

also all bots are apps
what you mean is probably message commands for a user apps

dense latch
#

reloading discord was making no difference until I fixed the mistake I mentioned above

#

"user-scoped" is probably the right term yeah

sage tendon
#

no its just called user app

#

officially

pulsar ferry
#

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?

echo wraith
pulsar ferry
#

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

sage tendon
#

why tho?

pulsar ferry
#

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

sage tendon
#

i mean just tell them in the first response the bot ever gives them ig

#

ah nvm

pulsar ferry
#

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

glossy tide
#

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

sage tendon
#

no

#

you should realize this via message commands

#

@glossy tide

glossy tide
sage tendon
#

yes

glossy tide
#

Ohhh okay

#

But

sage tendon
glossy tide
#

How does it work?

sage tendon
#

its just a regular button lol

glossy tide
#

No the message above is a webhook

#

Not Embed Generator

sage tendon
#

its a bot message so it can have a button attached to it

glossy tide
#

Hmm

lapis dock
#

It might be a webhook that embed generator created ?

glossy tide
#

Yes

sage tendon
#

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

glossy tide
#

Hm okay

pulsar ferry
#

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?

sage tendon
#

show what you mean

fresh sierra
sage tendon
#

cant if its not static

fresh sierra
#

you do can

sage tendon
#

no self if you call it from a class context

pulsar ferry
#

# 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)
fresh sierra
#

you can use the self from the view

sage tendon
#

just make join_game static

pulsar ferry
#

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

fresh sierra
#

you can pass the self.bot into the view

#

(which is something that i always do)

pulsar ferry
#

the above works. i am just trying to see if its most efficient way

fresh sierra
#

and then call it and use the view as self if you only need the bot

pulsar ferry
#
view = RPSGameView(self, game_id=None)  # Pass the cog instance to the view
fresh sierra
#

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

pulsar ferry
#

okay it sounds like my approach above is okay then?

fresh sierra
#

yeah

#

if it works it works

pulsar ferry
#

yeah true i guess thats a little less heavy

pulsar ferry
sage tendon
#

discord.Bot..?

pulsar ferry
#

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)
sage tendon
#

just make them static

pulsar ferry
#

Can’t because those static commands then would not be able to access the self.bot

sage tendon
#

then pass it.

#

as i just said.

pulsar ferry
#

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

sage tendon
#

if you make the method you need static you can just import it because it doesnt need a self parameter anymore

pulsar ferry
#

Hmm I can play around with it some more but from performance standpoint you think it would make any difference?

sage tendon
#

no

#

it just creates spaghetti code

maiden bloom
#

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

errant trout
maiden bloom
#

Any workaround until it goes live aside from switching to master?

errant trout
#

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

maiden bloom
#

Thanks. Any idea when .2 will be released?

echo wraith
maiden bloom
#

Is there a way to remove the test entitlement?

errant trout
dense latch
#

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)?

sage tendon
#

you need to pass the channel you got the message from

#

and not self.bot

dense latch
#

I am in a cog so self.bot is my client

sage tendon
#

i know

dense latch
#

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

sage tendon
#

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

dense latch
#

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

sage tendon
#

no idea

#

its probably only unique per channel

silk spire
#

IDs are unique, but message routes are per channel and message shrug

edgy nest
#

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

sage tendon
#

ID of any messageable* i think, since DMs etc also work

edgy nest
#

dms are channels

sage tendon
edgy nest
#

we call them DMChannel for a reason

sage tendon
#

hm

round heart
sage tendon
#

none

lofty parcel
#

They don't

round heart
#

So channels don’t belong to a guild in the same way messages belong to channels

errant trout
#

guilds are optional yes

#

(notice how most channel/message related endpoints don't require the guild id)

keen relic
#

Why doesn't BridgeCommand generate slash commands for aliases?

#
    name="wallet",
    description=f"Your {BOT_SETTINGS['name']} Wallet address and QR code.",
    aliases=["deposit"]
)```
little cobalt
keen relic
maiden bloom
#

How can I give away free entitlements? I see EntitlementType has a developer_gift attribute

errant trout
#

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

maiden bloom
#

Does a test entitlement have any differences from a real one?

silk spire
#

It's a type of entitlement meant for testing, so no, it shouldn't

fresh sierra
#

But it will not be free entitlement

#

Like the user will not get any value from that?

edgy nest
maiden bloom
#

That’s perfect lol. I can delete so much code now

fresh sierra
#

Or it’s only inside the code ?

edgy nest
#

the entitlement will show when recieved from discord, but because there is no subscription the user won't get roles or anything automatically

fresh sierra
#

Thanks

maiden bloom
edgy nest
#

no, test entitlements will not have a subscription, since they're permanent until removed

#

and have no billing flow

echo wraith
#

Did discord ever suggest how to name sure a user doesn't subscribe through discord after subscribing e.g. form a bots website?

errant trout
#

(and realistically all it entails is checking the user ID)

pulsar ferry
#

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
errant trout
#

(probably, idk the full details of your issue)

pulsar ferry
#

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)
pulsar ferry
errant trout
#

i'd honestly recommend giving every game a unique game_id

#

then you can use that

pulsar ferry
#

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 😕

errant trout
#

well

autumn gust
#

how do you make a command take multiple options, and when no option is given it defaults to all of the options?

errant trout
#

in your implementation this is technically fine so sure why not

pulsar ferry
autumn gust
#

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

pulsar ferry
#

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

errant trout
pulsar ferry
errant trout
#

yeah but like

#

do you want to delete the message, or remove the view

errant trout
pulsar ferry
#

hmm im not sure what it would look like if we remove the view and keep the message it would just be blank?

errant trout
#

so you'd just make several bool options

errant trout
pulsar ferry
autumn gust
errant trout
#

so do you want to get rid of JUST the view, or also the embed

errant trout
pulsar ferry
errant trout
#

then just interaction.edit with view=None

#

and your updated embed if you wish