#Basic Pycord Help (Quick Questions Only)

1 messages · Page 30 of 1

round rivet
#

Yeah

full basin
#

Ok that's awesome. Thank you.

fervent cradle
#

cant even use pycord in ohio

young bone
#

!tag install

civic jayBOT
#

Install pycord:

pip uninstall discord.py
pip install py-cord

Install pycord from git repository: (alpha)

pip uninstall discord.py
pip install git+https://github.com/Pycord-Development/pycord
fervent cradle
rare ice
rugged lantern
#

so cute

loud holly
#

is there a problem with install master branch on python 3.11? I seem to be getting the error that C++ 14.0 is required, but I'm not using VS

rugged lantern
loud holly
#

is it bc of python using C++ to compile into bytes? If I'm using the correct terminology?

rugged lantern
lost geyser
#

I got a quick question: If i work with files, does it make a signifcant improvement if i open them with a library like aiofiles? Or could i just read files normally without asynchronous execution.

silver moat
lost geyser
#

Yeah my file is neither big nor should it happen, that several users need to open it. But i try, thanks!

loud holly
#

will displaying if the variable is int, string or list help in performance since during compiling, python itself will decide the variable type?

uneven beacon
#

anyone knows how to fix this error?

hushed ledge
#

One message removed from a suspended account.

errant craneBOT
#

Here's the slash cog example.

loud holly
#

I believe that is the one you're looking for

#

@hushed ledge ^

hushed ledge
#

One message removed from a suspended account.

iron halo
#
    embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.display_avatar)
AttributeError: 'NoneType' object has no attribute 'id'```
how has this happened
cyan quail
#

you won't see any performance gains unless you seek out a compiler that specifically takes advantage of them

loud holly
#

I see, so is it best practice to go into enforcing typehinting where possible?

cyan quail
#

typehinting is nice for code readability/making your ide happy and is part of the many PEP guidelines so people do encourage its use

#

thus you could consider it good practice, but it's not going to impact the code itself

loud holly
#

:( Was hoping it'd help in performance a tiny bit

cyan quail
#

ultimately i guess try it out and see if you like it, i pretty much never bothered typehinting but i tried it on a recent cog i worked on and it did look pretty nice in the end

#

if you're working in an IDE/using stuff like copilot there's also a chance it can complete the typehints for you so it's not much extra work

loud holly
#

It'd be very good practice especially when learning languages that requires typehinting

#

Thank you!

cyan quail
#

allgood

uneven beacon
cyan quail
#

probably because there's like zero context there

#

you should be getting a full traceback

white wadi
#

Hi, im having problems with timeouts, self.disable_all_items() does nothing to the view so i tried this:

        async def on_timeout(self):
            for child in self.children:
                child.disabled = True
            await self.message.edit(content="You took too long! You have to send another command to continue :(.",
                                    view=self)

This works when the view is called in the slash command, but not in interaction or followup, there it just says that NoneType obj has no attribute edit:

Task exception was never retrieved
future: <Task finished name='discord-ui-view-timeout-17f7431f32310f4a8587cda87b378011' coro=<view.answer_mode.on_timeout() done, defined at /opt/bot/cogs/test.py:179> exception=AttributeError("'NoneType' object has no attribute 'edit'")>
Traceback (most recent call last):
  File "/opt/opt/bot/cogs/test.py", line 183, in on_timeout
    await self.message.edit(content="You took too long! You have to send another command to continue :(.",
AttributeError: 'NoneType' object has no attribute 'edit'

cyan quail
#

pycord version?

uneven beacon
#

thats the thing
i have no idea whats causing the error

cyan quail
white wadi
cyan quail
#

if im not mistaken the view.message implementation is still incomplete

#

hmm

#

there are a few ways around it i guess

white wadi
#

i tried the simple self.diable_all_items(), but same results, only works when in slash command

cyan quail
#

if it's the first ctx.respond or interaction.response.send_message, you can do view.interaction = await ctx.respond(...), then view.interaction.edit_original_response
if it's a subsequent ctx.respond or interaction.followup.send, you can do view.message = await ctx.respond(...) then view.message.edit

white wadi
cyan quail
#

but depending on when you send the view, you might get an interaction object; if that happens then you change the edit method

white wadi
#

i am sending the view on interaction (clicking button or select something in the select menu)

cyan quail
#

so in your button's callback you're doing something like await interaction.response.send_message i presume?

white wadi
#

i am sending a follow up message, but thats similar

#

i need the interaction to edit the first message

cyan quail
#

you defer first?

#

hmmm

white wadi
#

first i use response to disable the view in the first message,
then i use follow up to send another message with another view

#

and the view used with the follow has the problem with timeouts not working well

white wadi
pure jetty
#

Hey y’all, probably a dumb question: I’m attempting to use the change_presence method to assign a rich presence to my bot based on what it’s currently doing (aware this is global, but it’s a private bot) and as far as I’m aware everything is done per the docs, but for whatever reason all it ever does is update the name of the Activity, all other fields (assets, timestamps, etc) appear to be ignored. Are rich presences including images and time elapsed supported by (a) bots and (b) pycord?

#

I can throw in the code if needed.

cyan quail
pure jetty
#

Okay, was getting to that conclusion, so they seem to be limited to just name and description, right?

cyan quail
#

yeah just the standard statuses

#

you can do stuff like watching/listening/streaming but that's it

pure jetty
#

Okay sweet, thank you! Was wasting a lot of time on it and figured it probably works for normal users.

white wadi
proud mason
#

convert into int first and then add 1

#

number2 = int(number + 1)

#

you are adding 1 to number and then converting to int

#

but number is a string and + is acting as the concatenation operator

#

see the brackets

#

int(number) + 1 should convert number to an integer and then add 1 to it

#

yeah

rugged lantern
#

??

#

just use +=

#

every time i open this channel

#

i always see someone

#

asking for the most basic help

lethal hare
#

Is there a way to add options to a select menu based on who executed the command?

#

I made a thread for this, but if there is some kind of quick documentation available or something I figured I could ask here

meager mica
lethal hare
#
costumeView = discord.ui.View()

    if len(user_closet['paints']) != 0:
        paintSelect = discord.ui.Select(placeholder="Pick your Lackey's color", min_values=1, max_values=1, disabled=False)

        paintSelect.add_option(label="Black", value="black")
        for item in user_closet['paints']:
            paintSelect.add_option(label=item.capitalize(), value=item)
        costumeView.add_item(paintSelect)
meager mica
#

hey guys i was wondering what react messages permission name is i cant spell it good enuph to find it in docs facepalm

#

wait i found in source code lol

floral leaf
#

Anyone can help me so I can use on_interaction and slash commands created with @bot.slash_command()

silver moat
floral leaf
#

So I just have to put this single line in on_interaction and everything after this Code line works and my slash commands too? And thank you

lethal hare
#

My desired flow for this command is this: >User executes command --> They are presented with an ephemeral menu to select certain things, which is deleted upon completion --> based on those selections, the bot responds to the original message with a result non-ephemerally.

My issue right now is that when I use ctx.respond and the selection menu is deleted, the response message says "The message was deleted", as it is responding to the previous message and not the original command

Any way I can fix this?

full basin
lethal hare
# full basin Without relevant code, can't help.
   async def doneCallback(interaction):
        with BytesIO() as image_binary:
            generateLackey(ctx.author.id, lackeyChoices).save(image_binary, 'PNG')
            image_binary.seek(0)
            await interaction.response.defer()
            await ctx.respond(file=discord.File(fp=image_binary, filename=f'{ctx.author.id}s_lackey.png'))

    doneButton = discord.ui.Button(style=discord.ButtonStyle.primary, label="Done!")
    doneButton.callback = doneCallback
    costumeView.add_item(doneButton)

    await ctx.respond(content="Enter details", view=costumeView, ephemeral=True)

This is about as much as I can minimize without sending the entire thing

full basin
#

Why are you using ctx.respond inside a View callback

lethal hare
#

Which this obviously doesnt do, what SHOULD I be using in the view callback?

full basin
#

Im confused cause you have no ctx in a view callback

#

You only receive interaction

#

So you be responding to interactions with interaction.response.send_message

#

What you want to do is edit the original message

lethal hare
full basin
#

So it should be interaction.response.edit_message

lethal hare
lethal hare
lethal hare
#

hence why im stuck

#

Is this not possible

full basin
#

You must send a second respond or just don't make it ephemeral at all n

#

There's no other option

lethal hare
#

I dont want to reply to the ephemeral menu, because other users cannot see that

full basin
#

If you don't want the reply thingy

#

You'd just send a normal message. But you must pong the interaction

#

Or it'll "fail"

lethal hare
# full basin .

To other users though it will say "This message is unavailable" instead of "Libra used /command" because that first response was ephemeral

full basin
#

Yes

#

Refer to above messages

lethal hare
#

So just to confirm: Having a second interaction respond to the original command once the first response was deleted is not possible

full basin
#

You can send a second response. It just doesn't fit your needs or having it display "Libra used /command"

#

Just don't make the first response ephemeral

lethal hare
#

The first response is a menu I dont want others that did not use the command interacting with while the user that issued the command is doing so

#

This seems like it would be a common usecase, that or I am thinking about this completely wrong, which is probably the case. lol

full basin
#

You can run internal checks to prevent that

lethal hare
#

Ah I see

full basin
#

You just run a quick check before doing all the callback

loud holly
#

or is it only for classes

full basin
#

Or override on_interaction and run the check there to prevent the callback from being called

lethal hare
#

which is another reason that menu is ephemeral

#

Users with more access will have more options

loud holly
#

I see right

lethal hare
#

Im just going to edit the original menu and leave it ephemeral

#

unfortunate though, wouldve been neat

loud holly
#

is this a select or button object?

#

nvm it says button

lethal hare
#

Yep thats the "submit" button

#

Takes all the data from several submits and sends them to the generation function to send

loud holly
#

can you send in the costumeView as well pls

lethal hare
#

I know this likely isnt the best way to do this, but I was having trouble using selections generated per-user like this

#

open to suggestions

loud holly
#

I presume you don't know much about classes?

lethal hare
lethal hare
loud holly
#

it's a bit difficult to like follow the code especially without classes, but if you want all ur messages sent to be ephemeral, you can do that easily with classes

you can use the

interaction.response # once and then it is 

interaction.followup.send # same like the above and can be used ephemerally
lethal hare
loud holly
#

you can compare it in the __init__ and create the object using self

lethal hare
#

ah okay

#

i’ll give that a shot

loud holly
#

def __init__(....)

  if self.user == "":
    self.add_view(Select(...)
  else: 
      ....
lethal hare
rugged lantern
#

lil bro needs to learn what a decorator actually does

lethal hare
#

great commentary norman

#

thanks for the help @loud holly i’ll figure out how to write this the right way

subtle jay
#

Can bots go live/share screen?

silver moat
subtle jay
#

thanks for responding though

silver moat
#

ok

deft sandal
#

I feel dumb but I want to save an attachment to a specific file:

#

this doesnt work cause I need an "os.pathlike" object?

#

how would I convert the string I currently have to os.path?

patent escarp
#

How do I record audio in a voice channel?

#

https://github.com/Pycord-Development/pycord/blob/master/examples/audio_recording.py
I'm aware this exists, but I'm getting errors like:
OpusNotLoaded
So then I add py import discord discord.opus._load_default() #or discord.opus.load_opus() to the code, and get one of two results: py Required Positional Argument: name OpusNotLoaded

GitHub

Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/audio_recording.py at master · Pycord-Development/pycord

deft sandal
patent escarp
hollow drum
#

hey guys, how i can make a command that returns the replied message if exists?

patent escarp
hollow drum
#

i mean getting the message instance

#

not replying

#

when i reply to a message with a command, get that message instance

round rivet
#

message has a reference attribute

patent escarp
#

^

hollow drum
#

thanks

patent escarp
round rivet
#

opus has always been a weird one

#

do you have PyNaCl installed?

patent escarp
#

Yes i do

round rivet
#

opus is supposed to come bundled with the library

#

we never figured out why that error occurred

patent escarp
#

I see. I noticed that there are some differences comparing to discord.py, though I have not touched with discord.py in a while, that I don't know if that still works

#

So does this mean discord packages still can't really record audio from Discord?

round rivet
#

They can

#

There's just something wrong with your installation

rose flare
#
view=discord.ui.View

options=[]
for i in range(10):
    options.append(discord.SelectOption(
        label=i[0],
        value=i[1]
    ))

view.add_item(discord.ui.Select(
    placeholder = "Select",
    options = options
))

await ctx.respond(view=view)
#

how do I add a callback for this?

#

I looked at the Select Menus guide, but that needed a custom class

simple canopy
#

make a callback function and assign it to select

rose flare
#

which I'd be fine with, but I need to add the options dynamically

rose flare
simple canopy
#

.docslink discord.ui.Select.callback

simple canopy
#

well, it seems like subclassing is the way to go

rose flare
#

so I have to subclass discord.ui.Select?
ok I'll give it a try

rose flare
full basin
#

Read the error

#

Reading the error will help you solve the problem.

#

then learn basic python

#

"List indices must be integers not strings"

rugged lantern
#

learn python

full basin
#

And learn how to read errors, because your "solution" doesn't even solve the error

slender shuttle
#

It's on my VPS, what's the best way to solve it?

uneven beacon
#

anyone knows how can i fix this?

deft sandal
uneven beacon
rugged lantern
#

deal with it :(

deft sandal
fervent cradle
#

how to make second dropdown wait for first dropdown?

rapid geode
#

Traceback (most recent call last):
  File "c:\Users\Baban\Desktop\Folders\code playground\olympus-dev\Olympus-Private\main.py", line 2, in <module>
    from discord.ext import commands
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)
young bone
#

also do you use pycharm?

silver moat
#

Add a custom_id to the first select menu and use bot.wait_for("interaction",check=check) and include something about the interaction.custom_id in the chec

rapid geode
#

ago 0.0.95 aiohttp 3.7.4.post0 aiosignal 1.2.0 akinator 1.0.3 animec 0.4.2 astunparse 1.6.3 async-timeout 3.0.1 attrs 21.4.0 beautifulsoup4 4.11.1 braceexpand 0.1.7 bs4 0.0.1 certifi 2022.6.15 chardet 4.0.0 charset-normalizer 2.0.12 click 8.1.3 colorama 0.4.5 discord 2.0.0 discord-together 1.2.6 discord-ui 5.1.6 disputils 0.2.0 frozenlist 1.3.0 humanfriendly 10.0 humor-langs 1.0.1 idna 3.3 import-expression 1.1.4 jishaku 2.5.0 mojang 0.2.0 multidict 6.0.2 mysql 0.0.3 mysql-connector 2.2.9 mysql-connector-python 8.0.31 mysqlclient 2.1.1 pet-pet-gif 1.0.2 Pillow 9.1.1 pip 22.0.4 py-cord 2.2.0 pyreadline3 3.4.1 python-dateutil 2.8.2 qrcode 7.3.1 requests 2.26.0 setuptools 58.1.0 six 1.16.0 soupsieve 2.3.2.post1 typing_extensions 4.4.0 urllib3 1.26.9 wheel 0.37.1 yarl 1.7.2

young bone
uneven beacon
rapid geode
#

cool its working now thanks!

fervent cradle
verbal dawn
#

Dropdown selected value is just disappearing after editing the message. How could I fix it?

dry echo
#

discord.errors.HTTPException: 413 Payload Too Large (error code: 40005): Request entity too large
when sending an image (23MB) in on_message() and send them again mike

silver moat
# fervent cradle i dont really get it but can i ask for an example?
# select menu decorator
@discord.ui.select(..., custom_id = "select1")

# 2nd select menu
@discord.ui.select(...)
async def second_select_menu_callback(self, select, interaction):
  def check(interaction):
    return interaction.custom_id == "select1"
  await bot.wait_for("interaction", check=check)
verbal dawn
silver moat
#

I believe this is a discord limitation since there is no way to preset selected values for a Select Menu

verbal dawn
#

Yeah, but if a user selects the dropdown value and it edits it should stay and not clear it

silver moat
#

instead of editing the message you can send another message

#

which wouldn't update the select menu

verbal dawn
#

Expected & Reality

silver moat
#

nvm you actually can

#

you should get the values and edit the select menu so that those are selected

#

@verbal dawn

verbal dawn
#

I see

#

Could I get a small example?

silver moat
#
select = discord.Select(..., options = [discord.SelectOption(..., value = "option1")])

async def callback(interaction):
  for value in select.values:
    if value = "option1":
      select.options[0].default = True
#

and don't forget the edit the actual view

verbal dawn
cobalt tangle
verbal dawn
full basin
verbal dawn
#

I am dumb alr?

lost lodge
#

Hey guys!

#

How can read the Audit Log and filter it?

valid ibex
#

hey guys

#

how can ı uninstall pycord

#

because ı need install it clearly

#

why

lost lodge
#

not shure but i guess it's pip uninstall py-cord

fervent cradle
young bone
#

lol

valid ibex
#

what should ı write

lost lodge
#

y

young bone
#

That is basic python

#

Read the error

lost lodge
#

enable it

young bone
#

^

lost lodge
#

no

#

wait is your bot verified?

young bone
#

use discord.Intents.all()

lost lodge
#

do you have enabled all what i did?

#

ok

#

don't you what i did but your welcome ::)))

#

How can read the Audit Log and filter it?

valid ibex
#

guys ı install library

#

then ı write import discord

#

but ı cant

#

do you know what can ı do

lost lodge
#

send code

young bone
valid ibex
lost lodge
valid ibex
lost lodge
#

send the output

valid ibex
#

there are too many things

lost lodge
#

send it

#

else we can't help you

solemn idol
#

So how do I create a help menu using embeds?
The help command itself should be callable using /help
Very important I am creating the help menu in a cog called help.py

lost lodge
#

good

#

so that's good, you have installed it correctly

#

can you hower over the error and send a screenshot of the message that the idea sends

valid ibex
#

there is no error

lost lodge
#

and why you need help?

valid ibex
#

here is need be green

#

if its imported but here ı cant import it

lost lodge
#

you use vs code?

valid ibex
solemn idol
#

vsc doesn't directly show the imports as imports on the first time.

valid ibex
solemn idol
valid ibex
#

yes

#

windows 10

solemn idol
#

then open cmd

lost lodge
solemn idol
#

and type pip list
and show me the entire list it gives you

valid ibex
valid ibex
lost lodge
#

it's only an real error if you get a console error

valid ibex
#

can you send me a little code

#

for test it

lost lodge
solemn idol
#

strange...

#

try installing python as an extension for vsc if you havent already

#

maintained by microsoft

valid ibex
valid ibex
solemn idol
#

and this doesnt work in your terminal either?

#

perhaps its just vsc messing it up

#

for some reason

lost lodge
#

ok idk if that helps but create a venv:
python -m venv <project_path>

#

and reinstall pycord

valid ibex
#

but not working

#

ı cant understand anything

lost lodge
#

firs install the venv

solemn idol
#

try pip installing discord

lost lodge
#

@valid ibex could you create a thread in #969574202413838426 and ping me after you created, this is a deeper problem

solemn idol
#

I dont see pycord itself

#

I see py-cord but not pycord

verbal dawn
solemn idol
#

I have em both

verbal dawn
#

not pycord or anything that could cause conflict like having py-cord and discord at same time

solemn idol
verbal dawn
#

try removing pycord

lost lodge
#

no

#

pycord is something alse

verbal dawn
#

oh yeah

solemn idol
#

Woah

#

wait a minute wtf

verbal dawn
#

probably conflict

lost lodge
#

i would try using the venv

fervent cradle
#

any idea how to fix this

#

ok fixed

rotund current
#

Some of my users have noticed that Pings from my bot have been slow, or occasionally not going through at all. Is this a bot issue or a discord issue.
The pings are part of a message in a @<###> format.

safe stirrup
#

Is there a way to add a hyperlink to an embed footer?

#

Using fields is for squares! :( lol

solemn idol
safe stirrup
#

Darn.

solemn idol
#

But

#

I dont know if theres a limit to fields, so you could always add another field

#

which could contain your hyperlink

safe stirrup
#

True but the hyperlink is for a copyright page I'm required to add to this particular content so I was hoping to make it not so profound

solemn idol
#

Well you could add it in the author section

#

since that part does support links, not directly via the usual way of creating hyperlinks in an embed, but they do support it.

merry briar
#

how can you understand why cog doesn't work?
and then it starts, and then after the changes it does not want and it is not clear why

sage galleon
#

For a command option decorator type as int is there a way to limit the int given from 1-10 for example? Aside from handling it inside the command itself

fervent cradle
#

if commands.Bot is only for prefix commands then why is it so much used in cogs and also contains slash commands and stuff

silver moat
#

?tag discord.Client

obtuse juncoBOT
#

dynoError No tag discord.Client found.

fervent cradle
#

?tag client

obtuse juncoBOT
#
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
meager mica
#

whats the event for updated channel overwrites

cyan quail
meager mica
#

oh thanks

solemn idol
spark patrol
#

What page do you recommend for learning Python?

fervent cradle
proud mason
#

Is it possible to create a restart command for my bot?

fervent cradle
#

how can we format one liner for loops, like in the code below:

llist_embed.add_field(name='Activated Licenses', value='\n'.join([n for n in alic]))
#

i want to bold each element in the list but idk how to, i dont want to use it in the value directly coz then the format will apply to all items in the list except for the last one

buoyant pier
#

how i can check if member has timeout?

proud mason
buoyant pier
proud mason
lost lodge
#

Anyone know how to get the audit log of a member and how to filter it?

lost lodge
proud mason
rapid geode
#

is there any module to make paginators with buttons?

rare ice
lost geyser
#

How does Member.is_on_mobile() work? Because currently, it always shows me false, if i completely quit discord on pc and just use my mobile device.

rare ice
lost geyser
#

from the guild?

#

If i fetch from the guild, it still doesnt update...

rare ice
lost geyser
#

i tried, but the status of the member is still 'offline'

#

ah maybe i need an intent...

rare ice
#

Are you fetching from the guild?

#

Oh well that will do it

#

You should be enabling all intents

#

if you have them

lost geyser
#

nope, still offline

#

Do i need to activate any special scope before inviting the bot?

#

and this is my code

guild = await self.bot.fetch_guild(ctx.guild.id)  # type: ignore
member = await guild.fetch_member(ctx.author.id)  # type: ignore
print(member.name)
print(member.status)
rare ice
lost geyser
#

i use them already

rare ice
#

send me your full main.py file (token retracted)

lost geyser
#

well its a cog and the files are really long

#

could you specify what you need? Most of the stuff has nothing to do with this command

#
    @faq.command()
    async def list(self, ctx: discord.ApplicationContext, page: int):
        '''Get a list of all FAQ-Tags'''
        amount = 20
        tags = self.data.get_all_tags(amount, amount * (page - 1))

        # tabulate data
        lines = tabulate(tags, 1, 100)
        formatted = "\n".join(lines)

        guild = await self.bot.fetch_guild(ctx.guild.id)  # type: ignore
        member = await guild.fetch_member(ctx.author.id)  # type: ignore
        print(member.name)
        print(member._client_status)
        print(member.is_on_mobile())

        await ctx.send_response(f'\`\`\`{formatted}\`\`\`')

This is the command. (I want to know the status for the tabulate function, to make a table look better on mobile)

#
intents = discord.Intents.all()

bot = commands.Bot(intents=intents)

...

# run bot
loader.load(bot, 'cogs', ['test'])
bot.run(os.getenv('TOKEN'))
#

Do i need to activate any special permissions in the guild?

#

Duh. Fetching the member from the guild does not work. it will always return offline. If i get the member from the context directly, it does work. My problem in the beginning was just that i havent had any intents, but i needed them.

#

Anyways, thanks for your help @rare ice !

fervent cradle
proud mason
proud mason
#

yeah

#

wait no

#

i think its drop table

#

brb

#
#

no?
DROP TABLE test will delete the entire table

#

if you only want to delete certain rows then use delete statement
https://www.w3schools.com/sql/sql_delete.asp

#
meager mica
#

is there an event for category create i tried searching for on_category and catagory but i dont see anything about it

meager mica
#

oh its considered a channel

silver moat
#

you would be looking for CategoryChannel

meager mica
#

ohhhh

#

ty ty

meager mica
silver moat
meager mica
#

alr

lethal hare
#

Anyone know why I might be getting this error:

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.1.components.0.options: Must be 10 or more in length.
lethal hare
#

Confused you with someone else

#

still unhelpful, ill figure it out myself

young bone
#

numbers or letters

lethal hare
#

Like if I want a button that says "Done" that's 4 characters but completely relevant, right?

silver moat
#

please send code

lethal hare
#
def createSelectMenu(self, itemType):
        selectOptions = []

        async def selectCallback(self, select, interaction): 
            await interaction.response.defer()
            self.lackeyChoices[itemType] = select.data['values'][0]

        selectMenu = discord.ui.Select(
            placeholder = typeConfig[itemType]['placeholder'],
            min_values = typeConfig[itemType]['min'], max_values = typeConfig[itemType]['max']
        )

        for itemName in self.user_closet[itemType]:
            itemData = closetDict[itemName]

            selectMenu.add_option(
                value=itemName, 
                label=itemData['name'],
                emoji=itemData["emoji"]
            )

        selectMenu.callback = selectCallback

        self.add_item(selectMenu)

Function inside of a discord.ui.View class

#

I wasnt using .add_option before but I was trying to cover all my bases to track the error down

#

Here's the button

@discord.ui.button(style=discord.ButtonStyle.primary, label="Done")
    async def submitLackey(self, button, interaction):
        with BytesIO() as image_binary:
            generateLackey(interaction.author.id, self.lackeyParams).save(image_binary, 'PNG')
            image_binary.seek(0)
            await interaction.response.defer()
            await interaction.edit_original_message(content="", file=discord.File(fp=image_binary, filename=f'{ctx.author.id}s_lackey.png'), view=None)
young bone
#
  1. content="" it cannot be emtpy
  2. why do you use ctx.author.id in a button?
lethal hare
silver moat
lethal hare
#

for sure one moment

#

I think the issue is in where I am generating my option labels, itemdata['name'] might be throwing an undefined/none or somthing, but the "more than 10" error is confusing me on that

lethal hare
# silver moat could you show full traceback?
Ignoring exception in on_application_command_error
Traceback (most recent call last):
  File "/home/turbo/bots/HalloweenBoy/venv/lib/python3.8/site-packages/discord/commands/core.py", line 127, in wrapped
    ret = await coro(arg)
  File "/home/turbo/bots/HalloweenBoy/venv/lib/python3.8/site-packages/discord/commands/core.py", line 911, in _invoke
    await self.callback(ctx, **kwargs)
  File "main.py", line 617, in costume
    await ctx.respond(content="Pick your Lackey's costume!", view=userCostumeView, ephemeral=True)
  File "/home/turbo/bots/HalloweenBoy/venv/lib/python3.8/site-packages/discord/commands/context.py", line 275, in respond
    return await self.interaction.response.send_message(*args, **kwargs)  # self.response
  File "/home/turbo/bots/HalloweenBoy/venv/lib/python3.8/site-packages/discord/interactions.py", line 727, in send_message
    await self._locked_response(  File "/home/turbo/bots/HalloweenBoy/venv/lib/python3.8/site-packages/discord/interactions.py", line 975, in _locked_response
    await coro
  File "/home/turbo/bots/HalloweenBoy/venv/lib/python3.8/site-packages/discord/webhook/async_.py", line 213, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.1.components.0.options: Must be 10 or more in length.

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

Traceback (most recent call last):
  File "/home/turbo/bots/HalloweenBoy/venv/lib/python3.8/site-packages/discord/client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 209, in on_application_command_error
    raise error
  File "/home/turbo/bots/HalloweenBoy/venv/lib/python3.8/site-packages/discord/bot.py", line 1009, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "/home/turbo/bots/HalloweenBoy/venv/lib/python3.8/site-packages/discord/commands/core.py", line 359, in invoke
    await injected(ctx)
  File "/home/turbo/bots/HalloweenBoy/venv/lib/python3.8/site-packages/discord/commands/core.py", line 135, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.1.components.0.options: Must be 10 or more in length.
#

Line 617 is where the message with the view is sent

silver moat
#

can you print the view

lethal hare
silver moat
#

print(view)

lethal hare
#

yeah sure

lethal hare
silver moat
#

your select menu options don’t have a label

lethal hare
silver moat
#

hmm

lethal hare
#

I think it has something to do with my value, because I didnt hardcode that, I just did and its working, ill look into the function that it gets that data from, thank you

round rivet
#

In data.components.1.components.0.options: Must be 10 or more in length.

silver moat
#

what’s in the view’s __init__

round rivet
#

the fuck

silver moat
lethal hare
lethal hare
thin stag
#

is there a way of having a slash command's option be either one type of input or another? for example, having input be either a str or a discord.Attachment

silver moat
thin stag
#

Yes

#

you can kiiinda get the same effect with having a string option and discord.Attachment option with both not being required

#

but that also allows both as inputs and neither as inputs

west pebble
#

some_var: str | discord.Attachment?
Or a union?

thin stag
#

Extension 'countrybot.cogs.utility' raised an error: TypeError: Invalid usage of typing.Union

#

Nope

lethal hare
#

@silver moat here's the entire class, I'm at a loss as to why this is happening

class costumeView(discord.ui.View):

    lackeyParams = {}

    def __init__(self, user_closet):
        super().__init__(timeout=30)

        self.user_closet = {
            "accessories": ["knife", "wings", "cat", "witch"],
            "backgrounds": ["candy", "night", "slime"],
            "paints": ["paint_green", "paint_purple"],
            "masks": ["trick", "treat", "zombie"]
        }

        for index, itemType in enumerate(user_closet.keys()):
            if index == 4:
                break
            self.createSelectMenu(itemType)

    def createSelectMenu(self, itemType):

        async def selectCallback(self, select, interaction): 
            await interaction.response.defer()
            self.lackeyChoices[itemType] = select.data['values'][0]

        selectMenu = discord.ui.Select(
            placeholder = typeConfig[itemType]['placeholder'],
            min_values = typeConfig[itemType]['min'], max_values = typeConfig[itemType]['max']
        )

        for itemName in self.user_closet[itemType]:
            itemData = closetDict[itemName]

            print(f"name: "+itemData["name"])
            print(f"value: {itemName}")

            selectMenu.add_option(
                value=itemName, 
                label=itemData["name"]
            )

        selectMenu.callback = selectCallback

        self.add_item(selectMenu)

    @discord.ui.button(style=discord.ButtonStyle.primary, label="Done")
    async def submitLackey(self, button, interaction):
        with BytesIO() as image_binary:
            generateLackey(interaction.author.id, self.lackeyParams).save(image_binary, 'PNG')
            image_binary.seek(0)
            await interaction.response.defer()
            await interaction.edit_original_message(content="Your newly dressed Lackey!", file=discord.File(fp=image_binary, filename=f'{interaction.author.id}s_lackey.png'), view=None)

meager mica
#

is it possible to see who created a channel using on_guild_channel_create i also looked at channel_create audit log action but i didnt see anything there either

west pebble
#

You would use discord.AuditLogActions

meager mica
#

Alr never used audit log actions yet so that'll be fun

west pebble
#

its pretty easy

lethal hare
#

Yall what am i doing wrong here, its claiming its getting unexpected key args

thin stag
#

do you need privileged intents for User.display_avatar?

rugged lantern
#

why do u have a callback inside another function

silver moat
lethal hare
#

i’ve made a post for it

#

simpler code

#

how am i supposed to do what i’m doing here?

gleaming falcon
#

Or is 'select_callback' tied to that specific dropdown and I can just make multiple methods?

silver moat
gleaming falcon
#

Okay, the method name wasn't clear that it was custom and not an override of a specific callback class. Thank you

#

So, dumb question, will the callback be run when each dropdown is touched, or can I have a submit that processes it all then? (Although I am guessing I can't have five dropdowns with any other UI input, so maybe that's moot anyway)

gleaming falcon
#

Trying to create a UI that approximates a cron so people can schedule recurring reminders, but might have to get a little more creative/less complicated

rapid geode
#

what might be causing this error?

gleaming falcon
full basin
thin stag
#

I have some code in a loop. Anything that is an io method is accessing a sqlite3 database stored locally. Will having a loop like this with many iterations and many database reads and writes slow down my program?

    @tasks.loop(minutes=30) # make this lower if it doesnt affect performance
    async def advance_date(self):
        for guild_id in io.get_guilds():
            try:
                rpdate = io.load_rpdate(guild_id)
                channel_id = io.load_rpdate_channel(guild_id)
                guild_channel = await self.bot.fetch_channel(channel_id)
                last_posting = io.load_last_rpdate_posting(guild_id)

                if dt.datetime.now() - last_posting > dt.timedelta(days=1):
                    await guild_channel.send(embed=discord.Embed(title=f"The RP date is {rpdate}.", color=discord.Color.blurple()))
                    io.save_last_rpdate_posting(dt.datetime.now(), guild_id)

            except Exception as e:
                if isinstance(e, RPDateNotPostedError):
                    await guild_channel.send(embed=discord.Embed(title=f"The RP date is {rpdate}.", color=discord.Color.blurple())) 

                    io.save_last_rpdate_posting(dt.datetime.now(), guild_id)

Also, I do plan on upgrading the database reads/writes to aiosqlite. Assume this code is the same but with asyncio database reading and writing

#

on each iteration of the loop, it reads through the database containing the ids of all the guilds the bot is in, and then iterates through that list, where it loads data from a few entries. It then compares if one of the timestamp values is greater than 24 hours, and if it is, it will send a message and save the timestamp of when it sent that message

rapid geode
#
aiohttp==3.7.4.post0
disputils==0.2.0
pillow==9.1.1
py-cord==2.2.0
requests==2.26.0
discord-together==1.2.6
humor-langs==1.0.1
qrcode==7.3.1
akinator==1.0.3
pet-pet-gif==1.0.2```
#

my libs

meager mica
full basin
gray aurora
#

using version 2.2.2

rapid geode
gray aurora
#

oh actually I can replicate with just a simple example:

class Example(commands.Cog):
  def __init__(self, bot_: discord.Bot):
    self.bot = bot_

  greetings = SlashCommandGroup("greetings", "cog greetings")

  @greetings.command()
  @option("test", "enter text")
  async def hello(self, ctx: discord.ApplicationContext, test: str):
    await ctx.respond("some response")

AttributeError: 'str' object has no attribute '__name__'. Did you mean: '__ne__'?

#

removing @option allows the type to be inferred correctly, but I'd expect @option to work here?

#

I guess as a workaround using type annotation seems to work here using discord.Option

fervent cradle
#

why its not useable bruh

#

(i am not using class)

#

how do i block out token output from eval cmd

#

like if someone uses the eval cmd to get bot token, they get some other stuff instead

round rivet
#

don't make a public eval command please

fervent cradle
#

or if the eval gets hacked or something wrong happens

round rivet
#

there's no foolproof way to do it

#

as an example, jishaku tries to filter it but fails when the send method is called directly

fervent cradle
fervent cradle
#

rip

#

where do i put on_timeout?

steady sinew
#

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

Traceback (most recent call last):
File "C:\Users\shan's python work\PycharmProjects\da_pycord_botto\venv\lib\site-packages\discord\bot.py", line 992, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\shan's python work\PycharmProjects\da_pycord_botto\venv\lib\site-packages\discord\commands\core.py", line 358, in invoke
await injected(ctx)
File "C:\Users\shan's python work\PycharmProjects\da_pycord_botto\venv\lib\site-packages\discord\commands\core.py", line 135, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: KeyError: 't'

how do i fixx

#
@client.slash_command(description="Get a sassy sticker to add to your convo.")
async def sticker(ctx, query: Option(str, "Enter the search query for your sticker")):
    url = "http://api.giphy.com/v1/gifs/search"

    params = parse.urlencode({
        "q": query,
        "api_key": giphy_key,
        "limit": "5"
    })

    with request.urlopen("".join((url, "?", params))) as response:
        data = json.loads(response.read())

    print(data['data'[2]])

code

grizzled sentinel
prime steppe
#

does pycord work on python 3.11?

silver moat
prime steppe
#

is there a beta release that does?

silver moat
#

the master branch would work

prime steppe
#

ok, thanks a lot

meager mica
misty yew
#

How can I use mentions as prefix when I use bridge commands?

wind thunder
misty yew
wind thunder
#

U get mentions and prefix a!

misty yew
wind thunder
#

If u used bridge

misty yew
#

ok, thanks

wind thunder
#

Np

misty yew
#

Can I use MissingRequiredArgument, MissingPermissions from discord.ext.commands with bridge?

misty yew
#

In cog file I change @commands.command for @commands.bridge_command and have the error. Why?

young bone
#

also you need a bridge bot

misty yew
misty yew
#

How can I use has_permissions with bridge? (for example: @commands.has_permissions(administrator = True))

misty yew
silver moat
#

does it always fail?

misty yew
#

always

silver moat
#

on_application_command_error is the slash command error handler

silver moat
silver moat
#

why is commands underlined?

misty yew
silver moat
#

?

misty yew
# silver moat ?

I import from discord.ext import commands from global_sets.py, not in file, where my code
In my code from global_sets import *

misty yew
silver moat
#

ah, it's actually bridge.has_permissions

silver moat
#

could you update?

misty yew
silver moat
#

?tag install

obtuse juncoBOT
#
  1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
    python -m pip uninstall discord.py discord -y

2a. Install py-cord
python -m pip install py-cord

2b. Update py-cord
python pip install -U py-cord

Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.

Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord

misty yew
sweet tiger
#

how would I send a message on an exception (for example: I want the bot to send "You are not the owner" when the "NotOwner" exception is raised

silver moat
silver moat
misty yew
misty yew
silver moat
misty yew
silver moat
misty yew
silver moat
#

await member.send()

misty yew
silver moat
#

well, my understanding of that question is "will it work for slash commands?"

sweet tiger
#

my bot is responding to commands properly but "discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction" is being raised

silver moat
#

send code

sweet tiger
#

nvm i fixed it, forgot to delete a line

sage eagle
#

is there any jishaku fork for pycord (with slash command support)?

young bone
sage eagle
#

nah

young bone
#

?

rugged lantern
sage eagle
#

i have no message intents rn

rugged lantern
#

unlucky

sage eagle
#

i already sent a intent request its not approved yet

#

so i need slash command support

#

so is there any fork with slash command support?

misty yew
#

If you want, you can use bridge commands (slash, text-based, etc)

sage eagle
#

i have no message intents

young bone
#

why do you not enable it

sage eagle
#

my bot has over 100 servers

#

i cant just enable it

young bone
#

why?

sage eagle
#

i just cant

#

i need to send a request to get them

young bone
#

no?

sage galleon
#

Is there an argument I can pass to view.disable_all_items() to only disable the view items for a single user?

sage eagle
thin stag
thin stag
#

np

young bone
#

?

sage eagle
#

i think ill just port it myself xd

young bone
#

you can just use message contents without a bot verification

sage eagle
#

no

#

i have over 100 servers

young bone
#

try it...

sage eagle
#

i cant bro

#

i need intents for it

sage eagle
#

squid

#

hey

#

do you know any jishaku fork with slash command support?

silver moat
#

jishaku

sage eagle
#

its not working with py cord i think

silver moat
#

no bob made one

sage eagle
#

could i get link?

#

does it support slash commands?

silver moat
#

no

sage eagle
#

but thats what i am asking for

sweet tiger
#

how would I edit a channel's name

#

currently im getting "AttributeError: 'NoneType' object has no attribute 'edit'"

@tasks.loop(seconds=60)
async def my_loop():
    channel = bot.get_channel("1036353629382254713")
    await channel.edit(name=f"Players Online - {onlineUser}")
lost geyser
#

How do i access the response to a slash command? I want to add a reaction and later delete the response, but if i try

msg = await ctx.send_response(...)

the message gets send, but msg.message is Null

silver moat
sweet tiger
#

ah ok

misty yew
#

How can I get guild id in slash command? I try ctx.message.guild.id , but error discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'guild'

valid ibex
#

@silver moat sorry for ping ı cant import the library

#

ı already pip install it

silver moat
#

restart your IDE

#

If you are using Pycharm, click Python Packages on the bottom left and add py-cord to dependencies

sweet tiger
silver moat
sweet tiger
#
Ignoring exception in command updateplayers:
Traceback (most recent call last):
  File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 127, in wrapped
    ret = await coro(arg)
  File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 881, in _invoke
    await self.callback(ctx, **kwargs)
  File "D:\Coding Stuff\Python\Growtopia\Website Checker\websiteChecker.py", line 76, in updateplayers
    await ctx.respond("Begun updating!")
  File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\context.py", line 258, in respond
    return await self.interaction.response.send_message(*args, **kwargs)  # self.response
  File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 712, in send_message
    await self._locked_response(
  File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 959, in _locked_response
    await coro
  File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 211, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

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

Traceback (most recent call last):
  File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 992, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 358, in invoke
    await injected(ctx)
  File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 135, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
silver moat
#

show code for updateplayers

sweet tiger
#
async def updateplayers(ctx, boolval: discord.Option(bool)):
    channel = ctx.guild.get_channel(1036353629382254713)

    updatetxt = onlineUser

    if boolval == True:
        my_loop.start()
        await ctx.respond("Begun updating!")
    if boolval == False:
        my_loop.end()
        await ctx.respond("Ended updating!")

lost geyser
# silver moat you can use `ctx.message`

Thanks for the answer, but do not need the original message, but rather the response from the bot. But i found out that

msg = await ctx.interaction.original_response()

does work.

silver moat
#

try adding an await ctx.defer() at the beginning of that method

silver moat
lost geyser
#

oh well than that would be even more convenient. Thanks!

thin stag
#
class ErrorHandler(commands.Cog):

    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_application_command_error(self, ctx: discord.ApplicationContext, error: commands.CommandError) -> None:
        r"""The event triggered when an error is raised while invoking a command.

        Parameters
        ------------
        ctx: :class:`commands.Context`
            The context used for command invocation.
        error: :class:`commands.CommandError`
            The Exception raised.
        """
            
        if hasattr(ctx.command, 'on_error') or not isinstance(error.original, Exception):
            return
        
        match error:
            case commands.MissingPermissions():
                embed = error_embed("Invalid permissions!")
            
            case _:
                match error.original:
                    case e.ChannelNotSetError():
                        embed = error_embed("Channel not set!")

                    ...

                    case _:
                        print(error)
                        embed = error_embed("Unknown error!")
        
        await ctx.respond(embed=embed, ephemeral=True)

This is a shortened version of my error handler. For some reason, when it responds with the "Unknown error!" embed, the message is not ephemeral, despite ephemeral being true. Furthermore, every other error message is ephemeral. Does anyone know what might be happening here?

#

Here is an example of this happening:

sage galleon
#

Should I be retrieving a message ID in on_raw_reaction_add(payload) from a DB that was created from a command? I feel like its unecessary and there's another way I should be doing it. The message that will be reacted to is created in a command and I need that message ID inside of on_raw_reaction_add(payload)

full basin
fervent cradle
#

are the chances good? or i am doing something wrong

#

common has to be 60 or 100

#

(literally no idea if thats relateable to pycord)

silver moat
thin stag
meager mica
#

can i get message id of someone using a slash command with ephermal

#

i want report message link to go where they reported but not show there message

silver moat
#

so if the 15 minutes have elapsed, then the message would be deleted

meager mica
#

according to vsc .send returns None

#

so i cant make jump link

silver moat
#

Ephemeral messages are designed so that only your bot and the author can see the message.

meager mica
#

but i should still be able to get message id and it will link to around that

meager mica
#

let me show

#

gonna make link to this

#

#998272089343668364 message

#

it scrolls to where it took place

silver moat
#

ok?

meager mica
#

so is there a way i can get message id of slash command message

silver moat
#

or msg = await ctx.original_message(); msg.id

fervent cradle
fervent cradle
grizzled sentinel
rugged lantern
#

did they ask for this explanation or

proud pagoda
#

Is there any way to get a slash command in a subgroup without having to walk through all the commands in the SlashCommandGroup? I tried using bot.get_application_command("parent child") but it just returns None

graceful mason
#

How do I fix that AttributeError: 'Interaction' object has no attribute 'author'

graceful mason
#

oh, thanks!

graceful mason
#

why this doesn't work?

@option(required=True, name="name", description="asd")```
the @real compasstion doesn't display the name and the description
rare ice
#

.docs discord.Option

winter condorBOT
severe comet
#

If I want to store the usernames and userIDs of people who leave the server, would you guys recommend a MySQL/MariaDB/PostgreSQL server or should I go with a NoSQL implementation for the future stuff? Basically I'm trying to figure out which type of database has the most expandability for future projects

#

While of course having a decent async driver

gleaming falcon
#

Isn't there a method that extracts Mentionables (users/roles) from a string (not necessarily a Message), or did I make that up in my head?

Answer: raw_mentions and raw_role_mentions in discord.utils, it appears.

fervent cradle
#

is it possible to use commands.cooldown decorator for events

sage eagle
#

no

#

is there a way to use wait_for message event without a message intent?

fervent cradle
sage eagle
#

how can i get arguments/options from my slash command using ctx?

verbal dawn
#

Can I go above 25 choices inside of 1 choice?

lost geyser
#

Is there a way to disable a slash_command without making a check?

mellow tinsel
#

Is it possible to create a discord.ui.Select menu with a working callback without having to subclass it?

cyan quail
misty yew
#

Why I can't use ctx.message.created_at.timestamp() with slash commands?

mellow tinsel
grizzled sentinel
wet ore
#

Hey all! Is it possible to detect if a user is currently 'Priority speaker' while in a voice channel? VoiceState has a suppressed boolean but it's for stage channels only, trying to capture when a bot should start recording audio.

silver moat
errant craneBOT
#

Here's the slash autocomplete example.

verbal dawn
fervent cradle
#
class NitroView(View):
    async def on_timeout(self):
        expire_button = Button(label='Claim', style=discord.ButtonStyle.gray, disabled=True)
        view.add_item(expire_button)
        view.remove_item(accept_button)
        nitroexpire_embed = discord.Embed(title="You've been gifted a subscription!", description='Hmm, it seems someone already claimed this gift.')
        nitroexpire_embed.set_thumbnail(url='https://i.imgur.com/wI9q2Md.png')
        await self.message.edit(view=self, embed=nitroexpire_embed)
#

this is my view, and i get an error on timeout, that 'NoneType' object has no attribute edit

copper sparrow
#

I am currently getting these errors while trying to host on a VPS:

Traceback (most recent call last):
  File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/cog.py", line 757, in _load_from_module_spec
    spec.loader.exec_module(lib)  # type: ignore
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/home/ubuntu/YCCUtilities/cogs/commands_2.py", line 18, in <module>
    from normalize import normalize
ImportError: cannot import name 'normalize' from 'normalize' (/home/ubuntu/.local/lib/python3.10/site-packages/normalize/__init__.py)

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

Traceback (most recent call last):
  File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/cog.py", line 757, in _load_from_module_spec
    spec.loader.exec_module(lib)  # type: ignore
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/home/ubuntu/YCCUtilities/cogs/commands_2.py", line 10, in <module>
    from main import Duration, Punishment, PunishmentFromMessage
  File "/home/ubuntu/YCCUtilities/main.py", line 240, in <module>
    load_cogs()
  File "/home/ubuntu/YCCUtilities/main.py", line 118, in load_cogs
    bot.load_extension(f'cogs.{file[:-3]}')  # loads every python file
  File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/cog.py", line 893, in load_extension
    self._load_from_module_spec(spec, name)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/cog.py", line 760, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.commands_2' raised an error: ImportError: cannot import name 'normalize' from 'normalize' (/home/ubuntu/.local/lib/python3.10/site-packages/normalize/__init__.py)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/ubuntu/YCCUtilities/main.py", line 240, in <module>
    load_cogs()
  File "/home/ubuntu/YCCUtilities/main.py", line 118, in load_cogs
    bot.load_extension(f'cogs.{file[:-3]}')  # loads every python file
  File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/cog.py", line 893, in load_extension
    self._load_from_module_spec(spec, name)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/cog.py", line 759, in _load_from_module_spec
    del sys.modules[key]
KeyError: 'cogs.commands_2'

What could potentially cause this issue

#

nvm, resolved.

rugged lantern
fervent cradle
rugged lantern
#

there's so many errors

fervent cradle
#

like what

rugged lantern
#

im not gonna hold a lecture for you

fervent cradle
#

it worked before

fervent cradle
lost lodge
#

How can i get a member timeout?

            async for thing in ctx.guild.audit_logs(user=member, action=discord.AuditLogAction.member_update.mute):
                embed.add_field(name=f"Muted for {thing.target}", value="h")```
lost lodge
#

Help pls

uneven beacon
#

anyone knows whats wrong with my code?
(its supposed to print something in the terminal when someone joins/leaves a server)

uneven beacon
young bone
meager mica
full widget
#

Anyone ever had problems with commands permissions resetting in the Integrations Tab in Server settings on command sync?

#

Perms don't reset for commands loaded before bot.run(), but they are reset for commands loaded after the bot.run()

meager heron
#

Are multi-line string input Options a thing yet?

full widget
meager heron
#

Gotcha, thanks. I just remembered them demoing them and wasn't sure if they were out yet. Unfortunately, modals have a couple of issues, but if they're the only option, they're the only option!

pulsar spear
#

Is it possible to have a button (sent with an embed) callback in the same function where it was sent from? So that I can edit an embed using an existing variable within a function?

silver moat
#
async def command(ctx):
    button = discord.ui.Button(label=“Hello”)
    async def callback(interaction);
        pass
    view = discord.ui.View()
    button.callback = callback
    view.add_item(button)
    await ctx.respond(“Hi!”,view=view)
pulsar spear
left flume
#

just looking to confirm you can only have 1 interaction response, from an interaction component? Couldn't have a button edit a message and launch a modal?

silver moat
#

.docslink discord.Interaction.edit_original_response

silver moat
#

... isn't a response

left flume
#

ty

#

ahh so that could be used to edit the view, to disable the button, and the response interaction could launch the modal?

left flume
# silver moat yes

I couldn't get edit_original_response to work(kept getting webhook error), but this did, does that seem right? to be clear its editing an ephemeral message send by another interaction response.

@discord.ui.button(label='Change Bid', style=discord.ButtonStyle.primary)
    async def change_bid_callback(self, button, interaction):
        await self.message.edit(content="Changing your bid", delete_after=3)
        await interaction.response.send_modal(BidModal(self.item, self.ctx))
naive heath
#

ValueError: could not find open space for item

modal can have only 5 inputs?

fiery skiff
#

hi, is it possible to make dynamically generated buttons (view) to be persistent?

verbal gulch
#

Hello, Why this command does not work? I don't get any error, but it doesnt work + it terminates the bot

#
@bot.command()
async def checkcode(ctx: discord.ApplicationContext, codigo: str):
    try:
        check = licencias.find_one({'licencia': codigo})
        if check == None:
            await ctx.respond('Ese codigo NO es valido!')
            ae = False
        else:
            ae = False
            if check['type'] == 'mon':
                monedas = check['monedas']
            elif check['type'] == 'rol':
                roleid = check['rol']
                dias = check['dias']
            embed = discord.Embed(
                title='Propiedades de este codigo',
                color=discord.Colour.blurple()
            )
            embed.add_field(name='tipo', value=check['type'])
            if check['type'] == 'mon':
                embed.add_field(name='monedas', value=monedas)
            elif check['type'] == 'rol':
                embed.add_field(name='id del rol', value=roleid)
                embed.add_field(name='dias', value=dias)
            await ctx.respond(embed=embed)
    except Exception as e:
        await ctx.channel.send(str(e))
native gorge
verbal gulch
unborn veldt
#

how can i use on_interaction’s interaction.data

#

I want to know ctx.author in on_interaction

#

so…

#

any one can help me

neon bramble
#

interaction.user?

unborn veldt
#

in on_interaction

#

but i want to know ctx.author

#

isn’t interaction.user

neon bramble
#

???

#

you don't get a context object in that event

native gorge
unborn veldt
#

but

#

i don’t know how to use this

neon bramble
#

you want to get the user that triggered the interaction right?

native gorge
native gorge
unborn veldt
#

and then?

#

how to use

native gorge
unborn veldt
#

can i do this?

#

🤔

#

Owo(?

native gorge
#

user id? user name? user # number? you can get all of that with interaction.user

#

if this make it easier for you, just do this:

author = interaction.user```
unborn veldt
#

what is author

#

how did it get here

#

@native gorge

native gorge
#

I'm trying to get what you mean...

unborn veldt
#

ok

native gorge
unborn veldt
#

A=slash_command

i do not want a.author to press button

midnight wadi
#

i cant seem to make the bot prefix work, the mention works but not the prefix, even if i just put the prefix. I had this exact same code on another bot with another version of the pycord from github and it was working

bot = commands.Bot(
        command_prefix=commands.when_mentioned_or('d!'), activity=activity, status=status,   help_command=None, intents=intents, case_insensitive=True)

native gorge
unborn veldt
#

almost

native gorge
unborn veldt
#

but slash_command.author can’t use button

#

Mean ‘a’ use slash_command but ‘a’ can’t use button.

midnight wadi
#

with the mention

native gorge
gleaming falcon
#

The on_guild_[un]available events refer to Enabling/Disabling Invites?

#

Or does pausing the server not throw any event? I guess it's a guild edit event

pale knot
#

How do I get the emoji id from a reaction

#

For example this, how can I get the emoji ID

#

If I right click -> Copy ID, it just copies the message id

gleaming falcon
# pale knot If I right click -> Copy ID, it just copies the message id

Hm. That might be a regression; I don't remember if it ever copied the ID

Two ways:
You can right-click and "Copy Link" or "Open Link". The filename is the snowflake ID
Escape your emoji by putting a backslash in front of it

escaping troll
would be \:troll~1: which will print
<🧌945379443508150363>

#

lol stupid discord, but I think you get the idea

#

Programmatically from a reaction is a little easier. on_reaction_add is passed a Reaction object.
reaction.emoji is an Emoji object, so reaction.emoji.id is the ID.

Only works for custom emoji, not built-ins; emoji will simply be the str emoji character

pale knot
#

Thanks, right click open link works 👍

gleaming falcon
swift rivet
#

I have a bot that posts an embed and some buttons.
The left and right -most buttons cycle through each page of the leaderboard by getting the next page's data and editing the original message with an updated embed.

Whenever I press one of the next page buttons, it seems to work for the first couple of pages, and then I get an error saying "This interaction failed." with error code 10062.

I have no idea what's causing this error and the weirdest part is that it breaks at seemingly random intervals. Sometimes I can press the button all the way until page 6, sometimes it breaks on page 3.

Is it something to do with like...discord rate limits stopping the bot from editing the message? Or maybe something to do with the interaction timer for the button?

full widget
#

you could solve this by deferring the interaction before attempting to edit the embed, that way the interaction won't expire so quickly

pulsar spear
#

From docs
Raises
HTTPException – Editing the message failed.

swift rivet
pulsar spear
left flume
#

I used self.message.edit() to get it to work

rotund current
#

So I am having a problem with my bit, occasionally when a slash command that loops through data is run, the bot will go offline. Is this because of the interface with the heartbeat? The function is async, so shouldn't this not interfere with the heartbeat? Shouldn't pycord automatically attempt a reconnect?

rugged lantern
rotund current
#

It's a SQL database call, and then loopinf through the data, but it's using async Sqlalchemy

rugged lantern
rotund current
#

A few different loops have done it, here is one of them, probably the simplest loop that's caused it, so easiest to post the code

unborn veldt
meager mica
#

hey so whats the function to get message history in channel

native gorge
meager mica
#

i found the name for some reason i thaught it was channel.messageable history but ig its just history

unborn veldt
#

Doesn't this work for everyone?

full basin
unborn veldt
silver moat
vagrant scroll
#

Why this works only in 1 server?

full basin
severe comet
#

Anyone know how I can pass in an async function result as a parameter in another async function?

#

Basically I have an async function that outputs a list and want to use that list as my optionchoice for a slash command

errant craneBOT
#

Here's the slash autocomplete example.

silver moat
#

@severe comet

#

keep in mind that you still have to validate the inputs after they are inputted.

round rivet
#

there's nothing obviously wrong in what you've shown us so far

vagrant scroll
round rivet
#

I don't see anything wrong

#

What's the issue

vagrant scroll
#

It works perfectly in my server, but in other servers, what the bot is supposed to do after the user reacts, doesnt work

round rivet
#

does it have perms?

#

manage messages?

vagrant scroll
#

Thanks, that was xd

storm hinge
#

why is this thing here

[mp3 @ 00000176b18cfa00] Estimating duration from bitrate, this may be inaccurate
[mp3float @ 00000176b18f8340] Header missing
Error while decoding stream #0:0: Invalid data found when processing input

everything works well?

merry briar
#

If the command is executed for a long time, then discord sends - "The application did not respond". How can I increase the waiting time for command execution

somber remnant
#

Hello, i have a big problem
I've made some buttons and i want that the on_timeout doesnt trigger if the user used a button
There's a way to make this ?

steady sinew
#
Traceback (most recent call last):
  File "C:\Users\shan's python work\PycharmProjects\da_pycord_botto\bot.py", line 581, in <module>
    member: Option(discord.member, 'Enter the member you would like to ask the question',
  File "C:\Users\shan's python work\PycharmProjects\da_pycord_botto\venv\lib\site-packages\discord\commands\options.py", line 156, in __init__
    raise exc
  File "C:\Users\shan's python work\PycharmProjects\da_pycord_botto\venv\lib\site-packages\discord\commands\options.py", line 151, in __init__
    _type = SlashCommandOptionType.from_datatype(input_type)
  File "C:\Users\shan's python work\PycharmProjects\da_pycord_botto\venv\lib\site-packages\discord\enums.py", line 693, in from_datatype
    if issubclass(datatype, str):
TypeError: issubclass() arg 1 must be a class

Process finished with exit code 1

Im getting this error for the following code

#
@client.slash_command(description='Play the classic backbench truth or dare game with your friend')
async def truthordare(ctx, truthordare: Option(str, 'Ask someone whether truth or dare, then enter the query here',
                                               choices=['Truth', 'Dare']),
                      member: Option(discord.member, 'Enter the member you would like to ask the question',
                                     required=False)):
    global url
    if truthordare == 'Truth':
        url = 'https://api.truthordarebot.xyz/v1/truth'
    elif truthordare == 'Dare':
        url = 'https://api.truthordarebot.xyz/v1/dare'
    resp = requests.get(url)
    e = discord.Embed(title=truthordare, url="https://play-lh.googleusercontent.com/"
                                             "slAvsPRR2-TSV1P96Ob6e8JyvaTrRHnNVG6-kQN3XDHKWhGNufdqcUSGjAetpmFHBVQ",
                      description=resp['question'])
    await ctx.respond(f'{member}', embed=e)
merry briar
#
@commands.slash_command(guild_ids=[GUILD_ID], description="test")
    async def testh(self, inter: discord.Interaction):
        await inter.response.defer()
        await asyncio.sleep(2)
        await inter.response.edit_message(content="test")
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: InteractionResponded: This interaction has already been responded to before```

how is it correct?
full basin
#

So you just do ApplicationContext.defer and then ApplicationContext.respond and the library will manage what to do.

fallow hawk
#

anyone know why my variable wont update through the button callback? i've tried some random things and not sure why it wont update

rugged lantern
ivory harness
#

can someone point me in the right direction on which branch i need to get for python 3.11 support?

fallow hawk
#

everything else works

rugged lantern
#

ok and u've printed in the supposed callback?

fallow hawk
#

wdym print

#

yes i have a print statement

#

to see if it works

#

and it does

proud pagoda
#

?tag install

obtuse juncoBOT
#
  1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
    python -m pip uninstall discord.py discord -y

2a. Install py-cord
python -m pip install py-cord

2b. Update py-cord
python pip install -U py-cord

Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.

Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord

fallow hawk
#

ik python konk

rugged lantern
fallow hawk
#

yeah ik it’s basic i’m just rusty and never rly got familiar with async functions

west pebble
#
10 its
20 this
30 basic
fallow hawk
rugged lantern
#

calling async functions is basically the same as normal functions. provide code or nobody will help you as it is not possible

fallow hawk
#

here is my code, i had to cut out random parts since it wouldn't let me send it

#

would it be better to put the stopp variable in the command and not the __init__?

rugged lantern
#

why do you have one variable as a self var and one as not? remove the variable that is not in the instance of the class

fallow hawk
#

not sure

#

i deleted it and its fixed konk

rugged lantern
#

btw use interaction: discord.Interaction instead of ctx in your callback for better typehinting

west pebble
#

Typehinting is magic. It should be forced.

fallow hawk
#

yeah it really is magic

silver moat
west pebble
#

I use pycharm

pulsar spear
#

It possible to disable buttons in a view for only certain people? For example just allow buttons to be pressed by the original response author?

median tinsel
#
async def booster_update(ctx):
    booster_role = discord.Guild.get_role(1037515948283936900)
    embed = discord.Embed(title="Boosters",description="",color=discord.Color.blue())
    names = ""
    for member in booster_role.members: names+=f"{member}\n"
    channel = bot.get_channel(1023695423061372949)
    embed.add_field(names="",value=names,inline=False)
    await channel.send(embed=embed)
bot.run(TOKEN)
#

I keep getting this error

#

Application Command raised an exception: TypeError: Guild.get_role() missing 1 required positional argument: 'role_id'

#

but I do have the role id in there

limber bison
#

I am looking for something we can use for power rankings. I like using tiermaker or tierlists. does anyone know of any similiar sites that have an api?

#

i like the ease of drag and drop for the user. ideally they would just submit a link with like /rankings link_to_yours: and i have it parse it + math

pseudo dawn
#

Hi, I want to run my bot with loguru instead of logging...
For the code I write myself and the code in my main file this works fine.
I use a custom handler for logging, but the things in cogs and other files, this does not work, even if i set the custom handler there....
Any Ideas on what to do?

vagrant scroll
#

Is this supposed to work?

rare ice
vagrant scroll
#

._.xd

west pebble
#

Lol wow

rare ice
#

It’s not that hard to run your code and see if it works.

west pebble
#

So did it work?

mental maple
#

Can i got an sended webhooks?

#

Like scrape old webhooks

vagrant scroll
left flume
#

is it possible to edit the content of a message from another message's view? In my example I'm trying to have a slash command send an ephemeral message to the author, that controls an embed in a followup message that everyone else can see

safe stirrup
#

Quick question because I've never specified only two intents, but does discord.Intents.all() attempt to load all intents Discord has, or all intents that the bot is enabled for?

round rivet
#

all intents that exist

safe stirrup
#

Thank you

mental maple
#

@round rivet is it possible to get old webhook data to be reused?

#

If i have the webhook id?

round rivet
#

yeah

wet ore
#

Probably a question for the Developers: Is it possible to convert the async def received_message(self, msg) inside class DiscordVoiceWebSocket to a bot.event?

Inside received_message contains the below code:

    elif op == self.SPEAKING:
        ssrc = data["ssrc"]
        user = int(data["user_id"])
        speaking = data["speaking"]

What I need is the speaking var as this contains the op code (1) for normal speaking, (5) a user who is a priority speaker inside a voice channel. I'm thinking if i use it as an event i'll be able to action what i need in there, any help/ ideas would be appreciated, thanks!

cobalt tangle
#

So, I have a aiosqlite instance in main.py, how do I use that in cogs?

async def on_ready(self):
    if not self.persistent_views_added:
            self.add_view(TicketCreateView())
            self.persistent_views_added = True
    setattr(bot, "db", await aiosqlite.connect("level.db"))
    await asyncio.sleep(3)
    async with bot.db.cursor() as cursor:
        await cursor.execute("CREATE TABLE IF NOT EXISTS levels (level INTEGER, xp INTEGER, user INTEGER, guild INTEGER)")
    print("Bot is ready!")
``` (my on_ready function)
cyan quail
fringe socket
#

Here's what sucks about this channel sometimes. Its only active during the time when I'm asleep.

#

:(

cobalt tangle
#

so bot.db = Bot()?

#

bot() is my bot class

fringe socket
#

No

cobalt tangle
#

then how?

fringe socket
#

bot.db = whatever

cobalt tangle
#

whatever=?

fringe socket
#

and then call the variable through self.bot

cyan quail
#

as per your original question...

#

whatever your aiosqlite instance is

cobalt tangle
#

bot.db = await aiosqlite.connect("level.db")?

cyan quail
#

sure that works

cobalt tangle
#

alr

dreamy mauve
#

discord.errors.Forbidden: 403 Forbidden (error code: 50021): Cannot execute action on a system message
Is there a way to filter out the system messages?

cyan lark
#

if i'm want to add error how i can to do this?

#

bc when i did this not work work

#

NVM MB

rugged lantern
#

lil bro censor guild id as if we could use it for something

ivory harness
#

I am trying to import a class function from my other python file which scrapes instant gaming website trending games and returns 20 games each in a list. I want my bot to respond in a message with all those scraped games when /keys command has been given. But ctx.respond(<passed class function>) does not work. Any ideas on how to properly pass my own class functions?

rugged lantern
ivory harness
#

much appreciated!

pale knot
#

Hi I know members in voice channel are ordered by alphabetical name, but how about symbols. It seems like symbols are ordered higher than the letter 'a'. Is there any way I can find the order of all the symbols

midnight wadi
#

How can u use custom emojis inside of an embed?

midnight wadi
#

nvm i got it

still helm
#

I am trying to make a bridge command that reacts on both, prefix and slash command. But there is a problem with the second args = ctx.message.content.split(' ')

@bridge.bridge_command(description="xxx")
    async def xxx(self, ctx):
        if isinstance(ctx, commands.Context):
            args = ctx.message.content.split(' ')
            if len(args) >= 2:
                frage = ' '.join(args[1:])
                mess = await ctx.send('xxx'.format(frage))
                await asyncio.sleep(2)
                await mess.edit(content='xxx')
                #some other stuff
                await ctx.message.delete()
        else:
            args = ctx.message.content.split(' ')
            if len(args) >= 2:
                frage = ' '.join(args[1:])
                await ctx.respond(ctx.author.mention + ' xxx `{0}` xxx: `{1}`'.format(frage, random.choice(discordVariable.antworten)))

    args = ctx.message.content.split(' ')
AttributeError: 'NoneType' object has no attribute 'content'
cyan quail
#

you can use ord to get any character's unicode value, and chr to do the opposite

cyan quail
still helm
cyan quail
#

oh i see

#

the else is when it's a slash command