#Basic Pycord Help (Quick Questions Only)

1 messages · Page 10 of 1

prisma flicker
#

like whichever cog loads first

cyan quail
#

yeah i think that's just the order they appear in the internal command list

#

the default sort if you set sort=True is alphabetical

#

but you can pass in a custom function to sort them

prisma flicker
#

how do I set .description for context menu commands?

cyan quail
#

i don't think they have one? im not sure

#

yeah since you'd never see them

#

but in exchange they have looser name restrictions

#

like capitals and spaces

prisma flicker
#

yeah

#

like I have py desc = command.description if not desc: desc = "No description provided."

#

so they all just get "No description provided."

cyan quail
#

yeah

prisma flicker
#

thanks Nelo, this has all been very helpful 🙂

drowsy python
#

is there a way to get the command input that caused an error in an error handler? speaking in the context of a global handler using ext.commands

#

i see kwargs is a thing but i don't understand how to use it

cyan quail
#

or a slash command

drowsy python
#

prefix

cyan quail
#

just check ctx.message

#

or well ctx.message.content

drowsy python
#

huh

#

well, thanks for the assistance!

cyan quail
#

all good

drowsy python
cyan quail
drowsy python
#

oh?

cyan quail
#

this may be more useful for longer commands or commands with more vague arguments, since you can check specific ones instead of having to guess from message content

drowsy python
#

makes sense

cyan quail
#

e.g. in the example posted above, the body variable is whatever python code i threw into it

drowsy python
#

mhm

#

i'll probably toy around with it a bit

cyan quail
#

so just get ctx.kwargs["body"]

#

havefun

drowsy python
#

thanks again!

cyan quail
#

all good

fallen cove
#

seting up bot on the hosting platform, and trying to get it to load the cogs folder but cant get the relative path FileNotFoundError: [Errno 2] No such file or directory: '/cogs' A3PO.py is the main file. any help on getting a relative directory

for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        cog=filename[:-3]
        bot.load_extension(f'cogs.{filename[:-3]}')
        print(f'Loaded {cog}')
cyan quail
#

just do 'cogs'

fallen cove
#

okie

#

thanks

drowsy python
#

small update on kwargs

#

it seems that just using ctx.args gets more results than kwargs, presumably due to what type of command it is and all but that's good for future reference

#

just used non filtered versions here out of laziness

#

123 was the actual input i used so

cyan quail
#

ah yeah, i suppose it depends on how your command is defined

#

args also includes self (if the command is in a cog, typically the bot object) and ctx (being the context), but you already have access to these elsewhere

drowsy python
#

yeah

#

so i guess that's all for me but this'll be nice for anyone else in the future

#

likely would need to be looked at in the docs for the kwargs vs args bit

fiery tiger
#

on_command_error will work for / commands too?

fiery tiger
#

@silver moat ?

fervent cradle
#
@bot.slash_command(guild_ids=[XXX])
async def invite(ctx, options['id']):
    inviteuser.invite(account, plex, sections, options['id'])
    await ctx.send("Invited user with id {} to Plex server {}".format(options['id'], plex.friendlyName))
    async def invite(ctx, options['id']):
                                 ^
SyntaxError: invalid syntax
#

what am i doing wrong here?

prisma flicker
echo egret
fiery tiger
fervent cradle
#

dont i want this?

prisma flicker
#

You can't index a dict in your parameters

fervent cradle
#

isnt that a list?

prisma flicker
#

That's not valid python

#

Regardless you can't index it in the parameters

fervent cradle
#

so make a list

#

then pass it in?

prisma flicker
#

Sure

echo egret
#

I don't think I understand what you're trying to do...

fervent cradle
#

im trying to ask the user for their id

#

in the slash command

#
optionslist = ['id']

@bot.event
async def on_ready():
    print(f"We have logged in as {bot.user}")

@bot.slash_command(guild_ids=[XXX])
async def invite(ctx, options=optionslist):
#

is this right?

echo egret
#

Well just make a parameter id

fervent cradle
#

how

echo egret
#

Like a normal python function

fervent cradle
#

so add id after ctx?

prisma flicker
#
@bot.slash_command(guild_ids=[XXX])
async def invite(ctx, id: discord.Option(int, "ID of the user to invite")):```
echo egret
#

Yes

fervent cradle
#

oh thanks

#

can i make it required?

prisma flicker
#

it's already required unless you say it's not

fervent cradle
#

what does this mean?

echo egret
#

You can check for exemples on pycord's GitHub :)

fervent cradle
#

am i not qallowed to use id?

prisma flicker
#

it's just a warning

#

you now have two variables named id in the same scope

#

you really need to learn basic python before writing a discord bot

fervent cradle
#

i know

prisma flicker
#

so go do that

fervent cradle
#

im just scrapping this together because i need it asap

#

with github copilot doing half of it

prisma flicker
#

at least read the guide and skim the docs then

fiery tiger
#

@prisma flicker

#

Looking at the docs it doesn't really work the way i want to.

#

What i am trying to do is to check if there's a missing permission error.
Creating a global handler to check this

#

on_application_command_error

prisma flicker
#

what

#

what's not working?

fiery tiger
#

i said what i'm trying to do, checking that certain error if there's a missing permission

#

does it work the same?

#

nvm found out

#

nope nvm

#

what's the right event to check a missing permission for / commands

#

@prisma flicker u here?

prisma flicker
#

on_application_command_error

fiery tiger
#

yes i just seen

#

in the docs usage my bad, i got confused

prisma flicker
#

what's confusing you?

fiery tiger
#

the parameters they had, it works a bit different from a normal command that works with prefix

#

if it was error it would make a bit more sense in my head but i got it now

prisma flicker
#

so you're good now?

fiery tiger
#

yes x)

fiery tiger
cyan quail
#

none, it checks for any application command error

fiery tiger
#

yes but im doing it for missing permission

#

so u tryna say that the command misses permissions? 😂

#

ik its not sorted out of the list, its still in test progress

#

tryna find out how it works exactly

prisma flicker
#

you should get rid of the return and do else: raise error

fiery tiger
cyan quail
#

MissingPermissions is when the user is missing permissions from the commands.has_permissions check

fiery tiger
#

what about the bot?

cyan quail
#

you want BotMissingPermissions

prisma flicker
#

This check raises a special exception, BotMissingPermissions that is inherited from CheckFailure.

fiery tiger
#

Oh awesome, thanks a lot guys

fervent cradle
#

does anyone know how to put a description here?

full basin
#

Use discord.Option

errant craneBOT
#

Here's the slash options example.

prisma flicker
#

@fervent cradle ^

fervent cradle
#

thank you

#

❤️

loud holly
#

There's this bot that I'm interested in, called watchbot, I'm interested in how it doesn't get ratelimited, since it's watching 1000s of bots and checking the bots status every time, how do they do that if anyone knows

silver moat
#

on_member_update also watches for presence changes

peak wing
#
async def ar(ctx, word, emoji):
  if f'{word}' in ctx.message.content.lower():
    await ctx.message.add_reaction(f'{emoji}')
    await ctx.send('a')``` i made this command and it works but how can i make it add the reaction every time someone has 'word' in their message and not just once?
stark walrus
#

what's wrong here:

    if answer_1 == "":
UnboundLocalError: local variable 'answer_1' referenced before assignment```
stark walrus
#

form an if statement, use this count as your core method to compare with

#

basically this

#

Also use *

manic spoke
#

Can I have unicode emojis in the command description somehow?

#

How to pass regex rules

loud holly
fervent cradle
#

Python3.7 supported ofc

manic spoke
fervent cradle
#

async def on_member_remove(member): print(f"{member.id} has left the server")

#

this isnt detecting when people leave

#

intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(intents=intents)

#
GitHub

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

uploaded by the stripper pfp at 1:30:50 UTC-5

fervent cradle
#

thanks

manic spoke
#

can i use unicode emojis in command description

prisma flicker
manic spoke
copper dew
#

Don't remember exactly where

manic spoke
#

@copper dew @errant crane has it

#

though its not verified

#

most of bots has it

copper dew
#

hm interesting

#

Then I don't know anything past that

viral turtle
prisma flicker
copper dew
manic spoke
#

where is it

manic spoke
#

?

vast spire
#

I'm not sure if I can post this here, it's kind of a general discord bot question. I'm trying to add an About Me to my bot and it just won't show up. I followed every tutorial and stackoverflow post I could find, but I did exactly as they said. I put it in the description field on the developer page, and clicked save. Reloading the page shows it's still there, so it's actually saving. I thought it could be server lag, so I waited. It's been 5 hours and nothing.

vital blade
#

and u should ask that in discord developers server not here

vast spire
#

Ok, thanks :)

obtuse vale
#

how do i send stickers?

manic spoke
#

i want /bot and /bot test to be different commands

#

?

sleek schooner
manic spoke
manic spoke
#

i cant see this param here

#

is it not listed

#

also how can i make only 2 options available for 1 argument in my slash

cyan quail
manic spoke
#

😦

cyan quail
#

you can use slash groups, but you can't invoke the original group by itself if it has any commands

manic spoke
#

lets say you have the most important command in a category

#

then initializing the name of category would launch this main commands

manic spoke
#

is it possible to make

cyan quail
#

well you can pass choices into options

#

but you don't need that

#

because you can localize command and option names and descriptions anyway

manic spoke
#

nvm fixed

bleak cloud
#

what's this close thingy?
slash commands can be mentioned?

manic spoke
#

@bleak cloud type /close to close

#

if you want

#

but you dont want

#

since you didnt solve the issue

bleak cloud
#

no, i meant that blue text
it looks same as @mention or #mention

#

i didn't know slash commands can be mentioned

#

how?

smoky forge
#

</like so:1234567890>

bleak cloud
#

</wow thanks:1008344689428144187>

shadow stratus
#

Is slash subcommand counts in the 100 commands limit ? Or only the the main command counts ?

cyan quail
#

pretty sure all subcommands count

manic spoke
#

My application does not respond even after having everywhere

await InteractionResponse.defer()
crimson plover
#

does view.wait() return when a button is pressed

cyan quail
manic spoke
#

oh XD

cyan quail
#

in a command, you can shorten this to ctx.defer()

crimson plover
#

is view.stop() called internally

manic spoke
#

ohhhh thank you!

cyan quail
#

not automatically no

crimson plover
#

hmm

cyan quail
#

would be rather cumbersome if views stopped whenever a button is pressed without user choice

#

you can just call it yourself in the callback

crimson plover
#

how do u check if a view has timed out

#

like get a bool

shadow stratus
crimson plover
#

so when it times out stop is called

cyan quail
#

sort of

crimson plover
#

ok

cyan quail
#

i've see that floating around but it doesn't seem to have any basis

shadow stratus
#

there is one way to know

cyan quail
#

oh god

shadow stratus
#

Copy paste the same command and changing the name

cyan quail
#

but anyway the docs only say

An app can have the following number of commands:

  • 100 global CHAT_INPUT commands
  • 5 global USER commands
  • 5 global MESSAGE commands
    CHAT_INPUT includes all levels of slash commands
#

hmmmm

shadow stratus
#

this 100 limit is very low

#

There is only the main command in the integration tab in server settings

cyan quail
#

yeah but 62.5k is a very stupid number that doesn't actually make any sense

#

when you consider you can have a maximum of 50 integrations per server

#

your app would just crash

#

people just said 100*25*25 without actually verifying anything

shadow stratus
cyan quail
#

(maybe i will eat my words)

shadow stratus
#

Only one way to find out

cyan quail
shadow stratus
#

i will create a new app with a few commands and 100 sub commands

#

and i will see if it's working

manic spoke
#

still application doesnt respond

#

nothing in terminal

cyan quail
#

what's your actual code

manic spoke
#

?

#

i have a lot of files :/

#

and a lot of imports

#

from other files

cyan quail
#

the code related to the error

#

im not asking for your entire bot

manic spoke
#

i dont have any erros

#

The application did not respond

cyan quail
#

then whatever command is causing it to not respond

manic spoke
#

in discord chat

manic spoke
crimson plover
#

i deleted my message nvm

#

how do i do something like

#
interaction = ctx.send_response(..., view=view)
await view.wait()
button = view.get_pressed_button() # what function do I use
await what_interaction.edit_original_message(..., view=new_view) # what interaction do I use
#

but inside the slash command not the callback

#

i had to do something like

class CustomView(View):
    def __init__(self, *buttons):
        super(CustomView, self).__init__(*buttons, timeout=60)
        self.event = asyncio.Event()
        self.current = None
        self.interaction = None
        self.bot = None

    async def custom_wait(self, bot):
        self.bot = bot
        await self.event.wait()
        if self.is_finished():
            self.disable_all_items()
            raise EndCommand
        return self.interaction

class CustomButton(Button):
    async def callback(self, interaction):
        self.view.interaction = interaction
        self.view.current = self
        self.view.event.set()
#

and it still doesnt work

manic spoke
cyan quail
#

...............................

#

just await ctx.defer()

#

but you don't even need it

manic spoke
crimson plover
#

does interaction.edit_original_message need interaction.response.defer() to be called

cyan quail
#

no

crimson plover
#

so why does it not work without it

#

if i remove the defer it breaks

#

also does on_timeout trigger even if the view is replaced

cyan quail
#

well for one edit_original_message isn't actually a response

#

you should use interaction.response.edit_message

shadow stratus
#

@cyan quail i'm done with the test, i created 100 sub commands and i still can add regular commands

cyan quail
#

fair enough then

shadow stratus
#

That only count as 4 commands

#

because of the limit of 25 for each

#

And i even tried to add 25 more commands and all the commands works fine

#

?tag localization

robust sluiceBOT
#
>+++++++++++++++[<+++++++>-]<.>>++++++[<+++++++++++++++++>-]<.>
dry echo
#

which datatype should i use for storing a guild_id in mysql?

cinder pilot
#

I was using slash command groups and when I made it into a cog the cog is not loading

#

Nvm

#

It's client.load_extension() yea?

#

In the main file

#

idk whats wrong

simple canopy
#

🤔

grizzled sentinel
dry echo
grizzled sentinel
#

Just a second. I am looking something up to make sure my facts are straight.

grizzled sentinel
# dry echo and why?

nevermind, I was thinking of something different. It looks like big int is the best

dry echo
#

okay thank you guys!

cinder pilot
#

I followed this but cog isn't loading

grizzled sentinel
#

discord ids vary in length so you shouldn't limit the size.

grizzled sentinel
cinder pilot
grizzled sentinel
#

can you open your own thread and post your code

cinder pilot
#

Hm ok

cinder pilot
robust raptor
#

I am trying to create a view with some buttons
What the buttons do depend on external parameters
Is there a way to pass them into the view?

#

For example I enter a command
/command param1 param2

#

I want the buttons to reply the contents of param1 and param2 when clicked

rare ice
#

You can subclass discord.ui.View with buttons and pass the parameters you want into the view class itself.

robust raptor
#
class view1(discord.ui.View):
  @discord.ui.button(label='button')
  async def button_callback(self, button, interaction):
  await interaction.response.send_message(response)

How should I pass in the parameters to this?

smoky forge
#

you make the init with the args you need and add them as attributes

#

and when you construct the view you pass it like view1(arg)

robust raptor
#

right?

smoky forge
#

yep

#

also make sure you call super().__init__() for stuff like the timeout

fervent cradle
#

Is there a way to force update slash commands using default_permissions?

robust raptor
# smoky forge yep

When I do this it is telling me that the view object has no attribute "children" when I try to add that view to a message and send it

fervent cradle
#

Because it shows that for me too but I just ignore it since it works anyways

robust raptor
#

for declaring the class

class view1(discord.ui.view):
  def __init__(self,param1,param2,param3)
  self.param1 = param1
  self.param2 = param2
  self.param3 = param3

@discord.ui.button(......[buttons below]

for sending the message

await message.reply('some string',view=view1)
robust raptor
smoky forge
#
await message.reply('some string',view=view1(param1, param2, param3)) 
robust raptor
#

oh wait the section sending the message is actually

await message.reply('some string',view=view1(param1,param2,param3))
robust raptor
smoky forge
#

you still have to super ().__init__()

robust raptor
#

add that in, now works, thanks

#

can I have different styling for the buttons depending on the parameters?

#

or different enabled status depending on the input

peak wing
stark walrus
peak wing
#

im not using multi words for my ar command

fervent cradle
#

Whats the difference between default_permissions and default_member_permissions

naive remnant
#

How do I find a user by it's id?

fervent cradle
dry echo
#

is there any difference?

rugged lantern
#

pausing is not the same as stopping?

#

that's the difference

bronze vector
#

and stop stops? idk how to explain more

hearty mauve
#
import discord, json, os, random, asyncio, time, hostingserver
from discord.ext import commands,tasks
from datetime import datetime
from hostingserver import keep_alive

# imports things needed for bot (modules needed)

# bot token to activate bot

member = discord.Member

#client = discord.Client()

Game = discord.Game

Streaming = discord.Streaming

idle = discord.Status.idle

dnd = discord.Status.dnd

randomc = random.choice

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

client = commands.Bot(command_prefix=['m?', 'M?'], intents=intents, help_command=None, case_insensitive=True)

@client.event
async def on_ready():
  await client.change_presence(status=idle, activity=discord.Game(f"Not up for service yet! | {round (client.latency * 1000)} ms | In {len(client.guilds)} Servers"))
  print(f"logged into {client.user.name}")


@client.command()
async def help(ctx):
  embed=discord.Embed(title="Hey There!\nMuzocco! doesnt have any commands yet! Come back soon!", color=discord.Color.green())
  await ctx.reply(embed=embed)
``` why won't this work? (I just started using pycord)
#

No errors btw

dry echo
#

is there a way to force end the play() function so it automaticaly runs the after= function?

prisma flicker
#

man why are the bots dying

hearty mauve
young bone
hearty mauve
#

No

#

I just installed it

young bone
#

you know pip?

hearty mauve
#

Yes

young bone
#

you can see the version with pip

fiery tiger
#

So Missing access is basically a missing permission error

#

Just asking because the handler doesn't really seem to work.

#

and i am using this in order to set the perm for the / commands, i seen it in pycord application commands example

cyan quail
fiery tiger
#

awesome, thanks a lot

fiery tiger
#

if isinstance(error, commands.errors.BotMissingPermissions):

#

am i doing smth wrong? handler is not working

#

error message not being sent

cyan quail
#

commands.BotMissingPermissions

fiery tiger
#

i tried that too

cyan quail
#

but uhh

fiery tiger
#

doesn't work either.

cyan quail
#

what's the full error

fiery tiger
#

i just seen in the output commands.errors so i just used that

fiery tiger
cyan quail
fiery tiger
#

i think it says dangerous file but it's because of the .py

cyan quail
#

look at your first else

fiery tiger
#

i am

cyan quail
#

ok so

#

go through the logic

fiery tiger
#

so the logic here is if the len of the list is > 1 then text should be permissions

#

else it will be permission

cyan quail
#

not that one

fiery tiger
#

u said first else

#

oh

cyan quail
#

this is your code essentially ```py
if isinstance(error, commands.MissingPermissions):
...
else:
raise error

    if isinstance(error, commands.errors.BotMissingPermissions):
        ...
    else:
        raise error```
fiery tiger
#

it's happening because im raising the error

#

and then im checking the other thing

cyan quail
#

yeah, since you raised the error it stops there

#

so it never checks the second if

fiery tiger
#

Oh damn trust me i didn't notice

cyan quail
#

you want something more like py if isinstance(error, commands.MissingPermissions): ... elif isinstance(error, commands.errors.BotMissingPermissions): ... else: raise error

#

or just don't use else at all and assume you're always going to return beforehand

cyan quail
#

and do note since you made this an additional listener, your original error handler might still run separately

fiery tiger
#

I know, u mean sending the messages twice if there's already an error handler in the command?

#

Well yes i know about this, that's why im taking care of the error handler at the end

#

i have just top_role checks and if guild_owner

fiery tiger
#

BotMissingPermissions returns a list.

#

how does it have no len?

#

even if it's 1

cyan quail
#

you should be checking error

#

or specifically error.missing_permissions

fiery tiger
#

👍

#

@cyan quail It's working, thanks a lot

cyan quail
#

allgood

orchid hull
#

How can I get a user object from a username (i.e., user#0000)?

fiery tiger
#

discriminator?

#

user.discriminator

signal stratus
#

How can I stop the error from displaying in the Console?

prisma flicker
signal stratus
#

Whenever I stop the bot this error comes up, can I make it not show up anymore?

prisma flicker
signal stratus
prisma flicker
hearty mauve
young bone
hearty mauve
#

I dont know how to check the version with pip

#

I haven't used python in a while

young bone
#

You can do it with pip show py-cord

hearty mauve
#

Ok

#

@young bone version 2.0.0

robust raptor
#

Is it possible to have the button's appearance depend on external parameters without having to reconstruct the view every time the view is sent?
For example I run a command /command param1 param2 param3
The reply will contain a button which says param1 on it, with param2 as emoji and is disabled when param3 is true

hearty mauve
#
import discord, json, os, random, asyncio, time, hostingserver
from discord.ext import commands,tasks
from datetime import datetime
from hostingserver import keep_alive

# imports things needed for bot (modules needed)

# bot token to activate bot

member = discord.Member

#client = discord.Client()

Game = discord.Game

Streaming = discord.Streaming

idle = discord.Status.idle

dnd = discord.Status.dnd

randomc = random.choice

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

client = commands.Bot(command_prefix=['m?', 'M?'], intents=intents, help_command=None, case_insensitive=True)

@client.event
async def on_ready():
  await client.change_presence(status=idle, activity=discord.Game(f"Not up for service yet! | {round (client.latency * 1000)} ms | In {len(client.guilds)} Servers"))
  print(f"logged into {client.user.name}")


@client.command()
async def help(ctx):
  embed=discord.Embed(title="Hey There!\nMuzocco! doesnt have any commands yet! Come back soon!", color=discord.Color.green())
  await ctx.reply(embed=embed)
``` why won't this work? (I just started using pycord)
#

Version 2.0.0

prisma flicker
hearty mauve
orchid hull
#

How can I reset any activity (such as listening, watching, streaming, ...) on my bot

#

As in completely remove it

#

Nvm I got it

hearty mauve
#

From each

#

You'd use multiple task.loop for those

robust raptor
#

Will I be able to use buttons with discord.Client or do I have to use discord.Bot

hearty mauve
prisma flicker
fierce elm
#

Is there a hard limit on the amount of bots that connect from the same IP?

hearty mauve
prisma flicker
void fable
#

how would i pass context to my button view?

#

right now i just have it inside of my command function

#

but i wanna make a persistent view with it

full basin
void fable
full basin
#
view = MyView()
await ctx.respond(view=view)
view.user = ctx.author
#

Then you access to it with self.user in your view class

sonic lotus
#

I still didn't get the difference between e.g. fetch_member() and get_member()
If fetch_ takes an API call and sometimes even returns less data (fetch_guild()), in which cases should I use fetch_ instead of get_?

rugged lantern
#

you should always try using get as to save an API call and only use fetch when get is not valid

fervent cradle
#

trying to add a reaction to a message but still get this error

hooktest = Webhook(url)


    embed = discord.Embed(description="Test")
    mess = hooktest.send(embed=embed)
    await mess.add_reaction(':thumbsup:')
    await mess.add_reaction(':thumbsdown:')
await mess.add_reaction('👍')
AttributeError: 'NoneType' object has no attribute 'add_reaction'

But i am using

from dhooks import Webhook

What´s the actual way to send a webhook?

fervent cradle
verbal dawn
#

How do you pass a variable to button's label

eternal notch
#

What happened to discord.ext.tasks? It's telling me that it doesn't exist

ImportError: cannot import name 'tasks' from 'discord.ext' (unknown location)

#

nvm reinstalling fixed it

young bone
verbal dawn
#

like /example text
and the button pops up with the text

young bone
dry echo
#

should i use lavalink or ffmpeg?

verbal dawn
#

Anyways I'll use inside of command then

solid agate
#

is there a @command.guild_only() for slash commands?

young bone
solid agate
#

👍

young bone
grizzled sentinel
young bone
verbal dawn
#

Probably it's my skill issue

verbal dawn
#

thanks!

faint zodiac
#

is there a way to get an ApplicationContext from a Button callback? i know it gives an Interaction

#

can you go Interaction to ApplicationContext?

crimson plover
cyan quail
#

that is a response

#

so no defer required unless you're taking longer than 3 seconds

cyan quail
crimson plover
#

do i have to manually check if it has been 3 seconds to call response.defer()

verbal dawn
#
  async def button_callback(self, interaction):
    for child in self.children:
      child.disabled = True
      child.style = discord.ButtonStyle.secondary
    button.style = discord.ButtonStyle.success
    await interaction.response.edit_message(view=self)
faint zodiac
#

I have an interaction from a button callback, but need an applicationcontext so I can ctx.edit()

cyan quail
#

oh

#

you don't need to though

crimson plover
cyan quail
#

^

crimson plover
#

or interaction.response.edit_message

cyan quail
#

the latter if it's a response

#

the former if it's an edit after responding

crimson plover
#

wdym by it

#

if the edit is a response to a button press?

cyan quail
#

yes

faint zodiac
crimson plover
#

alr

cyan quail
#

then use interaction.edit_original_message

olive acorn
#

Hello there Guys

I need some help

So there is a new thing in discord developer portal under URL generator , redirect ui or something which I am not able to select or do anything with it
And because of that I am not able to get invite link for my bot
Does anyone know the fix?

faint zodiac
cyan quail
#

that's fine

#

just give it a try

faint zodiac
#

So the user clicks a button,

App responds with 0%

App updates message to 10%

#

And I need files too. iirc edit original message didn’t work

crimson plover
#

is there a way to subclass View and call something when any button is clicked or select is selected

cyan quail
#

well if that doesn't work, do something like py x = await interaction.response.send_message(...) await x.edit_original_message(...) because response.send_message returns a new interaction

crimson plover
#

is there a neater way to separate the check from the processing tho

cyan quail
#

wdym

#

if you really want, interaction_check can technically act as a callback for all components in the view

#

not that i recommend it

crimson plover
#

i just want to store the interaction and component as an attribute of the view

cyan quail
#

the standard procedure for something like this would be instead to assign the same callback to each component

#

components are already in view.children

crimson plover
#

which one is the one that is interacted tho

cyan quail
#

oh

#

i mean you'd have to use either callback or interaction_check then, both take only the interaction

#

you should be using custom_id to identify what was pressed

crimson plover
#

with interaction_check the actual component cant be accessed

olive acorn
#

Hello there Guys

I need some help

So there is a new thing in discord developer portal under URL generator , redirect ui or something which I am not able to select or do anything with it
And because of that I am not able to get invite link for my bot
Does anyone know the fix?

#

This is all that it shows

olive acorn
#

Yea

cyan quail
#

leave everything else blank

olive acorn
#

Yes
I do that only and it doesn't give anything in that Redirect thing

cyan quail
#

just ignore it

#

the actual url is below that

#

at the very bottom

olive acorn
#

It says this

cyan quail
#

the heck

olive acorn
#

Ikr

cyan quail
#

idk what you've done because that definitely doesn't show up here

crimson plover
#

nor for me 🤣

cyan quail
#

well the url generator doesn't matter

#

it's a generic template

olive acorn
#

I haven't done anything
It's my first time lookin at this

olive acorn
cyan quail
#

if you want specific permissions, use the permissions generator and pass the number into the permissions= section of the url

olive acorn
#

Doing that shows this

cyan quail
#

you need to put your bot's user ID in there

olive acorn
#

I did

olive acorn
cyan quail
#

oh i see

#

you turned on the oauth2 option

olive acorn
#

Oh ...

#

Yes
That is true

cyan quail
#

disable this

olive acorn
#

Thank you so much!

cyan quail
#

allgood

smoky forge
crimson plover
#

does a view timeout stop view.wait()

teal mica
#

Why when i press button, my bot regardless of adding reactions on message printing "Timeout!" ?
how i can do a wait_for on reaction add ?

@bot.listen()
async def on_interaction(interaction):
  if interaction.custom_id == 'balance':
    msg = await interaction.user.send("Hola!")
    await msg.add_reaction('🥳')
    try:
      await bot.wait_for("reaction_add", timeout=10.0, check=lambda user: user == interaction.user)
      print('Hola!')
      await msg.delete()
    except asyncio.TimeoutError:
      print('Timeout!')
      await msg.delete()
crimson plover
#

what permissions does a bot need to check when messages are deleted

cyan quail
cyan quail
cyan quail
#

luckily lambda works with multiple arguments; just separate them with a comma like a regular function

verbal dawn
#

Is there any way to implement self inside of button callback (command)

cyan quail
#

why

verbal dawn
#

Trying to disable all buttons once one of the buttons was clicked

cyan quail
rocky stump
verbal dawn
#
@bot.command()
async def button(ctx):
  view = View()
  
  search1 = Button(emoji=":grinning:", label="Button 1", style=discord.ButtonStyle.primary)
  async def search1_callback(interaction):
    search1.style = discord.ButtonStyle.success
    await interaction.response.edit_message(view=view)
    
  search1.callback = search1_callback

  view.add_item(search1)
  await ctx.send("Hi",view=view)
cyan quail
#

you don't need self; just refer to view

#

you're already doing it

smoky forge
#

in object oriented programming, self refers to the object itself

verbal dawn
#

Thanks

smoky forge
#

so if it's not in a class, you can refer to the object by its variable name

jovial shoal
#

any way to respond with an ephemeral message when certain words are used in chat?

cyan quail
#

nope

#

ephemeral messages can only be triggered from an interaction

jovial shoal
#

figured as much

#

darn

verbal dawn
#

Probably 7th time asking, how do you get button from the interaction

cyan quail
#

well you typically don't

#

you should be using custom_id to identify what was pressed

verbal dawn
#

I mean get the button u clicked on and then give new style

  search1 = Button(emoji="😀", label=search[0], style=discord.ButtonStyle.primary)
  search2 = Button(emoji="😀", label=search[1], style=discord.ButtonStyle.primary)
  search3 = Button(emoji="😀", label=search[2], style=discord.ButtonStyle.primary)
  
  async def search_callback(interaction):
    if interaction.user == ctx.author:
      for child in view.children:
        child.disabled = True
        search1.style = discord.ButtonStyle.secondary
      #.style = discord.ButtonStyle.success
      await interaction.response.edit_message(view=view)
    else:
      await interaction.response.send_message("That's not for you", ephemeral=True)
      return False
    
  search1.callback = search_callback
  search2.callback = search_callback
  search3.callback = search_callback

  view.add_item(search1)
  view.add_item(search2)
  view.add_item(search3)
cyan quail
#

you still have to use custom_id

verbal dawn
#

i did add them

#
search1 = Button(emoji="😀", custom_id="Search1", label=search[0], style=discord.ButtonStyle.primary)
cyan quail
#

then iterate through view.children and compare item.custom_id to interaction.custom_id

verbal dawn
#

alright

#

Thanks alot

cyan quail
#

all good

cyan quail
teal mica
# cyan quail it's because your check is slightly incorrect; the check for `reaction_add` requ...

nothing has changed
try my code and u will be understand what not working...

@bot.listen()
async def on_interaction(interaction):
  if interaction.custom_id == 'balance':
    msg = await interaction.user.send("Hola!")
    await msg.add_reaction('🥳')
    try:
      await bot.wait_for("reaction_add", timeout=10.0, check=lambda reaction, user: user == interaction.user)
      print('After reaction_add.')
      await msg.delete()
    except asyncio.TimeoutError:
      print('Timeout!')
      await msg.delete()
meager mica
#

how do i get a list of all slash commands

#

and there description

errant craneBOT
#

Item not found.

simple canopy
#

bruh

#

@meager mica there is .commands property inside your bot object

#

but its not documented somehow, or im blind

meager mica
#

oh

#

ok it returns list right

simple canopy
#

yes

prisma flicker
#

There's also .walk_application_commands()

meager mica
#
    commands =  main_bot.commands
    for command in commands:
        print(command)
    main_bot.run(main_config.BOT_TOKEN)
#

that only does the not slash commands

#

the built in help command

simple canopy
meager mica
#

ty

ashen pulsar
#

How can i edit a button after its pressed?

prisma flicker
ashen pulsar
prisma flicker
ashen pulsar
smoky forge
#

you make the callback edit the button

ashen pulsar
#

?

#

can you explain futher?

smoky forge
#

first you construct the button

#

then you make the callback func

#

and do the edits you want there

#

and then outside of the func you declare the callback

#
button = discord.ui.Button(...)
async def callback(interaction):
    ...
button.callback = callback

opal birch
#

how can I disable a button after a certain code had finished executing

fervent cradle
#

how do i make the response to a slash command only viewable to the person who executed it?

simple canopy
#

make it ephemeral

#

you have ephemeral kwarg in .respond()

#

so it will be .respond(ephemeral=True)

fervent cradle
#

thank you so much

simple canopy
#

you're welcome

crimson plover
cyan quail
#

you still need to see the messages so yeah

#

if you don't have view_channel you can't access the channel at all

#

and im pretty sure read_message_history also affects uncached messages

fervent cradle
#

so i left my bot in a vps and it worked until today only two commands work without me doing anything

#

is this only me

rigid sable
#

so I was merging by commands to slash with pycord and these commands have multiple wait_for() functions and they are asked in a series of steps, these functions work properly when they are a normal cmd. However, when merged to slash, only the first wait_for() works and the second one doesnt and just times out. Is there a reason why this is happening?

meager mica
silver moat
meager mica
#

oh tysm

fiery tiger
#

@cyan quail could i dm u? i wanna show you something, it's not about helping x)

#

is something new that i don't wanna post on this server because there may be someone that steals the idea haha

cyan quail
cloud python
#

what would be proper linux file permissions for a bot's .env? I want to run it from a virtual environment but also don't want anyone else able to read the token

#

atm it is -rw-r--r-- as a default

rare ice
#

Is this a @commands.command?

silver moat
#

slash commands? make another slash command.

#

text commands, add it in the decorator aliases=["alias"]

signal stratus
#

How can I disable certain slash commands completely in private chat?

prisma flicker
lapis quarry
#

I'm running into a strange issue where I have an option boolean for a slash command but the "True" and "False" options are not appearing and it takes in input as a string. Any suggestions?

clever lark
#

ive seen lots of bots now that have things in the 'Apps' section. What exactly is this called? Does pycord have support for it? If so, how is it referenced in the docs?

silver moat
#

There are two types of Context Menus, message and user.

#

they are MessageCommand and UserCommand respectively

clever lark
#

tysm!!

tiny wagon
#

installing py-cord[speed] automatically speedups the code or i need to edit something?

silver moat
#

you need to enable them

tiny wagon
#

how to enable?

silver moat
#

each one has to be enabled individually

tiny wagon
#

like what i need to do with code?

#

any command?

#

or just add py-cord[speed] in req.txt?

silver moat
#

there's more than that

#

lol

tiny wagon
#

um

#

didnt get any detailed docs for it

silver moat
#

you need to look up documentation for orjson aiodns Brotil cchardet individually afaik

prisma flicker
manic spoke
#

it returns str

#

but i need bot

manic spoke
#

heey

tiny wagon
manic spoke
#

idk

#

lets try it out

#

no

#

it is str

#

pls help

#

i need to check if bots role is higher

restive willow
#

Guys, please help. I'm trying to catch a message from a user. But I always get an empty message. (the event itself works, but I always catch void)```py
import discord
from discord.ext import commands

intentss = discord.Intents.default()
intentss.messages = True
botik = commands.Bot(intents=intentss)

@botik.event
async def on_message(message):
print("ok?..")
if message.author != botik.user:
print("ok?..")
if message.content.startswith('!test'):
print("ok?..")
print(message.content)```

manic spoke
#

and ugly (no offence)

restive willow
manic spoke
#
import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.messages = True
botik = commands.Bot(intents=intents)

@botik.event
async def on_message(message):
    print('1')
    if message.author != botik.user and message.content.startswith('!test'):
        print('ok?..', message.content)

Check intents = ||проверь интенты||

prisma flicker
#

And if you're writing a brand new bot you should just use slash commands

restive willow
#

Everything is no longer necessary. I realized my mistake

void fable
#

can my select menu have dynamically changing options?

prisma flicker
prisma flicker
void fable
#

idk if i worded it properly but lets say i have a command /aaa {difficulty}, depending on the difficulty it gives different list of options which have varying lengths

#

where my list of options would be coming from something like number = ['one', 'two', 'three', 'four']

prisma flicker
#

Yes you just send different options with each difficulty

#

Consider using a dict in that case if it makes sense

void fable
#

idk if it makes sense but i was going to try something like this

for n in number:
    b.append(discord.SelectOption(label = n, description = 'a'))
opal birch
plain marlin
#

please help, I registered slash commands as in my other cogs, but it only shows 6 slash cmommands and not all 8. Ping me than pls 🙂

manic spoke
#

with_size vs with_format vs with_static_format

cold rover
#

where's actual docs?

errant craneBOT
#
Represents a UI view.

This object must be inherited to create a UI within Discord.

.. versionadded:: 2.0

Parameters
-----------
*items: :class:`Item`
    The initial items attached to this view.
timeout: Optional[:class:`float`]
    Timeout in seconds from last interaction with the UI before no longer accepting input.
    If ``None`` then there is no timeout.

Attributes
------------
timeout: Optional[:class:`float`]
    Timeout from last interaction with the UI before no longer accepting input.
    If ``None`` then there is no timeout.
children: List[:class:`Item`]
    The list of children attached to this view.
disable_on_timeout: :class:`bool`
    Whether to disable the view when the timeout is reached. Defaults to ``False``.
message: Optional[:class:`Message`]
    The message that this view is attached to. 
    If ``None`` then the view has not been sent with a message.```
cold rover
#

disable_on_timeout - this is not

round rivet
cold rover
#

but it's not

round rivet
#

yes it is?

cold rover
#

this is not

round rivet
#

what do you mean that is not

cold rover
#

it just doesn't exist

errant craneBOT
#

discord/ui/view.py line 170

def __init__(self, *items: Item, timeout: Optional[float] = 180.0, disable_on_timeout: bool = False):```
round rivet
#

although I have noticed it's in attributes and not parameters

cold rover
#

but why i don't have so

round rivet
#

probably added after 2.0

cold rover
#

and don't upgrade in pypi?

round rivet
#

it's just not on pypi yet

#

docs reflect what's on GitHub

signal stratus
round rivet
#

should work maybe

verbal dawn
#

why does py-cord uninstall itself

crimson plover
#

why is view.message None when view.on_timeout is called

#

surely it should belong to a message

woeful spindle
#

How do I add a timestamp to my embed like this?

true stump
#

Is there a way to ensure that only the user issuing a slash command can interact with any UI the bot responds with? Besides using ephemeral messages.

Found:python async def interaction_check(self, interaction: Interaction) -> bool: return interaction.user == self.__context.author
but it requires to store the context or at least the author in the View subclass thixel
And I also don't know how to proceed from there...

cinder pilot
woeful spindle
cinder pilot
#

Then yes it will work

obsidian cargo
#

Is there a limit for choice options in an slash command?

woeful spindle
#

bcz that timestamp is wrong

#

it shows 18:12 but my time was 14:12

cinder pilot
#

Change region ig

woeful spindle
#

what region

cinder pilot
woeful spindle
cinder pilot
#

Oh ok

#

What's your time rn

#

I mean like UTC+2 etc

woeful spindle
#

UTC+1

#

wait, how do I get the unix time stamp of when a message was deleted?

cinder pilot
#
tzone = timezone(timedelta(hours=1))
timestamp = datetime.now(tzone)
#

Try this

crimson plover
#

why is view.message None when view.on_timeout is called

cinder pilot
cinder pilot
true stump
# woeful spindle does `datetime.utcnow()` not return the current timestamp?

The timestamp() method returns a POSIX timestamp / seconds since the epoch (1970-01-01) which always refers to UTC.

The Problem: if you call the timestamp() method on a naïve datetime object, Python will assume that the datetime object holds local time.

Although the utcnow() in datetime.datetime.utcnow() might suggest otherwise, it gives you a naïve datetime object. That is, it does not "know" it's in UTC. Therefore, if you call the timestamp() method, Python assumes that the datetime object passed to the function is local time and calculates the timestamp as such. It is then not what you would get from time.time().
(from https://stackoverflow.com/a/62006588)

In order to get a timezone aware utc datetime object, use something like this:py from datetime import datetime, timezone def get_utc_now() -> datetime: return datetime.now(timezone.utc)

crimson plover
#

why is view.message None when view.on_timeout is called

young bone
#

What is the max length for letters in a modal?

loud holly
#

the change presense, can it only be used during client events?

proud pagoda
loud holly
proud pagoda
#

You're welcome

frank yew
#

How can I know the id of a voice channel of a user connected to that channel?

proud pagoda
frank yew
#

sure,ty

proud pagoda
#

yw

frank yew
#

or memeber.voice

rocky stump
#

Hi everyone. What am I doing wrong here? I'm attempting to edit my message after I've used defer(), but I get Unknown Message or discord.errors.InteractionResponded: This interaction has already been responded to before:

            await interaction.response.defer()
            await interaction.message.edit(embed=Embed(title="Test",description="bb", color=Color.green()))
            #await interaction.response.edit_message(embed=await create_embed())

Neither one of these methods (message.edit or response.edit_message) work. if I remove defer, it works, but in my context I need defer()

proud pagoda
proud pagoda
#

Has the message already been sent?

rocky stump
proud pagoda
proud pagoda
#

try to use interaction.edit_original_message

rocky stump
frank yew
#

Why am I getting an error with this type of datetime?

today = datetime.today()
    time = today + timedelta(seconds = 2)
    @tasks.loop(time=time, count=1)
    async def blbla:
      ...
proud pagoda
#

You've just deferred it

frank yew
# proud pagoda What's the error?

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: Expected datetime.time or a sequence of datetime.time for time, received <class 'datetime.datetime'> instead.

rocky stump
proud pagoda
proud pagoda
proud pagoda
proud pagoda
#

You're welcome

rocky stump
# proud pagoda You're welcome

Cool that works. I really thought edit_original_message would edit the message I invoked the command on rather than the response

proud pagoda
#

Ok, great!

rocky stump
#

👍 Support from this channel is great I've been stumped many times

#

and always get an answer

obsidian cargo
#

Is there a limit for choice options in an slash command?

silver moat
#

wdym by choice options

obsidian cargo
#

in an slash command you can define which can be the choices the user can make for an specific parameter, my question is if is there any length limit for OptionChoice lists

obsidian cargo
#

thx

prisma flicker
serene spindle
#

how do you check when a button is pressed? I tried interaction_check, but it's not working(I'm probably using it wrong)

round rivet
true stump
#

Can't you have a slash command group and prefixed command group of the same name? I'm getting this error:Exception has occurred: AttributeError (note: full exception trace is shown but execution is paused at: <module>) 'SlashCommandGroup' object has no attribute 'remove_command' File "/Users/{user}/.pyenv/versions/3.10.6/envs/venv-yadc/lib/python3.10/site-packages/discord/cog.py", line 257, in __new__ parent.remove_command(command.name) # type: ignore

#

Oh I'm defining both in the same Cog, as I'm currently migrating to slash commands.

frank yew
#

How can I do a task in the background at a specific time passed by parameter?

proud pagoda
frank yew
# proud pagoda set the time kwarg to the datetime.time that you want it to happen at (or a list...

I explain what I would like to do:

A command that does one thing, wait X time and do another, but I don't want that in that X time the bot is stopped. I don't know if @task.loopwould be correct, since I don't want it to be executed every X time, but only once in a given time. That determined time would be when the command has been executed + 2 seconds, 1 hour, etc... that is what I want by parameter.

proud pagoda
frank yew
#

Because in the examples that I have seen to create a @task.loop I need the self.

proud pagoda
#

So if you have this code:

@tasks.loop(...)
async def my_task(self):
  ...

You would start it with:

self.my_task.start()
proud pagoda
#

Just don't supply self

#

So you would have something like this:

@tasks.loop(...)
async def my_task():
  ...

You would start it with:

my_task.start()
frank yew
#

Thank you, I will try it now. Another thing, what do commands.Cog do? I have read the documentation but I can't figure it out.

crimson plover
#

how do I get the message a view is attached to from View.on_timeout (so no references to context)

frank yew
# proud pagoda So you would have something like this: ```py @tasks.loop(...) async def my_task(...

I do this

@bot.slash_command(description='Al reformatorio! ⛓. Debe de existir el canal con el nombre: ⛓ Reformatorio ⛓')
@option("member", description="Quien se ha portado mal? 🤔")
async def reformatory(ctx, member: discord.Member):
    # Mirar si tiene el rol de reformatorio o administrador
    if (not ctx.author.guild_permissions.administrator) or (ctx.author.get_role(REFORMATORY_CHANNEL_ID) is None):
        await ctx.respond(f'{ctx.author.mention} No tienes permisos para hacer eso! 🤔')
        return

    name_channel = "⛓ Reformatorio ⛓"
    channel_reformatory = discord.utils.get(ctx.guild.voice_channels, name=name_channel)
    current_channel = ctx.author.voice.channel

    if channel_reformatory == None:
        await ctx.respond(f'No existe el canal {name_channel}', ephemeral=True)
        return

    await member.move_to(channel_reformatory)
    await ctx.respond(f'{member.mention} se ha movido al canal {name_channel} se ha portado mal 😡')


    today = datetime.today()
    # print_debug(today.time().gettimeofday())
    print_debug(today.time().hour)
    print_debug(today.time().minute)
    print_debug(today.time().second)
    print_debug(today.time().microsecond)

    time_cdown = today + timedelta(seconds=10)

    print_debug(time_cdown.time())

    #time = time(today.time().hour, today.time().minute, today.time().second,today.time().microsecond, tzinfo=timezone.utc)
    @tasks.loop(time=time(time_cdown.time().hour, time_cdown.time().minute, time_cdown.time().second, time_cdown.time().microsecond, tzinfo=timezone.utc), count=1)
    async def countdown_reformatory():
        await member.move_to(current_channel)
        print(f"Finished {member.mention}")

    countdown_reformatory.start()

But never prints finished

proud pagoda
#

Is it like an afk timeout thing?

#

Anyway, you have to do countdown_reformatory.start()

#

But I don't believe that it will update the time_cdown every time, just when the decorator is created

frank yew
proud pagoda
#

So you might just have to have a task that runs every few seconds, and have a dict which you store users and when to move them, and then in that task you check if its time to move the user, and if it is, then you do move them

proud pagoda
#

you're welcome

strange wagon
#

so when I use attachments as an option - where are the attachments uploaded?

#

ah figured it out

peak wing
#
async def test(ctx):
  for role in ctx.guild.roles:
    if role == ctx.guild.default_role:
      pass
    else:
      await role.delete()``` ```    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50028): Invalid Role``` how do ifix this error?
proud pagoda
peak wing
proud pagoda
#

Oh wait lol I didn't read your code properly

proud pagoda
peak wing
# proud pagoda Do `print(role.name)` before you try to delete it
async def test(ctx):
  for role in ctx.guild.roles:
    if role == ctx.guild.default_role:
      pass
    else:
      print(role.name)
    ``` ```Xenon
Dyno
Craig
news
ProBot ✨
Ear Tensifier
Ticket Tool
Previewer
Discobot
Lawliet
Luminous Nova
Dank Memer
MarriageBot
GiveawayBot
Emote Manager
OwO
Mudae
jailed
18+
16-17
13-15
female
male
pic
citizen
park random
Lean Sippers | Ban = Stripped
staff
Founder
Head Founder
Below
Above
God
Above God
Real Niggas
Co Owner
Owner
stain & nine
May<3
spawn
katana & xan
Helper
Server Managers
NewGen Owners
Yagami’s
!?
.
Top
kira & near
hi
$$$
hit
trusted
-
fio
Server Owner
hard
Mimu
Snitch
ServerStats
Quarantine
pluto
.gg/deathnote
bleed vanity
Wick Premium
Security Premium
negged
bleed
$
+
eren
legal```
#

it worked

#

printed every role besides @everyone

proud pagoda
peak wing
proud pagoda
#

Hm, try to use fetch_guild and then loop through the resulting guild

peak wing
#

oh wait

#

its one role

#
Ignoring exception in command test:
Traceback (most recent call last):
  File "/home/runner/FMFVOIF-nukebot-FNINOVJD/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 20, in test
    await role.delete()
  File "/home/runner/FMFVOIF-nukebot-FNINOVJD/venv/lib/python3.8/site-packages/discord/role.py", line 373, in delete
    await self._state.http.delete_role(self.guild.id, self.id, reason=reason)
  File "/home/runner/FMFVOIF-nukebot-FNINOVJD/venv/lib/python3.8/site-packages/discord/http.py", line 254, in request
    raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50028): Invalid Role

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

Traceback (most recent call last):
  File "/home/runner/FMFVOIF-nukebot-FNINOVJD/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/FMFVOIF-nukebot-FNINOVJD/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/runner/FMFVOIF-nukebot-FNINOVJD/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50028): Invalid Role```
#

Xenon

#

its not deleting because its a bot role

#

how do i make it ignore bot roles

proud pagoda
#

Yeah that's probably the issue

#

You could just use a try: except

#

So that way you can continue deleting all the other roles except the ones that you aren't allowed to delete

peak wing
#

i used except: pass and it woudn’t delete any roles

#

i need a if statement for bot roles

#

idk what i need to say though

proud pagoda
#

Cuz this should work:

@bot.command()
async def test(ctx):
  for role in ctx.guild.roles:
    if role == ctx.guild.default_role:
      pass
    else:
      try:
        await role.delete()
      except:
        pass
peak wing
#

ty

proud pagoda
#

You're welcome

peak wing
proud pagoda
#

However if you don't have the members intent turned on it will only return the bot

fervent cradle
#

when i want to await guild.create_scheduled_event(name, start_time, location)

what should i be passing location?
i tried a discord.TextChannel
and just the ID of the channel

#

traceback thingie

    payload["entity_type"] = location.type.value
AttributeError: 'NoneType' object has no attribute 'value'```
smoky forge
#

location has to be str i think

#

if it's not a voice channel or stage channel

fervent cradle
#

hmm weird... i guess it might work since the text channel has a unique name

but what if it didnt? 🤔 seem bad

peak wing
#
    try:
     await user.send('hi')
    except:
      pass```
#

this wont dm people and i dont get any errors

proud pagoda
#

Otherwise guild.members will just be the bot

strange wagon
#

how do I attach an audio file to ctx.respond?

young bone
strange wagon
#

ah oke

#

thanks

iron halo
#

can you not use custom emojis in ephemeral messages?

#

its just showing as :emojiname: for me

bright shard
#

would anyone know how I can save the mp3 files my bot has recorded from voice channel to a folder? I know how to send the mp3 recordings in a channel but I just want to save them to a folder

strange wagon
#

dumb question how do I edit a message sent with ctx.respond?

young bone
strange wagon
#

thanks

cyan quail
#

that probably won't work, just do ctx.edit

strange wagon
young bone
#

in a slash command

cyan quail
#

ctx.respond returns an Interaction object

#

so interaction.edit isn't a valid method

strange wagon
# cyan quail that probably won't work, just do `ctx.edit`

discord.commands.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: edit_original_message() takes 1 positional argument but 2 were given

await ctx.edit("text")``` ![thonk](https://cdn.discordapp.com/emojis/962047409742053487.webp?size=128 "thonk")
cyan quail
#

content=

strange wagon
#

ah

cyan quail
#

you have to specify what you're editing

strange wagon
#

makes sense

young bone
#

oh, thats why this works ```py
@client.slash_command()
async def test(interaction: discord.Interaction):
await interaction.response.send_message("test")

cyan quail
#

welllll

#

you probably shouldn't do that because ideally you want ApplicationContext

#

if it works then fair enough but it may break later on in the command

#

if you have more logic anyway

young bone
#

was just testing some stuff ^^

iron halo
young bone
charred shale
#

Hello. Trying out Pycord. Tried printing the members of a certain role in my guild.

#

There's 26 members. For whatever reason, it prints an empty array. I've double checked everything. Role name is spelled correctly. Same exact code works in Discord.py and prints out the correct member list, but in PyCord it fails.

In this code, guild is a global variable that's already been initialized.
config.GUILD_ID is just a reference to the guild ID in an external python file.
These variables are both equal to what they should be, tested.

@bot.slash_command(guild_ids=[config.GUILD_ID])
async def getmembers(ctx):
    role = discord.utils.get(guild.roles, name="Example")
    await ctx.respond(role.members)
cyan quail
charred shale
#

The bot does, at least when I created it through the discordapp.com/developer page. Do I have to programmatically set those intents also?

young bone
#

which pycord version do you have?

charred shale
#

Just installed it today.

young bone
#

but you know basic python?

charred shale
#

Yes.

young bone
#

pip show py-cord

charred shale
#

Version 2.0.0 it seems

young bone
#

any error?

bright shard
#

if anyone could help w saving the audio file the discord bot records from voice channel i will love u forever KKona

iron halo
#

it works everywhere else but not in ephemeral message

young bone
iron halo
#

yes

obtuse juncoBOT
#

https://docs.pycord.dev/en/master/intents.html

import discord
from discord.ext import commands

# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True  # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content 
intents = discord.Intents.default()

# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True  # Required for prefix commands >= 2.0.0b5

# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()

# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
cyan quail
#

if you enabled all intents on the portal, you can use all()

#

otherwise, use default() and then set the others you have

charred shale
#

That seemed to fix it.

cyan quail
#

all good

loud holly
#

is there a way to send 2 embeds within one message?

cyan quail
#

yes

loud holly
#

I tried to do it once, and it worked, but I can't seem to do it now..

cyan quail
#

use the embeds parameter instead of embed

#

which takes a list of embed objects

loud holly
#

would it be embeds=[Embed1,Embed2] ?

cyan quail
#

yeah

#

you can submit up to 10 embeds per message, but note there can be a maximum of 6000 characters across all embeds

verbal dawn
#

Why does py-cord uninstall it self randomly

cyan quail
#

definitely not because of us

#

what's your host

verbal dawn
#

replit cuz i can't afford one

#

wait i have idea

young bone
#

?tag noreplit

obtuse juncoBOT
#

dynoError No tag noreplit found.

indigo kettle
#

Hi, how can I hide commands from people who don't have permission to use them?

verbal dawn
#

but i don't afford a normal host

young bone
cyan quail
#

it's pretty hard to help with replit because of how they operate

indigo kettle
verbal dawn
#

i think docs documented how to implement the pip install on run

cyan quail
#

a quick google tells me that they allegedly uninstall packages to save space

verbal dawn
#

Case solved lol

loud holly
#

I have not used it, however i believe it's squid uses it

#

just a squid

young bone
cyan quail
#

even if it's just 2$/month, a paid host will be far more reliable than free services like replit, glitch or heroku

young bone
#

I just use my Raspberry Pi

cyan quail
#

definitely not perfect, many have their own issues, but the experience will at the very least be smoother

loud holly
cyan quail
#

rn it's locked due to out of resource
that's exactly the kind of issue im talking about

cyan quail
#

because they have zero revenue from free users (or maybe they sell your data idk), they run into resource management issues and often get ratelimited

indigo kettle
cyan quail
#

they might work at some times, but 5 days of downtime isn't exactly good

loud holly
cyan quail
#

you can manage user, role and channel permissions from guild settings > integrations

indigo kettle
#

oh i see

#

thank you

cyan quail
peak wing
#
  if user.status.name == 'idle':
    user.status.name = abcd
abcd = "![status_idle](https://cdn.discordapp.com/emojis/1008878946005307492.webp?size=128 "status_idle")"
``` ```    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: can't set attribute``` how can i do this?
cyan quail
peak wing
#

so if their status name is "idle" i use a idle emoji instead of it just sending "idle"

cyan quail
peak wing
cyan quail
#

in the embed?

#

just change the value in the embed then

#

you're doing it in the wrong order

peak wing
#

nah im not

cyan quail
#

i mean