#Basic Pycord Help

1 messages · Page 32 of 1

shell radish
#

ok i remembered correctly LOL

sage tendon
#

that is so awful omg

#

did no one ever think of changing this lmao

#

or is this a discord limitation

shell radish
sage tendon
#

embeds really need some love

shell radish
#

they're good enough

little cobalt
#

@vestal folio bitte versuch mehr die docs zu benutzen, sonst lernst du es nicht zu finden

sage tendon
#

sehr wahr

vestal folio
#

Die Suche ist seltsam

#

Wenn man nach was bestimmtem sucht bekommt man alles mögliche

little cobalt
#

Es gibt sogar ein * FELD* das nennt sich suche

vestal folio
sage tendon
little cobalt
sage tendon
#

das setzt vorraus dass man weiß dass die methode der guild gehört

#

das ist bei den docs nicht der fall :)

little cobalt
sage tendon
#

außerdem bekommt man in internationalen discords üblicherweise schneller hilfe wenn man english spricht :>

dense summit
fresh sierra
#

Use typing. Plsss

#

Like ctx: discord.ApplicationContext

#

It will look 10 times better and help you a lot

sage tendon
#

i love the "who asked" reaction when its literally a big help

errant river
#

how do i make selfbots in python ?

#

is there any python library

#

?

sage tendon
#

that's against the ToS

#

and there is zero point in doing that

errant river
#

like there is a lib in js

sage tendon
#

i repeat again,

  1. against the ToS
  2. no point in doing that
#

and if you really wanted to, you would've just googled it

lofty parcel
#

Congrats on being dumb enough to ask how to break the ToS in a server with discord staff

limber terrace
#

I dont think they read the chat here

#

Otherwise more people would get slappin here

limber terrace
#

But ill not grappin in my toybox to tellin you how

cosmic sonnet
#

when did pycord make interaction: discord.Interaction not valid for slash commands? I used to have a bot where this worked, I came back to it and now i guess using pycord 2.5 these commands no longer work so i've started to switch over to ctx: discord.ApplicationContext

#

related question, i have some code to send a modal that's initially triggered by a slash command, it used to work since the modal wanted an Interaction, but now since attaching the a cog w/ "Interaction" slash commands errors, i've had to change it over, and now i'm stumped, as await self.sendModal(ctx, poll, name, title, self.bot) doesn't seem to like me using ctx instead of interaction

sage tendon
sage tendon
cosmic sonnet
#

hm ok

#

my ide warned me that it was unexpected, ill just try to run it and see what happens

#

anyway i was just confused because these commands definitely used to work probably like 8 months ago

edgy nest
upper flint
#

Is there a way to create polls in pycord? Or is it not implemented yet?

rare condor
#

is there a way to add a single callback to all buttons in a view?

#

that for example grabs the custom id of the button that was pressed

#

button.callback = function() should do it

rare condor
#

embeds has a maximum of 10 elements.

what does this mean?

rare condor
#
pages_indv = [
    build_embed(
    title=f"{response[i]}",
    description='desc')
    for i in range(0, len(response), 20)
]

pages_grp = [
    pages.Page(
        embeds=pages_indv[i],
        custom_view=ViewListPaginator(response[i:i+20]),
    ) for i in range(0, len(pages_indv))
]

group = [
  pages.PageGroup(
      pages=pages_grp,
      label="All",
      default=True,
      author_check=True
  ),
  pages.PageGroup(
      pages=pages_grp,
      label="All - 2",
      default=False,
      author_check=True
  ),
]

paginator = pages.Paginator(
    pages=group,
    show_menu=True
)

await paginator.respond(ctx.interaction)

Thats how im doing it

upper flint
#

?

rare condor
#

solved

#

i was passing the embeds without it being a list

#
pages_grp = [
    pages.Page(
        embeds=pages_indv[i],
        custom_view=ViewListPaginator(response[i:i+20]),
    ) for i in range(0, len(pages_indv))
]

fixing:

pages_grp = [
    pages.Page(
        embeds=[pages_indv[i]],
        custom_view=ViewListPaginator(response[i:i+20]),
    ) for i in range(0, len(pages_indv))
]```
lapis dock
rare condor
#
class ViewListPaginator(View):
    def __init__(self, response):
        super().__init__()
        # row definido aqui
        item_list = [Button(label=f"{i+1}",custom_id=response[i]["id"]) for i in range(0, len(response))]
        
        for item in item_list:
            item.callback = button_callback
            self.add_item(item=item)
        

async def button_callback(self, interaction:Interaction):
    print(self.custom_id)

Error:

File "C:\Codes\YoruScans\venv\Lib\site-packages\discord\ui\view.py", line 426, in _scheduled_task
    await item.callback(interaction)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: button_callback() missing 1 required positional argument: 'interaction'```
#

the function button_callback has interaction argument already

#

any hints on solving this?

lapis dock
#

Button callbacks also take button as an argument

#

button than interaction

rare condor
#

oh thanks!

vague oak
#

Hi, is it possible to start bot with some proxy between me and discord??

sage tendon
#

connect your vps to a proxy

sly ember
sage tendon
#

what is the issue

#

> wants help
> never comes back

runic swan
#

i am tring to send an image but i am getting a n response

await ctx.respond(file=discord.File(fp=f"test.png"))
vestal folio
#

wie kann ich ein e art kanal auswahl in slash command setzen

#

so was nur in slash commands

little cobalt
# vestal folio

you know if you would ask that in english many would help you way faster

vestal folio
#

ich hab keine lust auf Englisch

sage tendon
#

dann musst du wohl warten

steep cliff
#

Und dann einfach nen Channel

sage tendon
#

wiedermal wäre es schneller gewesen die Docs zu lesen

runic swan
#

i am not able to send a image and it's giving me a error
NotFound: 404 Not Found (error code: 10062): Unknown interaction

#
    async def test(self, ctx):
        img=discord.File(fp="ac.png")
        await ctx.respond(file=img)
sage tendon
#

try with await ctx.defer() as the first line

#

your internet might be too slow to send it in time

runic swan
#

yes it's slow..

runic swan
sick thorn
#

Hi, Im trying to make /ping command. that working but bot response message "The application did not respond". Don't have any error log in console.
My code:

# commands/ping.py
from discord.ext import commands
class Ping(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
    @commands.slash_command(name="ping", description="Check bot's latency")
    async def ping(self, ctx):
        latency = round(self.bot.latency * 1000) # Convert to milliseconds
        await ctx.send(f'Pong! Latency is {latency}ms.')
def setup(bot):
    bot.add_cog(Ping(bot))
#bot.py
# ...
  for filename in os.listdir('./commands'):
      if filename.endswith('.py'):
          bot.load_extension(f'commands.{filename[:-3]}')
          print(f'Loaded: {filename[:-3]} command')

  # Run the bot
  bot.run(TOKEN)
sage tendon
#

you just send a message to the channel

#

use ctx.respond

sick thorn
maiden bloom
#

I'm getting this error and none of it is my code aside from the bot.run(TOKEN):

Traceback (most recent call last):
  File "/app/main.py", line 263, in <module>
    bot.run(TOKEN)
  File "/usr/local/lib/python3.10/site-packages/discord/client.py", line 766, in run
    return future.result()
  File "/usr/local/lib/python3.10/site-packages/discord/client.py", line 745, in runner
    await self.start(*args, **kwargs)
  File "/usr/local/lib/python3.10/site-packages/discord/client.py", line 709, in start
    await self.connect(reconnect=reconnect)
  File "/usr/local/lib/python3.10/site-packages/discord/shard.py", line 475, in connect
    raise item.error
  File "/usr/local/lib/python3.10/site-packages/discord/shard.py", line 180, in worker
    await self.ws.poll_event()
  File "/usr/local/lib/python3.10/site-packages/discord/gateway.py", line 603, in poll_event
    await self.received_message(msg.data)
  File "/usr/local/lib/python3.10/site-packages/discord/gateway.py", line 555, in received_message
    func(data)
  File "/usr/local/lib/python3.10/site-packages/discord/state.py", line 818, in parse_interaction_create
    interaction = Interaction(data=data, state=self)
  File "/usr/local/lib/python3.10/site-packages/discord/interactions.py", line 171, in __init__
    self._from_data(data)
  File "/usr/local/lib/python3.10/site-packages/discord/interactions.py", line 201, in _from_data
    self._guild = Guild(data=self._guild_data, state=self)
  File "/usr/local/lib/python3.10/site-packages/discord/guild.py", line 307, in __init__
    self._from_data(data)
  File "/usr/local/lib/python3.10/site-packages/discord/guild.py", line 515, in _from_data
    cache_joined = self._state.member_cache_flags.joined
AttributeError: 'Interaction' object has no attribute 'member_cache_flags'
sage tendon
#

what are you doing that causes that

maiden bloom
#

It just happens on a shard reconnection

grizzled loom
#

there is already a topic about it #1218470644216234045

little cobalt
lofty parcel
#

Bruh

maiden bloom
#

APScheduler==3.9.1
git+https://github.com/Pycord-Development/pycord.git
GitPython==3.1.42
PyYAML==6.0.1
python-dateutil==2.8.2
aiohttp==3.9.3
rsa==4.9

I was going to delete this question from there since I don’t think it’s related

sage tendon
#

dev version

#

hmmmmmmmmmm

lofty parcel
#

master is probably broken

grizzled loom
lean garnet
#

Hi, does pycord support user applications ?

lofty parcel
lean garnet
#

thanks

little cobalt
lean garnet
#

thanks

magic sail
#

is it possible to only display certain arguments of a command if another one was set with a specific value?

example:
mode has image and text as options, I want to display the aspect_ratio argument only if mode has been set to image

little cobalt
#

you are not the first one I saw with that Idea

#

I also had it in mind

shell radish
#

depending on the exact setup, you can maybe create command groups

magic sail
#

yeah I'm using command groups already xD

#

I'll just separate the command into 2

#

thanks!

little cobalt
#

alright ^^

maiden bloom
maiden bloom
lofty parcel
fresh sierra
#

is there a way to know which commands it is ?

Ignoring exception in on_connect
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 400, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/.local/lib/python3.11/site-packages/discord/bot.py", line 1178, in on_connect
    await self.sync_commands()
  File "/home/container/.local/lib/python3.11/site-packages/discord/bot.py", line 735, in sync_commands
    registered_commands = await self.register_commands(
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/discord/bot.py", line 599, in register_commands
    registered = await register("bulk", data, _log=False)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/discord/http.py", line 373, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 1.options.0.options.4: Option names are not unique in locale en-GB
In 1.options.0.options.5: Option names are not unique in locale en-GB
In 1.options.0.options.7: Option names are not unique in locale en-GB
sage tendon
#

probably the one you just changed

fresh sierra
sage tendon
#

time to do so one by one

fresh sierra
#

neverrrrrrrrr

sage tendon
#

then do it binary search style

fresh sierra
#

im way too lazy to do that 19 times

#

i will do a for command in ... bot.sync_commands

lapis dock
#

It's possible it's wrong for all of them :)

fresh sierra
#

In 1.options.0.options.4: Option names are not unique in locale en-GB
In 1.options.0.options.5: Option names are not unique in locale en-GB
In 1.options.0.options.7: Option names are not unique in locale en-GB

#

wait

lapis dock
#

Options 4,5,6 not command

fresh sierra
#

does the parameter name between localization has to be different

#

not it doesnt

fresh sierra
#

does subcommands appear has option ?

lapis dock
#

Sorry, I'm not sure on that one

fresh sierra
#

dw i will check

#

yep it was that

#

it was about subgroup

deft kestrel
#

Hi guys. Any example of ephemeral=True response with ctx.defer()? Without defer() it works fine. Thanks for the help!

little cobalt
deft kestrel
sage tendon
#

literally just pass it in the defer like you do in your message

deft kestrel
sage tendon
#

you cant un-ephemeral something, no

#

if the defer is ephemeral the response has to be, too

deft kestrel
#

So it's impossible?

sage tendon
#

depending on your code, you can try to defer as late as possible before the things that take a lot of time
Like, do pre-checks to then correctly defer ephemerally or not if possible

deft kestrel
#

Have a nice day

sage tendon
#

np

stray pasture
#

After the bot is running for less than 1 day, it crashes. I get this error message:

#

this is only happening with the new version py-cord==2.5.0

sage tendon
#

its a problem with bridge stuff

#

I think you need to replace Option with discord.BridgeOption

stray pasture
#

the decorator, or the ones in the Type

sage tendon
#

no idea about the decorator
ideally you shouldnt mix the way you do it anyway tho
but change the typehint versions and see if it works

stray pasture
#

yeah I have both, some is old code that I did not want to change all 😄

maiden bloom
stray pasture
#

so there is a fix in master

maiden bloom
#

Apparently. I haven’t had mine crash randomly since. Just fun shard reconnections for seemingly no reason

sage tendon
#

dev branch will be dev branch

maiden bloom
#

I’ve just been using the latest

stray pasture
#

I see will try that thank you !

maiden bloom
civic quiver
#

class MyModal(discord.ui.Modal):
    def __init__(self, interaction: discord.Interaction, verifyconfigmodal, db_conn: psycopg2.extensions.connection, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.db_conn = db_conn
        self.guild_id = interaction.guild.id
        cursor = db_conn.cursor()

        sql_query = f"""
            SELECT verification_questions, channel_id
            FROM guild
            WHERE guild_id = '{self.guild_id}';
        """

        cursor.execute(sql_query)
        result = cursor.fetchone()
        cursor.close()

        if result:
            verification_questions, channel_id = result

            if isinstance(verification_questions, list):
                questions_list = verification_questions
            elif isinstance(verification_questions, str):
                questions_list = verification_questions.split(';')  


            self.add_item(discord.ui.InputText(label=question1, placeholder="Example: coolEp1cGamer69"))
            self.add_item(discord.ui.InputText(label=question2))
            self.add_item(discord.ui.InputText(label=question3))
            self.add_item(discord.ui.InputText(label=question4))

This is the code I am trying to add to my app, I want to get the values inside the table in sql and assign them to the label inside a modal, this is the traceback im getting:

#
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
In data.components.1.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
In data.components.2.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
In data.components.3.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
#

I assume its a problem with the sql data being assigned to the label, how would i fix this

lapis dock
civic quiver
#

how should they be indented?

lapis dock
#

wait, nevermind, discord was just making them wrap lines

lapis dock
# civic quiver how should they be indented?

so the error is saying you are trying to put an input text on a view. You must have excluded some code in your message, so I think my original point stands. The self.add_items should be indented into the __init__ of the modal

civic quiver
# lapis dock so the error is saying you are trying to put an input text on a view. You must h...

This is the rest of the modal code:

    async def callback(self, interaction: discord.Interaction):
        embed = discord.Embed(title="Verification Questions:", color=0xe91e63)
        embed.add_field(name="Username:", value=self.children[0].value, inline=False)
        embed.add_field(name="Age:", value=self.children[1].value, inline=False)
        embed.add_field(name="How did you find this server?", value=self.children[2].value, inline=False)
        embed.add_field(name="Will you follow the rules?", value=self.children[3].value, inline=False)
        
        username = interaction.user.id
        
        channel = bot.get_channel(placeholder)
        await interaction.response.send_message("Thank you, we will review your submission!", ephemeral=True)
        await channel.send(embed=embed, view=StaffVerify(username))

and this is the class that sends the modal:

class MyView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)

        self.add_item(discord.ui.Button(label='Help', style=discord.ButtonStyle.link, url='https://mercury-bot.vercel.app'))

    @discord.ui.button(label="Verify", custom_id="button-1", style=discord.ButtonStyle.success)
    async def button_callback(self, button, interaction):

        guild_id = interaction.guild.id
        interaction.response.defer()
        
        db_conn = psycopg2.connect(
        database="placeholder",
        host="placeholder",
        user="placeholder",
        password="placeholder",
        port="placeholder")  


        modal = MyModal(interaction, verifyconfigmodal=None, db_conn=db_conn, title="Verify!")
        
        await interaction.response.send_message(embed=None, view=modal)
lofty parcel
#

interaction.response.send_modal which only takes the modal

#

and you cant defer the interaction in the button, modals cant be a follow up (plus, defer is a coroutine aka awaitable)

whole needle
#

is it possible to remove a timeout for a user

lofty parcel
whole needle
#

yep i read the docs haha

fresh sierra
#

How to pycord ?

fresh sierra
#

Or both work

deft bronze
#

How can i solve ssl 1006?
(tried with .tag sslfix) but doesn't work
im using win10

magic sail
#

how do I pass an image as argument to a slash command?

#

I've been using Option but idk what type I must pass there for it to accept (if possible)

shell radish
#

discord.Attachment is the proper type

magic sail
#

thank you!

sonic onyx
#

I'm trying to get pycord to run the basic example script but I run into No module named 'discord'

#

I'm on win10

frail ocean
#

Have you installed pycord

sonic onyx
#

yes, I actually just fixed the error. Now I'm getting that token must be of type str, not NoneType

#

I'm not exactly where I'm supposed to put the .env file with my token in it

frail ocean
#

Show your code without the token

sonic onyx
fresh sierra
sonic onyx
#

where do I put the .env file so it’ll get found?

fresh sierra
#

add in the dotenv file

#

TOKEN = ...

sonic onyx
#

I have that in my .env already

fresh sierra
#

you need to have the TOKEN like that

sonic onyx
#

TOKEN

fresh sierra
#

where you have that

sonic onyx
#

archivist_token.env

fresh sierra
#

or u can do

#

load_dotenv('archivist_token.env')

#

@sonic onyx does it work now ?

sonic onyx
#

Yea it seems to be working

deft bronze
#

How can i purge messages since an id?

#

Like idk every message after message id 2 in my discord channel

fresh sierra
#

get the message datetime

#

then use channel history with before=message time

#

and delete

deft bronze
#

nvm

fresh sierra
deft bronze
fresh sierra
#

How to get the shard_id of the instance ?

#

my goal :

        for guild in self.bot.guilds:
            if guild.shard_id != self.bot.shard_id:
                continue
fresh sierra
#

self.bot.shard_id return always None, even if the bot have more than 1 shard

maiden bloom
#

Did you read it? There is no shard_id attribute

fresh sierra
#

And whatever I wanna find a way to find the shard_id of the instance even if it’s doesn’t come from shard_8:

sage tendon
fresh sierra
#

That what I’m asking ;​​​ )​

sage tendon
#

what do you even need
you already have the shard id of the guild no?

fresh sierra
#

That is trigger for each instance

#

So with only fro guild in self.bot.guilds, it will do the action 4 times for each guilds

#

And not only 1

upbeat lintel
#

Hey everyone,
Are there any listeners/decorators I can use to run a piece of code every time a slash command is being executed? Let's say I want to log every command used, do I have to include the logging function call in every slash command I write or is there a more generic approach like a listener (similar to let's say on_message)?

fresh sierra
frail ocean
lost ocean
sage tendon
#

white mode is default

lost ocean
#

i know

#

but like

#

why burn your eyes

frail ocean
#

Can someone explain to me the best way to make commands both as slash and normal command? Most efficient?

sage tendon
#

bridge

frail ocean
#

How?

sage tendon
frail ocean
#

With normal i mean !help btw

sage tendon
#

i would call slash commands normal by now :>

frail ocean
#

Oh okay. Does this also work with discord.Option?

sage tendon
#

you need BridgeOption

frail ocean
#
    async def set(self, ctx, channel: discord.Option(discord.TextChannel, description="The channel where the flagquiz should be set.", required=True)):```
How will this work then
sage tendon
#

discord.BridgeOption :>

frail ocean
sage tendon
frail ocean
#

What with command groups?

sage tendon
#

i dont think those have a way to be bridged

#

use the docs :)

frail ocean
#
    flagquizslash = discord.SlashCommandGroup(name="flagquiz", description="Manage the flagquiz settings.")``` i have it like this rn
sage tendon
frail ocean
#

sänks

sage tendon
#

i mean i just searched it up

#

you can do the same

frail ocean
#
flagquiz.py konnte nicht geladen werden. Extension 'cogs.flagquiz' raised an error: TypeError: BridgeCommandGroup.__init__() missing 1 required positional argument: 'callback'``` ![HAhaa](https://cdn.discordapp.com/emojis/855856063176769537.webp?size=128 "HAhaa")
sage tendon
#

seems like you need to read the docs more :3

frail ocean
#

I dont get it lol

#

Some Docs are bad

#

callback? Like?

#
Extension 'cogs.flagquiz' raised an error: TypeError: Callback must be a coroutine.``` ![HAhaa](https://cdn.discordapp.com/emojis/855856063176769537.webp?size=128 "HAhaa")
sage tendon
#

dont call it, just name it

frail ocean
lofty parcel
#

The hell are you trying to do

sage tendon
#

bridge group lol

frail ocean
sage tendon
frail ocean
lofty parcel
#

The callback must be a coro.

#

Not some random string

sage tendon
#

man
not as string lol

#

just type the name as literal

frail ocean
lofty parcel
#

Literally refer to the function

#

Without calling it

sage tendon
#

group(functionname,...)

lofty parcel
#

That's what toothy said 4 times

frail ocean
sage tendon
#

I thought it was for the default command function but groups don't have like a default command so now I'm confused myself

#

I really don't know much about bridge so dark knows maybe

frail ocean
#

@lofty parcel HAhaa

lofty parcel
sage tendon
#

ah

frail ocean
lofty parcel
#

Just use bridge_group

lofty parcel
#

bridge.bridge_group?...

frail ocean
#

Extension 'cogs.flagquiz' raised an error: AttributeError: 'AutoShardedBot' object has no attribute 'bridge_commands'

sage tendon
#

bridge

#

not bot

frail ocean
#

Im not dumb

lofty parcel
#

I doubt autoshardedbot supports bridge commands

#

@errant trout do you happen to know. Dismiss

sage tendon
#

ah

lofty parcel
#

@frail ocean

#

Are you using the bridge auto sharded bot?

#

Or discord.AutoShardedBot

frail ocean
#

discord.

#

What is the difference?

sage tendon
#

holy shit this library has so much stuff I don't know of

lofty parcel
lofty parcel
sage tendon
#

bridge is a mess ong

#

I love my slash commands

frail ocean
sage tendon
#

Try it
run it

#

logically thinking there shouldn't be meaningful differences

lofty parcel
#

It quite literally inherites from commands.AutoShardedBot

#

With the addition of the bridge bot base

#

The library is literally open source you can check it by yourself

frail ocean
#
Ignoring exception in on_message
Traceback (most recent call last):
  File ".venv\lib\site-packages\discord\ext\commands\core.py", line 774, in _parse_arguments
    next(iterator)
StopIteration

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File ".venv\lib\site-packages\discord\client.py", line 400, in _run_event
    await coro(*args, **kwargs)
  File "\main.py", line 263, in on_message
    await client.process_commands(message)
  File ".venv\lib\site-packages\discord\ext\commands\bot.py", line 386, in process_commands
    await self.invoke(ctx)
  File ".venv\lib\site-packages\discord\ext\bridge\bot.py", line 144, in invoke
    await ctx.command.invoke(ctx)
  File ".venv\lib\site-packages\discord\ext\commands\core.py", line 1531, in invoke
    await self.prepare(ctx)
  File ".venv\lib\site-packages\discord\ext\commands\core.py", line 881, in prepare
    await self._parse_arguments(ctx)
  File ".venv\lib\site-packages\discord\ext\commands\core.py", line 776, in _parse_arguments
    raise discord.ClientException(
discord.errors.ClientException: Callback for flagquiz command is missing "ctx" parameter.```
sage tendon
#

read :3

lofty parcel
#

Start using your brain cells

frail ocean
#

Love you guys

deft kestrel
#

Is this a bug? In fact, there is an attribute description and I can get a description of the slash command, but for some reason PyCharm tells me that it doesn’t exist

frail ocean
#

Is there a way to check if the command is run as slash command or messae command

sage tendon
#

does it work?

deft kestrel
deft kestrel
#

ctx: discord.ApplicationContext

lofty parcel
#

.rtfm BridgeContext

sage tendon
#

call me crazy but no, ctx.command does not have a description attribute

#

but for some ungodly reason it does work

deft kestrel
#

But I can get it and description works :DD

sage tendon
#

seems like you can make your first github issue :)

#

My suspicion is that it's not an ApplicationCommand but a SlashCommand

#

which would mean this is wrongly typehinted

#

oh no i see the issue

#

slashcommand is a subclass of applicationcommand

#

so i'm unsure where the wrongness is now

#

i guess applicationcommand is the right typehint

#

if the highlight bugs you you could do command: discord.SlashCommand = ctx.command

sonic onyx
whole needle
whole needle
sage tendon
#

no

#

get pycharm

sonic onyx
deft bronze
#

me when ctx.send

sage tendon
#

because you dont typehint

#

which is entirely your issue

deft bronze
sage tendon
#

exactly

deft bronze
#

what does even typehint has to do 💀

sage tendon
#

everything..?

deft bronze
#

Idk if you mean it like the return of a function or definining the argument

sage tendon
#

if you dont typehint ctx as what it is, the IDE can't know at all what is supposed to be passed there

deft bronze
#

Can you elaborate?

deft bronze
sage tendon
#

that is typehinting

deft bronze
#

It still not working sometimes, like with bridge

sage tendon
#

as I said everything just seems broken af

#

not even the docs or the source code have it

lone hound
#

can't find the method to make my bot leave a VC. can anyone help me?

deft bronze
#

vc.leave

#

😈

lone hound
#

A

#

thought it was "vc.disconnect()" or something

deft bronze
#

idk im just kidding

lone hound
#

AA

deft bronze
#

@lone hound

civic quiver
#

Can someone help with this error, not sure how to fix:

class VerifyModal(discord.ui.Modal):
    def __init__(self, interaction: discord.Interaction):
        super().__init__(timeout=None)
        
        self.db_conn = db_conn
        self.guild_id = interaction.guild.id
        cursor = db_conn.cursor()

        sql_query = f"""
            SELECT verification_questions, channel_id
            FROM guild
            WHERE guild_id = '{self.guild_id}';
        """

        cursor.execute(sql_query)
        result = cursor.fetchone()
        cursor.close()

        if result:
            verification_questions, channel_id = result

            if isinstance(verification_questions, list):
                questions_list = verification_questions
            elif isinstance(verification_questions, str):
                questions_list = verification_questions.split(';')  


            self.add_item(discord.ui.InputText(label=question1, placeholder="Example: coolEp1cGamer69"))
            self.add_item(discord.ui.InputText(label=question2))
            self.add_item(discord.ui.InputText(label=question3))
            self.add_item(discord.ui.InputText(label=question4))

    async def callback(self, interaction: discord.Interaction):
        print("it works mommy!")



class MyView(discord.ui.View):
    def __init__(self, bot: commands.Bot):
        super().__init__()
        self.bot = bot

    @discord.ui.button(label="Send Modal", custom_id="send_modal")
    async def send_modal(self, button: discord.ui.Button, interaction: discord.Interaction):
        modal = VerifyModal(title="Modal via Button")
        await interaction.response.send_modal("Click the button to open the modal", view=modal)
#

Traceback:


    modal = VerifyModal(title="Modal via Button")
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: VerifyModal.__init__() got an unexpected keyword argument 'title'
lofty parcel
civic quiver
#
class MyView(discord.ui.View):
    def __init__(self, bot: commands.Bot, **kwargs):
        super().__init__(**kwargs)
        self.bot = bot

    @discord.ui.button(label="Send Modal", custom_id="send_modal")
    async def send_modal(self, button: discord.ui.Button, interaction: discord.Interaction):
        modal = VerifyModal(title="Modal via Button")
        await interaction.response.send_modal("Click the button to open the modal", view=modal)

Like this?

sage tendon
#

try it and see

civic quiver
#

nope

#

same error

lapis dock
#

you need to pass positional arguments before keword arguments, you have bot as a position argument

civic quiver
#

so like

self.title = title

?

sage tendon
#

pass bot to your view.

lapis dock
#

no, in your init your arguments are
self -> no need to do anything
bot -> you need to pass bot to the modal
**kwargs -> all additional keyword arguments will be put in a dict here

glossy latch
#

why the bot get blocked from accessing discord api

lapis dock
#

can you show the error or message you received

sage tendon
glossy latch
# lapis dock can you show the error or message you received
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/ext/bridge/bot.py", line 144, in invoke
    await ctx.command.invoke(ctx)
  File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 959, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 189, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward.
Ignoring exception in command None:
sage tendon
#

yea you've been ratelimited, good job

lapis dock
#

You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently.

glossy latch
#

why?

sage tendon
#

love the "in command None"

#

You spammed the API

lapis dock
#

do you have a lot of code?

sage tendon
#

or at least, went above its limits

glossy latch
sage tendon
#

does your bot ever edit channels quickly, or really do anything quickly

glossy latch
#

edit users nickname and sends logs quickly

lapis dock
#

edit channels, edit bot status, and send DMs are big ones

#

does it mass edit peoples nicknames?

glossy latch
#

nope

#

only when user join vc

sage tendon
#

well it says you exceed rate limits frequently sooo

lapis dock
#

about how quickly does the bot send logs?

glossy latch
#

i removed the code of edit nicknames and logs and still get ratelimited

sage tendon
#

thats not how it works

lapis dock
#

the ratelimit takes time to expire.
Basically discord was like you are sending too many requests so we are going to block all requests for x amount of time

sage tendon
#

just wait like an hour and see if it still says that

lapis dock
#

x could be 24 hours or more

#

Normally pycord handels ratelimits for you unless you are doing things way to fast

sage tendon
#

or are doing weird stuff too much

#

can you show us the code of anything your bot does repeatedly, like outside commands

glossy latch
#

i can't rn because i'm using phone rn but the errors has effects on this problem ?

sage tendon
#

?

#

the entire reason for the error is that you are blocked from the API lol

glossy latch
#

i mean when the bot get errors

#

nah

lapis dock
#

any errors that dont mention ratelimits might be the problem and when possible you should send them here

glossy latch
#

okey thank you

civic quiver
#

okay so I simplified all of my code down to just what I want to do in a seperate file, Im using the base code provided by the modal dialogs page and Im getting that title error. The modal is supposed to get the data from sql depending on the guild Id and put that data into the dialogs

#
class VerifyModal(discord.ui.Modal):
    def __init__(self, interaction: discord.Interaction):
        super().__init__(timeout=None)
        
        self.db_conn = db_conn
        self.guild_id = interaction.guild.id
        cursor = db_conn.cursor()

        sql_query = f"""
            SELECT verification_questions, channel_id
            FROM guild
            WHERE guild_id = '{self.guild_id}';
        """

        cursor.execute(sql_query)
        result = cursor.fetchone()
        cursor.close()

        if result:
            verification_questions, channel_id = result

            if isinstance(verification_questions, list):
                questions_list = verification_questions
            elif isinstance(verification_questions, str):
                questions_list = verification_questions.split(';')  


            self.add_item(discord.ui.InputText(label=question1, placeholder="Example: coolEp1cGamer69"))
            self.add_item(discord.ui.InputText(label=question2))
            self.add_item(discord.ui.InputText(label=question3))
            self.add_item(discord.ui.InputText(label=question4))

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



class MyView(discord.ui.View):
    @discord.ui.button(label="Send Modal")
    async def button_callback(self, button, interaction):
        await interaction.response.send_modal(VerifyModal(title="Modal via Button"))

@bot.slash_command()
async def send_modal(ctx):
    await ctx.respond(view=MyView())
frail ocean
#

As far as I know, 28 days are possible with a TImeout.
With this method, however, no more than 27 are possible. How do I fix this

time_val=27
    elif unit == 'd':
        return timedelta(days=time_val)```
civic quiver
sage tendon
frail ocean
#

What should i use instead

lapis dock
lapis dock
sage tendon
#

also, are you using timeout or timeout_for

civic quiver
lapis dock
#

you need to replace the init in your modal not in your view

#

your view code was fine

civic quiver
#

alright, so that solved the title problem, however, now interaction is the problem: TypeError: VerifyModal.__init__() missing 1 required positional argument: 'interaction'

#

I tried adding interaction: discord.Interaction to the init but that didnt do anything

lapis dock
#

that error means it is in the init but you are not passing it in VerifyModal

#

you probably do not need interaction so you can remove it from the modals init

civic quiver
#

okay, how do I pass it into the VerifiyModal

lapis dock
#

just like a normal function
rembed it has to go before the title= as that is a keyword argument and positional arguments always go first

frail ocean
frail ocean
civic quiver
#
    await interaction.response.send_modal(VerifyModal(interaction, title="Modal via Button"))
                                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: VerifyModal.__init__() takes 1 positional argument but 2 were given

😭

sage tendon
lapis dock
sage tendon
#

timeout_for specifically takes a timedelta

#

timeout does not

civic quiver
lapis dock
#

the modal

civic quiver
#
    def __init__(self, **kwargs):
        super().__init__(timeout=None, **kwargs)
frail ocean
sage tendon
lapis dock
#

.tag lp

sly karmaBOT
frail ocean
#

But its the same or?

sage tendon
#

No, it is not

frail ocean
#

almost

little cobalt
frail ocean
#

Has someone codet a activity here already

lapis dock
#

not in pycord, cuz pycord cant support activities

frail ocean
#

Yes i know

shell radish
frail ocean
shell radish
#

it was fine

grizzled loom
shell radish
#

sure

lost ocean
lean garnet
#

AttributeError: 'FFmpegPCMAudio' object has no attribute '_process'

    @commands.command()
    async def play(self, ctx: commands.Context, *, query: str):
        """Plays a file from the local filesystem"""

        source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(query))
        ctx.voice_client.play(
            source, after=lambda e: print(f"Player error: {e}") if e else None
        )

        await ctx.send(f"Now playing: {query}")
#

can anyone help please ?

frail ocean
frail ocean
lean garnet
#

when I try to pip install it, I have no results

lean garnet
#

Thanks, is it possible to use it on a pterodactyl panel ?

sage tendon
#

also did you install py-cord[voice]?

lean garnet
#

Yes I did

sage tendon
lean garnet
#

yes certainly

#

thanks

arctic plover
#

how to do it?

sage tendon
#

thats a user or message command

#

depending on if you click on a user or message

rugged lodgeBOT
arctic plover
frail laurel
#

why this doesn't work? am i passing the datetime object in a wrong way? I want it execute for e.g at 6 pm everyday

@tasks.loop(time=datetime.time(hour=16, minute=35))
async def open_channel(self):
    channel = await self.bot.fetch_channel(MOD_CHANNEL)
    await channel.send("Everything's ready to go")
sage tendon
#

do the docs say it takes a datetime.time object?

frail laurel
sage tendon
#

so it never runs? did you try printing?

#

and are you starting the task?

frail laurel
#

well yes, if i change the time attribute to seconds=10 it executes

sage tendon
#

try seconds = 0

sage tendon
#

time continues to plague developers around the world :>

frail laurel
#

well it'd be certainly better to just leave it to execute at the concrete hour of the day, it's a pain in the ass if I would had to adjust those seconds or hours based on time bot boots up

lapis dock
#

I think it uses a default timezone, you should either convert your time to UTC or specify your local timezone

#

(Assuming you have not waited a full 24 hours while testing)

frail laurel
#

the bot is local , and I don't know if datetime.time object gives me a possibility of specyfying the timezone whatsoever

#

It's so confusing

sage tendon
#

print a dummy time object and find out

#

but generally timezones are always assumed to be UTC unless specified otherwise

grizzled loom
sage tendon
#

read up

lapis dock
grizzled loom
rotund harness
#

Does autocomplete work on mobile at all? It appears to just load forever even with 1 option

lapis dock
#

You are probably not responding correctly

rotund harness
#

To autocomplete?

lapis dock
#

Try the /example command here

#

It's autocomplete works fine

rotund harness
#

Works here, but not one via my code, however my code does work with PC just not mobile

lapis dock
#

Hmm. Can you show your autocomplete function

little cobalt
#

how many str do you have at the autocomplete?

lapis dock
#

If you are constantly typing it will not load

lapis dock
#

That might take longer than 3 seconds, I suggest caching the API request response

rotund harness
#

ah so gotta get it within 3 seconds

lapis dock
#

Yes, that includes latency so latency from discord on your PC might be faster than on your phone so that might be the issue

sage tendon
#

API request in autocomplete is usually kinda hard yea

#

especially since you make an API call every single time the user times a letter

#

so if they type extremely fast you are absolutely spamming that api

lapis dock
#

You should look into a TTL cache.
Time to live. Essentially is a cache that will delete the cached item after x amount of time. So for example the autocomplete would see nothing in cache (be slow and not respond for 3 seconds) but than cache the results so for the next x amount of time no slow API calls are made.

rotund harness
crimson lily
#

Hi, I forgot how to edit a ctx.respond message I remember something like edit_original_message but that was for interactions can someone guide me rq

sage tendon
little cobalt
sage tendon
#

edit original response*

crimson lily
#

aight thanks a ton

little cobalt
sage tendon
#

edit original message is sync for some reason

#

okay nope, the docs just lied

crimson lily
#

await ctx.respond("Processing...")
await ctx.interaction.edit_original_message

Doesnt do anything for som ereason

#

Tried doing var = await ctx.respond...
var.edit but doesnt work either

sage tendon
#

show the actual code in your ide

crimson lily
#
async def crop_media(ctx: discord.ApplicationContext, attachment: discord.Attachment):
    await ctx.respond("Processing...")
    media_bytes = await attachment.read()
    media_filename = attachment.filename.lower()

    if media_filename.endswith((".png", ".jpg", ".jpeg")):
        await ctx.interaction.edit_original_message(content="Image detected, cropping...")
        cropped_bytes = crop_image(media_bytes)
    elif media_filename.endswith((".mp4", ".mov", ".avi")):
        await ctx.interaction.edit_original_message(content="Video detected, cropping...")
        cropped_bytes = crop_video(media_bytes)
    elif media_filename.endswith(".gif"):
        await ctx.interaction.edit_original_message(content="GIF detected, cropping...")
        cropped_bytes = crop_gif(media_bytes)
    else:
        await ctx.interaction.edit_original_message(content="Unsupported file format for cropping.")
        return

    await ctx.interaction.edit_original_message(content="Processing done. Uploading cropped media...")
    await ctx.send(f"<@{ctx.user.id}>", file=discord.File(cropped_bytes, filename=f"cropped_media.{media_filename}"))
    #await ctx.interaction.response.delete()
sage tendon
#

try _response

crimson lily
#

ctx_response?

sage tendon
#

edit_original_response

crimson lily
#

works

#

ty

sage tendon
#

wow

little cobalt
#

mhm, what is with that? {ctx.mention} instead of <@{ctx.user.id}>

sage tendon
#

yea _message is deprecated

#

so prolly kinda broken

#

why tf does it work differently tho?

#

it's quite literally just an alias

little cobalt
#

ye

frail laurel
#

can you validate input with regex in interaction before starting it? or only after it?

sage tendon
#

Wdym before starting it

lapis dock
glad totem
#

i have a website where a user can submit data, that data should get posted to the discord bot which then creates a new channel and posts the data in it. is there an easy way to go from submitting the data and posting it directly to the bot or do i need to upload it to a db and have the bot watching for changes in the db?

sage tendon
#

i mean, that isn't really pycord specific

glad totem
#

i mean, that isnt really helpful. idk if discord api/pycord provides support for posting data directly to the bot

sage tendon
#

Yea it isn't helpful, because you are asking a question that is out of the scope of a discord bot library
we can't help you connect your frontend to your backend

round heart
fresh sierra
#

with open_channel.start()

nova epoch
#

I feel like this is a really dumb question but I cannot find anything online (incl. the docs) so here I am:

I have an /invite command: ```py
@bot.command(name='invite', description='Invite a user to tobezdev Studios')
@commands.is_owner()
async def _invite(ctx, user: discord.User):
try:
await user.send(embed=discord.Embed(
title="tobezdev Studios - Invite",
description=f"""
Hey, {user.mention}!
You've been gifted an invite to tobezdev Studios by {ctx.author.name}.
You can join the studios using [this link](definitely a discord invite link), it expires in approximately 7 days.

Please note that you may be asked to verify in this server. Please DM tobezdev for a verification bypass when you join if you cannot verify successfully.
"""
))
return await ctx.respond(embed=discord.Embed(
title="Invite sent!",
description=f"Successfully invited {user.mention}.",
color=discord.Color.green()
))
except discord.Forbidden:
return await ctx.respond(embed=discord.Embed(
title="Invite Failed",
description="Failed to invite the specified user: Bot doesn't have permission to send messages to the user.",
color=discord.Color.red()
))```

My error is the default "A specified user ID was not valid" error produced by Discord - screenshot attached. The command works fine when mentioning a user inside of the current server, but raises the above mentioned error when someone outside of the server is mentioned, specifically using the <@xxxxxxxxxxxxxx> method.

My bot does not even receive the interaction and so I have narrowed it down to be an error specifically do so with the actual command, rather than the processing of it. Does anyone have any pointers? Thanks!

sage tendon
#

that's a prefix command or

frail ocean
#

Is there a way to check if a server has premium

nova epoch
sage tendon
#

Then 1. you need discord.Member, and 2. why _invite?

nova epoch
#

Just cause if I use help then it shadows the original help and my IDE errors out - just like to keep to the theme I guess 🤷

#

I'll try the discord.Member and let ya know

#

Still this error, with discord.Member instead of discord.User

sage tendon
#

...wait

#

you cant put a user in there that doesnt share a server with the bot

#

that doesnt work

nova epoch
#

bruhhhhhhhh

#

Is there a workaround, do you know?

sage tendon
#

Why even?

#

Why, for that command, would you ever need someone not in your server

nova epoch
#

It's a command to invite people to the server-

#

I'm not going to be inviting people who are already in the server.

sage tendon
#

does the bot share any servers with the invited people?

nova epoch
#

Yes, I could send them a link but it's my (soon-to-be) professional space and I want it to look good.
No, the bot is only in the 1 server where the commands are present.

sage tendon
#

Then you cant do that

#

bots cant dm people they dont share a server with for all i know

nova epoch
#

But then surely it'd raise a forbidden error rather than an invalid user id error?

sage tendon
#

Discord is stopping you before the command is sent to the bot

#

because that ID cannot be valid for that bot because its not sharing any servers with the bot

nova epoch
#

That's so stupid

sage tendon
#

not at all

#

why send stuff to the bot that cannot possibly work?

lofty hedge
#

does py-cord support polls ?

sage tendon
#

not yet on stable

nova epoch
#

Could there be a workaround maybe using the Discord API to get a user and then sending it like that?

lofty hedge
#

cool thanks.

sage tendon
#

it would be quite invasive to let bots dm literally anyone

nova epoch
#

Well yeah but like

#

It also prevents stuff like this

sage tendon
#

for good reason

#

You might have a legit reason for it

#

But what about the 10 others that scrape user IDs and spam the everliving fuck out of everyones dms? while not sharing a server?

nova epoch
#

Yeah I guess that is true

#

Time to do something wild and find a workaround for it

#

Thanks for the help :)

sage tendon
#

np

#

the workaround is doing it manually :>

nova epoch
#

My workaround is to make a new (public) server and invite people to that, and then keep the official one invite-only.

#

Probably a stupid idea but my brain is rotting slowly

sage tendon
#

are you sharing classified documents in that server or what

#

why this way of inviting even

nova epoch
sage tendon
#

@ everyone look my new server join now

#

:)

sonic onyx
#

So it turns out this is still giving me an issue. Console says token must be type str, not NoneType

nova epoch
sage tendon
#

But spam DMing everyone is?

sage tendon
#

and use [], not ()
it's a dict

sonic onyx
#

nevermind. fixed it myself by reducing the name of the .env file to only be the extension

sage tendon
#

ah

sonic onyx
sage tendon
#

os.getenv
but i think i was mixing it up with another method of using dotevn then

nova epoch
# sage tendon But spam DMing everyone is?

Exactly what I am trying to avoid, by sending professional-looking invite embeds to users. It keeps track of who has been invited and blocks sending if they already have an invite.

sage tendon
#

invites via bot DMs are the least professional thing i can think of

#

its just annoying and unsolicited

nova epoch
#

Maybe, but we all have our ways of doing things. Thanks anyways :)

sage tendon
#

you should ask some people then

#

i cant think of anyone that would not find that annoying

#

if you want anyone to actually join

#

Because with invites, your opinion of the method doesnt matter
The opinion of your target group does

nova epoch
#

I have asked 3 communities (most of which would like to join the server when it's finishes) to which the majority said bot embeds looked more professional, compared to a user DMing a plain link.

#

I did do my research beforehand.

sage tendon
#

alrighty

nova epoch
#

Probably not worth having an argument about, though.

sonic onyx
#

is this the correct appearance for python?

sage tendon
#

wdym appearance lol

sonic onyx
#

I loaded it in visual studio code, but I've never messed with python before

#

usually they color code the stuff, so I wanna make sure its the right setting for python

#

Not that it makes a huge difference anyways

sage tendon
#

if you only do python id recomend pycharm
but yea i mean its highlighting the keywords correctly lol

sonic onyx
#

I do c# and java too so I'd rather just use VS:C

sage tendon
#

jetbrains has you covered for all of those ;) but yea

grizzled loom
sonic onyx
#

Why not use vsc for python though?

sage tendon
#

think of it like this
A specialised IDE is near perfect at its perfection
VSC sucks at everything equally
:>

sonic onyx
#

ah

sage tendon
#

no but seriously, vsc is really annoying to make word good for one language

#

it can do everything a little but nothing great, except js which is i think like the "main" language that has full built in support

grizzled loom
#

what about c#?

sage tendon
#

is that not VS' territory?

grizzled loom
#

idk, didnt use them yet.

sage tendon
#

anyway #general :3

grizzled loom
#

just sniffed c# a tiny wee bit 😄

#

yes, sorry

sonic onyx
#

well, I guess there's no reason not to use pycharm

grizzled loom
#

bt2

limber terrace
#

someone here with a fancy guild info command to share?

#

i know how, just too lazy

sage tendon
#

yea

#
    @slash_command()
    async def serverinfo(self, ctx):
        """ Get the current server's info """
        guild = ctx.guild
        owner = await discord.utils.get_or_fetch(guild, 'member', guild.owner_id)
        embed = discord.Embed(color=discord.Color.random(), title=guild.name)
        embed.description = f"""
**Owner:** {owner.mention}
**Members:** {guild.member_count}
**Roles:** {len(guild.roles)}
**Verification:** {str(guild.verification_level).title()}
**Channels:** {len(guild.text_channels)} Text, {len(guild.voice_channels)} Voice
**Created:** <t:{round(guild.created_at.timestamp())}:R>
**Emojis:** {len(guild.emojis)}
**Stickers:** {len(guild.stickers)}
        """
        embed.set_thumbnail(url=guild.icon.url)
        embed.set_footer(text=f"ID: {guild.id}")
        if guild.banner:
            embed.set_image(url=guild.banner.url)
        features = ", ".join(guild.features).replace("_", " ").title()
        embed.add_field(name="Features", value=features)
        await ctx.respond(embed=embed)
limber terrace
#

thanks

sage tendon
#

fancy enough? :)

limber terrace
#

funny how different u can use the embed features

sage tendon
#

wym

#

also yes, the lack of indentation in the description is on purpose
do not indent it

limber terrace
#
**    @slash_command(name="help", description="When you know, you know (WIP)")
    async def help(self, ctx, command: Option(str, "The command you want to see the help for") = None):
        embed = discord.Embed(title="Help Menu", color=discord.Color(config()["color"]))
        casual_names = self.get_commands()[0]
        casual_name_and_desc = self.get_commands()[1]
        sub_names_and_desc = self.get_commands()[2]
        sub_names = self.get_commands()[3]
        subs = self.get_commands()[4]
        casus = self.get_commands()[5]
        sub_cmd_list_names = [item.name for subs in [i.subcommands for i in subs] for item in subs]
        sub_cmd_list = [item for subs in [i.subcommands for i in subs] for item in subs]
        sub_cmd_names_and_desc = [f"{item.mention} - {item.description}" for subs in [i.subcommands for i in subs] for
                                  item in subs]
        if command in sub_names:
            value = ""
            for i in subs[sub_names.index(command)].subcommands:
                value += f"{i.mention} - {i.description}\n"
            embed.add_field(name=f"Subcommands of {command}", value=value)
            embed.set_footer(text=random.choice(self.choices))
        elif command in casual_names:
            if casus[casual_names.index(command)].options:
                embed.add_field(name=f"Command:", value=casual_name_and_desc[casual_names.index(command)], inline=False)
                option_value = ""
                for i in casus[casual_names.index(command)].options:
                    option_value += f"``{i.name}`` - {i.description}\n"
                embed.add_field(name="Values", value=option_value, inline=False)
            else:
                embed.add_field(name="Command:", value=casual_name_and_desc[casual_names.index(command)], inline=False)
            embed.set_footer(text=random.choice(self.choices))
        elif command in sub_cmd_list_names:
            if sub_cmd_list[sub_cmd_list_names.index(command)].options:
                embed.add_field(name=f"Command:", value=sub_cmd_names_and_desc[sub_cmd_list_names.index(command)],
                                inline=False)
                option_value = ""
                for i in sub_cmd_list[sub_cmd_list_names.index(command)].options:
                    option_value += f"``{i.name}`` - {i.description}\n"
                embed.add_field(name="Values", value=option_value, inline=False)
            else:
                embed.add_field(name="Command:",
                                value=sub_cmd_names_and_desc[sub_cmd_list_names.index(command)],
                                inline=False)
            embed.set_footer(text=random.choice(self.choices))
        elif command:
            embed.add_field(name="404", value=f"Command ***{command}*** not found - Try again", inline=False)
            embed.add_field(name="Advise", value="/help doesn't need the group name for subcommands, \n"
                                                 "just try the name of the command.\n", inline=True)
            embed.add_field(name="Example", value="``/help ping`` instead of \n"
                                                  "``/help general ping``", inline=True)
            embed.set_footer(text=random.choice(self.choices))
        else:
            if sub_names_and_desc:
                embed.add_field(name="Command Groups:", value=' '.join(sub_names_and_desc), inline=False)
            if casual_names:
                embed.add_field(name="General Commands:", value=' '.join(casual_name_and_desc), inline=False)
            embed.set_footer(text="If you need help with a command, use /help <command/group>")
        embed.set_thumbnail(url=self.bot.user.avatar)
        await ctx.respond(embed=embed```
my prototype of my help menu command, vs how u build embeds
sage tendon
#

holy mother of code

limber terrace
#

yeah functional but not ready for takeoff

#

still missing things

sage tendon
limber terrace
#

i would embed.Embed(title=, description=, stuff=) while u use embed.description=

sage tendon
#

oh, yea
line length and readability :3

limber terrace
#

still can read it Xd

sage tendon
#

fair

limber terrace
#

but jesus i lost my notes, need to get new objects

#

lala deleted my notes in her server -.-

sage tendon
#

oh okay

limber terrace
#

yeah i use config files if i dont wanna have it mutiple times in the code

#

global changes and stuff

#

config() is just a function that puts a json in the RAM

@lru_cache()
def config():
    if os.path.isfile("config.json"):
        with open("config.json", encoding="utf-8") as fp:
            data = json.load(fp)
    else:
        with open("app/config.json", encoding="utf-8") as fp:
            data = json.load(fp)
    return data
sage tendon
limber terrace
#

yeah... not that hard

#

but lru cache is useful af and builtin

frail ocean
#

Is there a way to check if a server has premium

sage tendon
limber terrace
sage tendon
#

guild yes?

frail ocean
sage tendon
#

thats what i linked i think yes

frail ocean
#

I mean if a user has premium

#

Or a server

sage tendon
#

you clearly said server

#

and for user... you wont believe it....
discord.User

sonic onyx
#

So, I run this code and my bot activates, and it does print that it initiallized, but when I actually say !hello in my server that the bot is in, it doesn't do anything

sage tendon
#

thats a slash command lol

little cobalt
sonic onyx
#

so it has to be a slash command?

little cobalt
#

it is already a slash command

sage tendon
#

and you can remove the command_prefix from discord.Bot because discord.Bot is slash-only

sonic onyx
#

OH. It actually just worked for the first time when I put /hello

little cobalt
#

if you want to have a prefix command you have to use commands.Bot and ctx.send instead of ctx.respond

sonic onyx
#

so command_prefix isn't doing anything?

little cobalt
#

ye

sage tendon
#

not now, no

sonic onyx
#

so if I just remove that and leave intents=intents, nothing should change?

sage tendon
#

yes

#

i mean just do it and see lol

sonic onyx
#

alright it works

#

I don't understand what @default_permissions() does. What is a default permission? Is that like the everyone permissions?

sage tendon
#

default permissions the command gets set up with in the server

sonic onyx
#

so if I want to restrict a command for use by only people with a certain permission, would I use has_permissions()?

sage tendon
#

no

#

default_permissions(manage_guild=True...)

sonic onyx
#

ohhhh. is has_permissions() channel specific?

sage tendon
#

No, that makes it permanent and unchangeable

#

default permissions can be changed by the server owner

sonic onyx
#

huh. so default permissions are the permissions that i can give to people through roles and stuff?

sage tendon
#

has_permissions was more intended for prefix commands

#

yea just permissions

lapis dock
#

has_permission will only allow people with the ban permission to use it for example.
default permissions will only let users with the ban permission use it unless the server managers go into integration settings and set roles and users that should be allowed to use the command.

sonic onyx
#

Oh I think I understand now. So default_permissions will also take into account access given by integration settings

sage tendon
#

yea

#

and you should use that imo

sonic onyx
#

yea no reason not to in my case

sage tendon
#

so you dont take control away from the server owner

sonic onyx
#

conveniently I'm only making a bot for uses on my own server, so there's a lot of considerations that I don't exactly have to keep in mind. It doesn't make too much of a difference for me. That being said, I should get used to using the better option for most cases

sage tendon
#

also, has_permissions doesn't hide the command from people who cant access it i'm 90% sure, because those permission restrictions are never shared with discord i think

sonic onyx
#

administrator is a permission right?

#

guessing it is its own thing

sage tendon
#

yes

#

permission

cerulean lake
#

Hello I am getting a TypeError: Invalid usage of typing.Union when trying to use bridge.Context as a type hint. PyPy 3.10.

sage tendon
#

show your code

cerulean lake
#

part that's erroring

    @bridge.bridge_command(guild_ids=[config.MAIN_SERVER])
    @bridge.guild_only()
    async def import_instance(
        self, ctx: bridge.Context, guild_id: int, file: Attachment
    ):
sage tendon
#

which pycord version and which python version

cerulean lake
sage tendon
#

if you have no reason not to, update to 3.12
as for using the dev version, well, you should always expect there to be bugs in that

#

Oh

#

pypy is a different version of python basically?

#

well, thats likely why then

#

because that error shouldn't be happening really
try normal python

sonic onyx
#

Is there a function that I could use for my bot to just send a message in a specific channel when triggered? I want the bot to send a message in a channel as part of its startup process

sage tendon
#

bot.get_channel(id)
await channel.send()

#

and just in your on_ready

limber terrace
#

@bot.event
async def on_ready():
    with sql.session_scope("save") as db_session:
        pass
    print('--------------------------------------')
    print('Bot is ready.')
    print('Eingeloggt als')
    print(bot.user.name)
    print(bot.user.id)
    print('--------------------------------------')
    await bot.change_presence(
        activity=discord.Activity(name=f'/help | {bot.user.name}', type=discord.ActivityType.playing))```

smth like that but just with channel.send
cerulean lake
limber terrace
#

the hell is a bridge command?

sage tendon
#

bridgeextcontext is wrong tho (?)

#

bridgeextcontext is what gets passed when its used as prefix cmd, and bridgeapplicationcontext is passed when used as slash

#

or where did you see its deprecated

little cobalt
limber terrace
#

thanks

sonic onyx
limber terrace
#

i use sqlalchemy for sql stuff.

#

so i made some things for it to run it more smoother

#

db_session handling and stuff

sonic onyx
#

oh ok so that’s for working with something else

limber terrace
#
def init_db(uri):
    engine = create_engine(uri, pool_recycle=3600, pool_pre_ping=True, pool_use_lifo=True)
    db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False,
                                             bind=engine))
    Base.metadata.create_all(bind=engine)
    return db_session


@contextmanager
def session_scope(action):
    data = config()["sql"]
    try:
        session = init_db(f'mysql+pymysql://{data["user"]}:{data["password"]}@localhost/{data["database"]}')
    except Exception as e:
        print(e)
        session = init_db(f'mysql+pymysql://{data["user"]}:{data["password"]}@10.0.0.2/{data["database"]}')
    
    if action != "request":
        try:
            yield session
            session.commit()
        except:
            session.rollback()
            raise
    else:
        yield session
    session.close()```
#

this is what im using

sonic onyx
#

so what id be looking for is channel.send? Does that require me to import something other than just discord?

sage tendon
#

never used yield myself ngl

limber terrace
#

yield is fun as hell if u know how

sage tendon
#

yield is just return

#

literally

limber terrace
#

naaaaa

#

no

sage tendon
#

why tf do you have yield in a def?

limber terrace
#

return ends the def, yield returns and continues the def

sage tendon
#

or maybe im stupid

cerulean lake
little cobalt
#

and I still use pymongo with NOSQL

limber terrace
#

u use yield to return loop stuff lol

sage tendon
#

lol

limber terrace
#

like when u use stuff like with:

sonic onyx
#

so I define the channel I want it to send to as channel = client.get_channel(id) then do await channel.send(“text here”)?

limber terrace
#

yep

sonic onyx
#

also is there a difference between using ‘ and “?

#

Because if I remember correctly, it does make a difference in C++

limber terrace
#

not in python

#

thats why it is so much easier to learn than other c languages

sage tendon
#

it does, because you can use ' in " and " in '

limber terrace
#

wow u breaking my mind

#

ever tried this in javascript?

sonic onyx
#

what about quotes inside of quotes? What is the bypass sequence?

sage tendon
#

and dont forget """"

sage tendon
#

or just \"

sonic onyx
#

ah so it is the same as c++ there

#

I’ve got myself into a really strange area where I went halfway with Java, switched the C++ and went halfway

sage tendon
#

\ is universal really

sonic onyx
#

Now im starting python

#

so im mediocre with two other languages learning a third one lol

limber terrace
#

good luck, be careful when u start system programming with bash or powershell

commandline is mighty as fuck

sonic onyx
#

you can just destroy stuff can’t you?

limber terrace
#

destroys your computer within seconds

#

if u doin it the wrong way lol

sage tendon
#

can do that without any cmd or powershell

#

os.remove...

limber terrace
#

yeah thats just stupid

sage tendon
#

import os as cache

cache.remove()

sonic onyx
#

yea. my brother was reformatting a usb on my computer; really worried me since he wasn’t really sure which drive he was on after he started the reformat process.

sage tendon
#

wtf

sonic onyx
#

And I’m guessing if he reformatted my actual drive it would just delete everything

sage tendon
#

thats what reformatting does

little cobalt
sonic onyx
#

all because he wanted a window boot usb and didn’t want to wait for me to do it myself. Luckily he did select the right drive

limber terrace
#

wuhahahaahahahaha

little cobalt
sonic onyx
#

DATENTRAGER

#

hey are you German by chance?

limber terrace
#

no way, how did u know?

little cobalt
#

Immer diese duitser hier

sonic onyx
#

DU BIST LANGSAM

#

that’s all I remember

limber terrace
#

lol

#

last time i used diskpart at work i killed my windows server installation stick

sage tendon
#

#general

limber terrace
#

while killin 5TB of data as well

#

#💩posting

#

:D

cerulean lake
#

I'm getting weird fluctuations in my message sending?
Here is code

    @bridge.bridge_command(aliases=["ms"])
    async def ping(self, ctx: bridge.BridgeContext):
        """Gets the current ping between the bot and discord"""
        start = time.time()
        await ctx.respond(f"🏓 Pong! {round(max(time.time() - ctx.message.created_at.timestamp(), self.bot.latency)*1000)}ms")
        print(f"Ping took {time.time() - start} seconds to send")

It's not a personal ping issue, I've already tested that. This is just so weird to me?

sage tendon
#

bad net

#

on your or on discord's end

sonic onyx
sage tendon
#

bot

#

or whatever you called your bot var

#

show your code

sonic onyx
#

sh

#

ah*

#

hold on, subbing with bot variable

#

works now. recognized bot.get_channel and I forgot to put await before channel.send

#

why does it have to await anyways? Is that basically like 'wait for this to happen on the other client before moving on'?

sage tendon
#

yes and no

sonic onyx
sage tendon
#

its giving control back to the main thread until the to-be-awaited thing is done

#

that way that line of code doesnt block the rest of your bot

sage tendon
sonic onyx
#

ah

sage tendon
#

thats also why using aiohttp is a must to make API requests, else your bot freezes for the duration of a requests api call

limber terrace
#

if u capeable of multithreading aiohttp is just nice to use.
but async is recommended at least

sonic onyx
#

Also I force my bot offline by terminating the program through command prompt, but is there a way to kill the bot with a command from discord?

sage tendon
#

doing it like that is fine

#

but you can run bot.close

maiden bloom
#

Has anyone been having issues with on_guild_join() not being triggered on the dev master branch?

frail ocean
#

how can i use smth like that in a bridge command:

member: typing.Union[str, int]```
sage tendon
#

not a thing

sonic onyx
#

this won't show up as a command for some reason

sage tendon
#

restart discord

sonic onyx
#

like close and reopen discord on my computer?

sage tendon
#

yes

#

or ctrl+r

sonic onyx
#

I get this as an error

sage tendon
#

well close it

#

if you opened those

#

if not, shrug

#

i think you should be able to do exit()

#

but that exits the entire program

#

so you need to print before that

sonic onyx
#

Oh that’s what I want

#

well that gives me another error

errant river
#

i tried everything but this error is still there

sonic onyx
sage tendon
sonic onyx
#

lol i often forget that I have a ultrawide screen

sage tendon
sonic onyx
#

ohh, I see. The command itself says that the bot didn't respond, but it did execute and end the program

sage tendon
#

well, respond, then exit lol

#

you never respond to the interaction

sonic onyx
#

so I'll just throw in a ctx.respond

sage tendon
#

yea

#

ephemeral if you want

sonic onyx
#

now if I'm running the bot and I do just close the window running it, there's no way to have it deal with that is there?

#

because that would be instant termination of the program

#

therefore it couldn't say 'bot has been closed' or whatever, right?

sage tendon
#

well usually you wouldnt ru nthe bot on your pc unless for testing lol

#

and yea if you close the cmd it stops

sonic onyx
#

well I'm only using it for a specific niche purpose

#

so I'll only ever run it off my pc

sage tendon
#

there are tutorials on how to open cmds like that minimized / in the background

sonic onyx
#

I'm guessing I could actually set it up so that it could run on startup, couldn't I?

sage tendon
#

yea

sonic onyx
#

i got it! Task scheduler is really convenient

#

so I want to use a bot to give temporary access to a channel. Do I have to use roles to do that, or can I actually just give access directly to the user?

#

because in channel settings, I can see that you can assign permissions to individual users

limber terrace
#

Do it like microsoft

#

No group no access

sonic onyx
#

well my original idea was to create a role for each of the restricted channels that I wanted to control specific access to, and then use the bot to add and remove those roles from individuals to allow/deny them access

#

but I was wondering if using roles for that would even be necessary

limber terrace
#

Well..
This is overkill

sonic onyx
#

It's for a roleplay server. I am going to password-lock access to certain channels. you unlock them by using an access command with the correct password

#

hence the strange method

sage tendon
#

channels have member restrictions yknow

#

not just roles

sonic onyx
#

so I could instead change the member restrictions?

sage tendon
#

yes

#

p sure you can do that with pycord

sonic onyx
#

that'd be a lot easier than having a convoluted list of roles for accessing every locked channel

sage tendon
#

I mean yea

sonic onyx
#

Anyone know if there’s any functions that exist that deal with changing member restrictions in pycord?

#

I can’t find any related documentation

sonic onyx
#

Yes channel permissions for individual members

lofty parcel
sonic onyx
#

Ah thank you

stray pasture
#

Why would I used BridgeOption instead of Option ? It says in the doc that bridge is for both a Slash Command and a Prefixed Command. I don't want that, I only want slash command. But now it is saying that "Option is deprecated since version 2.5, consider using BridgeOption instead"

sage tendon
sonic onyx
#

What would function would I use to read for a response after the command is triggered?

sage tendon
#

wdym

sonic onyx
#

I want the bot to give a prompt, read the user’s next message, then do an action based on the response

#

I just don’t know how step 2 works

sage tendon
#

I think you can use bot.wait_for for that

#

look it up on the docs

#

or wait

#

.rtfm wait_for

sage tendon
#

yea

sonic onyx
#

So that will collect the next message?

sage tendon
#

You can make it do that yes
I think it's also described in the guide, as a way to wait for a reaction for example

sonic onyx
#

also where do I actually like a list of these functions in the docs?

#

The index?

sage tendon
#

Anywhere you want
it's python after all

frail ocean
sage tendon
#

You can't pass IDs as int

#

Try it, discord will stop you

#

You can only do that via a string option

#

Discord IDs are too long for the length of int discord allows

#

And even if that wasn't the case, options can only have one input type afaik

grizzled loom
#

yeah, if for some reason you really, really need that id and can not use some user object for it you have to length check, use isdigit, try to get or even fetch this user and keep in mind a baned member is discord.User not discord.Member.

#

and I'd never use names. at a certain size you'll run into cases where the name doesn't exsist

sage tendon
#

Yea but it might still be nice to have, you won't necessarily always have someone's ID
even tho you should be able to get that 98% of the time

grizzled loom
#

😂 Okay okay, it can be nice to have it as an option, but it's drawn to errors on both sides and you have to try/except everything.

sage tendon
#

pomelo usernames are ascii

grizzled loom
#

i just don't like relying on names

sage tendon
#

yea ik

lapis dock
#

Even if you use names it is possible to accidently ban the wrong person by accidently using display name instead of username

sage tendon
#

this is about unbanning

lapis dock
#

same applies (but is less importent i guess)

civic quiver
#

How do I edit the role hierarchy? Using role.edit(position=num) doesnt change the position at all but throws no errors

sage tendon
#

did you try hardcoding a few positions to make sure the num variable isn't the problem

#

also, is the bots highest role above where you're trying to move that role?

deft kestrel
#

how i can get the category name by his id?

sage tendon
#

like a channel

deft kestrel
sage tendon
#

yes, you get that like a channel

lapis dock
#

Toothy means you can use get/fetch_channel discord treats categories similar to channels

deft kestrel
#

but how i can get the one that i need by his id

#

nvm

gaunt vale
#

What would be the correct way to edit an message that has been sent to an moderation channel through modal callback? I'm sending and embed with 2 buttons but when interacting with it I want it to also edit the current message attached to the button. I've tried this but im sure its something im doing wrong regarding the message edit

class AcceptRejectView(discord.ui.View):
    def __init__(self, application_id):
        super().__init__(timeout=None)
        self.application_id = application_id

    async def disable_buttons(self):
        for item in self.children:
            item.disable = True
        self.stop()

    @discord.ui.button(label="Accept", style=discord.ButtonStyle.green, custom_id="accept_application")
    async def accept_button(self, interaction: discord.Interaction, button: discord.ui.Button):
        # Fetch and update message using the stored message_id from the database
        async with aiosqlite.connect('mybot.db') as db:
            cursor = await db.execute('SELECT message_id, channel_id FROM applications WHERE application_id = ?', (self.application_id,))
            data = await cursor.fetchone()
            
            if data:
                message_id, channel_id = data
                channel = interaction.guild.fetch_channel(channel_id)
                message = await channel.fetch_message(message_id)
                await message.edit(content="Application approved.", view=None)
                await db.execute('UPDATE applications SET status = ? WHERE application_id = ?', ('approved', self.application_id))
                await db.commit()

    @discord.ui.button(label="Reject", style=discord.ButtonStyle.red, custom_id="reject_application")
    async def reject_button(self, interaction: discord.Interaction, button: discord.ui.Button):
        async with aiosqlite.connect('mybot.db') as db:
            # Fetching user_id and message_id for the application from the database
            cursor = await db.execute('SELECT user_id, message_id FROM applications WHERE application_id = ?', (self.application_id,))
            data = await cursor.fetchone()
            if data:
                user_id, message_id = data
                # Updating application status in the database
                await db.execute('UPDATE applications SET status = ? WHERE application_id = ?', ('rejected', self.application_id))
                await db.commit()

        
        message_channel = interaction.message.channel
        message = await message_channel.fetch_message(message_id)
        await self.disable_buttons()
        await message.edit(content="Application rejected.", view=None)

        # Send DM to the user about the rejection
        member = interaction.guild.get_member(user_id)
        if member:
            await member.send("Your application has been rejected.")

And the the callback from modal if it helps:

        if moderation_channel:
            message = await moderation_channel.send(embed=embed)

            # Save application data including the message_id and channel_id to the database
            async with aiosqlite.connect('mybot.db') as db:
                await db.execute('''
                    INSERT INTO applications (unique_id, user_id, channel_id, message_id, ceo_name, airline_name, star_level, route_count, chosen_option, status)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ''', (unique_id, interaction.user.id, moderation_channel_id, message.id, ceo_name, airline_name, star_level, route_count, chosen_option, 'pending'))
                await db.commit()

                #Fetch app ID
                cursor = await db.execute('SELECT last_insert_rowid()')
                application_id = await cursor.fetchone()
            
            if application_id:
                view = AcceptRejectView(application_id[0])
                await message.edit(view=view)

lapis dock
#

your current code should have worked though. did you get any errors?

civic quiver
sage tendon
#

show your code

gaunt vale
sage tendon
#

button is the second argument

#

not the third

#

change the order

civic quiver
# sage tendon show your code
    async def callback(self, interaction: discord.Interaction):
        guild = interaction.guild
        username = interaction.user.id

        member = discord.utils.get(guild.members, id=username)        
        
        usercolor = self.children[0].value.replace("#","")

        color = int(usercolor, 16)

        color_role = discord.utils.get(guild.roles, name=color)


        if color_role is None:
            try:
                color_role = await guild.create_role(name=usercolor, reason="Creating color role", color=color)

                
            
            except discord.Forbidden:
                await interaction.response.send_message("I don't have permission to create roles.", ephemeral=True)
                return

            except discord.HTTPException:
                await interaction.response.send_message("Failed to create the role.", ephemeral=True)
                return

        try:
            await member.add_roles(color_role)
            await color_role.edit(position=3)
sage tendon
#

is that the button of a view or

civic quiver
#

This is a modal, takes the input of the hex color and assigns it to a role

sage tendon
#

did you try printing to see whether it even reaches that position, and which value the color_role variable has?

civic quiver
#

when ive tried to troubleshoot, it always says: "moved role to position". Let me do some tests in another file rq

sage tendon
#

also.... does it actually even assign the role?

lapis dock
#

I dont know if you just cut it off in the above code but the try at the bottom needs a matching except

civic quiver
#

Yeah the problem was the color_role was none

#

I fixed it thanks

sage tendon
#

so what was the fix

lean garnet
#

can we have this type of form with pycord ?

sage tendon
#

of course

#

thats a modal

#

check out the guide on those

lean garnet
#

Thanks, I didn't know the name of this so I searched "forms" on the guide and I found nothing

#

find it

#

ty