#Basic Pycord Help (Quick Questions Only)

1 messages · Page 25 of 1

fervent cradle
#

then delete the rsponse

#

or either make ephemeral= True to make it so that only one user sees it and that is the original author of the command

fierce elm
#

rtfm

fervent cradle
#

isn't there a way by which I can specify that I only need 2 fields in one line? because when ever I do it I get 3 in one line

spice oyster
#

Try using inline = False for the last one and the opposite for the others.

fervent cradle
#

oh wait

#

got an idea

bitter gull
#

does anyone know how to load/unload cog extensions? because I cannot get the slash commands to go on and off... xd

fervent cradle
#

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'Interaction' object has no attribute 'edit'

#
    msg = await ctx.respond("...")
    await asyncio.sleep(2)
    await msg.edit(content = f"...")```
fervent cradle
#

Hey!

    @commands.Cog.listener()
    async def on_message(self, ctx):
        if ctx.author.bot:
            return
        # Check if message author is self
        if ctx.author == self.bot.user:
            return

        # Check if message is in DMs
        if ctx.guild is None:
            await ctx.channel.send('Message author: ' + ctx.author.name)
            await ctx.channel.send(
                "**Tere!** Mina olen jumal. **Palun vastake `jah`, kui soovite saada kodanikuks.**")
            reply = await self.bot.wait_for('message', check=lambda message: message.author == ctx.author)
            if reply.content == "jah":
                await ctx.channel.send(
                    "**Palun saatke pilt oma Tallinna Reaalkooli õpilaspiletist. Võite oma isikukoodi ära blurrida, kui soovite.**")
            else:  # If reply is not "jah"
                await ctx.channel.send(
                    "**Okei, kahju. Kas te teadsite, et 98% lahedatest inimestest on juba kodanikud? Ja sina kindlasti seal 2% seas ei ole.**")```

This would retrigger the wait_for every time a message is sent.
What should I do?
#

I want basically any message in the dms to be a trigger for the wait_for

fervent cradle
#

how do you delete a response sent by the bot

spice oyster
#

If you have the Message object already, you don't need the first line.

fervent cradle
spice oyster
#

Actually, I need this. How do I get the Cog object to pass there? rooThink

fervent cradle
#
await ctx.respond("smthing", delete_after = {time})
...```
spice oyster
analog crest
#

How am I supposed to reset cooldown in a slash command group?
This is my current code for resetting slash commands cooldown

for command in self.bot.walk_application_commands():
    command.reset_cooldown(ctx)

But it raises the following error

'SlashCommandGroup' object has no attribute '_buckets'
ember grove
#

Is there any documentation for migrating from discord.py? more specificly 1.7.3

spice oyster
ember grove
#

This was very brief and just mentioned uninstalling the old lib, I'm more interested if I have to rewrite stuff and how much

ember grove
#

Thanks

spice oyster
#

Oh, right! I forgot about that page. floosh

jovial shoal
#

having issues using defer/followup
Very recently (last couple weeks), functions that used to work properly are now throwing

discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

when it gets to the await ctx.send_followup part of the code.

Everything else works normally, but it can't send messages/respond to users even with defer
The time between defer and the intended followup is under 10 seconds. Too long to do it without defer, but not even remotely long enough for the defer to expire

jovial shoal
# silver moat send code. thanks
    @slash_command(description="Whose address is this?")
    async def whose_address(self, ctx, address):
        await ctx.defer(ephemeral=True)
        addressee = ""
        address_ver = db['address_registry']
        for userid, user_info in address_ver.items():
            if address in user_info['address']:
                addressee = await self.client.fetch_user(int(userid))
                print(f"{ctx.author.display_name} queried {address} and found {addressee.display_name}, {addressee.id}")
                break
    
        if addressee != "":
            await ctx.send_followup(f"The resident of this address is {addressee}")
        else:
            await ctx.send_followup(f"Address not found")
silver moat
#

what does it show from the user side

jovial shoal
#

what do you mean?

#

they get an Application Failed

#

but I still get the print in the console

silver moat
#

so the defer doesn’t trigger.

jovial shoal
#

doesn't trigger?

silver moat
#

like it doesn’t say “Bot is thinking”

jovial shoal
#

I suppose not. I'm only getting screenshots from users with the Application Failed message. When I use it, it often/always works as expected

#

what might cause the defer to fail to trigger?

silver moat
#

maybe their discord isn’t up-to-date

jovial shoal
#

interesting

#

thanks for your help!

storm hinge
#

hi uh need emergency help idk what to put in await ctx.invoke()'s first parameter which is the command but what do i put in, do i pass in the coroutine? or what

#

ok nvm solved.

somber remnant
#

Hi! are the messages saved in cache by the bot removed after a while? is there a way to remove them to limit the memory?

coarse canyon
#

When I use: python3 -m pip install -U py-cord==2.2.0 I get an error: metadata-generation-failed

Does anyone know how to fix this, I’m using Python 3.10.7

spice oyster
loud holly
#

pip install py-cord--2.2.0

#

though I won't be upgrading yet, since I'll have to make the necessary changes 😭

glossy socket
#

hey, how can i add a button to a static message of the bot?

#

and keep them working even when the bot is restarted

worn forge
#

Hey I'd like to fetch a guild category by Category ID, is that possible?

worn forge
#
    Channel = await guild.create_text_channel(f':green_circle:︱hello')```

Unable to create channel, gives Error:

Channel = await guild.create_text_channel(f'🟢︱hello')

AttributeError: 'coroutine' object has no attribute 'create_text_channel'

granite crypt
#
class pointsView(discord.ui.View(timeout=None)):

Throws RuntimeError: no running event loop
Help

neon bramble
#

you don't subclass like that

neon bramble
granite crypt
neon bramble
# granite crypt How then

discord.ui.View(timeout=None) creates an instance of ui.View, when subclassing you put the class object inside the brackets, ex. (discord.ui.View)

granite crypt
#

Why do buttons stop working after bot restarts?

neon bramble
#

because the client doesn't know what callback to attribute to that particular button

#

you could make your own handler in on_interaction that checks the custom_id

#

or you could use "persistent views"

#

i think there's an example in the examples directory

granite crypt
loud holly
#

what's the difference between raw_status and status? Is it similar to other raw events vs events without the raw?

cyan quail
iron halo
#

is there like a rate limit on the bot starting it doesnt respond for like 30 seconds if i do it too quickly

cyan quail
iron halo
#

yea thats it

#

ill just wait a minute next time

quick temple
#

Is it possible to make a .check for a specific SlashCommandGroup?

cyan quail
cyan quail
#

any check functions or custom check functions

quick temple
#

oh wow

#

thanks

fervent cradle
#

is there a float value in Option()?

#

ah looks like there is

surreal glade
#
import discord
from discord.ui import Button
from discord.ext import commands
intents = discord.Intents.default()
intents.guilds = True
intents.messages = True
intents.message_content = True
intents.members = True
bot = discord.Bot(command_prefix='%', intents=intents, debug_guilds=758416321284276226)
TOKEN = "GRAHHHHHHHHHHHHHHHHHHHHHHHHH"



@bot.command(description="test")
async def ohio(ctx):
    await ctx.send(f"Latency {bot.latency} ")

@bot.group(description="test")
@commands.has_role("OHIO LEADER")
async def add():
    pass

@add.command()
@commands.has_role("OHIO LEADER")
async def councilmember(ctx, usr: discord.Member):
    await usr.add_roles("OHIO COUNCIL")
    await ctx.send("ohio council member added")



bot.run(TOKEN)

And then i get this error message

- TypeError: add() got an unexpected keyword argument 'guild_ids'
silver moat
#

full traceback, thanks

surreal glade
#
-Traceback (most recent call last):
- File "C:\Users\paul\PycharmProjects\stuffs\main.py", line 22, in <module>
-   async def add():
- File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\bot.py", line 893, in inner
-   group = cls(
- TypeError: add() got an unexpected keyword argument 'guild_ids'
silver moat
surreal glade
#

im trying to do slash commands

#

i deleted the command prefix thing but then it still gave me the same error

errant craneBOT
#

Here's the slash groups example.

silver moat
#

this is how you create a slash command group. it is different than prefixed commands.

bitter gull
tiny wagon
#

how can i use async init function to initialize a select menu?

surreal glade
#

addmember = discord.SlashCommandGroup("add", "peen")

@addmember.command()
@commands.has_role("OHIO LEADER")
async def councilmember(ctx, usr: discord.Member):
    await usr.add_roles("OHIO COUNCIL")
    await ctx.respond("ohio council member added")
bot.add_application_command(addmember)

Gives me this error

Ignoring exception in command add councilmember:
Traceback (most recent call last):
  File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\commands\core.py", line 127, in wrapped
    ret = await coro(arg)
  File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\commands\core.py", line 881, in _invoke
    await self.callback(ctx, **kwargs)
  File "C:\Users\paul\PycharmProjects\stuffs\main.py", line 25, in councilmember
    await usr.add_roles("OHIO COUNCIL")
  File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\member.py", line 975, in add_roles
    await req(guild_id, user_id, role.id, reason=reason)
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\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\bot.py", line 992, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\commands\core.py", line 358, in invoke
    await injected(ctx)
  File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\commands\core.py", line 127, in wrapped
    ret = await coro(arg)
  File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\commands\core.py", line 1171, in _invoke
    await command.invoke(ctx)
  File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\commands\core.py", line 358, in invoke
    await injected(ctx)
  File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\commands\core.py", line 135, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'str' object has no attribute 'id'

@silver moat

ebon hearth
#

you are giving a string "OHIO COUNCIL"

#

instead, give them the role object

soft girder
#

Is it possible to do this in PyCord, and if so, how? I if that study API REF. but I don't know what it's called.

wary rover
soft girder
#

I want those who do not have the right role to have this picture displayed. So that users do not touch the bot once again.

#

I just want the command unnecessary for the user to be unnecessary. Or so that this command could not use a certain role.

soft girder
#

Okay

#

Bye

wary rover
soft girder
#

Thx, for help

spice oyster
#

Is it possible to create a link to a Slash Command with pre-compiled options?
For example, I'd like the text Sky to be a link for /image name:sky.png size:1920.

wary rover
spice oyster
#

The user clicks on the word and the command appears in chat.

wary rover
spice oyster
#

The word goes in the description for a filed in an Embed.

fervent cradle
#

Hey, guys, is it possible to automate the new Pause Invites feature via the bot?

#

nvm.. await guild.edit(disable_invites=True)

#

thanks pycord, i love u

spice oyster
#

If I send context.user.mention in a private message, will it always appear as a mention/link to the user profile (eg. @spice oyster) or not?
Think about when you are not sharing a server with the user, so you likely never met before.

spice oyster
#

Is it possible to use something like @commands.is_owner() to check if a given user is in a list of allowed users to use that Slash Command?
I cannot use Roles because it has to work across different Discord servers where I don't have the power to add Roles.

spice oyster
#

Can my bot send private messages to users that have blocked private messages from people in the same servers as them?

fervent cradle
#

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: OSError: cannot open resource

#

?

#

why this error?

fervent cradle
spice oyster
fervent cradle
#

so umI have an idea

#

/image [provide choices]

#

and link those choices with the ids of secific images

#

and iterate through your db to find the id matching the request and grab the link

#

and display result

#

is this what you were asking?

#

@spice oyster

spice oyster
#

For example, I want to click on a link and get something like this in chat.

fervent cradle
#

oh

#

Idk is that even possible?

#

to get a template for a cmd?

spice oyster
fervent cradle
#

how do you get the command through a link?

spice oyster
#

#1023056728998289492 message

fervent cradle
spice oyster
fervent cradle
#

does slashcommandgroups work with slash command on your bot?

#

cause in mine the options never seem to appear

wary rover
#

The command will not be written but you can send an embed containing the command to be written

spice oyster
fervent cradle
#

can you give mea good tutorial for cogs?

#

current ones on yt are all outdated

wary rover
#

ahahah same prob

spice oyster
wary rover
#

You should not use create_group but SlashCommandGroup except that this one works only in a cog

#

@fervent cradle

#

I had the problem and spent my morning working on it

fervent cradle
#

looks like gotta make some cogs for my bot

wary rover
fervent cradle
#

k

#

thanks

wary rover
#

I have three files for my three groups of commands

fervent cradle
#

and if possible can you tell me what are the "handlers" and "modules" files?

west flume
#

Is there something wrong here?

west flume
wary rover
spice oyster
fervent cradle
#

k done

#

Ima go through examples

wary rover
# west flume

indentation, if you have copied the code from discord or a site you may have problems

woeful spindle
#

his indentation seems fine to me

wary rover
woeful spindle
#

never knew that was even a bug tc_shrug

#

I’ve never encountered it

wary rover
#

I had it again this morning, I had to delete and redo my indentation

woeful spindle
#

@west flume ^ seems like u will have to do that

wary rover
keen grove
#

how to check if a user has accepted rules or not?

storm hinge
#

why does interaction.response.delete_original_response() now return an unknown webhook error?

#

i need fix

keen grove
#

so pending will be true if not set up or in non-community servers by default?

spice oyster
#

What's the difference?

spice oyster
spice oyster
fervent cradle
#
@bot.command()
@commands.has_permissions(ban_members=True) 
async def ban(ctx, member: discord.Member, *, reason=None):
    try:
        await member.ban(reason=reason)
        embed=discord.Embed(title="**Moderation: User was Banned**",description=f"{member}, Has been banned .\nReason is `{reason}`. This ban was requested from\n{ctx.author.mention}",colour=0x42F56C)
        embed.add_field(name="Expiration:", value=f"``Permantly``", inline=True)
        embed.add_field(name="Banned By:", value=f"``{ctx.author}``", inline=True)
        await ctx.send(embed=embed)
    except Exception as e:
        await ctx.send(f"Failed to ban: {e}")


#

can someone help me?

fervent cradle
#

wait

#
Ignoring exception in command ban:
Traceback (most recent call last):
  File "/home/runner/Vilan-2/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 184, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 130, in ban
    await member.ban(reason=reason)
  File "/home/runner/Vilan-2/venv/lib/python3.8/site-packages/discord/member.py", line 665, in ban
    await self.guild.ban(self, reason=reason, delete_message_days=delete_message_days)
  File "/home/runner/Vilan-2/venv/lib/python3.8/site-packages/discord/guild.py", line 2973, in ban
    if not (0 <= delete_message_seconds <= 604800):
TypeError: '<=' not supported between instances of 'int' and 'NoneType'

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

Traceback (most recent call last):
  File "/home/runner/Vilan-2/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 342, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/Vilan-2/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 951, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/runner/Vilan-2/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 193, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: '<=' not supported between instances of 'int' and 'NoneType'****```
spice oyster
#

Maybe you forgot to pass it and it defaulted to None.

woeful spindle
#

nvm, indentation error

slim plaza
#

How do i make my bot available for multiple guilds? I had my one guild_id as a parameter for my @bot.slash.commands. When try to add another one i get "discord.erros.Forbidden: 403 Forbidden (error code: 50001): Missing Access

fervent cradle
spice oyster
fervent cradle
#

i guess yea

#

lemme check

cyan quail
#

lib issue, in member.ban add delete_message_seconds=0

#

will fix

fervent cradle
#

ok

#

ty

#

Does anyone know i can get the values from a websites dropdown menu? I just want a command that responds with everything in this list. Example:
Aghanistan Remaining (1)
Albania Remaining (2)
...

full basin
fervent cradle
# novel leaf try beautifulsoup4
page = get('https://mywebsite/test')
soup = BeautifulSoup(page.text, 'html.parser')
soup = soup.find('select', class_ = 'form-control')
items = soup.select('option[value]')
values = [item.get('value') for item in items]

print(values)
await ctx.respond(values)

I tried this which kind of works but it only returns the values ie "Afghanistan" and not the "Afghanistan Remaining (0)"

novel leaf
#

try values = [item.text for item in items]

fervent cradle
#

That worked! Thank you.

fervent cradle
novel leaf
#

[item.text for item in items if "(0)" not in item.text]

fervent cradle
#

Thank you very much! I appreciate it.

glossy socket
fervent cradle
#

daily limit? Isn't there a way around it?

#

Can anyone brief the situation, why am I getting this?

shrewd dome
#

you are getting this because you reached the daily limit of 200 application command creations

fervent cradle
#

slash command?

shrewd dome
#

I believe Pycord re-registers your command when you restart your bot

silver moat
silver moat
fervent cradle
#

cause even if I use an alt to send commands it doesn't work

glossy socket
errant craneBOT
#

examples/views/persistent.py line 74

await ctx.send("What's your favourite colour?", view=PersistentView())```
silver moat
fervent cradle
#

So like my bot can't process more that 200 commands a day

silver moat
fervent cradle
#

so what if my bot is in 5-6 servers and 10 people in each server use it

fervent cradle
shrewd dome
#

you probably restarted it too much

silver moat
fervent cradle
shrewd dome
#

maybe its changed since last time

silver moat
#

Pycord only registers/creates commands if the bot doesn't have them

shrewd dome
#

fair

#

then god knows how this dude reached 200 creates

#

😂

fervent cradle
#

lmao I am wondering the same thing

silver moat
#

could be shared host, not sure tho.

fervent cradle
#

shared *

#

ok nvm I think ima sleep

#

good night

silver moat
#

ok gn

worn forge
#

Hey, I'm trynna lock a channel I just created to a User and a Role
how do I create the overwrtire for this
I can create overwrite for Bot and Everyone, not sure how it's done for a Specific User and Role

glossy socket
#

hey, im trying to set up this persistent view, but i keep getting this error:

ValueError: View is not persistent. Items need to have a custom_id set and View must have no timeout

#

i did give all of the items a custom_id except the url button since that one cant have a custom_id

proud mason
#

did you set the view timeout to None?

glossy socket
#

i didnt set any timeout

#

so it should default to None right?

spice oyster
glossy socket
#

ahh thanks

spice oyster
#

How to get the "About Me" section of a given user? eddaniSherlock

iron halo
#

my bot keeps randomly saying interaction not found even when i use await ctx.defer()
is it just discord being slow or is it my problem

cyan quail
little hill
#

I noticed that bot.users fluctuates between restarts. what causes this?

little hill
#

is there a way to make it more consistent?

#

or is there a more accurate total-user-count?

desert pebble
#

hello again

#

client.run is a blocking call
anything after it isn't executed
how can i fix that?

gleaming falcon
opaque glacier
#

how do I set multiple lines on an embed?

#

for example:

#

so far i have:

young bone
opaque glacier
#

no im trying to create multiple lines for the description

neon bramble
#

add a \n

#

that being the escape code for the new line character

#

just like you have \t for a tab and \r for carriage return

spice oyster
#

How do I enumerate() here?

for offlaner, amount in zip(offlaners, amounts):
neon bramble
#
>>> for a, (b, c) in enumerate(zip("abc", "def")):
...     print(a, (b, c))
... 
0 ('a', 'd')
1 ('b', 'e')
2 ('c', 'f')
surreal glade
#
addmember = discord.SlashCommandGroup("add", "peen")

@addmember.command()
@commands.has_role("OHIO LEADER")
async def councilmember(ctx, usr: discord.Member):
    await usr.add_roles(id=1026656532642942986)
    await ctx.respond("ohio council member added")
bot.add_application_command(addmember)

And I get this error now

- Ignoring exception in command add councilmember:
- Traceback (most recent call last):
-  File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\commands\core.py", line 127, in wrapped
-    ret = await coro(arg)
-  File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\commands\core.py", line 881, in _invoke
-    await self.callback(ctx, **kwargs)
-  File "C:\Users\paul\PycharmProjects\stuffs\main.py", line 25, in councilmember
-    await usr.add_roles(id=1026656532642942986)
- TypeError: Member.add_roles() got an unexpected keyword argument 'id'

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

- Traceback (most recent call last):
- File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\bot.py", line 992, in invoke_application_command
-    await ctx.command.invoke(ctx)
-  File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\commands\core.py", line 358, in invoke
-    await injected(ctx)
-  File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\commands\core.py", line 127, in wrapped
-    ret = await coro(arg)
-  File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\commands\core.py", line 1171, in _invoke
-    await command.invoke(ctx)
-  File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\commands\core.py", line 358, in invoke
-    await injected(ctx)
-  File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\commands\core.py", line 135, in wrapped
-    raise ApplicationCommandInvokeError(exc) from exc
- discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: Member.add_roles() got an unexpected keyword argument 'id'
#

nevermind i got it

woeful spindle
#

How do I add multiple views to one message?

spice oyster
cyan quail
#

you can add multiple rows to a view, but there can only be 1 view per message

#

if you need to use a different row, add row= to your select/button object

woeful spindle
#

How would we add 2 buttons to a message then? Do they need to be in the same view?

cyan quail
#

? yeah

woeful spindle
#

That’s kinda annoying

cyan quail
#

views support up to 25 items (5 items in each of 5 rows)

#

how come?

woeful spindle
# cyan quail how come?

I wanna have a view for my Invite button and a different view for my support server button and sometimes I want both, so now I have to make 3 different views whereas if I could have multiple views in one message, I can just add both my support server view and Invite view rather than having to create a new view for both

#

hope that makes sense lol

cyan quail
#

but why different views?

woeful spindle
#

but sometimes I just want my invite button on my command

cyan quail
#

you can just programatically add the buttons

woeful spindle
#

or just my support server button

#

and sometimes I want both

cyan quail
#

like py view = discord.ui.View() if True: view.add_item(invite_button) elif False: view.add_item(support_button) else: ...the logic here is just an example, but it's not that complicated

woeful spindle
#

my brain is already broken looking at that 😅

cyan quail
#

eh...

cyan quail
#

are they both url buttons?

woeful spindle
cyan quail
#

if it's url buttons then it's even easier

woeful spindle
#

how so?

cyan quail
#

since you can only make them with discord.ui.Button so you aren't dealing callbacks

#

what decides whether it's an invite or a support server button?

woeful spindle
#

depends on the command really

cyan quail
#

did you subclass the view elsewhere? or are you just doing view=discord.ui.View()

#

might be easier if you showed the code

proud pagoda
woeful spindle
#

it works but I wanna have separate views

cyan quail
#

oh

woeful spindle
#

hold on let me remove the invite

cyan quail
#

yeah LOL

woeful spindle
#
class OnAzielInviteView(discord.ui.View):
    def __init__(self):
        super().__init__()
        
        style = discord.ButtonStyle.gray
        vote = discord.ui.Button(style = style, label = "Top.gg!", url = "https://top.gg/bot/981332858230698069/vote")
        support = discord.ui.Button(style = style, label = "Support", url = "https://discord.gg")
        self.add_item(vote)
        self.add_item(support)
cyan quail
#

ok isee

#

why don't we add a variable to the view call then? e.g. if you do view = OnAzielInviteView(invite=True) or something, it'll only add that button

#

there are several ways to go about this but that would keep it flexible

cyan quail
#

so simply we're looking to add stuff to __init__ py class OnAzielInviteView(discord.ui.View): def __init__(self, support=True, invite=True):then later on in the init, we just add conditionspy if support: ... # add the support button

#

this way, by default if you just call OnAzielInviteView() you'll have both buttons

#

but if you, for example, wanted to hide the support button, you would do OnAzielInviteView(support=False)

woeful spindle
#

Ooo, I see

cyan quail
#

you can change this as you wish to set defaults etc.

woeful spindle
#
class OnAzielInviteView(discord.ui.View):
    def __init__(self, invite = True, support = True):
        super().__init__()
        
        style = discord.ButtonStyle.gray
        vote = discord.ui.Button(style = style, label = "Top.gg!", url = "https://top.gg/bot/981332858230698069/vote")
        support = discord.ui.Button(style = style, label = "Support", url = "https://discord.gg")
        if support:
            self.add_item(support)
        if vote:
            self.add_item(vote)

Like this?

neon bramble
#

remember thy indentation

cyan quail
#

^

woeful spindle
#

yup just remembered lol

#

better now?

cyan quail
#

and perhaps change the elif to just if

#

because you're always checking both conditions separately

woeful spindle
#

got it, and could I add more buttons like this with the same type of idea?

cyan quail
#

mhm

woeful spindle
#

awesome, tysm :)

cyan quail
#

if you wanted you could also move the button creation inside the if statements so you don't have unused variables lying around

#

oh wait

cyan quail
#

e.g. they're you're overriding the support=True with support = Button, so maybe rename the buttons to support_button etc. so nothing clashes

woeful spindle
#

kk ty!

fervent cradle
cyan quail
#

wait

cyan quail
#

or did you use guild.ban(member, ...)

fervent cradle
cyan quail
#

it's fixed in the next release but just checking

fervent cradle
fervent cradle
cyan quail
#

interesting, from my testing it should have errored on member.ban but if it worked then fair enough?

naive steppe
#

Is there a rule against implementing automatic ban processes within a bot?

Like a blacklist that autobans when they join

I havnt fully read discord bot tos, and so im not fully educated if it would be some kind of foul play

cyan quail
#

there may be clauses/rules regarding how you store data used with your bot, necessary data etc., but autobanning in itself would be fine

vivid plaza
#

Guys. If anyone have a problem in his code, its easy to solve it, just fix it !

finite flame
#

someone has an idea why pycharm professional is letting SQL queries look so weird?

spice oyster
#

I have a question about merging lists in Python. Anyone knows how to solve this? rooThink

m = [("H", 1), ("A", 4)]
o = ["A", "B", "C", "H"]
r = create_results(m, o)  # How to implement this function to get these results?
print(r)
> [("A", 4), ("B", 0), ("C", 0), ("H", 1)]

I'm wondering if there is a better way to do it than just using nested for loops.

finite flame
spice oyster
#

Thanks! I'm trying to do something similar but it's not easy. I'll try your version.

#

It's basically the same code until break because I was still trying to figure out the end.

#

That's perfect! How did you solve it so quickly and with zero mistakes? I didn't think about the else after the for loop. wow

rugged lantern
#

or as a list comprehension, result = [(x, num) if letter == x else (letter, 0) for x, num in m for letter in o]

#

(dunno if it works, didnt test)

spice oyster
#

Thanks! I'll try tomorrow. Now it's kinda late here. blobpain

hasty spire
#

hello there, im trying to get the stats of my bot,
my code just returns a valueerror, idk what am i doing wrong

young bone
#

and what is the error?

hasty spire
#

oh sorry, it says ValueError, idk what i should replace

AttributeError: 'info' object has no attribute 'datetime'```
```discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: module 'discord.ext.commands' has no attribute 'ValueError'```
#

looks like my uptime var is the cause

silver moat
#

have you defined self.datetime?

hasty spire
#

lemme try

rugged lantern
#

why are u calling self

full basin
#

Probably a function they made?

rugged lantern
#

with this kind of question

#

i doubt it, respectfully

young bone
silver moat
#

what is self.datetime?

hasty spire
#

wdym?

#

wait now i tottaly dont understand, i defined my current time(current) then compare the current time with the execution time(idk if i use the right ones)

full basin
#

We don't know either. You coded it.

#

what is self.datetime

#

Where is that defined

hasty spire
rugged lantern
#

so why are u use it as a variable

full basin
#

If you can't read your own code, you shouldn't ask for help

hasty spire
#

ahhhh, im ashamed im sorry, thank you for making me realized the i should always 10x check my code, will remember this mistake for a lifetime
Edit: i forgot to make start variable as a global variable

#

works as intended now

hasty spire
full basin
#

Do you realize now - start will always be 0

hasty spire
#

oke now, thanks

boreal chasm
#

how do i get the channel that the command was executed in?

young bone
#

ctx.channel

fierce elm
#

Anyone know why this isn't working? (The on_timeout, I am actually using the view)

make_pages.py

class TicketButtonsView(discord.ui.View):
    def __init__(self, ticket_id):
        super().__init__(timeout=20)
        self.ticket_id = ticket_id
        self.add_item(TicketCloseButton(ticket_id=ticket_id))
        self.add_item(TicketDeleteButton(ticket_id=ticket_id))
        self.add_item(TicketOpenButton(ticket_id=ticket_id))

    async def on_timeout(self) -> None:
        logger.debug(f"TicketButtonsView timed out for ticket {self.ticket_id}")
        await self.message.delete()

make_pages.py

def make_view(ticket):
    view = TicketButtonsView(ticket_id=ticket.id)
    return view

tickets.py

    async def ticket_admin_list(self, ctx: ApplicationContext):
        """List all open tickets."""
        await ctx.defer(ephemeral=False)
        tickets = await get_all_open_tickets()
        if tickets is None:
            await ctx.respond("There are no open tickets.")
            return
        else:
            pages = []
            first_page = discord.Embed(title="Open Tickets", timestamp=arw.now('US/Eastern').datetime, description="All open tickets are listed on the following pages.")
            pages.append(Page(embeds=[first_page]))
            for ticket in tickets:
                pages.append(Page(embeds=[await make_embed(ticket, bot=ctx.bot)], custom_view=make_view(ticket)))
            pager = Paginator(pages=pages)
            await pager.respond(ctx.interaction, ephemeral=False)

I am not getting any traceback, yet the view doesn't delete the message on_timeout

fervent cradle
#

how do i send buttons to the next row

spice oyster
#

There is an attribute on Buttons, I believe. Search for Button in docs.

languid finch
#

how to remove global slash commands?

spice oyster
#

I need a Slash Command to only show in private messages with my bot. How to do it?
I don't want to use @commands.dm_only() as a decorator because the Slash Command will still be visible outside of private messages.
In other words, I need dm_only as attribute, similar to guild_only, but sadly it's not there.
Link: https://docs.pycord.dev/en/master/api.html#discord.SlashCommand.guild_only

analog crest
#

I deferred an interaction and tried to send a modal after, but it says this interaction has been responded before? I don't see this error when sending normal messages

obtuse juncoBOT
#

dynoError No tag code found.

fringe socket
#

?tag didnotwork

obtuse juncoBOT
#

dynoError No tag didnotwork found.

fringe socket
#

gahhhh

spice oyster
#

You have to do it differently (eg. send the Modal immediately, or add a Button to open it).

slate vortex
#

If Bot.debug_guilds is configured, is it possible to still create global commands at all? like override it on a per-command basis or something?

spice oyster
#

The bot will not create any global commands if debug guild IDs are passed.

slate vortex
#

wasnt sure if that was just a default behaviour or a hard restriction

spice oyster
#

Because of that change, for testing commands, I prefer to use guild_ids (from Slash Commands or Slash Command Groups) or a completely different bot just for testing purposes, depending on what I need to do.

slate vortex
#

fair enough, thanks

tiny wagon
#

How can i make a custom method of Bot instance? So that i can use it in other cogs too

finite flame
spice oyster
#

How to easily convert date_time = message.created_at into content = "<t:{date_time}:F>" printable format? Solved with int(date_time.timestamp()).

copper dew
fervent cradle
#

is it possible to make command groups like how we make slashcommand groups

#

smthing like this
?admin ban

#

its possible to do that in slash commands with the groups but can we do the same for prefix commands

tiny wagon
somber remnant
#

I'm probably going to ask a dumb question and get disowned, but there is no way to "hide" a / command so that only certain people (me and my friend) can use them?

copper dew
copper dew
#

Or the other way is to just load that command only in the guild that u and ur friends is in

somber remnant
fervent cradle
cyan quail
somber remnant
#

Yea ik that, but i want to make it for all the server my bot join
but if it don't have the perm, it wont work :/

cyan quail
#

but yeah no "direct" way to do it from the bot, it'd either be guild_ids or using default_member_permissions for stuff like administrator

somber remnant
#

And i need to add another intent e-e

#

My goal is to remove the messages intent, so i need to make bot admin command into slash commands

cyan quail
#

you can still use your prefix commands without the intent

#

just add the bot mention as your prefix

somber remnant
#

Nah it doesnt work :/

somber remnant
cyan quail
#

bots can read content for messages they're mentioned in

#

even without the intent

somber remnant
#

Ho i see

cyan quail
#

alternatively you could also just do them all in DMs

somber remnant
#

pretty interesting

somber remnant
#

How i can add the mention in prefix ?

#

remove the basic one ?

cyan quail
somber remnant
#

its easier that i think

#

So i'll try it rn

#

Another question, i need 2 intents for message :

intents.message_content = True
intents.messages = True```
If i remove one, it doesnt work anymore
Why ?
cyan quail
#

message_content is the privileged one for specifically message.content, message.attachments, message.embeds and probably a few others

#

while messages is for all message events; this isn't privileged and is necessary for the bot to see the message event at all

somber remnant
#

hmm

cyan quail
#

basically you need messages for prefix commands (at a minimum)

somber remnant
#

Okay, and i need it too with bot mention ?

cyan quail
#

yes

somber remnant
#

hmm

#

It's problematic, I wanted to remove it

cyan quail
#

is there any reason you don't want it at all?

somber remnant
#

I'm trying to remove as much as possible RAM from the bot. As i read, the messages intent keep message in caches, so if i remove it it would be nice

cyan quail
#

you can just disable/reduce the cache

#

by default it's limited to 1000 messages

somber remnant
#

How ?

cyan quail
#

inside commands.Bot, set max_messages=None or any integer to change the limit

somber remnant
#

I searched about the RAM on pycord/discord but found nothing, except how to raise an error when ram exceed something

#

Woaw it's work really well
Could it be a problem to set this one to None?

#

And, there is a way to remove cache from these too ?:

intents.reactions = True
intents.guilds = True
intents.members = True```
somber remnant
cyan quail
somber remnant
cyan quail
#

these days buttons are encouraged over reactions yes

somber remnant
#

For this reason, or another one ?

cyan quail
#

well

#

buttons are designed to be used as responses

#

and as interactions they don't rely on the message/other intents

somber remnant
#

I see

cyan quail
somber remnant
#

So i can remove all the cache if i put button instead of reaction 🤔 ?

cyan quail
#

it should work yeah

somber remnant
#

interesting so,I didn't really want to switch to buttons but...

#

And members work the same way that messages ?

#

I use a lot of user information, and also fetch_user(), etc...

cyan quail
#

members are a bit different from messages

#

the docs page on MemberCacheFlags somewhat explains what you can enable/disable

somber remnant
#

So, if i use interactions i want to keep interaction and from_intents ?
to remove the others i can make member_cache_flags.joined=False ?
or member_cache_flags.intents work ?

cyan quail
#

from_intents will set joined=True since you have the members intent

somber remnant
cyan quail
#

not quite, you need to form the object

#

similar to how you do Intents

somber remnant
#

Hoo i see

#

after or before commands.Bot ?

cyan quail
#

inside, no?

#

how did you do intents

somber remnant
cyan quail
#

but like

#

before/after

somber remnant
#

Before

cyan quail
#

then do the same

somber remnant
#

kay

granite crypt
#

Options keep disappearing from my slash commands. I have no idea why.

#

There’s supposed to be an option here. This is happening to every command…

somber remnant
#

So, like this :```member_cache_flags= discord.MemberCacheFlags.all()
member_cache_flags.voice=False
member_cache_flags.joined=False

then in commands.bot i add `member_cache_flags=member_cache_flags`
it's that ?
cyan quail
cyan quail
#

version?

#

of pycord

granite crypt
#

2.2 but i believe it happened on the older one too

cyan quail
#

will be fixed hopefully today when 2.2.1 releases, i think the best you can do is downgrade to 2.0.1

#

though this only breaks groups that were created with create_group

granite crypt
#

Ah so it’s a known issue?

cyan quail
#

if i'm not mistaken the issue isn't present with cogs

#

yeah

granite crypt
#

Alright then

#

I’ll downgrade for now

#

Thank you

granite crypt
cyan quail
#

did you mean cogs or groups?

granite crypt
#
info = bot.create_group(name="info", description="FAQ")
cyan quail
#

if you want you could move the commands to a cog and rework it a bit then load them, but if not then i'd say just downgrade

granite crypt
#

Yeah i’ll downgrade for now. Sounds easier

#

What’s the latest version before 2.2?

cyan quail
#

well... it was also broken on 2.1.3 and 2.1.1; 2.0.1 is the main version where it isn't broken

granite crypt
#

I was running on 2.1.1 without any problems until today

cyan quail
#

if it works on 2.1.1 then try that then

#

i wasn't sure if it was introduced in .1 or .3

cyan quail
#

yeah that's fine

somber remnant
#

How i can check if it's work like i want ?

#

i mean, how i can check if voice for exemple is not in cache anymore

spice oyster
#

Do you know an extension for Visual Studio Code that can highlight repeated block of codes in a file/project while ignoring space characters? eddaniSherlock

quick temple
#

Can a slash command option accept a command (so a command is referenced)?

cyan quail
#

you could go further and make it an autocomplete based on all your bot's commands, or use choices to show specific command names

rare ice
#

Can you run pip freeze in your terminal for me and send the output?

fervent cradle
#

How can I create a say command with slash

simple canopy
frozen salmon
#
class PersistentView(discord.ui.View):
    def __init__(self, bot):
        super().__init__(timeout=None)
        self.bot = bot
    
    options = []
    s = guild
    ss = self.bot.get_guild(s)
``` howcome self is undefined?
young bone
#

For what do you need the bot?

frozen salmon
frozen salmon
silver moat
patent escarp
#
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
Ignoring exception in command close:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 126, in wrapped
    ret = await coro(arg)
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 852, in _invoke
    await self.callback(self.cog, ctx, **kwargs)
  File "/home/container/commands/moderation/close.py", line 65, in close
    await ctx.send(f"{Author.mention}, you have been inactive for `{DurationConverter(seconds)}`. If you don't respond <t:{int((datetime.utcnow()+timedelta(minutes=10)).timestamp())}:R>, this ticket will be closed{', and you will be blacklisted.' if blacklist else '.'}")
  File "/home/container/.local/lib/python3.10/site-packages/discord/abc.py", line 1521, in send
    data = await state.http.send_message(
  File "/home/container/.local/lib/python3.10/site-packages/discord/http.py", line 353, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access```
I get Missing permissions, but I've never seen Missing Access. Any potential reasons why this happens?
silver moat
frozen salmon
patent escarp
#

And it has been sending messages

silver moat
#

because you are using slash commands, reinviting your bot with the application.commands scope also should happen.

patent escarp
#

The channel would have been deleted 20 minutes ago, and did not work

#

so when I did use /close again, got the error

silver moat
#

well, interactions bypass default channel permissions

#

did you mean to use ctx.respond instead of ctx.send?

patent escarp
silver moat
#

Could you send your code?

patent escarp
#

It's a very big file, but I'll send the essential

#
        if auto: #Starts a timer for the ticket to close
          try:
            seconds = TimeConverter(auto)
          except:
            return await ctx.respond(embed=SetEmbed(ctx.guild,
              "Invalid Argument",
              f"`{auto}` does not follow the correct time format.\nEx. `1h30m`, `1d16h40m1s`",
              discord.Color.red()), ephemeral=True, delete_after=30)
          view = discord.ui.View(CancelButton(ctx.author), timeout=None)
          Timer = await ctx.respond(embed=SetEmbed(ctx.guild,
            "Timer Started",
            f"This ticket will close <t:{int((datetime.utcnow()+timedelta(seconds=seconds)).timestamp())}:R>\n**Reason:** {reason}"), view=view)
          msg = await ctx.interaction.original_message()
          ChannelData["Timer"] = encrypt(msg.id, True)
          Save("Channels", ctx.channel.id, ChannelData)
          Save("Configuration", ctx.guild.id, ConfigurationData)
          if seconds > 600:
            seconds -= 600
            await asyncio.sleep(seconds)
            ChannelData = Load("Channels", ctx.channel.id)
            if ChannelData:
              if ChannelData["Timer"]:
                await ctx.respond(f"{Author.mention}, you have been inactive for `{DurationConverter(seconds)}`. If you don't respond <t:{int((datetime.utcnow()+timedelta(minutes=10)).timestamp())}:R>, this ticket will be closed{', and you will be blacklisted.' if blacklist else '.'}")
                await asyncio.sleep(600)
                ChannelData = Load("Channels", ctx.channel.id)
                if not ChannelData["Timer"]:
                  return
              else:
                return
          else:
            await asyncio.sleep(seconds)
            ChannelData = Load("Channels", ctx.channel.id)
            if not ChannelData["Timer"]:
              return
          try:
            await Timer.delete()
            await msg.delete()
          except:
            pass```
silver moat
surreal glade
#

@silver moat do u know how to do select menus IN slash commands, i cant find any documentation

errant craneBOT
#

Here's the slash options example.

surreal glade
#

thank you

bronze flame
#

this isnt related to the library but i think thats okay?
why cant i invite bots when i give them more scope than just bots?

bronze flame
#

im trying to give it the applitcations.commands scope (for slash commands) and it wont join the server
if i only give it the bots scope with admin it joins fine

#

this has been the case with every other scope that ive tried

cyan quail
#

so giving it both scopes doesn't let it join?

bronze flame
#

yeah

cyan quail
#

hmmmmm

#

so when inviting, does it not let you select the server, confirm permissions etc?

bronze flame
#

no all of that is allowed, i authorize it and everything, but it just will not join

cyan quail
#

are you sure it isn't being kicked by another bot?

bronze flame
#

i dont have other bots in my server

#

i could try making a dif app

#

nvm

#

it seems to work now i just flicked some random settings lol

cyan quail
#

nice

bronze flame
#

how do i get rid of this?

rare ice
#

You can’t

rare ice
bronze flame
#

dang

#

more like lamecord imo

#

can i at least delete the slash command when its used

fringe socket
fringe socket
#

with ctx.send

#

it makes it slower though

bronze flame
#

okay thankks

rare ice
#

No

bronze flame
#

nvm no thanks (im kidding)

rare ice
#

ctx.send doesn’t actually respond to the interaction

#

then you will get an interaction failed

fringe socket
#

Really though, just use ctx.respond

#

not worth it

bronze flame
#

alright

fringe socket
#

If you want the command to not show, just use ephemeral=True

rare ice
fringe socket
#

But that also hides the response

bronze flame
#

thanks for the help

fringe socket
#

:) welcome

rare ice
#

ephemeral=True hides the response, they are talking about the x used /command part

bronze flame
#

is that not hidden too?

rare ice
#

If you use ephemeral=True yes but only for the user

#

They wanted it removed entirely I think

bronze flame
#

no it suffices for what i need i think

fringe socket
#

However, bear in mind that if you use ephemeral=True then just note that the message will disappear for you too, after a few minutes, if you log out, etc.

bronze flame
#

yes alright thanks

fringe socket
#

:)

#

glad to help

bronze flame
#

sorry if its a lot of questions, im very new to using apis
whats wrong with this?

bronze flame
#

where

#

nvm

cyan quail
#

first line

bronze flame
#

man

cyan quail
#

also ctx.respond in slash commands

bronze flame
#

oh alright

fervent cradle
#

I am encountering a new issue

#

So I have made a modal suggestion thing

#

When I try it once it works fine

#

But when I try to send another suggestion the command doesn't show up in the list

#

and all of the bots command don't show up aswell

#

is this supposed to be a bug?

silver moat
#

yeah a discord bug

somber cloak
#

if something like await channel.edit(...) doesn't work because my bot is rate-limited, does it raise an error or return some unique value? i've been doing the following and was wondering if there's a better way

async def try_to_edit(obj_to_edit, **kwargs):
    try:
        async with async_timeout.timeout(1.5) as _:
            await obj_to_edit.edit(**kwargs)
        return True
    except:
        return False
bronze flame
#

how do i get user id when im given the tag and username?
or is there a way to get user id in a slash command that doesnt look ugly and user unfriendly

somber cloak
#

if you do, for example, \@mstang, you get my id: @somber cloak

bronze flame
#

wait what

somber cloak
#

idk if that helps, it's more for users

bronze flame
#

hold on brb

#

i dont think it would work

#

unless i did some scuffed thing where i make the bot send a message to figure out user id

somber cloak
#

yeah fair

bronze flame
#

well ill keep looking

somber cloak
#

maybe look at fetch_member or similar? you should be able to get the user object from the username i think

bronze flame
#

alright thanks

#

i think its backwards
it takes id as input and returns the name?

#

yeah it does

rare ice
#

fetch_member returns a discord.Member object, not a name.

bronze flame
#

ahhh

#

yeah i have a discord.Member object and want to get a user id

#

do you know if thats possible?

rare ice
#

member.id

winter condorBOT
bronze flame
#

youre so cool

rare ice
#

ok

naive steppe
bronze flame
#

cant believe i got hit with the ok

silver moat
#

you can use that to check the status code (429 if rl)

fervent cradle
#

bro wtf

#

I swear I just restarted the bot 2-3 times

#

and I reached the daily application command creates?

#

I was just working with modals

#

heck

fringe socket
#

Hold on

#

how do you host your bot?

#

@fervent cradle

fervent cradle
#

local host

fringe socket
#

Ok.

fervent cradle
#

didn't use any hosts

#

it's really frustrating but I think god wants me to have a life ig

fringe socket
#

Uh... spend the rest of today fixing any errors you find, and then try again tomorrow.

fervent cradle
#

but holidays are going on I have nothing but to sleep

fringe socket
#

If you are looking for a good host, I would suggest this guy.

#

Do NOT use repl.

fervent cradle
quick temple
#

Is there a way to store custom data in ApplicationContext? Or to pass a custom object from on_application_command -> the command itself -> on_application_command_completion. (Where the custom object is created in on_application_command)

fervent cradle
#

I'm testing the lavalink audio player in the docs
I used the exact same code, I get this error
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: ContentTypeError: 0, message='Attempt to decode JSON with unexpected mimetype: ', url=URL('http://lavalink-replit.repluser69.repl.co:443/loadtracks?identifier=ytsearch:never+gonna+give+you+up')
any idea how I could solve this?

somber remnant
#

Hello i have a problem with the buttons

I want to make two buttons, each will give one value for a variable (1 or 5)

but i don't want to make TWO callback, but ONLY one

#

And if possible, i don't want to make a common fonction, i want all in the button class

spice oyster
spice oyster
#

You can keep it inside that class. I think it's fine.

somber remnant
#

Hmm you think ? i'll try this

spice oyster
#

Yes, I use that method for some of my Views.

somber remnant
#

Can you show me an exemple ? cause it don't work for me

#

Okay, nvm, i found myself

#

Ty for the answer !

dusty linden
#

Is there a forum version of on_thread_create so that you can make a bot join a new forum thread automatically?

cyan quail
#

forum posts are threads

dusty linden
#

Oh I see what I did

#

I used on_thread_join instead of on_thread_create...

#

Thanks a bunch Nelo

waxen whale
#

lol

tame rose
#

Is it possible to load a slash command from a separate file?

rugged lantern
#

no, cogs exist for no reason

tame rose
#

If I understand it correctly, you're adding a slash command in a cog instead?

errant craneBOT
#

Here's the slash cog example.

spice oyster
#

Is there a way to tell Discord that I don't want to respond to a Slash Command or Interaction?
I basically want to get rid of the "This interaction failed" message without sending a message.

Solved by using interaction.response.edit().

tame rose
loud holly
#

I presume that autocomplete function cannot return a discord.Role e.g.

    async def get_option(ctx: ....):
        User_Option = ctx.options

        if User_Options == "role": return discord.Role
    
    @bot.slash_command()
    async def trying(
        ctx: .....4
        choosing: discord.Option(str, choices=["role"]),
        returning: discord.Option(autocompete=get_option)
    ):
        # STUFF

cobalt tangle
#

what error is raised when the embed cannot have more fields? (i am going to put in in a try: and except: area)

tame rose
#

How do you create a command group in a cog?

class Shop(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
    shop = self.bot.create_group('shop')

    @shop.command(description = 'Buy an item from the shop')
    async def item(self, itrc):
        ...
cobalt tangle
#
class Shop(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
    poll = discord.SlashCommandGroup("name", "description")

    @poll.command(description = 'Buy an item from the shop')
    async def item(self, itrc):
tame rose
#

Also is that the recommended way?

cobalt tangle
cobalt tangle
tame rose
#

🤔

#

I got it. Thanks

cobalt tangle
# tame rose I got it. Thanks

Ok, and you tried to use the main group, this is a subgroup capable type and i'm pretty sure this is supposed to be used in cogs

cyan quail
#

though since it supports OptionChoice, you could have name as the role name and value as the role ID to make it easier to get the role object within the command

marble jasper
#

Getting this error when using embeds=embeds and the total characters between 3 embeds is greater than 6000? I thought the 6000 character limit was just for a singular embed?

glossy socket
#

anyone got a clue why this import:

from discord.ui import Item

isnt working on my vps, while it does on my laptop? i installed pycord with pip3 install py-cord

glossy socket
round rivet
silver moat
spice oyster
marble jasper
#

That’s what the list above the traceback was printing

round rivet
#

the character limit is all embeda

marble jasper
round rivet
#

probably

#

it's documented as if it is

spice oyster
marble jasper
#

Bit weird that the character limit for one embed would be the same as that for 3 embeds when sent in the same message. Should I just send the embeds in separate messages then?

spice oyster
#

Actually, the docs for another library (not in Python) say it's per message.

The sum of all characters from all embed structures in a message must not exceed 6000 characters

marble jasper
#

Hmm that’s interesting.

round rivet
#

implying that it applies to the entire field

wary rover
#

Hello!
Do you know how to close modal after sending the data?

#

My code runs fine but the modal stays open and shows me a timeout, not cool!

round rivet
#

respond to the interaction

spice oyster
#

It's not like, say, Buttons in a View, that can use a random name for their callbacks.

wary rover
#

I can't edit my embed from my callback, otherwise I could have tried to do this.
I should not send a message after sending the modal...
I'll think about it, thanks guys 🙂

loud holly
spice oyster
#

Pycord should probably mention that in docs, instead of saying 6000 per embed.

spring drift
#

What lib should I use for mysql

#

Nvm

viral peak
#

is there a way to color a button for only the user that clicks it?

spice oyster
viral peak
#

thought so. thanks

spice oyster
glossy socket
#

is this command also in pycord?

@commands.has_role('RoleName')

pycharm auto complete doesnt give a has_role function, doing this import:

from python.discord import commands
raw gust
#

How can i make a slashcommand without the wrapper? At the moment i am doing the SlashCommand class manually and it works. But in the Docs it says "decorator or functional interface", but i cant find any function for it. Which function replaces the slashcommand wrapper?

white scarab
#

How can I get from a discord.Interaction the VoiceChannel the user is conected to (if conected to one)?

raw gust
#

Give the parameter a default value.

white scarab
fervent cradle
#

Hey, this question might have been asked before I'm not sure but how do I get the guild id of the Guild from which the slash command was sent

#

(Yes I read the docs, there are 2 references to guilds, I'm not sure what to do here)

white scarab
wary rover
#

Do you have any idea how to check in a modal if the value is hexadecimal and if it is not the case that it returns an error?

fair crescent
#

i want to delete the message with a button, but i cant do it ( inside a view)

cyan quail
fair crescent
waxen whale
#

you can't delete ephemeral messages

glossy socket
#

there was some script manager on linux so i can run multiple python files in the background does someone know the name of that?

spice oyster
#

My test bot is able to get user = interaction.message.mentions from a private message between my account and the bot account.
My live bot is not able to do the same from a private message between a random user and the bot account.
To be precise, I get an empty list for the live bot. I don't understand why there is such a difference. Do you have any ideas? Ping me.

Fixed by using user_id = interaction.message.raw_mentions[0] instead. Docs were a bit confusing but they eventually helped.

spice oyster
#

How can I respond to an Interaction (after a Button click) without actually responding?
I just need to mark it as responded to avoid the interaction failed error.

Fixed by adding await interaction.response.edit_message(view = self).

cyan quail
#

yeah

spice oyster
#

What does the pong() command do? I saw it in the docs.

cyan quail
#

responds to ping interactions

#

which you don't really get

#

it's just documented for sake of completion

spice oyster
#

Oh, ok! It's a sort of acknowledgement.

fervent cradle
#

Can I get file as an input from user?

silver moat
fervent cradle
#

kk

fervent cradle
#

lLike inorder to send you have to save the image then use the file path and stuff

#

but I don't want to save the file

silver moat
#

.docslink discord.Attachment

fervent cradle
#

Okay so let me make this clear:
I am making a command in which the user send an attachment to the bot, then the bot somehow saves the attackment to mongoDB (motor) and sends the user a confirmation message..

#

but before saving I want to test that the image can be resent to the user or not

#

don't want to save anything on the computer just either directly save or retrieve from the DB

#

So can someone shed some light on how should I execute these stuff cause I am kinda stupid to understand on my own

fervent cradle
#
await interaction.response.defer()
await interaction.response.send(embeds=[embed])```
I cant repsond to an interaction twice, how do I defer it, if that's the case?
fervent cradle
#

but when I change await.interact.response.send_message(embeds=[embed])
to await.interaction.followup.send(embeds=[embed]) I get this

fervent cradle
#

Actually no

#

That error was due to me typing ctx.respnd instead send modal

coarse spire
#

ah, ok

fervent cradle
#

Now even though I have followup set, I seem to have the same error

coarse spire
#

😕

fervent cradle
#

Truly sad

finite flame
full basin
cobalt tangle
#

can commands.Bot() take in owner_id

cobalt tangle
finite flame
#

then it doesn't

finite flame
cobalt tangle
finite flame
#

it's been some time since I last worked on my bot so I'm not exactly sure anymore

finite flame
cobalt tangle
finite flame
#

what was wrong?

cobalt tangle
#

Apparently, VSC does not save the file before running

#

and it saved when i only typed the o

cobalt tangle
finite flame
#

I think VSC doesn't save at all on its own? not sure tho, always stopped using it quite fast each time I tried it again

cobalt tangle
#

its just that i hate run & debug cuz it delays stuff

finite flame
#

ah ok

#

didn't actually know that feature tbh

cobalt tangle
swift pumice
#

Hello, so recently, I have been doing some development implementing FastAPI to create a web respose system using an API just for the web pokes, then using the bot to send the message, and I know that in order to run the ASGI manager I use, I have to run it differently using another async function to "serve" the server. Now I was wondering if that was possible through pycord too. Like is there a way that I can make a bot start from an already running async loop?

fervent cradle
#

Wait so

#

Bruh

fervent cradle
#

Isn't modal for forms and stuff, that usually takes time doesn't it,that's where defer would come in use

full basin
#

What

#

I think you're confused on what deffering does

#

When you defer, you're telling Discord you need more time to respond. So, my logic says you should defer on the modal callback.

fervent cradle
#

I have a dropdown menu for my help command and i will get this error relating to it once and awhile in my console. It doesn't impact the bot or command in any way but i would like to stop it from happening if i can. Any ideas?

Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/ui/view.py", line 412, in _scheduled_task
    await item.callback(interaction)
  File "/home/container/Bot.py", line 268, in my_callback
    await interaction.response.edit_message(embed=embed)
  File "/home/container/.local/lib/python3.10/site-packages/discord/interactions.py", line 928, in edit_message
    await self._locked_response(
  File "/home/container/.local/lib/python3.10/site-packages/discord/interactions.py", line 1057, in _locked_response
    await coro
  File "/home/container/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 221, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
fervent cradle
#

also the pycord website returns this error

#

nvm fixed

fervent cradle
#

hey kids

#

remember, when the dudes on stackoverflow or discord say, "read the docs", please read the docs, they're a life saver 👍

copper dew
swift pumice
# copper dew hm never tried running my bot under an ASGI server (probably won't any time soon...

Im more looking for a way to get it to log in and start functioning. I know that if I can get it to run during the already active loop, then I should be able to load cogs through the event loop. I would just need to know if there was a way with the pycord api to log in the bot and connect it during the active loop. Ik you said probably not, but maybe that wording helps better define what I mean

#

Is bot.run() an instance of asyncio.run(), if so, then it blocks the async loop, but the async loop has ways to start processes during its time running

still helm
#

in the examplecode of recording audio is the filename the user_id.mp3
I want to add the username, but i don´t understand how to solve this. I don´t understand how the id is generated

    async def finished_callback(self, sink, channel: discord.TextChannel, *args):
        recorded_users = [f"<@{user_id}>" for user_id, audio in sink.audio_data.items()]
        await sink.vc.disconnect()
        files = [
            discord.File(audio.file, f"{user_id}.{sink.encoding}")
            for user_id, audio in sink.audio_data.items()
swift pumice
#

I found it! Its bot.start(token) thank you for the help tho ^^

drifting sleet
#

My paginator is not sent ephemerally along with await ctx.defer(), is it normal behavior?

tame rose
#

ctx.defer() and a paginator?

drifting sleet
#

OK forgot there is ephemeral to defer too

drifting sleet
tame rose
#

What do you do when the slash command doesn't update?

drifting sleet
#

Wait, or just use @slash_command(guild_ids=GUILDS) and GUILDS is a list of Guild ids

tame rose
#

I already had that so ig I'll just wait?

drifting sleet
#

that ephemeral won't work, gonna open a thread

tame rose
#

What's the other method of adding options aside from decorators? Something like:

async def poll(self, itrc, \
choice1: discord.option(autocomplete = getframes, required = True), \
choice2: discord.option(autocomplete = getframes, required = True), \
choice3: discord.option(autocomplete = getframes, required = True)):
drifting sleet
#

These are not decorators, just function arguments

#

although not too pythonic look

cyan quail
tame rose
#

So discord.Option(str, autocomplete = getframes, required = True)?

cyan quail
#

yeah

#

(also required=True is a default so it's not necessary to include)

tame rose
tame rose
drifting sleet
#

if something's default it's already consistent 🙂

tame rose
#

Consistent look I mean

#

Is it possible to have variable default value or is it always constant?

cyan quail
#

set default=...

#

this will also force it to be optional though

tame rose
#

...?

cyan quail
#

being whatever you want

drifting sleet
#

option: discord.Option(str) = "default" also works

tame rose
#

So it also accepts a function?

cyan quail
#

assuming it returns a value, i guess...?

tame rose
#

I see. Thanks

#

Wait, do I have to keep the bot running until the slash command updates?

cyan quail
#

typically you restart to update slash commands

tame rose
#

I did that for 4 times now

cyan quail
#

what pycord version are you on?

tame rose
#

2.2.2

#

It shows Invalid interaction application command when I try to use it

drifting sleet
#

I just had that too, maybe some discord stuff

#

you could try restart your discord

tame rose
#

I did, now it's missing. I guess it's on Discord again

drifting sleet
#

you could start a thread with your code if it happens too often

gleaming falcon
#

General Python question. What's a good way to chain or statements to get something that isn't None (even (especially) if it's 0)?

result = a.get('a') or a.get('b') or a.get('c')

If a is None, b is 0 and c is None, you're still going to get None
I can't cast them to str, because then a would just return literal 'None'

gleaming falcon
#

I guess I can add all the values to a list and use next() to pull the first non-None, if it exists. 🤷‍♂️

resultlist = [a.get('a'), a.get('b'), a.get('c')]
result = next((item for item in resultlist if item is not None), None)
deep merlin
#

Hey!! How do I receive the interactions on the messages sent before the bot restart?

silver moat
spice oyster
gleaming falcon
spice oyster
spice oyster
cyan quail
#

kinda messy but py any([a.get(x) for x in ['a', 'b', 'c']])

#

oh wait

#

i suppose i misunderstood

spice oyster
#

It wasn't clear. They want to differentiate 0 and None.

cyan quail
#

regardless the answer is probably list comprehension

spice oyster
#

Without using next? eddaniSherlock

gleaming falcon
#

Surprised it's that unclear. I am searching a number of dict items and just want to find the first non-None item, including 0 (which is otherwise false-y)

cyan quail
#

if you don't want it to deal with falsey then you want is not None

gleaming falcon
#

As always, just wanted it as terse as possible. >.>

spice oyster
#

Now I forgot what I needed to ask when I came here. rooSob

#

Oh, right! Is there a way to validate values for Embeds?

#

I want to deal with whitespaces that, as far as I know, get removed automatically if there are no other characters.

#

I couldn't find the docs to check how it actually works on Discord side.

gleaming falcon
#

(Unless it's the super-cool zero-length character, which serves as a great hack to get columns)

#

So what is it that you are actually trying to do, determine if a field title/value has only whitespace?

spice oyster
spice oyster
#

Thanks! That's good enough. Actually, it's perfect because it also works with Enter.

#
if notes is not None and not notes.isspace():
    embed.add_field(...)

Can I do better than this? rooThink

spice oyster
gleaming falcon
spice oyster
#

That's probably a better solution. I'll try. eddaniSherlock

dull smelt
#

hi

#

I'll probably get a faster solution here so I might as well ask

spice oyster
#

You already have a thread going...

dull smelt
spice oyster
#

Just link it then. Same result, less space.

dull smelt
#

#1027467757945630770

spice oyster
dull smelt
#

one sec

spice oyster
fervent cradle
#

raised an error: AttributeError: 'Verification' object has no attribute 'Verification_slash' why am i getting this error?

class Verification(commands.Cog):  
    def __init__(self, bot):
        self.bot = bot
        self.bot.application_command(name="startverify", cls=discord.SlashCommand)(self.Verification_slash)
verification = discord.Embed(title="Get Verified!", description="Click the button below to get verified and be able to access the entire server!")
class Verify(discord.ui.View): 
    @discord.ui.button(label="Verify Me", style=discord.ButtonStyle.primary, emoji="🤝") 
    async def button_callback(self, button, interaction):
        @commands.command(name="startverify", description="Start The Verification Progress")
        async def startverify(self, ctx):
            ctx.respond(embed = verification, view=Verify)

def setup(bot):
    bot.add_cog(Verification(bot))```
```py
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]}")```
#

I cant see why, I've googled it, looked around my code, checked docs

#

(i used to code bots but havent in a while, so im rusty)

spice oyster
#

What is this supposed to do there? eddaniSherlock

self.bot.application_command(name="startverify", cls=discord.SlashCommand)(self.Verification_slash)
woeful spindle
#

Why is if message.guild.id == MY_SERVER_ID: raising an AttributeError: 'NoneType' object has no attribute 'id'

spice oyster
woeful spindle
#

I’m thinking it’s because someone tried to DM my bot but I’m not 100% sure..

spice oyster
#

I see. It could be. eddaniSherlock

jaunty plover
#

Hi all. I am newb and trying to write a background task but this task can not send anything to a particular channel. I am afraid that I might miss some Intents settings so I included the screenshots of that part too. I am using py-cord 2.2.0. I have spent a lot of times trying to get this work but nothing seems to work for me. Thank you in advance.

spice oyster
jaunty plover
#

Thank you for responding. I am very sure that I use the correct channel ID. But let me try your suggestion for 2.

fervent cradle
jaunty plover
#

I tried 2 and it still failed

#

I have literally looked at all the search results using google for this issue and I could not fix this

#

I just basically copy the channel ID there and use it directly in the codes

#

My bot could respond to commands in this channel so ....

silver moat
jaunty plover
wary rover
#

Hi!
I don't know if it's me who doesn't understand but I can't seem to add a link button.
Do you have a little tutorial or something to help me?

cyan quail
#

if you're trying to use the decorator it won't work

wary rover
#

Something like this?

cyan quail
#

well the button is fine but you kinda missed the point with view

#

how do you normally define and send a view?

#

or have you not used them before

wary rover
cyan quail
#

ah so you subclass

wary rover
#

The idea is to add this button to a list of buttons

#

But I confess that I don't understand the link

cyan quail
#

well typically you'd do view = discord.ui.View(), then view.add_item(...)

#

if it's a subclassed view, inside __init__ you could also do self.add_item

wary rover
#

Huuuh DERP

cyan quail
#

if you still don't understand, think of it like embeds

#

(i hope you've used them at least)

wary rover
cyan quail
#

ah i see

#

you want it in between the two? hmmm

wary rover
cyan quail
#

ok so

#

...this is probably in the example isn't it

#

oh well

wary rover
#

Yes, I'd like to add it here, for the moment I've looked at the old messages, it talks about class, super.init etc

silver moat
#

you should add it inside of the subclass still...

cyan quail
wary rover
cyan quail
#

damnit i knew there was an example but the NAMING

#

kinda close

errant craneBOT
#

Here's the link example.

cyan quail
#

i'd say refer to this example

wary rover
silver moat
#

what is your current code?

cyan quail
#

well that is indeed what you were looking for

#

hmm i guess the ordering...

silver moat
cyan quail
#

well

silver moat
#

since there is only one button on the other row

wary rover
cyan quail
#

let's say you want the url button after a callback button

#

.

silver moat
cyan quail
#

you didn't need to copy the whole class, the point was to use the __init__ functions inside your existing class

silver moat
#

Google is a view, not an Item.

wary rover
silver moat
wary rover
#

Ok it works, but it's not easy to understand the principle

#

I thought it was going to be before my first button