#Basic Pycord Help (Quick Questions Only)

1 messages · Page 82 of 1

silver moat
#

print converts it to a string?

#

like it uses the class's __str__ method

tiny token
#

Ok

#

So like Im kinda noob at python. Im wondering why as I just try to import main.py through my command class, guildapplicationchannelcommand, but every time I try to import main (regardles if Im using anything in it, I want to use the bot to add listeners for a button) I get circular improrts saying: "commands.guildapplicationchannelcommand' has no attribute 'run'" in my cog class. Ill send screenshots

#

You can look at the side for the hierarchy

#

and the top for what class your viewing. I Looked through the imports on main and other classes and I have no clue why its circular importing

eternal wing
#

What is the limit on amount of children for a modal? Or is there none and it will be scrollable?

eternal wing
#

Well yeah, like the inputFields

proud mason
#

5 input texts

eternal wing
#

Ok, thanks

copper flicker
#

When I try to create a button with .link style, I'm asked for the url, but if I specify the url, I get an error. How do I make a link button?

proud mason
#

that wont work, since link buttons cant have callbacks

copper flicker
#

thats workink, thx

long moat
#

uff, i hate the new usernames. I want my display name to work but if I don't set one on a server it doesn't recognise my default display name and just uses my username instead.

user.display_name is meant to right? Its just giving me thejuanog instead of TheJuanOG🔥

long moat
#

user.name gives thejuanog

#

if i have my display name set to "TheJuanOG🔥." or any other character "not" in my regular display name it show up as "TheJuanOG🔥."

#

if i don't have a server specific display name set, it reverts back to thejuanog >_>

#

first ss is with "TheDeveloperOG🔥" set as my nickname, second is reverting back to "default" display name.

long moat
dire fossil
#

Hello. I need to receive events from a lurked-mode server, such as voiceStateUpdate and messageReceived. The problem is that even after joining the server in preview mode, I don't receive events through the websocket. Maybe I need to send something to the websocket to get these events? After all, the client somehow receives them.

long moat
young bone
#

How to get the master branch one

long moat
#

yeh thats how i always update

#

my last update

#

probably outdated kek

young bone
#

yea

long moat
#

ok so user.name is acceptable

proud mason
#

i dont think there is a way to know if the install is outdated lol pain

long moat
#

or still .display_name

#

side-note: why force lowercase >_>

young bone
#

and at dev123

proud mason
#

hmm

long moat
#

i realise the "lowercase" call is entirely Discord's and nothing anyone here can do about it, its just frustrating kek

#

i dont want my name more "twitter" like; i've avoided twitter for years i don't need a twittery username

proud mason
#

lmao

proud mason
# long moat or still `.display_name`

iirc

member.name          -> username
member.global_name   -> global display name (global nick name)
member.nick          -> guild nick name
member.display_name  -> member.nick OR member.global_name OR member.name
proud mason
cyan quail
#

yes

#

(on master)

long moat
#

so i should probably use .display_name then.

#

or .global_name

proud mason
#

ill make a tag kek

long moat
# proud mason cool

final noob question; where can i find the changelogs? my server admin wants to see whats updated since our current version for any compatability issues with antiquated code

true loom
#

Please

long moat
#

oh hes here kek

cyan quail
long moat
#

thank you 🙂

#

@true loom ^ there nub

true loom
#

Ty

wary rover
#

Hi there!

I have a question about VSCode and PyCharm.
I recently decided to try PyCharm which seems to be much better.

I have two problems:

  • All my imports note an error
  • What is the python project type for a discord bot? (Pure Python, Django, Flask, etc etc)
waxen whale
#

pure py mostly

wary rover
#

Okay, but why are my imports wrong?

#

I have no import problems with vscode

young bone
bitter lance
#

if I want use fetch_guild(), should bot be in that guild?

proud mason
#

.tag tias

winter condorBOT
tiny token
#

Python I don't like. It's to easy to just shoot yourself in the foot

full basin
young bone
tiny token
full basin
quaint coral
#

Regarding buttons, is there a way to set a button as "disabled" on its decorator? Here's what I need: I need to generate my View containing a button that could be enabled or disabled based on a boolean variable I have received when instantiating it. I need the button to already appear either enabled/disabled, so I can't just check when the user interacts with it.

I think it's doable because I have seen bots that work pretty similarly to this, but I can't find a way to do it.

quaint coral
full basin
tiny token
#

Here's the imports

#

Guildapplicatipnchannel imports main. Handler(Cog) imports guildapplicatipnchannel

rain carbon
#

How do I get a user's display name

#

Nevermind

opaque needle
#
def generate_menu2():
    temp = []
    for i in range(len(role2_id)):
        role_names = role2_name[f'role2_name_{i}']
        role_ids = role2_id[f'role2_id_{i}']
        role_emojis = role2_emoji[str(f'role2_emoji_{i}')]
        temp.append(discord.SelectOption(label=role_names, emoji=role_emojis, value=str(role_ids)))
    return temp

class MyView2(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
    @discord.ui.select(
        placeholder="Выбирете цвет",
        min_values=1,
        max_values=1,
        custom_id="role2",
        options=generate_menu2()
    )
    async def select_callback(self, select, inter: discord.Interaction):
        role = inter.user.guild.get_role(int(select.values[0]))
        if role in inter.user.roles:
            await inter.user.remove_roles(get(inter.guild.roles, id=int(select.values[0])))
            resp = "Роль убрана!"
        else:
            await inter.user.add_roles(get(inter.guild.roles, id=int(select.values[0])))
            resp = "Роль добавлена!"
        await inter.response.send_message(resp, ephemeral=True)
#

How to limit the selection in the select menu? So that the user can select only one item.

opaque needle
#

So that the user can select only one item.

young bone
#

Edit it

opaque needle
opaque needle
#

max_values is already present, you can just check if he has no other roles when choosing a new one and if there is one to take away.

silver moat
#

I'm not sure I understand. What are you checking for, and how do you want to accomplish that from the user-side?

opaque needle
#

I need the user to have only the selected role, that is, if he cancels the role selection, then he needs to take the old role and give a new one.

silver moat
#

you can get user's roles with interaction.user.roles?

opaque needle
#

yes

neon prairie
#

I get discord.errors.ValidationError: Command and option description must be 1-100 characters long. from this function ```py
class mcon_enum(enum.Enum):
shirt=1
pants=2
basemorph=3
name=4

@bot.slash_command(name = "modify", description = "Change")
async def mcon(ctx:discord.ApplicationContext,name:str,what:mcon_enum,to:str):``` and it works when i remove mcon_enum

#

I changed it to use py-cord Enum, which from my understanding is just enum.Enum class mcon_enum(discord.Enum): And it works.. why? they are the same thing..

#

print(enum.Enum == discord.Enum) = False confusing

proud mason
#

Huh. That's not supposed to be like that...

tribal girder
neon prairie
#

so that makes enums unusable in py-cord?

#
if what is mcon_enum.pants``` is allways false, even if what is ``mcon_enum.pants``
and its the same for ``==`` ```py
if what == mcon_enum.pants``` allways false, even if what is ``mcon_enum.pants``
silver moat
#

that's not how slash command options are intended to be used?

neon prairie
silver moat
neon prairie
#

why cant we use enums?

silver moat
neon prairie
proud mason
#

enums should work tbh ThinkO_O

silver moat
neon prairie
#

it works halfway except for the logic part

silver moat
halcyon gorge
#

new username system pushed to master already right?

proud mason
neon prairie
#

just broken

proud mason
silver moat
#

what even is discord.Enum

neon prairie
#

but is not the same somehow

proud mason
#

The type of input that is expected for this option. This can be a :class:SlashCommandOptionType, an associated class, a channel type, a :class:Converter, a converter class or an :class:enum.Enum.
yea enum.Enum is supported

neon prairie
proud mason
proud mason
neon prairie
neon prairie
proud mason
#

hmm

#

what happens?

neon prairie
#

``

#

print(what is mcon_enum.shirt) # false print(what == mcon_enum.shirt) # false

#

I chose shirt in the option

proud mason
#

can you print what

#

also type(what)

neon prairie
proud mason
#

hmm

neon prairie
silver moat
#

1 is not a type?

neon prairie
#

oh shit

silver moat
#

print(type(what))

#

I think

neon prairie
#

lmao yeah

proud mason
#

yea lol 😂

silver moat
#

watch 1 be a string

proud mason
#

hmm you might need to check the value

neon prairie
#

what the fuck

silver moat
#

issue time?

proud mason
#

you would need to do what == mcon_enum.shirt.value

silver moat
proud mason
#

yea

neon prairie
#

it works fine when py if what == 1

proud mason
#

i think you can make your enum class a subclass of enum.IntEnum

proud mason
proud mason
#

refresh your client

silver moat
#

or just like try again

#

:p

neon prairie
proud mason
#

or maybe wait a few mins

neon prairie
#
if what == 1``` doing this is fine though
silver moat
#

yeah 1 doesn't tell you anything

#

the whole point of enums is to make it more readable

neon prairie
#
class mcon_enum(enum.IntEnum):
  shirt=1
  pants=2
  basemorph=3
  name=4``` breaks invisibly
#
class mcon_enum(enum.Enum):
  shirt=1
  pants=2
  basemorph=3
  name=4``` gives error
#
class mcon_enum(discord.Enum):
  shirt=1
  pants=2
  basemorph=3
  name=4``` makes py-cord give int instead (but works)
neon prairie
silver moat
#

time to make an issue I suppose

proud mason
young bone
proud mason
#

IntEnum should work the closest

#

or ctrl + shift + r for a hard refresh

silver moat
#

alt f4

#

and reclick for best refresh

zealous bear
#

what's the pycord version of original_response?

silver moat
#

iirc

neon prairie
zealous bear
#

im getting
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'ApplicationContext' object has no attribute 'original_response'

#

when i try and use original_response

proud mason
silver moat
#

.rtfm applicationcontext

proud mason
zealous bear
worldly schooner
#

Is there a way to avoid all commands from working? Like a Owner command that makes every command show a message like: "Commands are not working for now, try again later"

proud mason
#

do you logic inside that (i suggest using bot vars). if block command, respond to the command, and return false

#

?tag botvar

obtuse juncoBOT
#

Need to keep track of a variable between functions? No problem!

⚠️ Careful what you name it though, else you might overwrite something ⚠️

Just add it to your commands.Bot or discord.Client instance like so:

bot = commands.Bot(...)
bot.my_variable = 0

async def foo():
    bot.my_variable += 1

# In a cog
@commands.command()
async def counter(self,ctx):
    await ctx.send("Current Counter is at {}".format(ctx.bot.my_variable))

This also allows you to access this from other cogs/extensions/functions. Anywhere you have access to the bot instance

worldly schooner
#

thats what I thought on doing, but

#

the problem is the checking part

#

will I have to make a check on every single command?

young bone
#

mhm

proud mason
#

no

worldly schooner
#

Isnt there a way to have a like all command handler?

young bone
#

You mean error handler?

worldly schooner
#

like global error handler

proud mason
#

a bot check is a check which is only registered once on the bot instance

#

@bot.check

worldly schooner
#

yea but for check before a command starts

proud mason
#

.rtfm bot.checl

winter condorBOT
#

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

proud mason
#

.rtfm bot.check

proud mason
#

it is bot-wide, not command specific

worldly schooner
#

so it will only check when the instance gets online?

proud mason
#

uh

#

ofc

worldly schooner
# proud mason read this https://docs.pycord.dev/en/stable/api/clients.html#discord.Bot.check

The thing is, I have transaction commands BUT I dont make the transaction commands with rollback rules, so if someone is trading something and the bot stops in the middle of the transaction something will surely be vanished, so what I plan to do is to make a command that inutilizes all the commands in the bot, like accept trades command, so that will previne from people to make trades in the same hour as the bot goes off from a planned maintenance

#

so what im mainly looking for is like a global @before

#

to check if the bot variable is not false

proud mason
#

hmm

worldly schooner
#

like error handlers but that happens before a command

proud mason
#

there is global before_invoke too 👀

#

.rtfm bot.before_invoke

proud mason
#

is this of any help?

worldly schooner
#

🤯

#

lemme see

#

yeah definetelly is something that can help

#

tysm

proud mason
#

previne from people to make trades in the same hour as the bot goes off from a planned maintenance
this might be possible to do with checks too tbh

worldly schooner
#

@proud mason gpt banging also

young bone
#

Dont use gpt

worldly schooner
#

why not Weary

proud mason
worldly schooner
full basin
worldly schooner
#

about it being outdated ik it comes with info only from 2021 and before

full basin
#

And the library changed like 90% after 2021

livid wolf
#

So I have this kick command, and it is not DMing the user.

async def kick(ctx, user: discord.Member, reason: discord.Option(str)):
  embed = discord.Embed(title=f"Kicked from {ctx.guild}", description="Kicked from server.", color=0xE74C3C)
  embed.add_field(name="Reason", value=f"{reason}")
  embed.add_field(name="Kicked by", value=f"{ctx.author}")
  
  if user:
    await user.kick(reason=reason)
    await ctx.send(f"Kicked {user.display_name} from the server!")
    await user.send(embed=embed)
  else:
    await ctx.send("User not found. Please try again with a valid user.")  
    # Fail safe.
full basin
#

High chance bot and user don't share servers anymore, so dm can't go through.

livid wolf
quaint coral
full basin
#

Np

last mason
#

I'm trying to show a date in the footer of an embed but it's not formatting correctly. is this not possible using discord's timestamp format?

silver moat
#

however, you can set the timestamp of the embed with something like

embed.timestamp = discord.utils.utcnow()
#

yeah embeds have a specific timestamp field

last mason
#

oh ok

#

so that will only show the time in utc right

silver moat
heavy jungle
#

AttributeError: module 'discord' has no attribute 'Bot'

packages are py-cord PyGithub topggpy

young bone
#

github or pip one?

heavy jungle
#

pip

#

on a ptero server so

young bone
#

You need the github one

silver moat
heavy jungle
#

thanks guys

glossy forum
#

Hey, I got a little confused on how I'm supposed to use OptionChoice
consider following code, everything inside single cog, the command is a part of SlashCommandGroup

channel_types = [
    OptionChoice(name="Discussion - For a chit-chats about the posts", value="text"),
    OptionChoice(name="Posts - For discovering glorious wonders of the internet", value="post"),
    OptionChoice(name="Voice chat - For most vocal art enjoyers", value="vc")
]
action_types = [
    OptionChoice(name="Create - Create a new channel for the category", value="create"),
    OptionChoice(name="Add existing - Associate existing channel to the category", value="add"),
    OptionChoice(name="Remove - Remove channel from the category", value="remove")
]

@_category.command()
@discord.option("action_type", description="Select what do you want to do with the channel",
                choices=action_types, required=True)
@discord.option("channel_type", description="Select which channel you want to update",
                choices=channel_types, required=True)
@discord.option("channel", description="Select the channel to update (if relevant)")
async def update(self, ctx: ApplicationContext, category_alias: str, action_type: OptionChoice,
                 channel_type: OptionChoice, channel: TextChannel | VoiceChannel = None):
    ...

the current error is
TypeError: Invalid class <class 'discord.commands.options.OptionChoice'> used as an input type for an Option
Which I suppose make sense, considering how it works
My question is, if the user select one of the options, what's being passed to the function? value parameter?

young bone
glossy forum
# young bone for channel use `typing.Union[TextChannel, VoiceChannel]` and why is `channel_ty...

for channel use typing.Union[TextChannel, VoiceChannel]
I'm using Python 3.11, it should be equivalent, no?
why is channel_type: OptionChoice
Let's say it's an utils function for polishing the edges
so it creates 9 potential outcomes as it takes 3 actions (creation of new channel, adding existing channel and removing a channel), for 3 types of channels depending on intended use-case.
It's because I'm connecting it with the database and do other stuff related to the data there

young bone
#

For options you have to restart the bot everytime?

glossy forum
#

huh? No, It's constant. It's just I find it more user friendly to provide them options to choose from instead of making them type it
and later the outcome is gonna be handled by the match statement

#
action_t = action_type.to_dict()
channel_t = channel_type.to_dict()
match action_t["value"]:
    case "create":
        status = await create_and_setup(channel_t["value"])
    case "add": #etc
silver moat
#

Hey could you show the error with full traceback?

glossy forum
#

sure, I'd need to log on the VPS server first tho
but the error is because Option doesn't have OptionChoice as a valid input_type
from option.py's source code:

#
input_type: Union[Type[:class:`str`], Type[:class:`bool`], Type[:class:`int`], Type[:class:`float`], Type[:class:`.abc.GuildChannel`], Type[:class:`Thread`], Type[:class:`Member`], Type[:class:`User`], Type[:class:`Attachment`], Type[:class:`Role`], Type[:class:`.abc.Mentionable`], :class:`SlashCommandOptionType`, Type[:class:`.ext.commands.Converter`], Type[:class:`enums.Enum`], Type[:class:`Enum`]]
        The type of input that is expected for this option. This can be a :class:`SlashCommandOptionType`,
        an associated class, a channel type, a :class:`Converter`, a converter class or an :class:`enum.Enum`.
glossy forum
# silver moat Hey could you show the error with full traceback?
File "/root/commission_02_2023/bot/lib/python3.11/site-packages/discord/cog.py", line 774, 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 "/root/commission_02_2023/bot/cogs/serveradmin.py", line 16, in <module>
     class ServerAdmin(commands.Cog):
   File "/root/commission_02_2023/bot/cogs/serveradmin.py", line 173, in ServerAdmin
     @discord.option("channel_type", description="Select which channel you want to update",
     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   File "/root/commission_02_2023/bot/lib/python3.11/site-packages/discord/commands/options.py", line 406, in decorator
     func.__annotations__[name] = Option(type, **kwargs)
                                  ^^^^^^^^^^^^^^^^^^^^^^
   File "/root/commission_02_2023/bot/lib/python3.11/site-packages/discord/commands/options.py", line 230, in __init__
     raise exc
   File "/root/commission_02_2023/bot/lib/python3.11/site-packages/discord/commands/options.py", line 225, in __init__
     self.input_type = SlashCommandOptionType.from_datatype(input_type)
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   File "/root/commission_02_2023/bot/lib/python3.11/site-packages/discord/enums.py", line 821, in from_datatype
     raise TypeError(
 TypeError: Invalid class <class 'discord.commands.options.OptionChoice'> used as an input type for an Option
#

That's why I asked

My question is, if the user select one of the options, what's being passed to the function? value parameter?

#

so I'd use str or whatever
unless that would overwrite discord.option(..., choices=...)

silver moat
meager heron
#

Does a bot that has slash commands actually need the "use application commands" permission?

meager heron
#

ty 👌

#

Do invite links still need the "applications.commands" scope?

silver moat
#

still good to have ig

meager heron
#

And in discord.utils.oauth_url(), client_id is just bot.user.id, right?

neon prairie
#

how do I send multiple images in a embed?

silver moat
#

.tag embeds

young bone
neon prairie
#

is there a way to send images that arent in the embed then?

silver moat
#

You can use an image manipulation tool like pillow to combine your images

neon prairie
#

I think like 3 of the imports I have are only 3.11

young bone
neon prairie
glossy forum
neon prairie
#

but I only have links and dont have the bandwidth to get them as files

young bone
#

send(file=discord.File("path to file"))

silver moat
glossy forum
#

oh wait
I think I figured it out
edit: or actually nvm, I just diagnosed the problem
edit2: oh wait, I might've accidentally created a name collision with Pycord's internals

glossy forum
neon prairie
young bone
#

yea

neon prairie
#

it will shorten my micro sd cards lifespan too much I cant get around it

silver moat
neon prairie
young bone
#

request eh

silver moat
#

.rtfm discord.File

silver moat
#

yeah you can pass that into fp

neon prairie
#

thx

neon prairie
#

it took me 10 minutes to figure that out

#

fp = open(x,x)

#

its not the actual bytes

silver moat
#

it does say that it accepts bytes

neon prairie
#

probably

#

I still tried it and it didnt work so

silver moat
#

can you confirm that what you have actually are bytes?

neon prairie
#
    print(type(requests.get(i["imageUrl"]).content))
    imgs.append(discord.File(requests.get(i["imageUrl"]).content,"v"))```
#
  File "C:\Users\wells\OneDrive\Desktop\projects\Overseer\main.py", line 67, in msee
    imgs.append(discord.File(requests.get(i["imageUrl"]).content,str(pseudo)))
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\python\Lib\site-packages\discord\file.py", line 99, in __init__
    self.fp = open(fp, "rb")```
silver moat
#

uh what is .content supposed to do?

#

and the "v" parameter

neon prairie
#

it gives the actual bytes

#

"v" is the "name" of the file its a arguement for discord.File

silver moat
#

so shouldn't it be inside of the parentheses

neon prairie
#

it is?

silver moat
#

my bad sorry

neon prairie
#

lol

#

did I find another missing/broken freature

silver moat
#

full traceback?

neon prairie
#
Ignoring exception in command see:
Traceback (most recent call last):
  File "D:\python\Lib\site-packages\discord\commands\core.py", line 124, in wrapped
    ret = await coro(arg)
          ^^^^^^^^^^^^^^^
  File "D:\python\Lib\site-packages\discord\commands\core.py", line 982, in _invoke
    await self.callback(ctx, **kwargs)
  File "C:\Users\wells\OneDrive\Desktop\projects\Overseer\main.py", line 67, in msee
    imgs.append(discord.File(requests.get(i["imageUrl"]).content,str(pseudo)))
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\python\Lib\site-packages\discord\file.py", line 99, in __init__
    self.fp = open(fp, "rb")
              ^^^^^^^^^^^^^^
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "D:\python\Lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "D:\python\Lib\site-packages\discord\commands\core.py", line 375, in invoke
    await injected(ctx)
  File "D:\python\Lib\site-packages\discord\commands\core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte```
#

Application Command raised an exception: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte it parses the bytes type (from .content) as if its a string

#

but the first byte isnt a valid ascii character so it explodes

silver moat
#

fun. not sure if this specifically this image, could you try a different image to see if it yields any different results?

neon prairie
#

ye

silver moat
#

also, for the file thing, perhaps change it to

discord.File(
  fp = requests.get(i["imageUrl"]).content,
  filename = "v"
)
``` for readability sake.
neon prairie
#

its more readable for me the first way

#

the second way my eyes dont like to traverse multiple lines

silver moat
#

and maybe filename needs an extension like .png or .jpeg

silver moat
neon prairie
#

it was giving me a hard time trying a separate image so I put it in manually and same error

silver moat
#

well, there's this other problem about using requests

#

?tag requests

obtuse juncoBOT
#

Why you should not use the requests library for your bot
requests is a popular HTTP library for Python. It is however not a good option for Discord bots, since it is not async and blocking.

This essentially means that your bot will not be able to execute any code at all while a request is happening. Since requests usually take a few seconds to complete, this can have a detrimental effect on your bot's performance. E.g if a user executes a command that performs a request taking 5 seconds to complete, no one else will be able to use your bot for those 5 seconds.

Please look at using a HTTP library that has async support, such as aiohttp or httpx

neon prairie
#

async is so fucking annoying

silver moat
#

you chose py-cord, an asyncio-oriented library

neon prairie
#

theres no other non-asyncio libraries

#

like at all, some libraries are even using async without anything blocking

#

its so fucking dumb

#

im gonna rewrite rq to use httpx

silver moat
#

if you use aiohttp, it would be better because it comes installed with py-cord

neon prairie
#

ok

silver moat
neon prairie
#

what the fuck...

#

this isnt meant for one liners

silver moat
#

And I'm fairly certain you can do

async with aiohttp.ClientSession() as session: # creates session
    async with session.get(url) as response: # gets image from url
        image = await response.read()
        with io.BytesIO(image) as file: # converts to file-like object for discord.File to take
            file=discord.File(file, "just_an_image.png")
neon prairie
#

okay I shouldve expected this

silver moat
#

you can one-line it

#

but like it looks stupid

neon prairie
#

this feels like it probably has so much overhead that requests is still faster

silver moat
#

requests just has the overhead internally

neon prairie
#

requests uses a c library

#

I think

silver moat
#

premature optimization?

neon prairie
#

lol yeah

silver moat
#

if you hate the nesting make a helper function or something

neon prairie
#

yeah its gonna nest alot, I get the links from another link which I get from another link..

neon prairie
#

I just typed a sentence so fast discord thought I was spamming

silver moat
heavy jungle
#

bot.topggpy = topgg.DBLClient(bot, toptoken, autopost=True, post_shard_count=True)
gives
TypeError: DBLClient.__init__() takes 2 positional arguments but 3 were given

#

i dont see why

neon prairie
#

when there are multiple files discord is for some reason ignoring their size

heavy jungle
heavy jungle
#

alright

silver moat
neon prairie
silver moat
#

see it's weird

#

kinda

#

idk discord thought it was a good feature to add

neon prairie
#

very

#

it makes my thing look ugly 😭

dense gorge
#

There's still no way to edit a message such that you remove the file attachment, right?

#

As I understand it, that's an API issue that Discord doesn't offer that feature? I know that was the case when I last made a bot that needed to do it in like 2021.

dense gorge
#

Real shit??

silver moat
#

you edit them with the attachments kwarg iirc

dense gorge
#

I tried file = None and file = discord.Missing--

#

But not file?

#

Aha.

silver moat
#

file is for uploading them

dense gorge
#

But only for uploading them. Roger roger.

silver moat
#

yah

dense gorge
# silver moat yah

Mmmnope. Turns out that attachments allows you to edit new files into the message as an upload, but not to delete them.

#

Tried every method in the book before buckling and checking the docs, and they confirm this.

silver moat
#

If [] is passed then all attachments are removed.

#

not sure what you're reading

dense gorge
#

Hold on, let me try that for myself and kick myself if I missed that.

#

Okay, wow. I'm sorry.

#

I misread the docs and forgot the most obvious form of passing in null into a list arg.

#

Thank you very much.

silver moat
#

yay

cinder pelican
#

I think I'm in the right place. I am attempting to create a form that would contain multiple kinds of components (so modals won't work)

Why can't you add InputTexts to a discord.ui.View? Is that a Discord limitation or a Pycord limitation?

silver moat
cinder pelican
#

Gotcha. There seems to be a lot of those.

Thank you very much

tribal girder
#

is self.add_item necessary when subclassing discord.ui.View? i don't see it in guide

proud mason
#

You would ideally use the decorator when subclassing

tribal girder
#

ok, if my view in different files, how do i use them?

proud mason
quiet field
#

I'm using bridge_command and I have a command that uses modals. The modal works when used with a / prefix but not with a regular prefix. When used with a regular prefix, it gives the following error

Traceback (most recent call last):
  File "C:\Users\amogh\Documents\GitHub\MiscBot\venv\Lib\site-packages\discord\ext\commands\core.py", line 178, in wrapped
    ret = await coro(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\amogh\Documents\GitHub\MiscBot\src\cogs\general.py", line 58, in qotd
    await ctx.send_modal(modal=ModalCreator())
          ^^^^^^^^^^^^^^
AttributeError: 'BridgeExtContext' object has no attribute 'send_modal'```
cyan quail
#

it has to be from an interaction

quiet field
#

Is there no workaround?

young bone
cyan quail
#

(tbf, why would you want to send a modal through prefix? making it slash means it pops up without any command output remaining in chat)

young bone
cyan quail
#

Pretty much

halcyon gorge
#

so I am trying to try and find a fast way to go through the documentation, is there a way for me to see the member variables and functions of an object quickly?

#

I am struggling to do so quickly via google

#

something like during an on_message(message) I can see what functions/members the message parameter has

full basin
#

Search directly the object?

young bone
#

discord.Message

full basin
#

Each object has the attributes and methods below

halcyon gorge
#

but I'm looking for something like this

full basin
#

You don't click the first

#

You click the one that has (Python class, ...)

vapid pumice
#

Is there anyway to extend a deffered interaction past 15 minutes when you know that a function will take 15+ to execute?

silver moat
vapid pumice
silver moat
#

yeah

vapid pumice
#

ohhhhhh

#

okiee I didn't know it worked that way! That makes sense...the webhook object is what times out

vapid pumice
# silver moat yeah

Thanks! Hope you've been well Squid <3
I've come a long way on my coding journey since joining here. Very thankful for you and other NCs around

silver moat
full basin
#

NC? stare_extreme

vapid pumice
full basin
#

Oh. Ic

wet coral
#

Is a message id always a fixed digit length like a user id (18)? I'm not sure what sql type I should use for a message id.

silver moat
#

this is how IDs are generated

#

I’ll suggest using a string

#

but it’s up to you

wet coral
#

so a simple bigint sql type should do the job?

#

unsigned ofc

#

I was just a bit confused because for use id's I'm simply using BIGINT(18)

#

oh i just read the number is just the display width.

cyan quail
#

discord uses string since it's the most reliable for compatability, we have it as int in python because it's convenient

#

if you're confident bigint is best for you then go for it

wet coral
#

well bigint is 8 bytes = 64 bits, so it should work.
But thanks for the help

quasi stratus
#

Hi everyone, i'm back with a quick question about the API.
When i look to some attributes like guild in discord.Message in on_message in sometimes equals to None. What causes this ?

wet coral
quasi stratus
#

Sorry i forgot to mention that some of the messages i got were in a guild not dm message

quasi stratus
# young bone Can you show your intents?
    intents = discord.Intents.none()
    intents.members = True
    intents.guilds = True
    intents.bans = True
    intents.emojis_and_stickers = True
    intents.webhooks = True
    intents.messages = True
    intents.message_content = True
    intents.reactions = True
    intents.auto_moderation_configuration = True
    intents.auto_moderation_execution = True```
quasi stratus
#

👌

#

Also, i don't know why but my on_user_update is not triggered

quasi stratus
young bone
wet coral
#

Whats the best way to interact with another component in the same view, from inside a component callback?

quasi stratus
simple canopy
#

Hi, is this intended for bridge command to return discord.User instead of discord.Member when using prefixed command specifically in this situation?

fervent cradle
#

hi, I changed the name of my function and yet it doesnt update on discord. why could this be?

long torrent
#

is there a bridge equivalent for bot_has_permissions, since using it in a bridge command doesnt seem to work.

proud mason
simple canopy
#

stable 2.4.1

proud mason
#

Hmm there was a minor update with options in bridge. Try using master branch

#

Not sure if it would affect this

simple canopy
#

using member: discord.Option(discord.Member)
gives error when trying to use prefixed command.
something "couldn't translate discord.Option"

simple canopy
proud mason
#

Also try member: discord.Member

simple canopy
#

oh yeah, master branch fails :p

#

ValueError: mutable default <class 'discord.utils._MissingSentinel'> for field name is not allowed: use default_factory

proud mason
#

Hmm yikes

#

Oh right there was an issue for it

#

Are you on 3.11?

simple canopy
#

yes

proud mason
#

Yea it just broke yesterday after a pr got merged

#

💀

simple canopy
#

member: discord.Member works, but there is no way to actually configure display settings of an option?

#

using syntax like this produces the same issue

#

removing decorator makes it work

proud mason
#

I think introducing a new bridge.Option would be the only way to successfully work every time

simple canopy
#

i guess there is an issue in bridge option translation implementation

#

yeah

proud mason
#

Monkey patching discord.Option is very janky

proud mason
simple canopy
#

that's unlucky

proud mason
simple canopy
#

well, that's okay enough, at least it works

#

been trying to fix this thing for friend

proud mason
#

If you want you can make a GitHub issue, so somebody can work on a better fix (eventually)

simple canopy
#

im lazy fuck 😔

proud mason
simple canopy
#

yeah, that's what the dude was doing

#

but it looks so fucking bad

#

💀

#

and the caching problems with the NoneType errors, duh

proud mason
#

Lol

proud mason
quasi stratus
#

my on_member_update works but not my on_userupdate

eternal wing
#

Is it normal that the member.display_name shows the username not the server or regular display name? This is happening for members who have changed to the new username system, works fine with the old usernames...

proud mason
quasi stratus
#

yeah

obtuse juncoBOT
#
member.name          -> username
member.global_name   -> global display name (global nick name)
member.nick          -> guild nick name
member.display_name  -> member.nick OR member.global_name OR member.name
proud mason
#

this is for master branch

eternal wing
#

I also was doing member.nick and member.name but those 2 returned "None"

mossy holly
#

Hey guys I have a small problem:
Sometimes when I restart my bot I have this error when launching a slash command (see screenshot); does someone know what could cause this ?

proud mason
#

there should be more text above this

mossy holly
#

I think it might be because either I restart the bot too fast (see the script below) or because the process doesn't get killed properly when I stop the bot (again see script + screenshots)

#!/bin/bash

# Script de gestion du bot (lancement, arrêt, etc.)

day=$(date +"%F")
timestamp=$(date +"%H_%M_%S")



start_bot() {
    # Création du dossier du jour s'il n'existe pas encore
    # (jour du lancement du bot)
    mkdir -p logs/$day

    echo "Lancement du bot..."
    nohup python3 -u argobot/main.py &> "logs/$day/nohup_$timestamp.out" &
    echo $! > pid

    # Pour accéder facilement au log courant
    rm logs/current.log > /tmp/trash
    ln -s $day/nohup_$timestamp.out logs/current.log
}


stop_bot() {
    kill -s 10 $(cat pid)
    sleep 0.1
    echo "Bot hors ligne"
}


if [ "$#" -lt "1" ]; then
    echo "Utilisation: $0 [start|stop|restart]"
    exit 1;
fi


if [ $1 = "start" ]; then
    start_bot
fi


if [ $1 = "stop" ]; then
    stop_bot
fi


if [ $1 = "restart" ]; then
    stop_bot
    sleep 0.25
    start_bot
fi


if [[ $1 =~ ^log.* ]]; then
    cat logs/current.log
fi

(I handle the SIGUSR signal (10) in my bot, calling bot.close() when receiving it)

proud mason
# mossy holly

show how you create the view in devArgoBot/argobot/cogs/general.py", line 40

mossy holly
#

I also tried this as my stop function to make sure all process are killed but I still have the error occasionnaly

stop_bot() {
    kill -s 10 $(cat pid)
    echo "Bot hors ligne"
    sleep 0.1

    while ps | grep $(cat pid);
    do 
        kill $(cat pid)
    done
}
#

With MenuRecherche being this

proud mason
#

hmm

mossy holly
#

(sorry it's in french, can translate if necessary)

proud mason
#

do you have a select menu with no options?

mossy holly
proud mason
#

ah this might be a race condition

#

are you making the view on ready? nope it is a cmd

quasi stratus
#

Maybe it's due to the CritereSelect or OperatorSelect ?

mossy holly
quasi stratus
#

In the init of MenuRecherche

proud mason
mossy holly
proud mason
#

because then you can override bot.start() or smth to load the static data

#

subclassing recommended

cyan quail
#

but if the view is initialized in the command, it shouldn't matter?

mossy holly
#

I already subclassed my bot so yeah bot.start() seems a good idea

proud mason
quasi stratus
#

You should check if the data is correctly loaded from your db

mossy holly
#

yep it seems like a good idea too, i'll try to load the static data before connecting the bot (it doesn't need the bot to do it) and make error handling 😄

mossy holly
cyan quail
#

...no?

proud mason
#

you would ideally do stuff like this

async def start(...):

  # your code

  await super().start(...)
#

thats it

mossy holly
#

Ok thanks (I was confused I completely forgot the bot.run lmao I wondered where was the start called)

mossy holly
spring hare
#

Is there any good guide to linked roles for pycord/discord.py?

#

Does pycord supports linked roles?

eternal wing
#

what is linked roles?

novel jay
#

I don't wanna resend soo uhh ^

cyan quail
#

uhhh there aren't any built in methods for memory checking

untold spoke
#

how do i report a bug of pycord ?

#

we can select 2 times the same values even if its in 2 differents view

quasi stratus
#

I guess by opening an issue request on the github

untold spoke
untold spoke
cyan quail
untold spoke
young bone
#

I also dont see the issue

cyan quail
#

that's a discord decision

untold spoke
cyan quail
#

it's the same select

untold spoke
#

nope its not

cyan quail
#

it literally is

untold spoke
#

but i really change the view so

spring hare
#

That's discord design choice

cyan quail
#

you forgot to update the message

#

you're already editing the embed, so just add view=...

untold spoke
# cyan quail you forgot to update the message
category_open.callback = self.category_open_callback
        view = discord.ui.View(category_open)
        await ctx.send(embed=embed, view=view)

    async def category_open_callback(self, interaction: discord.Interaction):
        embed = interaction.message.embeds[0]
        embed = discord.Embed(title="Tickets tools setups", description=embed.description,color=Couleur)
        await add_footer(embed)
        embed.add_field(name="Tickets open", value=selected_category.mention, inline=False)
        category_close = discord.ui.Select(
            select_type=discord.ComponentType.channel_select,
            channel_types=[discord.ChannelType.category],
        )
        category_close.callback = self.category_close_callback  
        view = discord.ui.View(category_close)
        await interaction.response.edit_message(embed=embed, view=view)

#

look

cyan quail
#

you created a new view, but did you ever actually send it?

untold spoke
#

last line

spring hare
#

As far as I know, discord or pycord don't update view if it's the same

untold spoke
#

the first is category_open

#

and the other category_close

spring hare
#

If your views have the same parameters

untold spoke
#

only with select so

spring hare
#

Try to change select menu name

untold spoke
#

this ? category_close

spring hare
#

yup

untold spoke
#

first is category_open then category_close

#

so its not the same

spring hare
untold spoke
spring hare
undone smelt
#

i have a local discord bot for my small community for friends. i'm itching to rewrite my bot but have been putting off until v3. The disclaimer text hasn't been changed in awhile, would you guys recommend not using v3 for this low-stakes bot?

spring hare
#

V3 is just not ready for public use. There is no reason rn to use v3 over v2

undone smelt
#

Thanks friend. While you're here, do you have a bot with cogs you'd like to show off? I'm curious how others structure their cog bots

spring hare
#

You mean folders or code?

undone smelt
#

all the above, a repo preferably

spring hare
#

I have a lot of internal abstract classes in my code, you will probably not understand 50% of my code

#

But I just use similar approach like in guide and examples

young bone
meager heron
#

When a guild appears in the bot's guild cache, does that mean the guild's members are also cached, or is there a chance they won't yet be?

spring hare
#

If you don't have members intents, you will not get guild's members

meager heron
#

I do have the intent. I'm talking about bot startup

#

I have some commands that rely on users having a certain role in a certain server

untold spoke
#

@spring hare i have try to change parameter like the placeholder but nothing change

spring hare
#

Try to change select type?

untold spoke
undone smelt
#

do you guys pin a specific version usually?

proud mason
#

i usually pin a minor version

#

like 2.4

#

so any patch update like 2.4.1, 2.4.2 etc come through

young bone
round rivet
#

I use ~= for versions and let dependabot update them

versed fern
#

How do I access the bot object inside of a modal callback?

silver moat
versed fern
#

thx

#

Actually, I wanted to use the bot object in order to access to error_webhook I initialized in on ready (self.errors_webhook=...). Thus, it's not part of the client object return by discord. How do I access the webhook as clean as possible inside the modal callback?

round rivet
#

uh

#

interaction.client.error_webhook?

versed fern
#

PyCharm thinks that interaction.client.error_webhook doesn't exist which is why I didn't run the bot 🤦‍♂️, but it somehow works haha

loud sail
#

hey, why does the bot only joins the channel and not play audio? i have ffmpeg installed and defined as the system environment varibale as well.

round rivet
#

try restarting your terminal

#

and make sure ffmpeg is on your path

loud sail
# loud sail

now works. I restarted my PC and reinstalled everything (including the current py-cord version).

meager heron
quasi stratus
#

I'm coming back with my question,

I have this event :

    @commands.Cog.listener()
    async def on_user_update(self, before: User, after: User):
        print(after.mutual_guilds)
        # etc...

But it's never triggered, i have set the members intent (my on_member_update works) can someone expalin to me why it's not working ? :/

proud mason
#

iirc, there can be a fix by making Interaction inherit from typing.Generic, and then passing your bot class while typehinting

silver moat
quasi stratus
#

I've been on this page countless times

silver moat
#

leaving guilds isn’t one of them?

quasi stratus
#

The print is just to check

#

I don't care about leaving/joining the guild

#

When i update my username etc... it's not triggered

silver moat
#

I don’t think it works properly with migrated users, yet

quasi stratus
#

Well, even before i migrated it wasn't working

#

I also tried to change my avatar

silver moat
#

perhaps wait until on_ready is fired?

quasi stratus
#

i can do command, and the on_member works. Just my on_user is never triggered

#

The bot is fully launched

silver moat
quasi stratus
#

yeah

silver moat
#

sorry I don’t know, then

quasi stratus
#

np

#

(happy birthday btw)

loud sail
#

hey, what's that called in py-cord?
that the bot first thinks before answering.

spring hare
#

defer?

quasi stratus
loud sail
#

ah, thanks 😄

livid wolf
#

How do you do this in an embed?
I don't think its append_field because it only takes one argument

quasi stratus
#

I would say it's simply a long description

#

Or a field without a name

topaz ruin
#

it uses this symbol "`"
`text`
text

livid wolf
#

But the listing part

topaz ruin
#

you mean like getting all the links into the embed?

livid wolf
#

No. So I'm working on a command that lists the user's roles.
In that screenshot, how would I do that? Listing the roles?

#

As an embed

#

I do have an idea, let me try that

topaz ruin
#

use

  rolelist = [r.mention for r in ctx.user.roles if r != ctx.guild.default_role]
  roles = "\n".join(rolelist)
#(https://stackoverflow.com/questions/62386397/discord-py-list-the-users-roles)

to get the roles
then to send them as an embed

  embed = discord.Embed(title="Your title", description=roles)
  await ctx.respond(embed=embed)
topaz ruin
#

indeed

young bone
#

basic python ;3

livid wolf
#

I did not think of that, thanks.

#

It works :D

topaz ruin
#

nice

copper flicker
#

I try to create a channel with certain rights, but I get an error.

        user_id = interaction.user.id
        print(user_id) # here user_id equals the real id
        overwrites = {
            guild.default_role: discord.PermissionOverwrite(read_messages=False),
            guild.me: discord.PermissionOverwrite(read_messages=True),
            guild.get_role(1114861309033467914): discord.PermissionOverwrite(read_messages=True),
            guild.get_member(user_id): discord.PermissionOverwrite(read_messages=True)
        }
        print(user_id) # here user_id is None```
error :
```py
TypeError: get_member() got an unexpected keyword argument 'id'```
#

How can I fix it?

silver moat
spring hare
#

Just use get_member(id)

meager heron
#

One of the servers my bot is on appears to be cursed. For some reason, after a few weeks of being on this server, I start to get the following error when a slash command is used:

File "/opt/venv/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped
ret = await coro(arg)

File "/opt/venv/lib/python3.10/site-packages/discord/commands/core.py", line 1312, in _invoke
await command.invoke(ctx)

File "/opt/venv/lib/python3.10/site-packages/discord/commands/core.py", line 372, in invoke
await self.prepare(ctx)

File "/opt/venv/lib/python3.10/site-packages/discord/commands/core.py", line 292, in prepare
if not await self.can_run(ctx):

File "/opt/venv/lib/python3.10/site-packages/discord/commands/core.py", line 400, in can_run
return await async_all(predicate(ctx) for predicate in predicates) # type: ignore

File "/opt/venv/lib/python3.10/site-packages/discord/utils.py", line 699, in async_all
for elem in gen:

File "/opt/venv/lib/python3.10/site-packages/discord/commands/core.py", line 400, in <genexpr>
return await async_all(predicate(ctx) for predicate in predicates) # type: ignore

File "/opt/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 2129, in predicate
permissions = ctx.channel.permissions_for(ctx.author) # type: ignore

AttributeError: 'PartialMessageable' object has no attribute 'permissions_for'

Why is it suddenly getting a PartialMessageable instead of a channel?

#

(I don't know exactly which line in my code is causing the error; this is the entiretly of the error message in my logs)

quasi stratus
#

Hi, i have another unknown issue.
I'm gathering all my errors but when my cog_check is returning False it does get handled :

    @commands.Cog.listener()
    async def on_application_command_error(self, ctx: ApplicationContext, error: DiscordException):
        if isinstance(error, Forbidden):
          pass
        elif isinstance(error, CheckFailure): # Should pass here right ?
            await ctx.respond("You didn't match the command checks") 
        else:
            await ctx.respond("Unknown error occured")```
#

But it goes to the else statement

honest spoke
meager heron
honest spoke
#

hmmmmmmmm

meager heron
#

The error seems to be in the core library, too

honest spoke
meager heron
#

I know that if the server removes and re-invites the bot, it works again

honest spoke
#

Im suggesting u to debug the libarry
Set a breakpoint at discord/interactions.py line 267 and look what if guild is None or if the code is hitting the if statment for some reason.
Or the channel is simply not cached

honest spoke
#

Then you can check channel and guild

meager heron
#

I think this will be very difficult to debug, unfortunately. I’m not on the server, and as I said, it works fine for a number of weeks

#

I do appreciate the suggestion, however

silver moat
#

what type is the error anyways

meager heron
#

AttributeError, if you’re asking me

silver moat
#

no, I was referring to @quasi stratus.

#

@meager heron @quasi stratus perhaps make a new forum post for each of your issues?

quasi stratus
#

Well, because it was a minor one i was not thinking of opening a new thread

#

But i'll see

honest spoke
quasi stratus
#

I'll check it

quasi stratus
silver moat
#

could you do something along the lines of print(type(error))

quasi stratus
#

I did a __repr__() so the type is checkFailure as you can see

honest spoke
#

Do you have by any chance pycord and a other dicord.py like lib installed ?
Could be that you take the wrong namespace

#

could you show pip list ?

quasi stratus
#

I checked the namespace and i only have pycord 2.4.1

honest spoke
silver moat
#

which CheckError are you using, discord.CheckError or commands.CheckError?

quasi stratus
#

commands

silver moat
#

yeah you're supposed to use the discord one

#

for slash commands, right?

quasi stratus
#

Ho okey

#

Yeah

#

I see the error

#

Yeah working better

#

Thanks ❤️

silver moat
#

yay

quasi stratus
#

Alright, one strange error down. Still need to figure out my user_update one x)

frank thistle
#

Does Pycord allow you to use these new global display names

silver moat
frank thistle
#

hmm ok ill have a look

#

hopefully be in main / stable soon

meager heron
silver moat
warm grotto
#

Is there a particular way to rename channels a lot faster? Everything seems to be running smoothly except for renaming a channel, which takes 6 minutes for some odd reason

silver moat
warm grotto
# silver moat ratelimits exist. Also stop using bare-excepts

Right, but the ones after the channel naming (changing overwrites and position) were running fast. I just had to separate them into three separate commands as shown above to debug what was taking the longest to edit the channel. In my code, I did:py try: await message.channel.edit(name=channelname,overwrites=Overwrites,position=len(message.channel.category.channels)) except Exception as e: print(e)There wasn't any other await functions other than:

  • fetching a message from the channel
  • editing a message from the channel
  • sending a message in a separate channel
round rivet
#

the rate limit for channel name/topic changes is 2 per 10 minutes

#

also why are you doing 3 different edits

#

you can do 1

warm grotto
#

Again, had to make 3 different edits just so I can debug what was taking the longest

silver moat
warm grotto
round rivet
#

the rate limit for channel name/topic changes is 2 per 10 minutes

silver moat
#

hey plun, where do you get these figures or do you just know them

round rivet
#

they were announced in ddevs when they were changed

silver moat
#

is there a list of each individual thing's ratelimits

round rivet
#

no

warm grotto
#

And is that per channel, per guild, or per application?

round rivet
#

per channel

silver moat
#

and per ip

warm grotto
#

Dang, that rate limit is... pretty strict. I guess its just a matter of finding an alternative way to indicate when a ticket has been assigned to an agent

earnest widget
#

does on_command_error also apply to slash commands?

silver moat
earnest widget
#

ty

earnest widget
#

oh yeah and what was the attribute to make it so that after u choose an option in dropdown it resets back to nothing

long moat
#

ValueError: mutable default <class 'discord.utils._MissingSentinel'> for field name is not allowed: use default_factory

has a fix been found for this?

#

using global_name gives this ^

proud mason
long moat
proud mason
#

lul

dapper flare
#

TypeError: issubclass() arg 1 must be a class can anyone help me with this?

#

full error

proud mason
#

discord.Option O uppercase

dapper flare
#

ohh

#

seems working thx

proud mason
#

nice

loud sail
#

hey, why isn't the message here ephemeral?

        if ctx.voice_client is None:
            await ctx.defer()
            await asyncio.sleep(2)
            return await ctx.respond("Ich bin mit keinem Sprachkanal verbunden.", ephemeral=True)
cyan quail
tribal girder
#

is there a event listener when the bot is going to offline? like when a vps is down, i can close a background process

cyan quail
loud sail
loud sail
#

hey, i always had this as a last restart in my code in discord.js, how can i do something like this in py-cord?

 const starttime = `<t:${Math.floor(interaction.client.readyAt / 1000)}` + (style ? `:${style}` : '') + '>'
#

since when the bot is online just ...

meager heron
#

You can get the time in on_ready

proud mason
proud mason
rare ice
#

I'm getting this error when I have these children in a modal (that sounds weird)

  File "/home/container/.local/lib/python3.9/site-packages/discord/ui/view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "/home/container/cogs/economyv2.py", line 63, in set_desc_callback
    await interaction.response.send_modal(modal)
  File "/home/container/.local/lib/python3.9/site-packages/discord/interactions.py", line 1056, in send_modal
    await self._locked_response(
  File "/home/container/.local/lib/python3.9/site-packages/discord/interactions.py", line 1090, in _locked_response
    await coro
  File "/home/container/.local/lib/python3.9/site-packages/discord/webhook/async_.py", line 221, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.1: The specified component exceeds the maximum width
In data.components.0.components.2: The specified component exceeds the maximum width
In data.components.0.components.3: The specified component exceeds the maximum width
In data.components.0.components.4: The specified component exceeds the maximum width
children=[discord.ui.InputText(label="Starting Amount", style=discord.InputTextStyle.short, placeholder="Starting amount of coins", max_length=5, min_length=1, value=economy_data['settings']['starting_amount']), discord.ui.InputText(label="Currency Name", style=discord.InputTextStyle.short, value=economy_data['settings']['currency_name']), discord.ui.InputText(label="Currency Emoji", style=discord.InputTextStyle.short, max_length=2, value=economy_data['settings']['currency_emoji']), discord.ui.InputText(label="Robbing?", style=discord.InputTextStyle.short, placeholder="'Yes' or 'No'", max_length=3, min_length=2, value=("Yes" if economy_data['settings']['robbing'] == True else "No")), discord.ui.InputText(label="Maximum Payout", max_length=5, min_length=1)]
spring hare
rare ice
#

ill check

rare ice
spring hare
rare ice
#

oh the max is 5?

#

i thought it was 6 :/

spring hare
#

yup

#

Exactly 5

rare ice
#

mb

#

wait no?

#
In data.components.0.components.1: The specified component exceeds the maximum width
In data.components.0.components.2: The specified component exceeds the maximum width
In data.components.0.components.3: The specified component exceeds the maximum width```
rare ice
hoary plover
#

Hi

rare ice
#

In data.components.0.components.4: The specified component exceeds the maximum width

hoary plover
#

How yall going

rare ice
#

#general

#

this is your only verbal warning

#

this channel is for help only

hoary plover
#

Alr sorry pls dont warn me

full basin
rare ice
#

yeah

hoary plover
#

I need to stop running my bot if my bot in render but since it is running 2 times i have a doubt . Can i use try except block for client.run(token) except if the client is already logged

#

Except if it already on ready

hoary plover
rare ice
#

why are you pinging for help

#

because im in this channel doesn't mean i have to help you

hoary plover
#

Oh sorry

full basin
#

@rare ice have you tried removing one input

rare ice
#

yes

full basin
#

Same error?

rare ice
#

i also tried removing the value

hoary plover
#

Btw in disxord.py there is a thing called command.has permissions can i use it in pycord too. Because i have error with that

silver moat
#

label/placeholder could be too long?

rare ice
#

.rtfm commands.has_permissions

winter condorBOT
hoary plover
#

I need to stop running my bot if my bot in render but since it is running 2 times i have a doubt . Can i use try except block for client.run(token) except if the client is already logged

full basin
#

It's just 1 - 3 words

hoary plover
rare ice
hoary plover
#

Anyone pls answer my qn. Im new to coding and programming

full basin
#

Girl

hoary plover
#

I need to stop running my bot if my bot in render but since it is running 2 times i have a doubt . Can i use try except block for client.run(token) except if the client is already logged

full basin
#

Take a chill pill

rare ice
#

stop spamming your question

full basin
#

Stop posting it over and over again

hoary plover
#

Im sorry but i didnt get ans so

hoary plover
waxen whale
#

-mute 920850442425102367 4h gives chill pill

wanton pondBOT
#

🔇 Muted Haruki#8003 for 4 hours

rare ice
#

damn children on discord

#

no maturity

full basin
waxen whale
#

just mute them next time w/o warning

#

they need to learn patience or to go

topaz ruin
#

is it possible to have separate descriptions for sub commands?
like each command would have it's own description

rare ice
#

agreed

waxen whale
#

but imma change that to a timeout now

scenic raven
#

Hi! My bot has a command that sends message to the channel to the command was invoked in. Is there a way to check if the bot has permission to send messages in that channel before trying, or should I just catch discord.Forbidden?

waxen whale
#

-unmute 920850442425102367 switch to timeout 1h

wanton pondBOT
#

🔊 Unmuted Haruki#8003

waxen whale
full basin
copper pine
#

My bot uses Bridge Commands and the bot logs the use of the commands, but only logs when it is executed as slash command :/

full basin
#

.rtfm discord.Channel

scenic raven
topaz ruin
#

*when i run the command

waxen whale
#

@full basin @rare ice

#

:)

#

my hammer is warming up

waxen whale
full basin
#

"To make sure they notice it" girl thinks we're blind or somethin

waxen whale
#

do we have a

#

-tempban

#

no sad

#

And both timeout and mute 4h is same for me. Im gonna slep now so no difference

#

well then

rare ice
#

hm

rare ice
waxen whale
wanton pondBOT
#

🔨 Banned Haruki#8003 indefinitely

rare ice
#

they are definitely under 13

#

or a very immature 13 yr old

waxen whale
#

ye

#

they're also on beluga

rare ice
#

so yeah they are under 13

#

if they act like beluga

waxen whale
#

imma look in their logs. i bet they are logged somewhere

rare ice
#

:/

waxen whale
#
  • 23 filtered
#

very immature

rare ice
#

discord moment

#

the first option's label is longer than the second and it is throwing an error on the second

#

when i remove the first option the 2nd option works yikes

#

both options work when I remove one of them

full basin
copper pine
waxen whale
full basin
#

The function name says it all lmao

#

It only runs on application commands

#

on_command is for normal commands

waxen whale
rare ice
#

how do I do another action row?

copper pine
waxen whale
#

imma look rq what we do internally

#

thats weird

rare ice
#

this is my BasicModal class

class BasicModal(discord.ui.Modal):
  def __init__(self, title: str, children: list):
    super().__init__(title=title)
    for c in children:
      self.add_item(c)
    self.interaction = None
    self.response = None
  async def callback(self, interaction):
    self.interaction = interaction
    self.response = self.children
    self.stop()```
am i doing it wrong to where it wont do action rows?
waxen whale
#

hmm it shoud do it correctly

#

weird..

proud mason
#

Those will get fired for both, slash version and prefix version

proud mason
#

Not sure about placeholder

rare ice
#

its not longer

proud mason
#

Hm

#

Try adding 1 input field at a time, that too with 1 by 1 parameter addition

rare ice
#

i did

#

lala is testing it

proud mason
#

O

waxen whale
#

om the problem is that the payload is incorrect

#

to_dict internally produces

#

and thats not intented

rare ice
#
``` with rows manually defined for each child
waxen whale
#

thats still totally wrong

rare ice
#

modal = BasicModal(title="Economy: General Settings", children=[discord.ui.InputText(label="Starting Amount", style=discord.InputTextStyle.short, placeholder="Starting amount of coins", max_length=5, min_length=1, value=economy_data['settings']['starting_amount'], row=0), discord.ui.InputText(label="Currency Name", style=discord.InputTextStyle.short, value=economy_data['settings']['currency_name'], row=1), discord.ui.InputText(label="Currency Emoji", style=discord.InputTextStyle.short, max_length=2, value=economy_data['settings']['currency_emoji'], row=2), discord.ui.InputText(label="Robbing?", style=discord.InputTextStyle.short, placeholder="'Yes' or 'No'", max_length=3, min_length=2, value=("Yes" if economy_data['settings']['robbing'] == True else "No"), row=3), discord.ui.InputText(label="Maximum Payout", max_length=5, min_length=1, row=4)])

waxen whale
#

i think we have a bug here

rare ice
#

o

proud mason
waxen whale
#

each components needs an own row

#
{
   "title":"Economy: General Settings",
   "custom_id":"d8510e99078d5da3167ce97ddc767134",
   "components":[
      {
         "type":1,
         "components":[
            {
               "type":4,
               "style":1,
               "label":"Starting Amount",
               "custom_id":"8956171120bad39c8e28117bdd09dd2d",
               "placeholder":"Starting amount of coins",
               "min_length":1,
               "max_length":5,
               "value":100
            }
      }, ..
   ]
}
#
    def to_dict(self):
        return {
            "title": self.title,
            "custom_id": self.custom_id,
            "components": self.to_components(),
        }

    def to_components(self) -> list[dict[str, Any]]:
        def key(item: InputText) -> int:
            return item._rendered_row or 0

        children = sorted(self._children, key=key)
        components: list[dict[str, Any]] = []
        for _, group in groupby(children, key=key):
            children = [item.to_component_dict() for item in group]
            if not children:
                continue

            components.append(
                {
                    "type": 1,
                    "components": children,
                }
            )

        return components

no clue why this does not work

proud mason
waxen whale
#

yes

proud mason
#

Ah ok

#

Wait then why tf is the inner components a list??

#

Discord™️ ?

waxen whale
#

i.e.

#
{
    "components": [
        {
            "type": 1,
            "components": [
                {
                    "type": 4
                    //..
                }
            ]
        },
        {
            "type": 1,
            "components": [
                {
                    "type": 4
                    //..
                }
            ]
        },
        {
            "type": 1,
            "components": [
                {
                    "type": 4
                    //..
                }
            ]
        }
    ]
}
#

bcs in message components you can have multiple components in a row

#

but modals = 1 row per item

proud mason
#

Ah bruh so they shared the same base platform for views and modals

waxen whale
#

yes

#

and if anyone asks why i'm here without doing python: i don't need to know python to find the shit

rare ice
#

is it a discord bug?

#

wouldn't be suprised

waxen whale
#

no pycord bug

rare ice
#

ah

proud mason
#

weird how this went unnoticed until now??

waxen whale
#

yeah............

#

i wonder why

#

here's the buggy line

#

or better said function

#

for child in children append to components within new row and return components

#

the fix ^

spring hare
#

All of that time, modals were bugged? doggokek

waxen whale
#

yep

spring hare
#

How this went unnoticed? lmao
I built an entire bot around modals and never had any problems doggokek

waxen whale
#

idfk

meager heron
#

I've also never encountered it, and I use a lot of modals

spring hare
#

lmao

rare ice
waxen whale
#

u not

rare ice
#

:/

waxen whale
#

pycord needs to fix it

rare ice
#

k

waxen whale
cyan quail
#

oh no

waxen whale
#

oh yes

waxen whale
#

start

cyan quail
# waxen whale .

so specifically to_components is broken...? im struggling to understand

#

like others have said we haven't noticed this at all LOL

waxen whale
#

ya

#

it should wrap every text input in a seperate row

cyan quail
#

ah

cyan quail
# waxen whale it should wrap every text input in a seperate row

can't repro the error ```json
{
"title":"wow",
"custom_id":"ccea69df58ed5a9a38909d8ea9a6eeb8",
"components":[
{
"type":1,
"components":[
{
"type":4,
"style":1,
"label":"Why?",
"custom_id":"bcb707311a4194cdd55bcb7bcf54b27c"
}
]
},
{
"type":1,
"components":[
{
"type":4,
"style":1,
"label":"Why?",
"custom_id":"8f7861daf245ab8d2857b7e8ec7c5573"
}
]
},
{
"type":1,
"components":[
{
"type":4,
"style":1,
"label":"Why?",
"custom_id":"8db31db2a76d1bb3d6266e9a1eb3c4ee"
}
]
},
{
"type":1,
"components":[
{
"type":4,
"style":1,
"label":"Why?",
"custom_id":"d9bb65fb12e97317d0339630af213ea6"
}
]
},
{
"type":1,
"components":[
{
"type":4,
"style":1,
"label":"Why?",
"custom_id":"1ac9eeec74a9930b99e12399673458f0"
}
]
}
]
}

waxen whale
#

tf

cyan quail
#

everything already seems fine... but that being said, I do recognise that error with modals from some weeks ago

#

but idk how it happens

waxen whale
#

@rare ice

#

which version

rare ice
#

2.4.1 i think

cyan quail
#

both master and 2.4.x seem fine to me

waxen whale
#

hmm

cyan quail
#

ik it's possible but there seems to be some other trigger

waxen whale
#

confusing af

rare ice
#

yeah 2.4.1

waxen whale
#

so it might be your code or pycord doin some weird race condition

rare ice
#

i doubt its my code

#

everything seems logical

#

its a simple subclass

rare ice
cinder pelican
#

There's no way to get a selector into a embed, correct? Or am I missing something?

(Edit: misspoke)

cinder pelican
spring hare
#

No
You can't really change position of your ui components
They are always under your message, and you can only change their position with other elements (rows/pos)

cinder pelican
cyan quail
# rare ice i doubt its my code

just in case, can you give me full sample code that would reproduce this (as you would on github)? i tried with your class above and it still worked fine

rare ice
#

bruh even this doesn't work, same errors

class GeneralSettingsModal(discord.ui.Modal):
  def __init__(self, bot, economy_data: dict):
    self.bot = bot
    self.economy_data = economy_data
    self.response = None
    self.interaction = None
    super().__init__(title="Economy: General Settings")
    self.children=[discord.ui.InputText(label="Starting Amount", style=discord.InputTextStyle.short, placeholder="Starting amount of coins", max_length=5, min_length=1, value=economy_data['settings']['starting_amount'], row=0), discord.ui.InputText(label="Currency Name", style=discord.InputTextStyle.short, value=economy_data['settings']['currency_name'], row=1), discord.ui.InputText(label="Currency Emoji", style=discord.InputTextStyle.short, max_length=2, value=economy_data['settings']['currency_emoji'], row=2), discord.ui.InputText(label="Robbing?", style=discord.InputTextStyle.short, placeholder="'Yes' or 'No'", max_length=3, min_length=2, value=("Yes" if economy_data['settings']['robbing'] == True else "No"), row=3), discord.ui.InputText(label="Maximum Payout", max_length=5, min_length=1, row=4)]
  async def callback(self, interaction):
    self.response = self.children
    self.interaction = interaction
    self.stop()```
#

@cyan quail even that doesn't work

cyan quail
# rare ice bruh even this doesn't work, same errors ```py class GeneralSettingsModal(discor...

this breaks it with your exact error because you shouldn't assign children directly.
using add_item has consistently worked for me without breaking ```py
class BasicModal(discord.ui.Modal):
def init(self, title: str, children: list):
super().init(title=title)
for c in children:
self.add_item(c)
self.interaction = None
self.response = None

async def callback(self, interaction):
    self.interaction = interaction
    self.response = self.children
    self.stop()

economy_data = {
"settings": {
"starting_amount": "1",
"currency_name": "nice",
"currency_emoji": "..",
"robbing": True
}
}

class Example(commands.Cog):
def init(self, bot):
self.bot = bot

@commands.command()
async def modal(self, ctx):
    modal = BasicModal(
        title="Economy: General Settings", 
        children=[
            discord.ui.InputText(label="Starting Amount", style=discord.InputTextStyle.short, placeholder="Starting amount of coins", max_length=5, min_length=1, value=economy_data['settings']['starting_amount']),
            discord.ui.InputText(label="Currency Name", style=discord.InputTextStyle.short, value=economy_data['settings']['currency_name']),
            discord.ui.InputText(label="Currency Emoji", style=discord.InputTextStyle.short, max_length=15, value=economy_data['settings']['currency_emoji']),
            discord.ui.InputText(label="Robbing?", style=discord.InputTextStyle.short, placeholder="'Yes' or 'No'", max_length=3, min_length=2, value=("Yes" if economy_data['settings']['robbing'] == True else "No")),
            discord.ui.InputText(label="Maximum Payout", max_length=5, min_length=1)]
    )
    
    b = Button(label="Modal 1", custom_id="1")
    v = View(b, timeout=None)
    async def d(i):
        await i.response.send_modal(modal)
    b.callback = d
    await ctx.send(view=v)