#Basic Pycord Help

1 messages · Page 63 of 1

sage tendon
#

i'm not sure how much this is a python or pycord fault tho
ctypes seems to be a builtin so.. i guess its a python bug?

errant trout
#

yes

#

we don't officially support 3.13 yet

sage tendon
#

Yea i know, but it seemed odd for .1 to break when .0 worked

#

and i just wanted to throw it in because maybe whoever handles 3.13-proofing rn isnt aware of this

errant trout
floral ice
#

what is the fastest way for me to get anyones username?
fetch user?

#

i need to get like 10 usernames in one command

jolly tundra
#

Quick question.

discord.on_application_command_error(context, exception) triggers for both prefix commands and slash commands?

sage tendon
echo wraith
echo wraith
sage tendon
#

ohwell

jolly tundra
#

So on_command_error just for commands

echo wraith
#

for views you have the view's own handler

jolly tundra
#

And the other for slash, interactions, etc

floral ice
sage tendon
#

yea

jolly tundra
#

ok

sage tendon
floral ice
lofty parcel
#

You should try to get the user from the cache first.

floral ice
#

oh that would be super nice, how?

#

is that get_user()?

sage tendon
#

the docs are great, use em

floral ice
#

"Returns a user with the given ID."

#

this is all

sage tendon
#

yea, and that's exactly what you want lol

lofty parcel
#

What else do you expect lol

#

It ain't gonna do a magic trick

floral ice
#

it just gets the user?

#

what about cache?

sage tendon
sage tendon
lofty parcel
#

get_ methods get stuff from cache

floral ice
#

what if it is not in cache?

sage tendon
#

fetch_

#

but you should avoid that wherever possible

#

And if the user isn't in cache for some reason (e.g. left all mutual servers) get will return none

lofty parcel
sage tendon
#

typically every user who shares a server with your bot should be in cache unless your bot has thousands of users

floral ice
sage tendon
#

read.

floral ice
#

thx

sage tendon
#

also, reading the source code is also possible when the docs don't mention something you find important

lapis dock
sly karmaBOT
#

Any function that starts with get_ in Py-cord is retrieving the related object from your bots cache. If the object is not in the bots cache the get_ method will return None. Because of this behavior you should check if the get_x method is None and if it is use the fetch_x method.

Why Is Using fetch_ Without Using get_ First Bad?
The fetch_ method makes a call to the discord API. This API call is unneeded if you already have the information. It will also make your command take longer because it will have to send and than wait for a response from the discord API. It will also contribute to the discord APIs global rate limit of 50 requests per second.

What Is Cache?
The cache is a temporary storage inside your bot. It holds many objects from members to messages. When you restart your bot the cache will be empty. When the cache is full it will delete older objects to make space for the new objects.

round heart
#

AttributeError: 'ForumChannel' object has no attribute 'fetch_message'

What? Since when

sage tendon
#

you need a thread

#

i forgot, can bots send 2000 or 4000 characters

maiden bloom
#

Is it possible to set an interaction deferral as ephemeral while not having the first follow up response be ephemeral? I'd like to have the possibility of using ephemeral responses after the deferral but don't want it for every message. When I enable it for the deferral, the first follow up message is ephemeral even if I explicitly set it to not be.

await ctx.interaction.response.defer(ephemeral=True)
await ctx.send_followup(embed=self.string_to_embed(embed_msg_str), ephemeral=False)

This code results in the follow up message being ephemeral^

#

and if I don't use ephemeral in the deferral there's no possibility of using it in the follow up messages

maiden bloom
#

So the first follow up will have to be ephemeral?

torn barn
#

Yes

sage tendon
#

also, just use ctx.defer and ctx.respond

#

shortcuts & make your code less error prone

maiden bloom
#

I thought you could only respond once and only when an interaction hasn't been deferred?

sage tendon
#

respond will handle all cases

maiden bloom
#

Ah, must be new then. Thanks

sage tendon
#

meh, i know it since forever

lofty parcel
#

It's kinda new

#

.respond didn't behave like that in the past

shell radish
upper hearth
#

whats the thing called where its autocomplete but the names shown in the list are different from the ones that are actually sent in the command

sage tendon
#

autocomplete

#

you just pass OptionChoices instead of plain strings

echo wraith
#

And use value

upper hearth
#

oh thats so much easier than i thought tysm

verbal torrent
#

does anyone know, how i can get the url of the invite link a user used?

sage tendon
#

you can't directly

#

You have to track all existing invites, and just check which one has more uses after a user joins

verbal torrent
#

ok. thx.

shadow bear
#

Is there a way to get Discord to defer automod to a bot? I'm setting up a community server for my university and I'm interested in being able to filter some content, and it'd be ideal to be able to prevent it being sent in the first place (like the profanity or mention filters do), but I can't remember if this is actually a thing or if I just made it up one day and tricked myself into believing it

lofty parcel
#

Your bot can create automod rules

#

But you can't prevent the user from sending the message by yourself

shadow bear
#

like can I only use these, even with a bot?

sage tendon
#

You can make custom rules using a bot

#

will also give your bot a badge

#

But honestly if it's a small server, and only one server in general, it's easier to just do it yourself in discord

lofty parcel
sage tendon
#

oh yea true

lapis dock
#

I don't understand why bots would set up automod rules. Is it just so less technical people don't have to do it themselves or is there something extra bots can do?

lofty parcel
#

Ig some bots offer an easier command to setup a rule

#

Uhh Carl bot switched to automod rules i think?

#

Or some big bot like that

sage tendon
#

its just so bots that already have block rules anyway can do it right inside discord & prevent messages from being sent in the first place

shadow bear
#

but its fine, deleting the message will be fast enough

#

just opens a different can of worms

sage tendon
#

like what functionality

lapis dock
#

The main 2 things that I still see on servers that use automod are spam across channels and advertisements. It seems to be able to cover everything else pretty well

sage tendon
#

i mostly use it to quickly mute trolls spamming 1000000 variations of slurs, all handled via regex
insta 1d mute, so they're taken care of even with mods offline

errant trout
#

basically everything you're asking for is already possible in guild settings, im not sure what else you'd want

shadow bear
#

mainly

#

It's fine though, I can just do it via the bot and delete messages

#

it'd just be easier to win over this lecturer if we could prevent the abusive messages being sent in the first place, but as the saying goes, better late than never :^)

sage tendon
#

i dont see what a bot can do here that automod cant

shadow bear
#

Well regex doesn't work, it doesn't know what context is. An algorithmic approach would

sage tendon
#

so you want AI automod, oh boy

#

trust me, i've tried, it's really not a 100% approach

#

Just have mods like every other server and block the most common shit with automod

shadow bear
#

We can't just throw mods at the server for T&S, and we're all based in the same country, so if someone decides to spam when the committee are asleep, there's nothing we can do really

#

if I'm honest it's excessive, but I've been asked to implement it shrug

sage tendon
#

well good luck, all i'll say is that AI automod is hard to get right

#

It really sounds like whoever tasked you with this isn't the brightest ngl

shadow bear
#

I've got to bridge the gap between 50yo+ lecturers concerns and the ideas of 18 year olds

sage tendon
#

No, conceptually
No server ever has AI automod, they have mods and automod

shadow bear
#

Oh yeah

sage tendon
#

And, i tried
No matter which model, most are defeated relatively easily if you want to

shadow bear
#

oh well

#

can't win them all eh

#

I'll just lie to the lecturer and say that the automod does what he asked :^)

#

and hope it never needs to ACTUALLY do what he asked

round heart
#

For View timeouts, is that based on the message send, or the last interaction?
Docs do say last interaction, but I don't see anything in pycord source that updates it

#

mm, I see it. When a callback is dispatched, _timeout_expiry is advanced.

lofty parcel
#

Indeed they're based on the last interaction

loud kayak
#

this error occured after a few hours: Event loop stopped before Future completed.

future: <Task finished name='Task-4' coro=<Client.run.<locals>.runner() done, defined at /home/container/.local/lib/python3.9/site-packages/discord/client.py:790> exception=RuntimeError('Concurrent call to receive() is not allowed')>
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 792, in runner
    await self.start(*args, **kwargs)
  File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 756, in start
    await self.connect(reconnect=reconnect)
  File "/home/container/.local/lib/python3.9/site-packages/discord/shard.py", line 477, in connect
    raise item.error
  File "/home/container/.local/lib/python3.9/site-packages/discord/shard.py", line 180, in worker
    await self.ws.poll_event()
  File "/home/container/.local/lib/python3.9/site-packages/discord/gateway.py", line 612, in poll_event
    msg = await self.socket.receive(timeout=self._max_heartbeat_timeout)
  File "/home/container/.local/lib/python3.9/site-packages/aiohttp/client_ws.py", line 315, in receive
    raise RuntimeError("Concurrent call to receive() is not allowed")
RuntimeError: Concurrent call to receive() is not allowed```
livid nymph
#

I'm trying to have an upload function where I can upload multiple files. Currently I have async def upload(self, ctx, attachments: list): as the function however it cannot take a list as a parameter. I was able to get one to upload when changing it to upload(self, ctx, attachments: discord.Attachment)

glad garnet
lofty parcel
#

You can only receive one per option.

fresh sierra
jolly tundra
#

Is there a way to get the user install counter with pycord?

errant trout
#

but 2.7 isn't out yet; if you're using a 2.6 release or lower you can instead run await bot.http.application_info() directly and parse the dict for approximate_user_install_count

jolly tundra
#

Ok ty

loud kayak
#

The bot is find without shards but I can’t do that anymore since it’s in more than 2.5k servers where it requires shards.

#

This is annoying as fuck

#

This bug

#

Goes offline every hour or so

#

Can someone please fix this, I’m sure people in my situation just switched to discord.py since it’s a breaking bug

torn barn
#

I have tried to reproduce it but I don’t seem to be able to

#

Try reinstalling aiohttp and py-cord

fresh sierra
nova epoch
#

Is there a set character limit for discord.Embed.description or is it to do with screen size?

sage tendon
#

read the docs

nova epoch
#

I always read the Docs and do a couple Google searches before coming here, am I blind?

#

I am indeed blind. Thank you :D

fresh sierra
#

does the shard keep an info about since when it was connected ?

distant owl
#

am probably dum but how can i send voice_messages as a bot (user installable app)

echo wraith
lapis dock
distant owl
sage tendon
#

Because it's possible

#

it's just a bit hacky and weird

distant owl
#

Ye but can't figure out how ahah am not smart enough

sage tendon
#

and whatever other bot you use might use another library, or pycords master branch, or they did it themselves

distant owl
#

The other bit runs on a slightly modified discord.js

sage tendon
#

I don't get why people want voice messages so bad tho, instead of mp3s

distant owl
#

Am now trying to figure out what it does different

distant owl
lofty parcel
#

You don't get a player on mobile if it's a mp3 file

sage tendon
#

oh yea
complete idiocy by discord

echo wraith
#

mp3 is deprecated

sage tendon
#

no it isnt

#

mp3 is probably the dominating audio format for sending sound files if not in the form of proprietary stuff like voice messages

lofty parcel
#

I think wav is now used

sage tendon
#

proprietary tho

echo wraith
sage tendon
#

who said its deprecated?

echo wraith
#
Fraunhofer Institute for Integrated Circuits IIS
mp3

mp3 encodes and stores music. An mp3 file takes up just 10 percent of the storage space of the original file, meaning music can be quickly transferred over the Internet and stored on mp3 players. As a result, music fans’ entire collections fit onto a device no bigger than a matchbox.

#

It's not supported anymore

sage tendon
#

the licensing terminated

#

its still widespread

daring valve
#

There are always more superior file formats, which are just not used cuz it's new
Like webp vs jpeg

distant owl
#

I somehow use ogg opus for most audio files

loud kayak
rotund harness
#

Anyone knows the limits for message commands (A UI-based command that shows up when you right click or tap on a message), i know its 5 per bot, however is there a global limit for this, lets say if 3 bot has 5, i havent exactly found this in the documentation

rotund harness
errant trout
#

i don't think it's specific to commands, but servers are limited to 50 integrations

#

the developer should only worry about their own bot's command limit

#

(you just get a stupidly long command list)

fallen torrent
#

anyone have a repo/link to a repo that has a public user application, i want a user app to look at for an example

rugged lodgeBOT
#

Here's the slash users example.

errant trout
#

it's just a matter of setting the install and integration types

fallen torrent
errant trout
# fallen torrent so how do i make it so commands can only be used by users that installed the app...

the example above includes some comments on the usage ```py
@bot.slash_command(
# Can only be used in private messages
contexts={discord.InteractionContextType.private_channel},
# Can only be used if the bot is installed to your user account,
# if left blank it can only be used when added to guilds
integration_types={discord.IntegrationType.user_install},
)
...

@bot.slash_command(
# This command can be used by guild members, but also by users anywhere if they install it
integration_types={
discord.IntegrationType.guild_install,
discord.IntegrationType.user_install,
},
)

fallen torrent
#

okay so in theory if i remove the guild_install integration_type, it wont work in guilds right?

errant trout
#

do you not want users to use it in guilds at all, only DMs?

#

setting user_install means users can only add it to their account, not adding a bot to a guild, but they can still use it anywhere

fallen torrent
#

ah no i mean as in, i dont want ppl to utilize it as an actual bot (like they add it to a server as an integration), just want it to only be on their acc

#

okay perfect

#

appreciate the help

errant trout
#

yep GuraThumbsUp

fallen torrent
errant trout
#

ehhh

#

apart from the priveliged intents, intents are related to the events the app recieves

#

if you don't plan on your bot being anywhere, then for the most part they have no effect

#

just note that user apps are relatively limited; they will ONLY work with specific data recieved in the interaction

#

if you're used to being able to access guild attributes and methods with regular bots, you have to throw all that out the window

fallen torrent
#

but does the user app have access to say all the guilds the user is in, and can it access messages inside a guild the user is in?

errant trout
#

nope

#

because the user app isn't a bot

fallen torrent
#

ooh that kinda sucks

errant trout
#

it's not in the guild, unless someone already installed it to that specific guild

fallen torrent
#

makes sense

#

is the app still able to dm other users (using maybe bot.fetch_user or something) just fine

errant trout
#

not unless they share mutual servers

#

(being the bot and the user)

fallen torrent
#

gotcha

errant trout
#

basically you have to treat user app commands as if the bot isn't in the server at all

fallen torrent
#

and user apps can still do all the view stuff right, has the same core functionality as a bot

errant trout
#

if it's through interaction responses then yeah

fallen torrent
#

perfect thank you

errant trout
#

(note: maximum 5 followup responses per interaction)

fallen torrent
#

whattt is that a user app only thing

#

swear ive never seen that with my regular bots

errant trout
#

yes

fallen torrent
#

uhm is user apps on a different pycord verson than 2.5?

errant trout
#

why are you on 2.5 www

#

added in 2.6

fallen torrent
#

oh ughhh

#

what a pain

errant trout
#

is there an issue with 2.6?

fallen torrent
#

no i just didnt even know there was a 2.6 😭

errant trout
#

well we're on 2.6.1

fallen torrent
#

WHAT

#

jesus.

errant trout
#

#library-updates

naive ferry
#

Anyone know what happened here?

sage tendon
#

Can be a response you sent too late without a defer

naive ferry
sage tendon
#

You have 3 seconds to respond to a slash command by default
That error usually means you fail to respond in that time window

naive ferry
#

Oh

#

Is there a way to give me extra time?

sage tendon
#

i mean first of all make sure every code path leads to a response in your command
and if you really have heavy code that needs 3 seconds, you can use await ctx.defer() at the start of the command

naive ferry
#

Perfect! That worked :33

lapis dock
#

defer is often used when you have to make a API or database call. Also any image/file manipulations stuff. Those are all considered slow operations.

frail ocean
#

Can some1 tell me whats wong?
aiohttp.client_exceptions.ClientPayloadError: Response payload is not completed

sage tendon
#

what are you doing that causes that

fallen torrent
#
@ltc.command(name='me', description='Allows you to display your LTC address for others to send to.', integration_types={discord.IntegrationType.user_install})
    async def me(self, ctx: discord.ApplicationContext):
        await ctx.respond("hai")

am i doing something wrong? the applications authed to my account but this command doesnt show and the cog gets loaded fine too

fallen torrent
#

anyone?

frail ocean
errant trout
#

doesn't work for subcommands

round heart
#

🤔 Are there ways to get arguments into autocomplete= references? functools.partial or lambda or something?

sage tendon
#

like how

round heart
#

As in.. Say you have an autocomplete=search_records, but maybe there's a flag to search only records that are 'active' (or some other arbitrary flag)

autocomplete=functools.partial(search_records, active=True)

sage tendon
#

hm no idea
I'd just make a second function for that and call the first function while passing the appropriate parameter

round heart
#

You'd have to make two separate autocomplete methods. That's what I'm trying to avoid is all

sage tendon
#

not really

#

the other method would have 1 line

#

but there is probably some smart way to do this but idk it, id do it like i said

round heart
# sage tendon not really

...what? You'd have to have search_records and search_active_records. That's two methods. Sure they could call different parameters of a centralized method they both reference, but that doesn't negate what I said.

sage tendon
#

actually

#

hm

#

ChatGPT says
autocomplete = lambda: funcname(flag=True)

#

which honestly does make sense but i never really use lambda in python

round heart
#

The problem with that specifically is you need the autocompletecontext, which we don't have yet

sage tendon
#

ah yea

round heart
#

Anyway, functools.partial() appears to suffer from the same issue (which I actually don't fully understand, the whole idea is to bind the parameters but still be able to inject the rest of the method args)

sage tendon
#

example = lambda **kwargs: funcname(flag=True, **kwargs)

#

either kwarg or arg, not sure what autocomplecontext is passed like

#

but that looks like it should work

lofty parcel
#

It contains the previously selected options

sage tendon
#

what they mean is they basically wanna prefill that flag per function

lofty parcel
#

ah

round heart
lofty parcel
#

So it's something you set in your code?

round heart
#

Right. Say I have a big dict/list/whatever of animals
But a particular command may be specific to dogs, so I only want to provide autocomplete results for items that are in my list of dogs.

lofty parcel
#

ohhh

round heart
#

Granted, I can just make an autocomplete method called autocomplete_dogs that filters them, but it would be helpful if I could have a single autocomplete method that would allow for the autocomplete= definition to set some context.

sage tendon
round heart
sage tendon
#

show the error and your code

#

if its unresolved reference did you import it lol

round heart
#

It's a local function, homie

sage tendon
#

s h o w

round heart
#

It just doesn't like it being in a lambda

round heart
# sage tendon s h o w

Open your own IDE, find a method with an autocomplete, and put your autocomplete method in a lambda. unresolved reference is pretty self-explanatory.

sage tendon
#

or just make a screenshot so there are no misunderstandings

round heart
sage tendon
#

weird

round heart
#

I've never seen lambda *args anyway (but it is A Thing)

sage tendon
#

i mean its just how you catch a list of all args, works in a lambda too ig

round heart
#

So yeah, anyway; I cannot bare-reference my method, and of course self. doesn't work either.

sage tendon
#

but it works without the lambda:?

round heart
#

Yes, autocomplete=clm_vault_autocomplete is fine, as well as every autocomplete within a class. Which I admittedly always thought was weird.

edgy nest
#

that is mildly odd

#

is that just your ide

round heart
#

Which part

edgy nest
#

does the code run

round heart
#
vault_id: Option(str, "Target Vault", autocomplete=clm_active_autocomplete, required=True),

runs just fine and has for year(s) at this point

edgy nest
#

¯_(ツ)_/¯

#

lambda should be just fine for your use

frail ocean
#

Can some1 tell me whats wong?
aiohttp.client_exceptions.ClientPayloadError: Response payload is not completed

sage tendon
#

i'm wondering if it has to do with the lambda being inside of the function header as opposed to a decorator (or anywhere else)

sage tendon
round heart
frail ocean
round heart
edgy nest
#

lambda is just an inline function

sage tendon
frail ocean
#
Traceback (most recent call last):

  File "/usr/local/lib/python3.10/site-packages/discord/client.py", line 400, in _run_event

    await coro(*args, **kwargs)

  File "/data/cogs/flagquiz.py", line 250, in on_message

    country = random.choice(await request.json())

  File "/usr/local/lib/python3.10/site-packages/aiohttp/client_reqrep.py", line 1161, in json

    await self.read()

  File "/usr/local/lib/python3.10/site-packages/aiohttp/client_reqrep.py", line 1101, in read

    self._body = await self.content.read()

  File "/usr/local/lib/python3.10/site-packages/aiohttp/streams.py", line 373, in read

    block = await self.readany()

  File "/usr/local/lib/python3.10/site-packages/aiohttp/streams.py", line 395, in readany

    await self._wait("readany")

  File "/usr/local/lib/python3.10/site-packages/aiohttp/streams.py", line 302, in _wait

    await waiter

aiohttp.client_exceptions.ClientPayloadError: Response payload is not completed```
sage tendon
#

so i guess the data you got from the API isn't "completed" whatever that means

edgy nest
#

wheres the line you made the request on

round heart
sage tendon
lofty parcel
#

It probably takes a while for the api to fully respond?

#

Does that even make sense

sage tendon
#

There are cases where an API returns data across multiple responses

lofty parcel
#

Idk

frail ocean
#

I can show you how i do the request

sage tendon
sage tendon
#

and print the http code please

frail ocean
#
                                    connector = aiohttp.TCPConnector(verify_ssl=False)
                                    async with aiohttp.ClientSession(connector=connector) as client_session:
                                        async with client_session.get(url=flag_api) as request:
                                            country = random.choice(await request.json())
                                    country_name = country['name']['common']
                                    country_name_de = country['translations']['deu']['common']
                                    country_flag_url = country['flags']['png']
                                    difficulty = country['idd']['root']```
sage tendon
#

print response.status

frail ocean
#

I can try on pc. Give me a moment

sage tendon
#

also, why the whole connector= bit?

round heart
#

To turn SSL verification off

frail ocean
frail ocean
sage tendon
#

i mean you put it there

#

and it does say verify_ssl=False

#

so i assumed you know why you put that there

round heart
#

.. . that's literally what you're doing in the first line. lol. You create your own Connector with the verify flag off, then load that into ClientSession

frail ocean
#

Is that a problem?

round heart
#

Eh. It does slightly speed up operation, and you're not really doing anything here where a domain hijack would cause issues. But it's not a good habit to get into

#

Verifying SSL is a pretty important security concern.

frail ocean
#

Is it wrong? Afaik it didnt work without that

sage tendon
#

so thats ChatGPT code then?

frail ocean
#

I asked bc ssl didnt work

round heart
#

"wrong" is subjective. I don't think it's the source of your issue, though.

frail ocean
#

Im not sure if i asked here or chatgpt

lofty parcel
#

Google says its something timing out

#

What's the flags api you're using

frail ocean
round heart
# edgy nest lambda is just an inline function

Anyway, putting it in the lambda does indeed seem to change the context. It can no longer find my method within the class ('name <method> is not defined), but if I make a method outside of the class, it captures that reference just fine. But that's dirty.

lofty parcel
sage tendon
sage tendon
#

ah nvm

#

that might be why

#

API returns garbage

lofty parcel
#

Are you making the request everytime?

#

Why not just make one and store the result

#

-# not related to the issue but

frail ocean
#

On pc it works

sage tendon
#

too much what

frail ocean
#

Data

sage tendon
#

its like 2mb max

round heart
# edgy nest lambda is just an inline function

Interesting

autocomplete=lambda self, *args: self.clm_vault_autocomplete(*args, active=True) actually works

However, it cannot be a coroutine (which makes it not a longterm solution), otherwise it says it wasn't awaited, which I guess is because the lambda fails the coro test in utils.basic_autocomplete

frail ocean
#

On Pc it works

round heart
round heart
sage tendon
#

the JSON it returns is malformed

sage tendon
frail ocean
lofty parcel
sage tendon
frail ocean
#

It does

round heart
# frail ocean And how?
self.flags = []

if not self.flags:
  ...
  async with client_session.get(url=flag_api as request:
    self.flags = request.json()

random.choice(self.flags)
round heart
sage tendon
frail ocean
sage tendon
#

The JSON is not correct.

#

my browser literally tells me that when i open the website

frail ocean
#

What?

lofty parcel
#

it doesnt for me

#

but postman doesnt get a response at all

frail ocean
#

my api req worked

round heart
#

Chrome is getting a 200, but no response data.

frail ocean
#

Try firefox

fallen torrent
#

still doesnt show my commands

round heart
#

Anyway, you should also have some error handling for whether the API doesn't return valid json.

sage tendon
frail ocean
round heart
#

Yeah, that's interesting. How the hell did it push 167K of ... nothing (I don't think it did, it's just the content-length header)

sage tendon
#

yea then its randomly wrong

round heart
lofty parcel
round heart
#

So I'm willing to bet the aiohttp erorr you're getting is related to that.

round heart
#

Then wget will try to access and download the content at the URL

lofty parcel
#

or a curl

frail ocean
#

I dont want to download xD

sage tendon
sage tendon
round heart
sage tendon
#

download json once, always have it accessible within fractions of a second

#

vs downloading it for seemingly minutes every time

#

seems like an easy issue for me

frail ocean
#

If i run that i have the json?

sage tendon
#

only one way to find out

lofty parcel
round heart
# sage tendon that might be why

So, the server is closing the connection after 65326 bytes, which is why you have the 'unterminated string'. I noticed after my wget that I actually did have some data, it's just truncated.

frail ocean
round heart
#

Yes. Look up how to open files.

#

Now you won't need to make HTTP calls at all

frail ocean
#

Thankss ❤️

lofty parcel
#

surprised you dont know how to open json files

sage tendon
frail ocean
#

I do

sage tendon
#

just as i predicted

round heart
lofty parcel
#

meh

frail ocean
#

ChatGPT my friend and helper 😄

lofty parcel
#

bitch what chat gpt

#

we helped you

frail ocean
#

To rewrite the json get

lofty parcel
#

oh

frail ocean
#

Ye

#

Thanks ❤️

sage tendon
#

lol

round heart
#

lmao pin this.

edgy nest
#

pin of shame

round heart
#

@echo wraith the speed demon

echo wraith
echo wraith
round heart
echo wraith
#

It's really a matter of preference

bleak abyss
#

I'm using a "dev" version of my bot so the real bot is not offline while doing testing, but i am now using app emojis but the issue is that my dev app don't have all the emojis i have on my real app. Is there anyway to fix that without uploading all the emojis in the two apps ?

round heart
#

It’s stored on the app account (you can see this by going to your Discord applications page). If they’re two separate apps, then that’s two separate emoji pools

lapis dock
#

You can use the API to upload them I believe. So you could copy them all over. How to do this and if it is implemented in Pycord, I don't know

violet star
#

not sure if it's an issyou or issme but bridge commands wont work properly when i make them in a cog, prefix works but not slash. The bot can make commands because i have smth in main.py which works properly

violet star
sage tendon
#

its not really that they have nitro they just have many of the perks of nitro

frail ocean
#

Can I ask here smth about py?`not pycord

sage tendon
frail ocean
sage tendon
#

what is your question

#

yea im not gonna condone cheats in any way shape or form

frail ocean
#

I just want to try haha

sage tendon
#

there is no gain

#

either you get banned or you get a virus, or it doesnt work at all

frail ocean
#

kk

#

ok

violet star
sage tendon
#

are you loading your cogs in on_ready?

#

if yes, do it before that

violet star
# sage tendon are you loading your cogs in on_ready?
  async def on_ready(self):
        print(f'Logged in as {self.user}')
        for cog in os.listdir("cogs"):
            if cog.endswith(".py"):
                try:
                    if cog == "cogs.commondata.py":
                        continue
                    self.load_extension(f"cogs.{cog[:-3]}")
                    print(f"Loaded cog: {cog[:-3]}")
                except Exception as e:
                    print(f"Failed to load cog {cog}: {e}")
                    raise e
        print("All cogs loaded!")```
violet star
sage tendon
#

why does everyone load cogs in that same convoluted-ass way

#

i dont get it

violet star
#

what would be optimal

sage tendon
#

well you cant use the way i use i think because you have a non-cog file in your cogs folder

#

but

#

this is what i do

#

but you could even pass recursive=True to the top one, that way it also loads cogs in any subfolders

violet star
#

aight

sage tendon
#

not sure if it ignores non-cog files, but in any way its way simpler than what you, and seemingly most others, do

#

i think its in the guide as well and IMO its just overcomplicated and prone to errors

#

But yea slash commands need to be registered before the bot starts to be automatically synced by pycord thus you need to load cogs with any slash commands before starting the bot

violet star
#

got it

#

works thank you very much :D

#

Also how do i make the help command also bridge, and also remove these duplicates from the help menu

sage tendon
#

no clue, the help command is kinda weird ngl
never had it work right

#

i just make my own, its really just an embed after all

errant trout
#

so it's basically just legacy practice that people still try to use

sage tendon
#

I wish the guide would be updated in many regards

#

and would put bridge and prefix under a "legacy" section

errant trout
sage tendon
#

i think thats just the default help command built into the library

errant trout
#

no we only have a prefix one

#

definitely doesn't look like that

edgy nest
#

it can be overriden to look like that

#

while still using the internal logic

errant trout
#

hmmm i guess, but i wanted to check if they did their own logic anyway

violet star
#

discord froze up while uploading 💀

errant trout
#

rip

round heart
violet star
errant trout
#

ahhh i see

sage tendon
#

i mean the duplicates are because you take all commands and bridge commands really are just two commands in a trench coat

errant trout
#

filter_commands logic ignores application commands

#

but it was never updated for BridgeCommand

#
            if not isinstance(command, discord.commands.ApplicationCommand)```
sage tendon
#

oh

errant trout
errant trout
#

(also tip: isinstance can take a tuple of types for the second arg)

violet star
#

aight thanks

#

time to not use an actual debugger

errant trout
#

truuuuue

sage tendon
#

debuggers are for wannabes OR complex issues
no in-between

violet star
#
[<discord.ext.bridge.core.BridgeExtCommand object at 0x749c5c205e20>, <discord.commands.BridgeSlashCommand name=player_info>, <discord.ext.bridge.core.BridgeCommand object at 0x749c5c25b2c0>, <discord.ext.bridge.core.BridgeExtCommand object at 0x749c5c206000>, <discord.commands.BridgeSlashCommand name=java_status>, <discord.ext.bridge.core.BridgeCommand object at 0x749c5c25b2f0>, <discord.ext.bridge.core.BridgeExtCommand object at 0x749c5c206270>, <discord.commands.BridgeSlashCommand name=bedrock_status>, <discord.ext.bridge.core.BridgeCommand object at 0x749c5c1d1f70>]
violet star
#

imma just submit a pull request tbh

errant trout
#

yeah fair lol

#

maybe it should just reverse the check to isinstance(command, Command)

violet star
#

xd

errant trout
#

actually nvm that's stupid

#

eh...

violet star
#

now im scared of getting rejected by CI

errant trout
#

it'll tell you what the issue is anyway

violet star
#

CI's so agressive can't even mark stuff as archived

sage tendon
#

lol

violet star
#

got it working

#
prefix_commands = [
            command
            for command in commands
            if not isinstance(command, (discord.commands.ApplicationCommand, bridge.core.BridgeCommand))
        ]```
violet star
#

nvm i cant send a pr because 2656

humble turtle
echo wraith
#

Oh that's me

sage tendon
#

i think they are aware of that PR given they were the ones to bring it up..

echo wraith
violet star
violet star
echo wraith
sage tendon
#

They're saying that other instances using the filter will break i think

echo wraith
#

If it works don't touch it

little cobalt
#

Do I have to use discord.Cog or commands.Cog for a bridge cog?

echo wraith
#

commands.Cog I think

sage tendon
#

id say try it and see lol

#

takes 1m to check

cosmic swift
#

if i use # in a json file for the number of something multiple times how can i use it in a f string without it greying out the rest of the line

#

like if i just do {#} it would grey out the rest or would i have to change # to another symbol

cosmic swift
errant trout
#

or do you mean python dicts

cosmic swift
#

no like its a json file im getting it from and if i try to use the # variable from json in my embed thats written in python

#

it makes it a comment

#

instead of looking at it as a variable

errant trout
#

...can you show an example

cosmic swift
#

yes 1sec

#

async def embed(Name,  pokemonid, ):
  discord.Embed(      
  title = f"Infos about {Name}:"
  ID of {Name}: {#}
  )
errant trout
#

then no

cosmic swift
#

like no as in it doesnt work

errant trout
#

anything after a # in python is plaintext

cosmic swift
#

or wdym exactly

#

ah

#

okay thx 🙏

errant trout
cosmic swift
#

ngl i just wrote it for the example

#

idk if its correct eitherway

#

this is my first time working with embeds and like my third day with pycord shrug

errant trout
#

are you trying to access a json key named # inside an fstring

cosmic swift
#

oh thats what u mean

#

im dum

#

i shouldve used f'...'

errant trout
#

yeah

cosmic swift
#

yea its 5am in my time dont mind it

rugged lodgeBOT
#

Here's the timeout example.

loud kayak
#

is there any event that is triggered when the bot disconnects from discord?

fresh sierra
frail ocean
#

user.display_avatar.url_as(format='jpg')
How does this work with never versions?

little cobalt
sage tendon
lofty parcel
#

Days without Fabio reading the docs: 460

sage tendon
#

yea, sigh

#

its like 3 clicks from User

#

its LITERALLY 3 clicks from User

frail ocean
sage tendon
#

display_avatar is of type asset.

#

docs are clear on that

lofty parcel
#

You don't need it, it is what it's returned

frail ocean
#

i searrched for avatar, as, format

lofty parcel
#

discord.User -> Avatar -> Asset -> with_format method

frail ocean
#

didnt searched user

sage tendon
#

thats on you

frail ocean
#

Ye

lofty parcel
#

You should kinda know by now avatar is an asset type

#

It has been a thing for ages

frail ocean
#

Didnt codet for ages

sage tendon
#

has nothing to do with that

#

i always go to the base class i use if i need anything below it unless i am 100% certain of the type of said thing
or check the type of what you need by hovering over it

#

and i mean your IDE should autosuggest the methods for display_avatar, which arent many

echo wraith
#

Ctrl click

#

I changed my keybinds

sage tendon
#

yea i was referencing something useless nvm

echo wraith
#

Oh ok

#

I changed a buck keys actually now that I think about it

pseudo lichen
#

is it even possible to use cogs with discord.Bot? My first time trying pycord rn, and I thought it would be better to start with discord.Bot and not the "old" command.Bot, but I keep running into issues and I cant find anything about Cogs with discord.Bot on the docs

sage tendon
#

sure you can

#

just dont load them in on_ready (that will make slash commands not show up)

#

@pseudo lichen what's the issue you're having exactly

sage tendon
#

commands.Cog works too

little cobalt
#

that is right

errant trout
#

commands.Cog just has slightly modified functions to support prefix commands, otherwise it's identical to discord.Cog

summer knot
#

How can I prevent the heartbeat from stopping while an AI is processing (with torch and transformers)

lofty parcel
summer knot
#

But ill try that

lofty parcel
#

The hell are you doing in that poor cpu

summer knot
#

Since the server does not have a GPU

fallen torrent
#

and yes field names is a list

pseudo lichen
#

whats the best practice to delete a ctx.respond after x seconds?

#

delete_after only exists for ctx.send, right?

sage tendon
#

p sure respond has it too, try it out

pseudo lichen
#

yeah my bad it does, works now.

#

But just ran into another issue 😅 Trying to create a purge command rn, and I want it to read the permissions of the channel and re apply them to the new creatd channel. But I somehow cant access the overwrites.. I i try to print the ctx.channel.overwrites but I cant get anything

torn barn
#

Just do channel.clone

#

.rtfm Channel.clone

lofty hedge
#

Task was destroyed but it is pending! it appears in my terminal randomly

pulsar ferry
#

Hey guys - is it possible to spin up a web server to run in parallel with pycord?

Trying to do something like this but cant seem to get the discord bot to play nicely

# Function to run FastAPI server
async def run_fastapi():
    config = uvicorn.Config("main:app", host="0.0.0.0", port=3333)
    server = uvicorn.Server(config)
    await server.serve()

# Run the bot in its own event loop in a background task
def run_bot():
    loop = asyncio.get_event_loop()
    loop.create_task(bot.start(SWEEPY_TOKEN))

# Main function to run bot and FastAPI server concurrently
async def main():
    # Run the bot in the background
    run_bot()

    # Run FastAPI server concurrently
    await run_fastapi()

if __name__ == "__main__":
    # Run the event loop and handle both bot and server
    asyncio.run(main())
Task exception was never retrieved
future: <Task finished name='Task-11' coro=<ConnectionState._delay_ready() done, defined at /Users/ethan/Python Projects/SweepsElite/.venv/lib/python3.11/site-packages/discord/state.py:589> exception=ValueError('The future belongs to a different loop than the one specified as the loop argument')>
lofty parcel
pulsar ferry
lofty parcel
#

.rtfm create_task

sly karmaBOT
#

Target not found, try again and make sure to check your spelling.

lofty parcel
pulsar ferry
# lofty parcel The server a task of the bot

hmm does this automatically run it in the background? couldnnt i just do something like

@tasks.loop(count=1)
async def run_fastapi():
    config = uvicorn.Config(app, host="0.0.0.0", port=8000)
    server = uvicorn.Server(config)
    await server.serve()
lofty parcel
#

Well you have to start the task

#

You can see i start the task on the cog's init

pulsar ferry
#

ah yep got it working thanks!

#

one other quick question..

#
        guild = bot.get_guild(GUILD_ID)  # Replace GUILD_ID with your actual server ID
        owner = guild.owner
        embed.set_author(name=owner.name, icon_url=owner.avatar.url)
#

Cant seem to pull owner info - i have the intents set and admin pems

#

is this the right way to pull it?

lofty parcel
pulsar ferry
#

i think the guild

lofty parcel
#

Debug it and tell me what it is

pulsar ferry
#

yep guild returning None

#

also have


intents = discord.Intents.default()
intents.members = True  # Enable member-related intents
intents.guilds = True

# Initialize bot with intents
bot = discord.Bot(intents=intents)
lofty parcel
#

When are you getting that guild?

#

On a command?

pulsar ferry
#

yes on command but being called without ctx from fasatpi endpoint

#
async def add_thread(ctx, casino_name, link: str, description: str, tag: str):
    channel = bot.get_channel(CASINO_CHANNELS[casino_name])
    thread_name = f"{link}"
    existing_thread = await find_existing_thread(channel, thread_name, link)
    if existing_thread:
        if ctx is None:
            return {"message": f"Thread already exists: [Go to Thread]({existing_thread.jump_url})"}
        else:
            return await ctx.respond(f"Thread already exists: [Go to Thread]({existing_thread.jump_url})", ephemeral=True)

    embed = discord.Embed(
        title=f"{link}",
        description=description,
        color=discord.Color.blue(),
    )
    if ctx is None:
        guild = bot.get_guild(GUILD_ID)  # Replace GUILD_ID with your actual server ID
        print(guild)
        owner = guild.owner
        embed.set_author(name=owner.name, icon_url=owner.avatar.url)

    else:
        embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar.url)

    target_tag = discord.utils.get(channel.available_tags, name=tag)
    thread = await channel.create_thread(
        name=thread_name,
        content=description,
        embed=embed,
        applied_tags=[target_tag] if target_tag else [],
    )
    if ctx is None:
        return {"message": f"[{tag.capitalize()} Posted]({thread.jump_url})"}
    else:
        await ctx.respond(f"[{tag.capitalize()} Posted]({thread.jump_url})", ephemeral=True)
#

ahh wait - fetch_guild seems to be getting the guild now... owner still not workign though

lofty parcel
#

get it, if none, then fetch it

#

Fetching it is an api call

#

Do the same for the user

#

.rtfm get_or_fetch

pulsar ferry
#

...so doing this works although doesnt seem optimal

        guild = await bot.fetch_guild(GUILD_ID)  # Replace GUILD_ID with your actual server ID
        owner = await bot.fetch_user(guild.owner_id)
        embed.set_author(name=owner.name, icon_url=owner.avatar.url)
lofty parcel
#

Yeah get or fetch it through the owner_id

#

That's why I'm telling you to get first and then fetch

pulsar ferry
#

ah the get_or_fetch

lofty parcel
#
guild = bot.get_guild
if not guild:
      guild = await bot.fetch_guild

owner = await bot.get_or_fetch_user(guild.owner_id)
pulsar ferry
#

why not just

        guild = await get_or_fetch(bot, "guild", GUILD_ID)
        owner = await get_or_fetch(bot, "user", guild.owner_id)
        embed.set_author(name=owner.name, icon_url=owner.avatar.url)
lofty parcel
#

Whatever you prefer

silk spire
little cobalt
#

getch? Wtf

sage tendon
#

yea, thats just worse straight up

pulsar ferry
#

Does anyone have any tricks for getting around the 25 option limitation in slash commands?

pulsar ferry
#

hmm okay let me look into this thanks

pulsar ferry
#

got it thanks!

pulsar ferry
#

Is there a way to create / delete tags from a forum channel?

lofty parcel
#

.rtfm ForumChannel.edit

sly karmaBOT
lofty parcel
#

You pass available_tags

pulsar ferry
#

im writing a bot for a server that shares giveaway links and the idea was to have 1 channel with a tag for each site the giveaway is from, but there are several dozen... so the idea now is to create a seperate forum channel for each site and then have a giveaway / freebie / promo type tag but its going to be a lot of channels :/

sage tendon
#

Just make a thread for each site

pulsar ferry
sage tendon
#

why do you need tags?

#

Just have one thread for each giveaway site, and then post the giveaway in the correct thread

pulsar ferry
#

when you say thread, youre saying 1 forum channel, and then within 1 different post for each site?

sage tendon
#

Forumchannel

  • Giveaway site 1
  • Giveaway site 2
    etc
#

with each site being its own thread / post

#

yes

pulsar ferry
#

well the only problem with that is i dont want all the history

sage tendon
#

then delete the old giveaway messages

pulsar ferry
#

if i do a seperate post for each giveaway, they can auto archive

#

plus its much easier for someone to come in and see the lsit view of all the links (titles of each one)

#

scrolling through a single thread isnt great because you cant filter / sort, etc.

pulsar ferry
# lofty parcel .rtfm ForumChannel.edit

whats the proper way to create the channel?

async def create_channels():
    channel_names = ["channel1", "channel2", "channel3"]
    tags = [discord.ForumTag(name=tag, emoji=emoji) for tag, emoji in zip(["freebies", "promos", "giveaways"], ["🎰", "💰", "🏆"])]

    guild = await get_or_fetch(bot, "guild", GUILD_ID)

    for name in channel_names:
        # Check if the channel already exists
        if not await find_channel_by_name(name):
            # Create the forum channel
            forum_channel = await guild.create_text_channel(
                name=name,
                topic="Discuss topics here!",
                type=discord.ChannelType.forum,
                # default_thread_auto_archive_duration=1,  # 1 day
                # default_sort_order=0,  # Sort by creation time
            )

            # Update tags after the channel is created
            await forum_channel.edit(available_tags=tags)
sage tendon
#

i have no idea where you got that type= kwarg from lol

pulsar ferry
#

ah yeah that did it

round heart
#

I have a stupid, basic question. Files that are uploaded through discord.Attachment are binary. Say that's a CSV; what's the best way to read that as text? I thought I could just throw it at csv.DictReader, but it also doesn't like that it's binary

#

Seems one way I can do this is through codecs.StreamReader

errant trout
#

the general point is you can upload anything as long as you have a valid method of converting it to bytes

round heart
errant trout
#

ohh wait, i thought you meant to upload a csv

round heart
#

no no, accessing an uploaded csv

errant trout
#

if it's from an attachment to work as csv hmmmm

#

if you want to be lazy you could just save the file

#

otherwise your library will probably have a way to load a csv from bytes?

#

typically open methods also allow you to pass bytes you got from read

round heart
#

This worked for me. With attachment as discord.Attachment:

file = await attachment.to_file()
stream_reader = codecs.getreader('utf-8')
wrapper = stream_reader(file.fp)

csv_reader = csv.reader(wrapper)
header = next(csv_reader)
for row in csv_reader:
    ...

(I know I can use DictReader, but I want to ensure the headers are correct)

round heart
errant trout
#

why are you using to_file > file.fp

round heart
#

What else would I be using? discord.Attachment has a to_file which returns a discord.File object. Within that is fp, which is the BytesIO instance

errant trout
#

read

#

or do you specifically want bytesio for some reason

round heart
#

I don't want BytesIO, I want StringIO.

read() just turns it into a flat text file, I can't iterate through that with the csv lib

errant trout
#

then pipe the text back into stringio?

round heart
#

S..ure, but then it becomes no different than what I'm doing lol. 🙂

errant trout
#

well.. bytesio and stringio handle different things

round heart
#

I know. What I'm doing is taking the BytesIO and using the StreamReader to convert it to StringIO. You're taking the text and stuffing it into StringIO. Is there a specific performance implication I'm missing?

errant trout
#

i'm probably just missing the point, ignore me if your flow works

lofty parcel
#

Fuck bytes

#

Decimals for the win

round heart
round heart
stray pasture
#

I am trying to change an member nickname by doign the code:

    async def replace_username(self, member: discord.Member, to_replace_regex: str, replace_str: str) -> bool:
        nickname = member.nick
        if nickname is not None:
            nickname = re.sub(to_replace_regex, replace_str, nickname.strip())
            if nickname != member.nick:
                await member.edit(nick=nickname)
                return True
        return False

When running I am getting an embed error:

#

I check the permissions, the bot have Permissions.manage_nicknames. Just to be sure I also tried with the bot with admin permissions

#

also tried with bypass_verification=True, tried also with await ctx.defer(ephemeral=True) and ephemeral=False

#

Anybody know what could be the cause ?

stray pasture
#

oh never mind, there is some custom global error handler I did long ago

#

just found it 😄

cosmic swift
#

can i use something like https://discohook.org/ to make a format in which i want to give information out with instead of the add_field thingy

stray pasture
pulsar ferry
#

Can anyone point me to the proper way to parse an embeds fields?
getting None when trying to print out the fields

async def find_existing_thread(channel, link):
    for thread in channel.threads:
        first_message = await thread.fetch_message(thread.id)
        if first_message.embeds:
            embed = first_message.embeds[0]
            embed_dict = embed.to_dict()
            claim_field = next((field for field in embed_dict.get("fields", []) if field["name"].lower() == "claim"), None)
            print(claim_field)
            if claim_field and claim_field["value"].lower() == f"[click here]({link})".lower():
                logger.info(f"Found existing thread with matching claim link: {claim_field['value']}")
                return thread
    return None
cosmic swift
lofty parcel
cosmic swift
#

instead of using add_field

lofty parcel
#

I don't get the relation between discohook and add_field

#

They're quite literally two different things

cosmic swift
#

whats the difference

pulsar ferry
cosmic swift
#

or how u fixed it *

pulsar ferry
#

was referring to my post above not yours sorry

lofty parcel
cosmic swift
lofty parcel
cosmic swift
#

alright

#

thx

lofty parcel
#

Not sure what you're even trying to do

pulsar ferry
# lofty parcel Just iterate over embed.fields (without it being a dict)

got it thanks

```Python
async def find_existing_thread(channel, link):
    for thread in channel.threads:
        first_message = await thread.fetch_message(thread.id)
        embed = first_message.embeds[0] if first_message.embeds else None
        if embed and any(f.name.lower() == "claim" and f.value.lower() == f"[click here]({link})".lower() for f in embed.fields):
            logger.info(f"Found existing thread with matching claim link.")
            return thread
    return None
cosmic swift
#

trying to make my output look better than the {} i previously been putting out

lofty parcel
#

Huh? What {}?

cosmic swift
#

i got a json file in which i got information and i just parse it from there and print it out

lofty parcel
#

OK and

cosmic swift
#

theres no and

#

idk what u expect rn

lofty parcel
#

God now I'm even more confused why you wanted to use discohook and the relation with add_field

cosmic swift
#

thought that theres maybe a way that lets me use discohook

#

idek if i can copy the message from the website i just remembered it existed

lofty parcel
#

WHY do you want to use discohook?

#

You want to build an embed?

#

Or what

cosmic swift
#

cause im unsure about how add_field works and it wouldve made it easier prob

cosmic swift
lofty parcel
#

Did you even read the docs

#

.rtfm Embed.add_field

sly karmaBOT
cosmic swift
#

i didnt read the docs ive been watching yt videos

#

most of them are old so idrk if i can rely on them tbh

lofty parcel
#

So you've been blindly copying code

cosmic swift
lofty parcel
#

You never rely on YouTube tutorials

#

You read the docs

cosmic swift
#

its different bots they were making

cosmic swift
#

i tried making a embed once

#

i dont think i did it correctly

#

look at it 1sec

#
async def embed(Name, id, HP, Type_1, Type_2, Total, Attack, Defense):
  discord.Embed(      
  title = f"{Name}:",
  description = f"Information about {Name}:",
  color= discord.Color.red
  )
  embed.add_field(name=f"ID of {Name}", value={id}, inline = False)
  embed.add_field(name="Type 1:", value={Type_1}, inline = False)
  embed.add_field(name="Type 2:", value={Type_2}, inline = True)
  embed.add_field(name="The Total Stats:", value={Total}, inline = False)
  embed.add_field(name=f"Healthpoints:", value={HP}, inline = True)
  embed.add_field(name=f"Attackpoints:", value={Attack}, inline = True)
  embed.add_field(name=f"Defencepoints:", value={Defense}, inline = True)
lofty parcel
#

You're overriding your own method with the variable

#

That's gonna give you some issues

cosmic swift
#

can u explain what u mean by that

#

cuz i dont understand ngl

lofty parcel
#

And you're not assigning your discord.Embed to any variable?...

cosmic swift
#

can u explain what u meant before

lofty parcel
#

You're literally plain slapping a discord.Embed but not in any variable

#

Rename your function.

cosmic swift
#

i should read docs

#

💔

lofty parcel
#
async def create_embed(...):
      embed = discord.Embed(...)
      ....
cosmic swift
lofty parcel
#

It's literally what I'm pointing out

#

Rename your function

cosmic swift
#

oh alr

#

yea done that

lofty parcel
#

Yes OK congrats

cosmic swift
#

🥳

lofty parcel
#

Now you need to return the embed...

cosmic swift
#

how can i use the embed in a context though

lofty parcel
#

Do you know python?

cosmic swift
#

yea I do

#

i been previously just been printing out the {}

#

thats why im asking

lofty parcel
#

You don't know how to use your own function?..

cosmic swift
#

im not here for getting bashed fr

lofty parcel
#

my_awesome_embed = await create_embed(...)

cosmic swift
#

just trying to get it running

#

thx

lofty parcel
#

Girl you're expected to have python knowledge.

#

This is basic python, not nasa calculus.

cosmic swift
#

💔

#

thanks for the help eitherway

lofty parcel
#

I don't know what else you want me to explain.

#
async def create_embed(...):
      embed = discord.Embed(...)
      ....
      return embed 
lofty parcel
cosmic swift
#

yeah i know im gonna get it running

#

i know how

#

now

#

thats why i said thx

lofty parcel
#

If you say so

bitter meteor
#

In slash commands for arguments can you have more than 25 choices from the dropdown menu?

sage tendon
#

only with autocomplete

bitter meteor
#

do i just pass autocomplete = True?

sage tendon
#

no, read the docs

pulsar ferry
#

could someone please help me out with the proper way to have the bot do something on reaction?

sage tendon
pulsar ferry
#

I'm trying to watch for reaction on thread specifically and change tag accordingly

pulsar ferry
sage tendon
#

if thats in a cog, you need to use a listener

pulsar ferry
#

right now im not using any cogs, everything jsut in my main.py

sage tendon
#

well, what are your intents first of all

pulsar ferry
#
intents = discord.Intents.default()
intents.members = True
intents.guilds = True

sage tendon
#

guilds is part of default intents

pulsar ferry
#

ok but i have all of them i believe?

sage tendon
#

well looks fine to me
did you restart your bot, and did you make sure it has access to whatever you are reacting to

pulsar ferry
#

yes because the post is from the bot itself

sage tendon
pulsar ferry
#

oh does it matter if its the default emoji on threads?

sage tendon
#

no idea how thats handled internally

#

but it shouldnt matter

little cobalt
sage tendon
#

yea then your bot somehow doesnt have that message cached

sage tendon
#

It might be that message intent is required but its not documented but not sure

pulsar ferry
#

so should i be using the raw reaction add though?

sage tendon
#

I mean you can use either but if the normal one doesnt work (because your bot doesnt have that message cached, somehow) then you gotta use the raw one

or try to see if adding message intents fixes it, that'd be my only guess rn

pulsar ferry
#

hmm adding the intent didnt solve it

bitter meteor
pulsar ferry
#

How can i edit the tags directly on a thread post?

sage tendon
forest horizon
#

Is there a way to get a list of messages in a channel that have been edited since a given time?

sage tendon
pulsar ferry
# sage tendon https://docs.pycord.dev/en/stable/api/models.html#discord.Thread.edit

Still a little stuck on this... for some reason its not letting me grab the available_tags?

@bot.event
async def on_raw_reaction_add(payload: discord.RawReactionActionEvent):
    if isinstance(await bot.fetch_channel(payload.channel_id), discord.Thread) and str(payload.emoji) == "✅":
        thread = await bot.fetch_channel(payload.channel_id)
        message = await thread.fetch_message(payload.message_id)
        total_checks = sum(r.count for r in message.reactions if str(r.emoji) == "✅")
        # Proceed if there are enough checks
        if total_checks > 0:
            channel = bot.get_channel(payload.channel_id)
            applied_tags = thread.applied_tags  # Applied tags on the thread
            verified_tag = discord.utils.get(channel.available_tags, name="Verified")
            not_verified_tag = discord.utils.get(channel.available_tags, name="Not Verified")
            # If "Not Verified" tag exists, remove it, and add "Verified" tag
            if not_verified_tag:
                applied_tags.remove(not_verified_tag)  # Remove the "Not Verified" tag
            if not verified_tag:
                applied_tags.append(verified_tag)  # Add the "Verified" tag
            # Update the thread with the new tags
            await thread.edit(applied_tags=applied_tags)
Traceback (most recent call last):
  File "/Users/ethan/Python Projects/EliteSweeps/.venv/lib/python3.12/site-packages/discord/client.py", line 412, in _run_event
    await coro(*args, **kwargs)
  File "/Users/ethan/Python Projects/EliteSweeps/main.py", line 171, in on_raw_reaction_add
    verified_tag = discord.utils.get(channel.available_tags, name="Verified")
                                     ^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Thread' object has no attribute 'available_tags'
sage tendon
#

does the post have any tags

pulsar ferry
#

yes because when i print applied tags i see them

#

i dont know why i cant get the available tags fromt his

            verified_tag = discord.utils.get(channel.available_tags, name="Verified")
sage tendon
#

oh, yea, i misread

#

Thread.available_tags isnt a thing

#

the forum channel has it

pulsar ferry
#

oh?

sage tendon
#

docs help

pulsar ferry
#

yeah sorry i struggle with the docs on where i need to look 😅

sage tendon
#

i mean you knew about available tags so just search that lol

#

gives 1 result

pulsar ferry
#

oh wait i guess because the channel in this scenario is actaully the forum?

#

i was confusing the actual thread with the channel

#

i.e. this channel = bot.fetch_channel(payload.channel_id) is returning the thread, not the forum

sage tendon
#

yea, and the error tells you that too

pulsar ferry
#

yeah kinda confusing that its still called channel

sage tendon
#

also, you shouldn't fetch 3 things every single time a reaction is added

#

use the cache and only fetch when needed

pulsar ferry
#

yeah that was my next question, how i could do this in a much better way hahah

sage tendon
forest horizon
sage tendon
forest horizon
#

Yeah, that I'm already doing. Just want to pick up any changes that might have happened while the bot was offline. Guess there's not a good way to handle that.

round heart
#

Isn't there also on_raw_message_edit for messages that may not be cached by the bot any longer?

sage tendon
sage tendon
#

there isn't really a magic cure for that

#

what do you need this for anyway

forest horizon
#

Long story, but the short form is that I support a music streamer that uses a discord channel for keeping notes about various songs he's learned live on his streams, and I have a bot that goes back and does a bunch of indexing on them and a few other things... but sometimes we discover that something we did in the past has, for example, a non-normalized name for a song, which we eventually go back and correct. That kind of thing.

(you could argue that using discord as a storage for this kind of thing is broken, but I have no control over that)

The reality is the bot will almost always be online and really shouldn't miss edit events, but I am a paranoid bitch that likes to do things correctly rather than "it'll usually work [until something unexpected happens]"

sage tendon
#

i mean how many messages are in that channel
i doubt itll be thousands
for the rare case that the bot goes off you can just slowly iterate through all messages to "catch up" if you missed anything, on startup

echo wraith
#

that shouldn't be too heavy of an api load

#

especially if it's only down for short times.

sage tendon
#

no

#

that doesnt work

echo wraith
#

why would it not ?

sage tendon
#

since any message from whenever could be updated in the downtime

echo wraith
#

yeah but you can have a reasonable buffer ig

sage tendon
#

my solution is the only possible one that doesnt miss any edits 100%

echo wraith
#

yeah makes sense

sage tendon
#

and if you do it slowly so you dont exhaust any ratelimit you can get it done in a few mins depending on how many messages there are

echo wraith
forest horizon
#

Fortunately we don't really go back and update things often so it shouldn't be a huge ideal to just cope with the bot missing things when the stars align perfectly for allowing it to happen.

safe quarry
#

should I go python for discord bots, or a different lang

lofty parcel
#

People have a weird thing of calling languages better than other ones.

safe quarry
#

should I use pycharm

#

i have it on my pc rn

lofty parcel
#

Again, you use whatever you prefer

safe quarry
#

well im comfortable with jetbrain IDEs and one of them is pycharm

#

any recommended plugins if you use it?

lofty parcel
#

I don't use pycharm

safe quarry
#

Did bot coding change

#

for python

lofty parcel
safe quarry
#

im trying to use the code in the guide, but it won't run

lofty parcel
#

What code

#

What wont run

#

What errors

safe quarry
lofty parcel
#

God what's with people and being vague these days. We can't read minds.

safe quarry
#
import os # default module
from dotenv import load_dotenv

load_dotenv() # load all the variables from the env file
bot = discord.Bot()

@bot.event
async def on_ready():
    print(f"{bot.user} is ready and online!")

@bot.slash_command(name="hello", description="Say hello to the bot")
async def hello(ctx: discord.ApplicationContext):
    await ctx.respond("Hey!")

bot.run(os.getenv('TOKEN')) # run the bot with the token```
lofty parcel
#

That code is pretty much up to date.

#

You still haven't said what's not working

#

?

lofty parcel
safe quarry
#
Traceback (most recent call last):
  File "c:\Development\PyCharm\Python Projects\Eterneon\eterneon.py", line 1, in <module>
    import discord
  File "C:\Users\EternalHell\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\__init__.py", line 27, in <module>
    from . import abc, opus, sinks, ui, utils
  File "C:\Users\EternalHell\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\abc.py", line 58, in <module>
    from .voice_client import VoiceClient, VoiceProtocol
  File "C:\Users\EternalHell\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\voice_client.py", line 55, in <module>
    from .player import AudioPlayer, AudioSource
  File "C:\Users\EternalHell\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\player.py", line 29, in <module>
    import audioop
ModuleNotFoundError: No module named 'audioop'
PS C:\Development\PyCharm\Python Projects> & C:/Users/EternalHell/AppData/Local/Programs/Python/Python313/python.exe "c:/Development/PyCharm/Python Projects/Eterneon/eterneon.py"
Traceback (most recent call last):
ckages\discord\__init__.py", line 27, in <module>
    from . import abc, opus, sinks, ui, utils
  File "C:\Users\EternalHell\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\abc.py", line 58, in <module>
    from .voice_client import VoiceClient, VoiceProtocol
  File "C:\Users\EternalHell\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\voice_client.py", line 55, in <module>
    from .player import AudioPlayer, AudioSource
  File "C:\Users\EternalHell\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\player.py", line 29, in <module>
    import audioop
ModuleNotFoundError: No module named 'audioop'```
lofty parcel
#

You're using python 3.13, audioop was removed as a standard library.

#

Downgrade or install audioop-lts

safe quarry
#

okay

#
    @bot.event``` now im confused here? why is it saying theres an issue here when its the exact same on the guide
lofty parcel
#

What's the error

safe quarry
#

TypeError: Client.event() missing 1 required positional argument: 'coro'

#

missed that part

errant trout
#

note we don't officially support 3.13 yet, i'd recommend 3.12 or below for now

crimson lily
#

on changing the code of a discord view, the views that were before the code change no longer work right

sage tendon
#

highly depends on what exactly you changed

crimson lily
#

it was a very minute change, i didnt expect it to break the old views

#

is it possible to make the old views work again? be it through changing the code back to original

crimson lily
sage tendon
#

views in general stop working if you restart the bot unless you make them persistent

#

,tag persistent

#

damn i forgor

crimson lily
#

yeah they're persistent

sage tendon
#

1s

#

ah

#

yea well what did you change then lol

sage tendon
#

oh

#

yea that shouldn't break it

#

does it keep working on bot restart if you dont change anything?

crimson lily
#

yep does

#

weird

#

o well

crimson lily
#

Guessing views that have values passed onto their headers wont ever be persistent?

#

Feeling like thats the problem I have with the current view

sage tendon
#

what

errant trout
#

think someone deleted a question on threads, the Guild.active_threads fetch function returns them in descending ID order but we cannot guarantee the same for cache (e.g. guild.threads, channel.threads)

pulsar ferry
#

i had posted the question then deleted it because i think i answered it myself... just called for thread in reversed(channel.threads): to get it newest to oldest

errant trout
#

fair

pulsar ferry
#

but it sounds like youre saying its not always going to give me latest in doing this?

errant trout
#

we do not sort cached threads at all

#

(i think?)

#

but if you fetch guild.active_threads, or synced threads when the bot starts up, discord should return them as newest to oldest

pulsar ferry
#

it could just be coincidence that i got the latest then, but to be safe what would be the proper way to fetch?

async def find_existing_thread(channel, link):
    for thread in reversed(channel.threads):
        first_message = await thread.fetch_message(thread.id)
        embed = first_message.embeds[0] if first_message.embeds else None
        if embed and any(f.name.lower() == "claim" and f.value.lower() == f"[click here]({link})".lower() for f in embed.fields):
            logger.info(f"Found existing thread with matching claim link.")
            return thread
    return None
errant trout
#

i mean you can always use sorted with a lambda function

pulsar ferry
#

what is the attribute to sort it on?

errant trout
#

id is easy enough

pulsar ferry
#

oh lower id are older im assuming?

errant trout
#

discord IDs (Snowflakes) are effectively timestamps

#

yep

pulsar ferry
#

so something like this?

async def find_existing_thread(channel, link):
    for thread in sorted(channel.threads, key=lambda t: t.id, reverse=True):  # Sort by ID descending
        first_message = await thread.fetch_message(thread.id)
        embed = first_message.embeds[0] if first_message.embeds else None
        if embed and any(
            f.name.lower() == "claim" and f.value.lower() == f"[click here]({link})".lower()
            for f in embed.fields
        ):
            logger.info("Found existing thread with matching claim link.")
            return thread
    return None
#

cool will test it out thanks!

errant trout
#

i guess one pitfall, it's possible that the first message was deleted

#

but if you're working in a controlled environment where that doesn't happen then no need to worry i guess

pulsar ferry
#

the first message in each thread is a message posted by the bot - so it shoudlnt be

#

yeah this is custom bot for 1 server

#

seems to be working thanks again

errant trout
#

allgood

pulsar ferry
#

One other question - i thought doing something like this would have the thread disappear after 24 hours? its seems like they are all still showing... What does "archive" mean on discord forums?

    thread = await channel.create_thread(name=thread_name, embed=embed, applied_tags=tags, auto_archive_duration=1440)
errant trout
#

this option in thread/post settings

pulsar ferry
#

you mean like how this is showing?

errant trout
#

mhm

#

well if you have it open it'll show regardless

#

but outside of that thread, it won't after the duration

pulsar ferry
#

yeah i gues i dont really get what that does because if i have a bot thats creating the threads anyway, it doesnt show there until someone "joins" it or types in the thread

#

what i was looking for was more just always only showing the last 24 hours of posts when they go to the forum

errant trout
#

it only applies to threads you have joined yes