#Basic Pycord Help (Quick Questions Only)

1 messages · Page 33 of 1

cobalt tangle
#

then

#

why r u subscripting it twice

#

oof nvm

vivid plaza
#

it won't work if I subscribe it once

#

💀

cobalt tangle
#

its not easy to view code on mobile yk

#

wait

vivid plaza
#

oh 💀 yeah right

cobalt tangle
#

do u not use aiosqlite

vivid plaza
#

sqlite3

cobalt tangle
#

bruh

#

try using aiosqlite but not related rn

vivid plaza
#

The other code is working with sqlite3

cobalt tangle
#

wait

cobalt tangle
#

but not related rn

#

wait

#

r u sure price[0][0] is a str

vivid plaza
#

Btw the message.mentions[0].id == 994347081294684240 returned False

cobalt tangle
#

price[0][0] in message.content

cobalt tangle
#

r u sure the message had proper mentions

vivid plaza
vivid plaza
vivid plaza
#

The things that returns False Are:

                print(message.content.startswith(f"**💰 | {message.author.display_name}, has transferred "))
                print(message.mentions[0] == 994347081294684240)
#

Others are True

vivid plaza
#

Okay

cobalt tangle
#

try

#
if "**💰 | {message.author.display_name}, has transferred" in message.content:
grizzled sentinel
#

print(message.mentions[0] == 994347081294684240) this will never return true because message.mentions returns a list of abc.User objects. you are comparing to an id. You will need to get the ID from the user object.

cobalt tangle
#

instead of startsWith

cobalt tangle
cobalt tangle
vivid plaza
#

Yes I'm trying it

cobalt tangle
#

tell me if that returns True

vivid plaza
#

False False True True

#

same as it was

cobalt tangle
#

what

#

print ur message.content

#

it works for me in vsc

vivid plaza
#

alr did

#

and here's my message.content

cobalt tangle
#

hm

#

print message.mentions

grizzled sentinel
#

\💰 != : moneybag:

vivid plaza
#

it is

#

💰 💰

cobalt tangle
#

it looks different on certain UI's

vivid plaza
#

Yup !

grizzled sentinel
#

its the correct emoji but the content seems to return discords name. The emoji is its own Unicode character. You are trying to compare it to text with a name that does not convert to an emoji on anything except within discord

cobalt tangle
#

maybe try just member.name

vivid plaza
vivid plaza
#

?unicode 💰

#

nvm

grizzled sentinel
#

No what i saying is you need to use :moneybag: not the emoji in your code for checking in the message

vivid plaza
#

okay

#

Let me try it again

#

Still returning False

cobalt tangle
#

wth

#

mind hopping on VSC Live Share maybe?

vivid plaza
cobalt tangle
#

Everything should be fine

vivid plaza
#

but wait I didn't define member?

cobalt tangle
vivid plaza
cobalt tangle
#

dms link

vivid plaza
#

wait

#

let me sign in first

#

I logged in I'll dm u my lnk

cobalt tangle
#

k

wanton wedge
#

i cant seem to send a message with the bot

#

i made the bot like 1 year ago and now i cant seem to send a message

#

whats wrong with this

jovial shoal
cyan quail
#

probably missing message_content intent

vivid plaza
#

hello this might be a dumb question and a read docs question. But how to make commands.has_permissions(administrator=True) but in slash_command

#

and where is it in docs

young bone
vivid plaza
#

@discord.default_permissions(administrator=True) ?

young bone
#

default_permissions is to hide the command for user which doesn´t have the permissions

vivid plaza
#

Okay thanks

vivid plaza
cyan quail
vivid plaza
#

okay thanks !

wanton wedge
jovial shoal
oblique river
#

i want to ban the member and not me "await interaction.user.ban()"

full basin
#

Then take a discord.Member option

oblique river
wanton wedge
#

but i do have manually enabled admin perms for the bot in the server itself

oblique river
#

Is it not possible to decide between the interaction.author and the interaction.member in PyCord?

oblique river
# jovial shoal the author is a member object

yes i want to ban a user and i want to do it through the user command but the problem is that i have interaction.user and it wants to ban me instead of the user i have selected that means i have to use interaction.author.ban ?

jovial shoal
#

interaction doesn't have an 'author' attribute. You likely want interaction.message.author

oblique river
#

but its not a message

#

i want to use Apps

limber urchin
#

You should be passing a user parameter to your user command though, right?

#
@user_command(name='mycommand', description='Example command')
async def my_user_command(self, ctx, user):...

Like this

#

The user parameter is the user you used the command on

limber urchin
#

Yeah, so why do you need to get the user through the interaction object?

oblique river
#
class Select(MyModal):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.add_item(...)

    async def callback(self, interaction: discord.Interaction):
      ...

    @commands.user_command(name="Modal")
    async def test(self, ctx: discord.ApplicationContext, user: discord.Member):
        modal = Select(title="Review")
        await ctx.send_modal(modal)```
limber urchin
#

I still don't see why you can't just use the user parameter

#

You can pass the user as a parameter to your Select class

oblique river
#

how do you mean when the class is above the command

limber urchin
#

So your user command is part of your Select class? Well in that case just set self.user = user and reference that in your callback

oblique river
limber urchin
#

Set self.user in your command executor. Obviously it won't work there

oblique river
limber urchin
#

I would advise you to learn a bit more Python before going into Bot development. You don't seem to know how OOP works in Python well enough yet

#

And as per #help-rules you should at least have a basic understanding of it before asking for help here

oblique river
#

w8 my fault i make a mistake

#

its the same self.user = user xD

limber urchin
#

Like said, try to learn a bit more how classes work in Python. Me telling you what to do and you guessing until you get it right won't be very progressive

glad brook
#

why the hell is this not working...

#
import discord

intents = discord.Intents.default()
intents.message_content = True
intents.members = True

debug_guilds = [ 1040291339901870200 ]

bot = discord.Bot(
    intents=intents,
    debug_guilds=debug_guilds
)

@bot.event
async def on_ready():
    print("lets gooo")

@bot.slash_command()
async def greet(ctx, user: discord.Member):
    await ctx.respond(user.display_name);
#

its giving me this error:

#

also yes im running the bot

limber urchin
#

Which version of Python are you using?

glad brook
#

latest

#

3.11

limber urchin
#

PyCord only works with Python 3.11 if you use the master branch

glad brook
#

ah okay

#

how do i get the master branch pacakge again

limber urchin
#

?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

glad brook
#

thank you

#

what version of python do i need to use for stable branch?

limber urchin
#

3.10

#

or lower

glad brook
#

alright

#

ty

limber urchin
#

👌

spice oyster
#

Is it possible to create and send a text file without temporarily saving it on disk? rooThink

limber urchin
#

Not sure, maybe using tempfiles

spice oyster
#

I don't get how to convert the string into a byte-like object, that I need to use for this method.
I've tried bytes() and encode() but they didn't work. Do you know another way for doing that?

limber urchin
#

Did you try

my_str = 'Hello World'
byte_object = str.encode(my_str)
neon bramble
#

can't you just do my_str.encode()?

spice oyster
limber urchin
#
@slash_command(name='example')
@commands.cooldown(1, 3, commands.BucketType.user)
async def example(self, ctx):
    ...
harsh canyon
#

in the process of migrating from discord.py to pycord and got this error

#

google didnt com eup with anything

harsh canyon
errant craneBOT
limber urchin
#

You need to import the module as well

#

from discord.ext

jovial shoal
#

If Discord is experiencing latency issues, is it reasonable that application commands might fail as a result?
Even with defer(), users are finding the commands failing during periods of high client latency

limber urchin
#

Yes, if Discord's API is having trouble, commands will fail

#

There isn't much to do about that, unless you add some error handling to detect an outage

#

You need to catch the commands.CommandOnCooldown error

peak chasm
#

to get the "user id" of the one using the command I have to put "ctx.id?"

limber urchin
limber urchin
#

"doesnt work" is not enough, you need to explain exactly what goes wrong and the errors you are getting

harsh canyon
#

does pycord have an equivalent of @bot.hybrid_command from discord.py?

peak chasm
#

yesterday they sent me that syntax and I wanted to know if it can be done somehow with choices=

errant craneBOT
#

Here's the bridge commands example.

harsh canyon
#

ty

cyan quail
#

should be discord.Member

fervent cradle
full basin
fervent cradle
#

ty it works

peak chasm
full basin
#

You sure about that?

#

Works for me

peak chasm
full basin
peak chasm
#
@bot.command(name="add_user",description="Create account for the user")
async def add_user(ctx,user:discord.option(name="user",description="Select to user for adding",choices=discord.Members)):
    resp = await api_sql.db_add_user(user.author.id)
    if resp:
        await ctx.respond("Agregado Correctoidemente")
    else:
        await ctx.respond("Ya existe manito usted")
#

spanish xddd

#

the rest in english

peak chasm
full basin
#

discord.Option(discord.Member, ...)

peak chasm
#

async def add_user(ctx,user:discord.option(discord.Member)):

#

will be my version of discord py?

harsh canyon
young bone
peak chasm
young bone
peak chasm
# young bone that is not the full list
aiodns                    3.0.0
aiofiles                  22.1.0
aiohttp                   3.8.3
aiohttp-socks             0.7.1
aiosignal                 1.2.0
altgraph                  0.17.2
anyio                     3.6.1
asgiref                   3.5.2
async-generator           1.10
async-timeout             4.0.2
attrs                     21.4.0
auto-py-to-exe            2.20.1
beautifulsoup4            4.10.0
bottle                    0.12.21
bottle-websocket          0.2.9
bs4                       0.0.1
certifi                   2021.10.8
cffi                      1.15.0
chardet                   4.0.0
charset-normalizer        2.0.10
click                     8.0.3
colorama                  0.4.4
commonmark                0.9.1
cryptography              36.0.1
discord-webhook           0.17.0
Django                    4.1.2
Eel                       0.14.0
et-xmlfile                1.1.0
Flask                     2.0.2
Flask-MySQLdb             0.2.0
frozenlist                1.3.1
future                    0.18.2
gevent                    21.12.0
gevent-websocket          0.10.1
greenlet                  1.1.2
h11                       0.12.0
html5lib                  1.1
httpcore                  0.15.0
httpx                     0.23.0
idna                      3.3
itsdangerous              2.0.1
Jinja2                    3.0.3
loguru                    0.6.0
lxml                      4.7.1
MarkupSafe                2.0.1
multidict                 6.0.2
mysql-connector-python    8.0.26
mysqlclient               2.1.0
numpy                     1.22.1
openpyxl                  3.0.9
outcome                   1.1.0
pandas                    1.4.0
pefile                    2022.5.30
Pillow                    9.0.0
pip                       22.2.2
protobuf                  3.18.0
py-cord                   2.1.3
pycares                   4.2.2
pycparser                 2.21
Pygments                  2.13.0
pyinstaller               5.1
pyinstaller-hooks-contrib 2022.7
PyNaCl                    1.4.0
pyOpenSSL                 21.0.0
pyotp                     2.6.0
pyparsing                 3.0.9
pytesseract               0.3.8
python-dateutil           2.8.2
python-dotenv             0.19.2
python-socks              2.0.3
pytz                      2021.3
pywin32-ctypes            0.2.0
requests                  2.26.0
rfc3986                   1.5.0
rich                      12.6.0
selenium                  4.1.0
setuptools                58.0.4
six                       1.16.0
sniffio                   1.2.0
sortedcontainers          2.4.0
soupsieve                 2.3.1
sqlparse                  0.4.3
trio                      0.19.0
trio-websocket            0.9.2
typing_extensions         4.3.0
tzdata                    2022.5
urllib3                   1.26.8
webencodings              0.5.1
Werkzeug                  2.0.2
wheel                     0.37.0
whichcraft                0.6.1
win32-setctime            1.1.0
wsproto                   1.0.0
XlsxWriter                3.0.2
yarl                      1.7.2
zope.event                4.5.0
zope.interface            5.4.0

limber urchin
#

I'd recommend using some sort of virtual environment to avoid conflicts, and a requirements.txt file to keep track of the libraries you need to install for your bot to work.

peak chasm
meager mica
woeful spindle
#

Anyone know why I’m getting this error? I’m can’t seem to find why..

Ignoring exception in on_connect
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 377, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/.local/lib/python3.9/site-packages/discord/bot.py", line 1138, in on_connect
    await self.sync_commands()
  File "/home/container/.local/lib/python3.9/site-packages/discord/bot.py", line 692, in sync_commands
    registered_commands = await self.register_commands(
  File "/home/container/.local/lib/python3.9/site-packages/discord/bot.py", line 570, in register_commands
    data = [cmd["command"].to_dict() for cmd in filtered_deleted]
  File "/home/container/.local/lib/python3.9/site-packages/discord/bot.py", line 570, in <listcomp>
    data = [cmd["command"].to_dict() for cmd in filtered_deleted]
  File "/home/container/.local/lib/python3.9/site-packages/discord/commands/core.py", line 841, in to_dict
    "options": [o.to_dict() for o in self.options],
  File "/home/container/.local/lib/python3.9/site-packages/discord/commands/core.py", line 841, in <listcomp>
    "options": [o.to_dict() for o in self.options],
  File "/home/container/.local/lib/python3.9/site-packages/discord/commands/options.py", line 315, in to_dict
    "type": self.input_type.value,
AttributeError: 'NoneType' object has no attribute 'value'
woeful spindle
#

anyone?

peak chasm
#

what should I put in @Bot.command() so that only admin can use it?

meager heron
peak chasm
peak chasm
woeful spindle
# peak chasm code?
@bot.slash_command(description = "View Aziel's current commands.")
async def help(self, ctx: discord.ApplicationContext):
    if not ctx.author.id == 831118106876969021:
        return await ctx.respond("This command is under maintenance.", ephemeral = True)
    pages = [
        discord.Embed(title = "test page 1"),
        discord.Embed(title = "test page 2")
    ]
    await ctx.respond(embeds = pages[0] if isinstance(pages[0], list) else [pages[0]], view = ButtonMenu(pages, 10, ctx.author))
#

I believe it’s this command since when commented out, I no longer get the error

peak chasm
#

I think it's the if and else

woeful spindle
#

hmm, let me try remove it

#

nope, i still get the error when using:

    await ctx.respond(embeds = pages[0], view = ButtonMenu(pages, 10, ctx.author))
peak chasm
peak chasm
woeful spindle
peak chasm
#

you should put the condition before or a function that does it in that case you could use "embed = def selec_embed"

meager heron
#

Mine was for slash commands

woeful spindle
peak chasm
woeful spindle
#

although i don’t believe it’s the if condition causing the error, I just tried embed = pages[0] yet I still get the same error

meager heron
#

I haven’t touched them in a year, though

peak chasm
#

try this

#
embed = discord.Embed(color=0x32CD32)
if condition:
  embed.title("test page 1")
else :
  embed.title("test page 2")
await ctx.respond(embed = embed)
#

and try taking out that "s" Maybe it has something to do with it, I wouldn't know how to tell you

woeful spindle
#

and I’m using buttons to swap through embeds

#

so there is no 1 embed

#

Which is why I had a pages list

#

which was a list of embeds

peak chasm
#

oh if it's buttons I couldn't help you yet I haven't gotten to that part :S

woeful spindle
#

ah no worries, hopefully someone else knows :)

full basin
#

@woeful spindle why don't you use the built in paginator

errant craneBOT
#

Here's the modal dialogs example.

meager mica
#

this if for me i couldnt find it

oak elm
#
    @discord.ui.button(
        label="Make a feedback",
        style=discord.ButtonStyle.primary,
        custom_id="nftgoio:feedback:make",
    )
    async def make_feedback(self, button: discord.ui.Button, interaction: discord.Interaction):
        await interaction.response.defer(ephemeral=True, invisible=False)
        followup = interaction.followup

        select_bord_view = SelectBoardView(boards=(await canny.client.list_boards()))
        msg = await followup.send(
            content="Please select a board and a category",
            view=select_bord_view,
        )
        await select_bord_view.wait()

        select_cate_view = SelectCategoryView(
            categories=(await canny.client.list_categories(select_bord_view.select.values[0]))
        )
        msg = await msg.edit(
            content="Please select a category",
            view=select_cate_view
        )
        await select_cate_view.wait()

        modal = FeedbackModal(title="Submit a feedback")
        await msg.send_modal(modal) 
        await modal.wait()

        print("board", select_bord_view.select.values[0])
        print("category", select_cate_view.select.values[0])
        print("author_mail", modal.children[0].value)
        print("title", modal.children[1].value)
        print("detail", modal.children[2].value)
        # edit followup: pop category select
    await msg.send_modal(modal)
AttributeError: 'WebhookMessage' object has no attribute 'send_modal

How can I send modal after two view . I tried to use followup, but it seems not work

full basin
#

Consider subclassing views and using callbacks

oak elm
#

I have no idea how to do that, may I have an example ( Pseudo code ) to show the right thing

#

I am stuck FalseFacePalmLaugh

errant craneBOT
#

Here's the confirm example.

oak elm
#
    @discord.ui.button(label="Confirm", style=discord.ButtonStyle.green)
    async def confirm_callback(
        self, button: discord.ui.Button, interaction: discord.Interaction
    ):
        # Don't send anything
        # await interaction.response.send_message("Confirming", ephemeral=True)
        self.value = True
        self.stop()

I noticed If comment out interaction.response.send_message, discord tips me interaction failed
Can I not response any message?

mortal junco
#

@worldly tendon howssss that game

cyan quail
#

but you can delete the message after if you wish (delete_after kwarg also works)

oak elm
proven ferry
#

Is there a solution?

proud mason
proven ferry
limber urchin
#

In what way did it "not work"

woeful spindle
soft bramble
#

@copper yew uh sorry for ping but you made BridgeCommandGroup right? if so is it possible to create it in a cog? trying to do so and struggling. I have seen the example

cobalt tangle
#

how do I get all the commands of my bot, divide them via cogs and have paginator for them?

#

an idea is enough for me

#

the issue is i have groups

cobalt tangle
#

iterate through?

#

walk_commands()?

cyan quail
#

bot.cogs is a list of cog objects
Cog.walk_commands() goes through every command, group and subcommand in said cog

cobalt tangle
#

Oh

#

and does it return a group if it encounters a group?

cyan quail
#

yes

cobalt tangle
#

and i can do group.walk_commands() right?

cyan quail
#

well Cog.walk_commands already includes subcommands from groups

cobalt tangle
cyan quail
#

which is why you can do command.qualified_name to get its full name

cyan quail
#

also slight correction, bot.cogs is a dict mapping of cog_name: cog_object

full basin
cyan quail
#

you can iterate through dicts in several ways

#

if you just want the object, you can use dict.values()

#

for the key, you can iterate just through dict

#

and if you want both, you use two variables to go through dict.items() py for name, cog in bot.cogs.items():

full basin
#

ok my question was really dumb

#

thanks lol

#

also, cant we access the slash command desc? as it returns a ApplicationCommand it only has 3 attributes

cyan quail
#

SlashCommand inherits from ApplicationCommand so command.description will work

#

because message and user commands don't have descriptions

cobalt tangle
#

im having trouble with Paginatir

#

paginator*

#

I want 10 commands to be shown on an embed at once

#

and I have a dropdown to pick Which cog's commands to view

cobalt tangle
full basin
rough path
#

how to add my no of servers in myactivity

cobalt tangle
#

in discord.Activity

proud mason
rough path
rough path
cobalt tangle
#

code?

vivid plaza
#

As you guys can see the netflix value went to spotify and the minecraft value went to netflix, Really weird

rough path
full basin
# rough path yes

bot.guilds returns a list. Figure out the rest and make an attempt. We don't spoonfeed here.

vivid plaza
#

anyone can help ?

peak chasm
full basin
#

Because it raises an error

#

And you must handle it

chrome skiff
peak chasm
full basin
#

Why not?...

woeful spindle
#

how do i edit the message a button is on with interaction?

limber urchin
cyan quail
#

Not quite, original_response is the response to the message and not the message itself

#

Id just recommend using interaction.response.edit_message

woeful spindle
woeful spindle
limber urchin
#

Could you show the full code?

woeful spindle
#

sure I’ll be on my pc in about 10-15 mins so I can send it then if that’s fine

limber urchin
#

Ah, your parameters for the buttons are in the wrong order, it's supposed to be self, button, interaction

woeful spindle
#

it seems to be working now, tysm! :)

#

although, my timeout for the buttons doesn’t seem to be working, the buttons don’t get removed after my set timeout and instead when using the buttons after my set timeout, I get a "interaction didnt respond" error on discord with no error on my console

lapis quarry
#

Anyone know how I can add set options for a parameter for a slash command, but also have a default value that isn't one of the choices?

meager mica
#

hey so i want to get a list of all the members who has permission to view channel so i can have somthing like users in ticket field

#

is that possible

#

without manually storing each one using for loop or somthing

#

is it this? im kinda confused what this does

peak chasm
#

Could pass me the API section to do something similar to this? pls 🥺

#

only the interactive box not the giveaways xd

errant craneBOT
#

Here's the modal dialogs example.

rocky dawn
#

is there a way i can make a specific user of the bot see and use slash commands (without changing integrated properties on discord)

peak chasm
harsh canyon
#

is there a tutorial or some examples somewhere about unpack_audio?

#

i can only find one reference in the docs

simple canopy
#

well, you iterate through role members and send a message?

#

.doclink discord.Role.members

stark walrus
#
import discord

bot = discord.Bot()

@bot.slash_command()
async def help(ctx, name: str = None):
    name = name or ctx.author.name
    await ctx.respond(f"Coming soon!")

@bot.user_command(name="Say Hello")
async def hi(ctx, user):
    await ctx.respond(f"{ctx.author.mention} says hello to {user.name}!")

bot.run(```
#

how to know if my comand is global or not (help command)

rocky dawn
peak chasm
#

so that they don't see it you will have to do a command with prefix "." or other than "/"

rocky dawn
woeful spindle
#

you can’t make it not show without changing the integrated permissions on discord afaik

rocky dawn
#

interesting, so what would be the best method to load and unload cogs

simple canopy
#

your (help) should be global

stark walrus
#

Ohh yay

peak chasm
#

How can I do so that if I choose an option, another 2 appear?

slash command

silver moat
peak chasm
#

i try this but no lol

silver moat
peak chasm
#

or do I do them separately?

rocky dawn
young bone
peak chasm
silver moat
peak chasm
#

will have to be done separately then, thanks <33

#

Can entry be restricted? make the options only enter numbers or characters?

silver moat
#

yes

errant craneBOT
#

Here's the slash options example.

rocky dawn
peak chasm
rustic parcel
#

i cant use $

#

somehow

young bone
peak chasm
#

does anyone know how to do this?

simple canopy
#

at least not in that way of usage

#

you should just use pip install without $

full basin
#

The fact you got an answer 4 hours ago.

#

And ignored it.

abstract otter
#

Hello! I am trying to get a referenced message from a slash command. However, when I use ctx.message, its value is None. But I need to somehow get the command's .reference attribute. Im honestly not sure if thats even a thing you can do, but I thought I'd ask!

abstract otter
woeful spindle
full basin
abstract otter
#

like, replying to a message with a command

#

but now that i think about it i dont think you can really do that

#

discord kind of gives the illusion of that happening but you arent really replying

#

Basically what I want to do is reply to a message with /convert and it will convert the attachments of that message to a different format

full basin
#

You can't use a slash command while replying.

#

The reply will just go away.

abstract otter
#

thats what I figured, thank you!

rustic parcel
meager mica
#

@commands.has_permissions(
administrator=True,
) how do i make it respond you dont have permission to use this instaed of just hrowing error

full basin
rustic parcel
#

Last time I made a threat and no one helped me

#

Am I supposed to wait until idk what happens

meager mica
#

adding try except every time seems inneficant

full basin
#

There's something called error handlers

#

You can't try except a decorator

#

At least try to investigate before being sarcastic on someone's anwer

meager mica
#

it was seperate comments

full basin
#

Your response was still sarcastic.

meager mica
#

because your response was helpless

full basin
#

Follow up questions exist.

#

I was looking for the example.

meager mica
#

thank you

peak chasm
#

Are these values ​​proper to the class?

limber urchin
#

If you have two children on your view, then yes

peak chasm
#

or perfect, is that in the class there is no children and I did not know xD

limber urchin
#

what

peak chasm
#

Notice children does not appear as a variable xd

limber urchin
#

I'm sorry, I don't understand you

solid gull
#

what was client. renamed too

round rivet
solid gull
#

so why is it not being registered

#

i lost my old codebase so im back like 200 days old

limber urchin
#

Hard to say without seeing any error messages or your code

solid gull
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'client' is not defined

#
import discord
import json
import requests

from discord.ext import commands

class Toontown(commands.Cog):

    """Cog for Toontown commands"""

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


    #TTR Districts Command
    @commands.command(pass_context=True, aliases=["ttr_districts", "ttr"])
    async def ttrdistricts(self, ctx):
        ttr_districts_api = "https://www.toontownrewritten.com/api/population"
        ttr_districts_response = requests.get(ttr_districts_api, verify=True)
        ttr_districts_json = ttr_districts_response.json()
        ttr_districts = ttr_districts_json["populationByDistrict"]
        ttr_districts = json.dumps(ttr_districts, sort_keys=True, indent=2)
        ttr_districts = ttr_districts.replace('"', '')
        ttr_districts = ttr_districts.replace(',', '')
        ttr_districts = str(ttr_districts)[1:-2]
        embed = discord.Embed(
            title=f'Toontown Rewritten Population',
            description='\uFEFF',
            colour=0x98FB98,
            timestamp=ctx.message.created_at)
        embed.set_thumbnail(url="https://i.ibb.co/RzrzDVh/TTR.png")
        embed.add_field(name="Population:", value=ttr_districts, inline=True)
        embed.set_footer(text=f"Ran by: {ctx.message.author} • Yours truly, {client.user.name}")
        embed.set_author(name=client.user.name, icon_url=client.user.avatar.url)
        await ctx.send(content=None, embed=embed)

def setup(bot):
    bot.add_cog(Toontown(bot))
limber urchin
#

You haven't defined a variable called client anywhere in that code

#

It's also not recommended to use the requests library for Discord bots as it's not async and will block code execution while the request is pending. But that's another issue

neon raven
#

I am trying to make a class having all the mod commands in my bot. I have a variable called config containing most of my config for the bot. but using commands.has_role() it says self is not defined.

class ModCommands(commands.Cog):
    def __init__(self, bot, config):
        self.bot = bot
        self.config = config
    
    @commands.command()
    @commands.has_role(self.config.get('modrole'))
    async def ping(self, ctx):
        await ctx.send('Pong!')

And here is the traceback

 File "d:/PythonProjects/aspect bot/main.py", line 4, in <module>
    from mod import ModCommands
  File "d:\PythonProjects\aspect bot\mod.py", line 4, in <module>
    class ModCommands(commands.Cog):
  File "d:\PythonProjects\aspect bot\mod.py", line 10, in ModCommands
    @commands.has_role(self.config.get('modrole'))
NameError: name 'self' is not defined

Any help?

limber urchin
#

self is only accessible inside of methods that have it as a parameter, so it doesn't exist in your decorator

neon raven
#

Any help on how I can access the variable?

limber urchin
#

The best way would be to write your own check inside of the command. alternatively try to do something with global variables but I'm not sure if that would work

neon raven
#

Okay ig. Lets see if it works

limber urchin
#

You could always just write your own has_role method and use that inside of your commands. Would probably be the neatest option

neon raven
#

Or i think I can configure this in the integrations section of the server itself

limber urchin
#

Up to you

neon raven
#

@limber urchin

#

I checked the Integrations section, / commands did not show up any explanation to why it might have happened?

limber urchin
#

Are the commands registered in the guild?

neon raven
#

I have no idea

#

how do I register it

limber urchin
#

Well can you use the command in a chat?

neon raven
#

I can't find them, how do I register it?

limber urchin
#

You can specify a list of guild IDs as the debug_guilds parameter when you create your Bot object. That way commands will automatically register directly in those guilds. If you don't, your commands will be global but it takes some time for them to sync

solid gull
#

Its been so long how do i call bot.commands inside of a cog

#

sorry comamnds.bot

limber urchin
#

I'm not sure what you're asking, why would you need to call that inside of a cog?

#

you should only create a bot instance once, preferrably in your main file

neon raven
#

config = Config()
debug = config.get('debug')
print(f'Debug mode is {debug}')
bot = discord.Bot(command_prefix=config.get('prefix'), debug_guilds= debug)
@bot.event
async def on_ready():
    print('Bot is ready.')


bot.add_cog(ModCommands(bot, config))
bot.run(config.get('token'))

is this the correct way to add debug guilds? Also why is add_cog() giving an error?

 File "D:\PythonProjects\aspect bot\env\lib\site-packages\discord\cog.py", line 544, in _inject
    bot.add_command(command)
AttributeError: 'Bot' object has no attribute 'add_command'
solid gull
#

i thought i have to prefix that with bot

limber urchin
limber urchin
solid gull
#

this is all i have

 def __init__(self, bot):
        self.bot = bot```
limber urchin
#

Yeah? So why can't you use self.bot?

solid gull
#

i just figured i couldnt let me test that

limber urchin
#

huh?

solid gull
#

i lost like 2 months worth of work

limber urchin
#

I don't get how that would prevent you from using self.bot

neon raven
#

@limber urchin Why is bot.add_cog() returing an error.

Traceback (most recent call last):
  File "d:/PythonProjects/aspect bot/main.py", line 16, in <module>
    bot.add_cog(ModCommands(bot, config))
  File "D:\PythonProjects\aspect bot\env\lib\site-packages\discord\cog.py", line 639, in add_cog
    cog = cog._inject(self)
  File "D:\PythonProjects\aspect bot\env\lib\site-packages\discord\cog.py", line 550, in _inject
    raise e
  File "D:\PythonProjects\aspect bot\env\lib\site-packages\discord\cog.py", line 544, in _inject
    bot.add_command(command)
AttributeError: 'Bot' object has no attribute 'add_command'
limber urchin
neon raven
#

2.2.2

limber urchin
#

Are you sure there are no conflicting packages? Like discord.py

neon raven
#

nope, using a venv

limber urchin
#

Hm, not sure then

hallow oriole
#

Hi guys, I currently try to log all slash command uses by using on_interaction. That also works pretty well, I just have one question: Is there a special attribute/function or so, which gives me the full command string?
So a attribute that gives me something like /group subcommand option1: value1 option 2: value2? That would make my life much easier...

limber urchin
solid gull
#

more actual question now:

server.icon_url_as what is called nmow

rare ice
winter condorBOT
hallow oriole
rare ice
solid gull
#

is icon_url still a thing

rare ice
#

No

solid gull
#

is there an alternative to it

limber urchin
#

Read the docs

neon raven
#

!help cogs

civic jayBOT
#

No command called "cogs" found.

neon raven
#

!help

limber urchin
#

Don't use this channel to spam commands

#

go to #app-commands or #883236900171816970

neon raven
#

How do I add cog?

config = Config()
debug = config.get('debug')
print(type(debug))
bot = discord.Bot(command_prefix=config.get('prefix'), debug_guilds= debug)
@bot.event
async def on_ready():
    print('Bot is ready.')


bot.add_cog(ModCommands(bot, config))
bot.run(config.get('token'))

class ModCommands(commands.Cog):
    
    def __init__(self, bot, config):
        self.bot = bot
        self.config = config
    
    @commands.command()
    async def ping(self, ctx):
        await ctx.send('Pong!')

This is right? but discord.Bot() is having issues adding cog, switching to commands.Bot() makes it work, why is it happening?

discord.Bot() shows this error

Traceback (most recent call last):
  File "d:/PythonProjects/aspect bot/main.py", line 16, in <module>
    bot.add_cog(ModCommands(bot, config))
  File "D:\PythonProjects\aspect bot\env\lib\site-packages\discord\cog.py", line 639, in add_cog
    cog = cog._inject(self)
  File "D:\PythonProjects\aspect bot\env\lib\site-packages\discord\cog.py", line 550, in _inject
    raise e
  File "D:\PythonProjects\aspect bot\env\lib\site-packages\discord\cog.py", line 544, in _inject
    bot.add_command(command)
AttributeError: 'Bot' object has no attribute 'add_command'

py-cord == 2.2.2

limber urchin
#

Because discord.Bot is a different class than commands.Bot

neon raven
#

So can I not add cogs in discord.bot ?

limber urchin
#

No

neon raven
#

sorry my bad

neon raven
#

How do get channel by id?

limber urchin
#

it's edit_original_response, not edit.

peak chasm
limber urchin
#

It's an example for how to create buttons that grants a user a role when clicking on them

peak chasm
limber urchin
#

yes

peak chasm
#

do you have any example? 🥺

limber urchin
#

Create a view, store a reference to the embed you want to change in the view, on the button callbacks, edit the embed to your liking

peak chasm
#

something like

async def button_callback():
  page -=1
  await interaction.response.send_modal(modal)

my example is horrible :'c xdxd

#

I better make it real and see haha

#

I'll be back in a few hours xd

limber urchin
#

Try on your own and come back if you run into any specific issues, we can't provide help with an entire feature

peak chasm
#

yep i will do that

#

thanks <3 bailame

#

Sorry if the things I say are misunderstood, my English is bad xd

limber urchin
#

What do you mean?

#

Like a cooldown for changing options?

peak chasm
#

I'm looking for how to delete everything and send a "thanks"

thin sierra
#

app commands not appearing without debug_guild list, do we must to use list for every guild?

limber urchin
#

No

#

The debug_guilds is to instantly register your commands to a specific set of guilds. Omitting the parameter will make your commands global but it can take up to an hour for the commands to register

thin sierra
#

like every time after code change?

cobalt tangle
#

how do I sync a channel

limber urchin
thin sierra
limber urchin
#

But you shouldn't be registering your commands as global while you're developing anyways

#

Just remove the param when you're done with your changes and ready to release them

thin sierra
#

got it

cobalt tangle
#

how do I add cooldown for interaction?

cobalt tangle
limber urchin
#

You need to implement it yourself

cobalt tangle
#

ok

cobalt tangle
# limber urchin You need to implement it yourself
class TicketCreateView(discord.ui.View):
    def __init__(self, bot):
        super().__init__(timeout=None)
        self.bot = bot
        cd_mapping = commands.CooldownMapping.from_cooldown(1, 120, commands.BucketType.member)

    @discord.ui.button(
        label="Open Ticket",
        style=discord.ButtonStyle.blurple,
        custom_id="create_ticket:blurple",
    )
    async def create_ticket(self, button: discord.ui.Button, interaction: discord.Interaction):
        view: TicketCreateView = self.view
        bucket = view.cd_mapping.get_bucket(interaction.message)
        retry_after = bucket.update_rate_limit()
        if retry_after:
            return await interaction.response.send_message("Sorry you are on cooldown, cooldown: 120s")
``` should work right?
limber urchin
#

Try it and see NPCMechanicShrug

cobalt tangle
#

thats why I asked

#

or i wouldve tried it

fervent cradle
#

I've tried installing the latest version of pycord, and im getting this error preventing it from finishing the installation.
ERROR: Failed building wheel for yarl
Failed to build multidict yarl
ERROR: Could not build wheels for multidict, yarl, which is required to install pyproject.toml-based projects

limber urchin
#

Upgrade pip with python3 -m pip install --upgrade pip

wooden lodge
#

how do i register Slashcommands in Discord with Pycord?

limber urchin
#

They will automatically be registered globally unless you define debug_guilds in your bot instance's init function

fervent cradle
wooden lodge
#

i started a JS handler who registerd for me a /ping command, the command worked and was registerd, after i started my PY bot again, the Ping command was deleted and no new one was registerd... and i dont use debug_guilds

limber urchin
#

You don't need a 3rd party handler to register commands

#

Global commands can take up to an hour to register

fervent cradle
#

building 'yarl._quoting_c' extension
error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
[end of output]

note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for yarl
Failed to build multidict yarl
ERROR: Could not build wheels for multidict, yarl, which is required to install pyproject.toml-based projects

#

I installed it though

wooden lodge
#

uhm, with the handler written in JS it was instant registerd

but i will wait an hour and see

limber urchin
#

Did you try doing what the error message tells you to do?

fervent cradle
#

yes

fervent cradle
#

Would anyone know how to edit a ephemeral message? This piece of code works on non-ephemeral messages but returns a "400 - Invalid Form Body" otherwise

cyan quail
#

So you've messed up something with your View

foggy mortar
#

why it says this
File "f:\fun\Desktop\coding practice\python practice\bot_pycord\main.py", line 2, in <module> from discord.ext import commands File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\__init__.py", line 18, in <module> from .flags import * File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\flags.py", line 57, in <module> @dataclass ^^^^^^^^^ File "C:\Program Files\Python311\Lib\dataclasses.py", line 1221, in dataclass return wrap(cls) ^^^^^^^^^ File "C:\Program Files\Python311\Lib\dataclasses.py", line 1211, in wrap return _process_class(cls, init, repr, eq, order, unsafe_hash, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\dataclasses.py", line 959, in _process_class cls_fields.append(_get_field(cls, name, type, kw_only)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\dataclasses.py", line 816, in _get_field raise ValueError(f'mutable default {type(f.default)} for field ' ValueError: mutable default <class 'discord.utils._MissingSentinel'> for field name is not allowed: use default_factory

fervent cradle
limber urchin
foggy mortar
#

um so i should downgrade my python

limber urchin
#

Either that, or install an unstable version of pycord

foggy mortar
#

what is the difference between unstable and stable

limber urchin
#

The unstable version may have bugs in it as it isn't fully released and tested yet

foggy mortar
#

how can i do that

limber urchin
#

.tag install

winter condorBOT
#

pip install py-cord

limber urchin
#

oops

#

?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

cyan quail
#

(Or just don't use 3.11 dab)

limber urchin
#

^^

foggy mortar
#

lol

#

imma try the unstable

#

are the basic stuff still the same?

limber urchin
#

You can read the changelog on github, but I don't believe there should be any major changes

foggy mortar
#

ok

grand prairie
#

Can Anyone Help Here 🙂

grizzled sentinel
#

My guess it you are turning an old bot with message commands into a bot with application commands?
THis should help

#

?tag forbidden

obtuse juncoBOT
#

You get a 403 Forbidden (error code: 50001): Missing Access as error?
You might've added your bot in the past without the applications.commands scope.

What to do?
Old way: Re-add the bot with the applications.commands scope.

New way: Since 11/07/2022 discord automatically includes the applications.commands scope in OAuth. You just need to re-add the bot with the bot scope. See [#discord-api-updates@996103073111998544](#discord-api-updates message) for more infos.

grizzled sentinel
#

Basically just re-invite the bot

solemn idol
#

Ok so,
I'm trying to make my bot delete logs older than 3 days listed in my # log channel.
I already got far enough to create the log functions itself

# Edit log
    @commands.Cog.listener()
    async def on_message_edit(self, message_before, message_after):
        member = message_after.author.mention
        the_channel = message_after.channel.mention
        channel = client.get_channel(log)
        channel_id = message_after.channel.id
        if channel_id == log:
            return channel_id == log
        else:
            pass
        em = discord.Embed(title="Message edited!", description = f"{member} has edited a message in {the_channel}.", color = em_yellow)
        em.add_field(name = "**Message before:**", value = message_before.content)
        em.add_field(name = "**Message after:**", value = message_after.content)
        await channel.send(embed = em)

and

# Purge log
    @commands.Cog.listener()
    async def on_message_delete(self, message):
        member = message.author.mention
        the_channel = message.channel.mention
        channel = client.get_channel(log)
        channel_id = message.channel.id # Built this stuff in here due to cog listeners (checkers), do not support ctx.
        if channel_id == log:
            return channel_id == log
        else:
            pass
        em = discord.Embed(title = "Message deleted!", description = f"{member} has deleted a message in {the_channel}.", color = em_red)
        em.add_field(name = "**Message:**", value = message.content)
        await channel.send(embed = em)

But now I want my bot to automatically delete logs older than 3 days which it sent itself in # log
I was thinking of using message.created_at somehow but I have no idea how.

full basin
#

Tasks?

solemn idol
#

It just has to delete any message older than 3 days in my log channel, yes I know the limit of deleting messages is 14 days but if theres no message older than 14 days in the channel it should be fine.

grand prairie
#

the bot even has all intents and admin perms

errant craneBOT
#

Here's the background task example.

limber urchin
solemn idol
#

oh

#

that seems simple enough, thanks.

grizzled sentinel
grand prairie
#

same as this

#

both bot and application.commands ticked

grizzled sentinel
#

Are you on the latest pycord version?
Also I assume you copied the URL at the bottom of the page In the image above and not somewhere else.

grizzled sentinel
#

join is an int not a list

hybrid oasis
#

anyone know: is it possible to edit an ephemeral view when it times out?

grizzled sentinel
#

It is possible, make sure to have proper error handling if the message does not exist anymore.
It should work the same way as editing a non ephemeral view on timeout

hybrid oasis
#

self.message is NoneType when it's ephemeral though! how can i get the message object?

#

my timeout code, super simple

grizzled sentinel
#

how long is the timeout

hybrid oasis
#

i've got it at 30s for testing

grizzled sentinel
#

The message that this view is attached to. If None then the view has not been sent with a message.
From the docs i think you need something else. Give me one second

hybrid oasis
#

maybe i need to pass the message/interaction to the view as a separate object? thinkingincircles

opaque glacier
#

for some reason import commands isn't working

#

can someone please help?

full basin
#

You need to import it from somewhere chief

grizzled sentinel
full basin
#

Full path is discord.ext.commands

opaque glacier
#

thanks

hybrid oasis
young bone
#

self.client.get_channel()

grizzled sentinel
solemn idol
sullen ledge
#

is there a way to still use prefix commands as well as slash commands?

young bone
#

I cannot use the slash command again here...

young bone
solemn idol
#
from discord.ext import bridge

bot = bridge.Bot(intents = intents, prefix = !)
#

you can still use the slash command decorator and prefix commands in your bot

solemn idol
young bone
solemn idol
#

no... it seems like the parameters within the decorator are false..

solemn idol
#

because this works

hybrid oasis
#

passing the original_message to the view and that works like a charm! ❤️

grizzled sentinel
#

You always have to try a few things with ephemeral because they act weird on discords side

hybrid oasis
#

so glad i got this figured out 😍 my game's UX increased by 100% now

#

thank you very much!

fervent cradle
#

error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
[end of output]

note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for yarl
Failed to build multidict yarl
ERROR: Could not build wheels for multidict, yarl, which is required to install pyproject.toml-based projects

I cant install pycord, i have installed C++ 14.0

neon bramble
#

you're trying to install a module with c components without a c compiler i guess

meager heron
#

Map to str

wintry gulch
#

Hey! Does anyone know how I could access the guild id in cogs/init.py?
Thanks!

wintry gulch
#

I have some models :

class GuildConfig(Model):
    id = fields.BigIntField(pk=True, unique=True, nullable=False)
    prefix = fields.TextField(default="$")
    mod_enabled = fields.BooleanField(default=False)```
And in the __init__.py I would like to load the specified cog if it's enabled
fervent cradle
neon bramble
#

could you send the whole traceback

fervent cradle
#

yeah sure sorry

#

Traceback (most recent call last):
File "C:\Users\Wacky\Documents\FoolishBot\main.py", line 6, in <module>
from discord.ext import commands
File "C:\Users\Wacky\Documents\FoolishBot.venv\Lib\site-packages\discord\ext\commands_init_.py", line 18, in <module>
from .flags import *
File "C:\Users\Wacky\Documents\FoolishBot.venv\Lib\site-packages\discord\ext\commands\flags.py", line 71, in <module>
@dataclass
^^^^^^^^^
File "C:\Users\Wacky\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 1221, in dataclass
return wrap(cls)
^^^^^^^^^
File "C:\Users\Wacky\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 1211, in wrap
return _process_class(cls, init, repr, eq, order, unsafe_hash,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Wacky\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 959, in _process_class
cls_fields.append(_get_field(cls, name, type, kw_only))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Wacky\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 816, in _get_field
raise ValueError(f'mutable default {type(f.default)} for field '
ValueError: mutable default <class 'discord.utils._MissingSentinel'> for field name is not allowed: use default_factory

full basin
#

What's your python version

fervent cradle
#

11

full basin
#

Are you using the github version

#

Stable doesn't support 3.11

fervent cradle
#

I installed it on python.org, not github & used pip install py-cord==2.0.0rc1

full basin
#

That version is old as hell

fervent cradle
#

Oh lol

full basin
#

Uninstall py-cord and install the github version

#

?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

fervent cradle
#

alr will do

fervent cradle
fervent cradle
#

Obviously TOKEN is the token

sullen ledge
#

how would i go about adding a user cooldown to a interactive button?

full basin
sullen ledge
silver moat
full basin
#

What's join

#

What it actually is

#

Print it

sullen ledge
#

and the commands.CooldownMapping doesnt exist on the api docs

silver moat
#

please use an actual IDE.

wintry gulch
#

I think he's using pterodactyl

fervent cradle
young bone
#

you really should start to use cogs...

fierce hazel
#

Am I understanding the checks argument from SlashCommand right that I can pass any function into it and it will only allow the command to execute if the check function returns the equivalent of bool True?

woeful spindle
still helm
#

does a bridgeCommand works with checks too?

silver moat
woeful spindle
#

I have this custom check but my command is still executing.. anyone know why?

foggy mortar
#

Traceback (most recent call last): File "F:\fun\Desktop\coding practice\python practice\bot_pycord\main.py", line 10, in <module> bot.intents = discord.Intents.all() ^^^^^^^^^^^ AttributeError: property 'intents' of 'Bot' object has no setter

#

why?

silver moat
#

intents should be passed in when the bot object is created.

still helm
# silver moat yes

trying to check the link in my bridgecommand if it´s a tiktokurl

 async def checkURL(self, ctx):
        print("in function")
        linkPrefixes = ['https://m.tiktok.com', 'https://vt.tiktok.com', 'https://tiktok.com',
                        'https://www.tiktok.com', 'https://vm.tiktok.com/']

        for link in linkPrefixes:
            if link in ctx:
                print("True")
                return True
        return False

    @bridge.bridge_command(description="xxx", checks=checkURL)
    async def tikload(self, ctx, link):
        if link is not None:
            if isinstance(ctx, commands.Context):
                await ctx.message.delete()
                await ctx.send("xxx", delete_after=5)
                .....

but i get TypeError: 'function' object is not iterable

still helm
#
Ignoring exception in on_interaction
Traceback (most recent call last):
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 377, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1141, in on_interaction
    await self.process_application_commands(interaction)
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 822, in process_application_commands
    await self.invoke_application_command(ctx)
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1088, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 371, in invoke
    await self.prepare(ctx)
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 291, in prepare
    if not await self.can_run(ctx):
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 400, in can_run
    return await async_all(predicate(ctx) for predicate in predicates)  # type: ignore
TypeError: 'function' object is not iterable
silver moat
silver moat
still helm
#

it is

silver moat
#

I don't see where checkURL is used.

still helm
woeful spindle
silver moat
#

like how the decorator is used.

tender seal
#

what do I do
I have PyCord installed

#

I reinstalled it,

#

what do I do

silver moat
#

pip list in terminal and show output thanks.

tender seal
#

pycord 0.1.1

#

if I sent the whole list I'd have to send a txt file

#

do I have to

silver moat
silver moat
#

?tag not pycord

obtuse juncoBOT
#

dynoError No tag not found.

tender seal
#

I'm trying to make a bridged bot

silver moat
#

?tag notpycord

obtuse juncoBOT
#

The library name is py-cord not pycord

tender seal
#

so it has both slash and prefixed at the same time

tender seal
#

oh wait I thought there was like 3 times more

#

well here it is

errant craneBOT
#

Here's the slash cog example.

silver moat
tender seal
#

I thought I uninstalled it

silver moat
#

allegedly

tender seal
#

well uh thanks

tender seal
#

yeahhh well now it says a different error

silver moat
#

restarted vsc?

tender seal
#

maybe I should

#

same thing though

#

after restart

silver moat
#

huh. try reinstalling py-cord?

fiery tiger
#

after saving the user OAuth2 token for a user after allowing me to use guilds.join how can i make the user join back to the guild?

tender seal
#

ehh, maybe I'll try Sublime Text

#

also vscode just crashed for me

#

wow.

#

closed itself

silver moat
jaunty raft
#

hey guys why is it not working?

silver moat
#

.tag idw

winter condorBOT
#

Saying it doesn't work or asking what's wrong with this code is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.

jaunty raft
#

i setted those options

#

but it doesnt show up

silver moat
woeful spindle
# silver moat like how the decorator is used.
@bot.slash_command(description = "Use Aziel's Help Panel!")
@checks.mod_only()
async def help(ctx: discord.ApplicationContext):
    emb = discord.Embed(colour = 0x2f3136)
   # and all the other unimportant stuff
jaunty raft
#

to know

#

Sorry

silver moat
jaunty raft
#

but the options

tender seal
#

huh

#

this is weird..

#

so I uninstalled pycord and ran my code

tender seal
#

and it shows the same error

silver moat
#

strange.

tender seal
#

and discord still imports somehow

woeful spindle
tender seal
#

OHHHH I'm dumb

silver moat
#

you can run await ctx.respond and return False seperately

tender seal
#

I have py-cord installed

#

btw why is there pycord and py-cord

jaunty raft
silver moat
#

?tag notpycord

obtuse juncoBOT
#

The library name is py-cord not pycord

tender seal
#

ok

#

why does pycord exist, however

jaunty raft
#

oh so it's choices

#

and not options

silver moat
fervent cradle
#

Will slash commands take a bit to appear? I made a slash command and it isnt showing

vale garden
#

global slash commands take up to an hour

silver moat
tender seal
#

ok guys now it works

#

thanks

fervent cradle
fervent cradle
silver moat
fervent cradle
#

oh

foggy mortar
#

my command have an error `Ignoring exception in command privchannel:
Traceback (most recent call last):
File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\core.py", line 178, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "F:\fun\Desktop\coding practice\python practice\bot_pycord\main.py", line 15, in privchannel
id2:str = ctx.args[1]
~~~~~~~~^^^
IndexError: list index out of range

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

Traceback (most recent call last):
File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\bot.py", line 347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\core.py", line 950, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\core.py", line 187, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range`
code:https://paste.pythondiscord.com/qalagaxopu

cyan quail
#

pretty sure the global 1 hour wait was removed a while back yeah

foggy mortar
#

why

fervent cradle
cyan quail
silver moat
foggy mortar
#

ok

fervent cradle
#

I restarted my discord client & made sure its reading all of the code

cyan quail
silver moat
fervent cradle
fervent cradle
cyan quail
#

are you loading cogs in on_ready

woeful spindle
#

like this?

fervent cradle
# cyan quail are you loading cogs in on_ready
import os

from dotenv import load_dotenv
load_dotenv()
from discord.ext import commands


bot = commands.Bot(intents = discord.Intents.all(),command_prefix='!', activity = discord.Activity(type=discord.ActivityType.playing, name="BennixMC"))
@bot.event
async def on_ready():
    print('I am online')
@bot.event
async def on_application_command_error(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        await ctx.respond(f'This command is on cooldown, Try again in {round(error.retry_after)} seconds')
directories = ["Fun commands", "./Utility Commands","./Embeds"]
for directory in directories:
    for filename in os.listdir(directory):
        if filename.endswith(".py"):
            
          bot.load_extension(f"{directory[2:]}.{filename[:-3]}")

bot.run(os.getenv("TOKEN"))``` (If this code is slightly outdated, then is because its old code haha)
#

^ no im not loading it in on ready

tender seal
#

hi there uh

cyan quail
#

seems fine i guess

tender seal
#

so I'm making a bridged bot

cyan quail
#

what does the cog look like

tender seal
#

if that makes sense

#

and when I use a command, nothing happens

fervent cradle
# cyan quail what does the cog look like
import discord
from discord.ext import commands

class Server(commands.Cog):
    def __init__(self, bot):
        self.bot = bot



@commands.slash_command(name="serverinfo") 
async def serverinfo(self, ctx):
        await ctx.respond("Server Info..")




def setup(bot):
    bot.add_cog(Server(bot))
cyan quail
#

well

fervent cradle
tender seal
#

as in if I use a prefixed command (prefix being t?) it doesn't work
but it works with the slash command

cyan quail
#

your command isn't actually in the cog

fervent cradle
#

ill help if i can but am rusty

tender seal
# fervent cradle show ur code
intents = discord.Intents()
intents.message_content = True

bot = bridge.Bot(command_prefix="t?", intents=intents)
print("BOT INITIALIZING...")
@bot.event
async def on_ready():
  print("BOT ONLINE")

@bot.bridge_command()
async def sum(ctx, a: int, b: int):
  print('someone used sum command ooo')
  await ctx.respond(a + b)

bot.run(_token)
fervent cradle
#

the def

cyan quail
#

yes

#

because that class is the cog

tender seal
#

works with the slash command, doesn't if i do t?sum 1 2

#

in chat

tender seal
#

oh

cyan quail
#

you should do Intents.default() instead of just Intents()

tender seal
#

ok

#

I'll try that

fervent cradle
#

Appreciated it works now, will get to actualy doing this

tender seal
#

thanks

#

man you guys are life savers for beginners

silver moat
tender seal
#

yeah LOL

#

nah if they're integers, it does actual math

#

if I saved the arguments as strings however it would respond with 69

tender seal
silver moat
#

woo

#

with the current snippet, it is hard to see what you are doing. Please share more code.

tender seal
#

hey chat
because I'm lazy, and it's like 11pm
how do I check if a user has admin perms

rare ice
#

.docs discord.Member

winter condorBOT
tender seal
#

I thought it was discord.User

rare ice
#

If you read the docs you’d know.

silver moat
silver moat
tender seal
#

ok but which one of these is the admin attribute 😭

tender seal
#

excluding methods

rare ice
#

.guild_permissions

tender seal
#

guild_permissions?

#

ok

rare ice
#

.guild_permissions returns a tuple of permissions

#

that a member does and doesn’t have

tender seal
#

ok

#

and then I can look for "administrator"?

rare ice
#

.docs discord.Permissions.administrator

rare ice
#

That will be in discord.Permissions, what is returned

#

It will either be True or False

tender seal
#

so now with that out of the way

#

is it ctx.member or what is it

rare ice
#

Well what are you trying to do

tender seal
#
async def say(ctx,
        msg: Option(str, 'The thing you want the bot to say',
              required=True, default=None), 
        hidden: discord.Option(str, 'Do you wanna keep it secret?', choices=['True', 'False'], required = False, default='True')
        ):
  if not hidden:
    await ctx.respond(f'{msg}')
  else:
    await ctx.send(f'{msg}')
spiral nacelle
#

Can you have "wild cards" in URL links

silver moat
#

ctx.author can return a member or a user depending on the context

tender seal
#

I really don't wanna dig through the docs

#

ok thanks

rare ice
tender seal
#

yeah sorry if I'm getting on your nerves

silver moat
silver moat
spiral nacelle
#

So the 122 needs to read as anything

silver moat
#

so you are fetching an image but you don't know part of the url?

spiral nacelle
#

Just the day number changes

silver moat
#

or am I misinterpreting the question

#

does the change regularly?

spiral nacelle
#

Every day +1

silver moat
#

ok so what's the issue?

full basin
#

Then why are you comparing an ID with a Member object

fervent cradle
#

why isnt

Server = discord.Embed(title="Server Statistics", description=f"Server Owner: {ctx.guild.owner}\n Server Name: {ctx.guild.name}\nMember Count: {mem}", color = 0x1295db)
 Server.set_footer(f"Server ID: {ctx.guild_id}")``` working? It worked before i added the footer.
#

Dw abt the indentation, just messed up when sending

opaque glacier
#

How do you set multiple lines for embed?

fervent cradle
opaque glacier
#

thanks

full basin
#

do you realize that will always default to your else? a member object will never be the same as an id

opaque glacier
#

should work

young bone
fervent cradle
#

no

young bone
#

set_footer(text="")

fervent cradle
#

Oh thanks

opaque glacier
#

myb

woven harbor
#

hi, a bit of a noob question here:

how do you supposed to pass variables into a decorator?

e.g. with this code is there anyway to put self.placeholder into the decorator

full basin
#

youd need to subclass your select and then add it to your view

woven harbor
#

oh boy

#

that seems like a mess maybe ill just hardcode this for now

full basin
#

its almost the same thing lol

#

instead of subclassing a view, you subclass the select and pass the parameters

#

then just add it to a view

woven harbor
#

wait

#

ok let me try it

#

ok i can subclass the select, but i dont get how to pass the parameters

#

should i just append my subclass to view.childrens

#

maybe i didn't subclass this properly decorators are weird

wintry gulch
#

Hey, sorry for re-asking.

What I would like is a way to load cogs if the option is enabled (in the db)

So I have some models:

class GuildConfig(Model):
id = fields.BigIntField(pk=True, unique=True, nullable=False)
prefix = fields.TextField(default="$")
mod_enabled = fields.BooleanField(default=False) ```
and I have my cogs/_init_.py which loads the cogs as so:
```python
def setup(bot: 'Nethra'):
bot.add_cog(Moderator(bot))

but in order to get the guild config I need its id, and I can't figure out how! If anyone knows how I could do this, I would be very grateful! Thanks!

foggy mortar
#

how can you make a permission overwrite object and what will the syntax of it be?

full basin
foggy mortar
#

ok got it

woven harbor
#

does anyone know whats missing im getting this error when trying to make a persistent view

#

view has no timeout

#

and there's a customid set

#

nvm

#

im bad i was calling super init again later

wooden lodge
#

Hello, i have a bot related question. For a while now i saw that the second bot does not have an online symbol. Does anyone know what is going on with this? Like how did he hide that even though he is online

full basin
#

The bot is connected through http connections

mortal junco
#

Guys I know this is kinda stupid but how do I make my bot run by just opening the py file

#

I paid for a bot hosting just for them to tell me they don’t support the way I open it

sweet tiger
#

How could I check if a user is server muted / not server muted

sweet tiger
full basin
sweet tiger
silver moat
sweet tiger
#
@tasks.loop(seconds=60)
async def my_loop(userobj, memberobj):

    if memberobj.voice.mute == False and memberobj.voice.deaf == False:
        await memberobj.edit(mute=True)
        await memberobj.edit(deaf=True)
    else:
        print("user already muted / deafened")
Traceback (most recent call last):
  File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\tasks\__init__.py", line 176, in _loop
    await self.coro(*args, **kwargs)
  File "D:\Coding Stuff\Python\Discord\Other Miscellanious Bots\Mute Annoying People\constantlyMuteAnnoyingPeople.py", line 20, in my_loop
    await memberobj.edit(deaf=True)
TypeError: Member.edit() got an unexpected keyword argument 'deaf'```
#

anyone able to help?

silver moat
sweet tiger
#

bruh im dumb, thanks

silver moat
lilac citrus
fringe socket
#

Nice bot pfp

#

How'd you make it?

weak hatch
#

because it doesn't have.

fervent cradle
#

looks nice

fervent cradle
#

so im getting this error

Ignoring exception in command whitelist_user:
Traceback (most recent call last):
  File "C:\Users\Nikola\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 124, in wrapped
    ret = await coro(arg)
  File "C:\Users\Nikola\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 980, in _invoke
    await self.callback(ctx, **kwargs)
  File "c:\Users\Nikola\Documents\fn id lookup\bot.py", line 57, in whitelist_user
    if user.id not in whitelist['users']:
AttributeError: 'str' object has no attribute 'id'

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

Traceback (most recent call last):
  File "C:\Users\Nikola\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\Nikola\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 375, in invoke
    await injected(ctx)
  File "C:\Users\Nikola\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'str' object has no attribute 'id'```
which ive never had before
#

command

@bot.slash_command(description="Add or remove a user from whitelist (BOT OWNER ONLY)")
@option("action", str ,description='"add" or "remove"')
@option("user", str ,description='The user you wish to whitelist')
async def whitelist_user(ctx, action, user: discord.User):
    if ctx.author.id in whitelist['owners']:
        action = action.lower()
        if action=="add":
            if user.id not in whitelist['users']:
                manage_whitelist(user.id, "+", "users")
                await ctx.respond(embed=discord.Embed(description=f"Added `{await bot.fetch_user(user.id)}` ({user.id}) to Premium whitelist!", color=0x5ed515), ephemeral=True)
                await user.send(f"`{await bot.fetch_user(user.id)}` has whitelisted you! You can now use `/lookup`!")
                log(f"{await bot.fetch_user(ctx.author.id)} ({ctx.author.id}) has whitelisted {await bot.fetch_user(user.id)} ({user.id})")
            else:
                await ctx.respond(embed=discord.Embed(description=f"`{await bot.fetch_user(user.id)}` ({user.id}) is already whitelisted!", color=0xea0000), ephemeral=True)
        elif action=="remove":
            if user.id in whitelist['users']:
                manage_whitelist(user.id, "-", "users")
                await ctx.respond(embed=discord.Embed(description=f"Removed `{await bot.fetch_user(user.id)}` ({user.id}) from whitelist!", color=0x5ed515), ephemeral=True)
                log(f"{await bot.fetch_user(ctx.author.id)} ({ctx.author.id}) has removed {await bot.fetch_user(user.id)} ({user.id}) from whitelist")
            else:
                await ctx.respond(embed=discord.Embed(description=f"`{await bot.fetch_user(user.id)}` ({user.id}) is already whitelisted!", color=0xea0000), ephemeral=True)
    else:
        await ctx.respond(embed=discord.Embed(description="Only a owner can use this command :slight_smile:", color=0xea0000), ephemeral=True)```
#

any ideas?

jaunty raft
#

Thats my idea

#

change my mind

fervent cradle
jaunty raft
fervent cradle
#

i did define that

#

async def whitelist_user(ctx, action, user: discord.User):

jaunty raft
#

so u want it to autocomplete members?

fervent cradle
#

yea

#

and it did before but now it doesnt

jaunty raft
#

but it will expect a string

#

Not a member

#

So it will cast it to a string

fervent cradle
#

user: discord.User isnt right then?

#

ohh

jaunty raft
#

Like it must be maybe a discord.Member or a discord.User obj

fervent cradle
#

@option("user", str ,description='The user you wish to whitelist') this? so id have to change str to discord.User?

jaunty raft
#

Yeah

#

Or discord.Membet

#

Member

fervent cradle
#

yeah works now

#

im confused, i havent had that issue before

chrome skiff
#

Is this #discord-api-updates message already added to pycord?

limber urchin
#

Not yet, it's a planned feature

chrome skiff
#

okay

woeful spindle
#

don’t think that’s got anything to do with pycord…

foggy mortar
#
  File "F:\fun\Desktop\coding practice\python practice\bot_pycord\main.py", line 2, in <module>
    from discord.ext import commands
  File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\__init__.py", line 18, in <module>
    from .flags import *
  File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\flags.py", line 57, in <module>
    @dataclass
     ^^^^^^^^^
  File "C:\Program Files\Python311\Lib\dataclasses.py", line 1221, in dataclass
    return wrap(cls)
           ^^^^^^^^^
  File "C:\Program Files\Python311\Lib\dataclasses.py", line 1211, in wrap
    return _process_class(cls, init, repr, eq, order, unsafe_hash,
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Program Files\Python311\Lib\dataclasses.py", line 959, in _process_class
    cls_fields.append(_get_field(cls, name, type, kw_only))
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Program Files\Python311\Lib\dataclasses.py", line 816, in _get_field
    raise ValueError(f'mutable default {type(f.default)} for field '
ValueError: mutable default <class 'discord.utils._MissingSentinel'> for field name is not allowed: use default_factory
#

why?

limber urchin
#

If you're using Python 3.11 you need to use the unstable version of pycord

#

so either downgrade your Python, or use the master from GitHub

foggy mortar
#

ah i forgot it again 🤦‍♂️

limber urchin
#

Looks like an error from the googletrans module you're using, not much we can do to help you here

sullen ledge
#

is any1 aware of any way to add a cooldown to a button (one where the cooldown only applies for the user)

limber urchin
#

There is no way to do this with the library right now, so you would have to implement your own solution for it

foggy mortar
limber urchin
#

I would do something like this:

- Set up a globally available dict with button IDs as the keys and lists/sets as the values
- When a user clicks a button, add the user to the list mapped to the button ID
- Remove the user from the dict after x number of seconds
- Every time the user clicks on a button, check if they are part of the list/set mapped to the buttons ID
foggy mortar
#

yea that would be what i do

limber urchin
#

I personally prefer using sets as they are way faster than lists when checking if something is part of it, but it depends on your solution and how you want to implement it

foggy mortar
#

how can you make descriptions for a option in a slash command?

limber urchin
#

Add a description='Your description here' parameter to your Option constructor

foggy mortar
#
@bot.command(description="sends the option you put") 
async def option(ctx,option:str): 
    await ctx.respond(f"{option}")

where would i put it?

limber urchin
#

import Option from discord.commands and type hint your option to that instead, it allows you to set a type, description and requirement. Like this

from discord.commands import Option

@bot.command()
async def my_command(ctx, option: Option(str, description='My option description', required=True))
...
foggy mortar
#

ok ty

limber urchin
foggy mortar
#

would it be discord.commands or discord.ext.commands?

limber urchin
#

discord.commands

foggy mortar
#

ok

#

user1:discord.commands.Option(input_type=discord.Member,description='User 1') but the option is just a str not letting me choose the user

#

or do i have to do from discord.commands import Option

#

nvm got it sorted

fervent cradle
#

With discord.ui buttons, is there any way to just store if an interaction has happened? I don't want to react to the interaction right away, but rather know if the user clicked yes/no and do something with that later. I saw #discord.InteractionResponse.defer, but I don't understand how it works.

limber urchin
fervent cradle
limber urchin
fervent cradle
#

Hmm that's not what I'm looking for.

#

I want to have a message ask for example a yes/no question, and simply store what the user clicked so I can use that information later on in the command.

limber urchin
#

I mean I don't think you have to respond to a button interaction, you can just store it. But it's always good to acknowledge a button click so that the user knows something has happened when they clicked it and doesn't think the button didn't work

fervent cradle
#

Well really my question is how do I store it, lol

limber urchin
#

It depends on how you want to use it later

atomic wolf
#

Im new to py-cord and this stuff and i get an error "discord.errors.InteractionResponded: This interaction has already been responded to before" i know what it stands for but i don't know how to fix it 😅

limber urchin
atomic wolf
#

But i have to edit it twitce

limber urchin
#

Then edit it, don't respond

fervent cradle
#

Bot asks question, user clicks button "option 1" or "option 2", all I want to store is the str text that's on the button. So if the user clicks "option 1", I store "option 1" into another var

limber urchin
fervent cradle
#

was about to say that

#

just store it in a variable unless you cant

limber urchin