#Basic Pycord Help (Quick Questions Only)

1 messages · Page 2 of 1

proud pagoda
fervent cradle
#

ty

proud pagoda
#

Instead of while true just set the interval at which the task should be run

fervent cradle
#

kk

signal stratus
fervent cradle
#

I have a bot that can be used with slash commands but also with "?" as a normal prefix, when I host the bot over Sparked Host the "?" commands don't work even tho the slash commands and everything else work
if I host exactly the same script locally everything works fine, can anyone here help me?

rugged lantern
#

yeah because url is supposed to be... url?

#

url = link

#

is not a valid url unless you have the variable link

#

try without using the decorator

#

i said decorator

#

@discord.ui.button

#

instead use self.add_item(Button(label =...))

#

i'm on phone i can't give the proper usage for it

#

no. inside your view class, which you've not super().__init__()
btw

cyan quail
#

i.e. print(discord.__version__)

fervent cradle
cyan quail
#

upgrade to 2.0.0

#

b4-b5 was an intents change

#

once you're on 2.0.0, you need to set intents.message_content = True; if you're already using intents.all(), then you don't need to change anything

fervent cradle
#

Ok imma try thanks

fervent cradle
cyan quail
#

how many servers is your bot in?

fervent cradle
#

more than 15000

cyan quail
#

oh my

#

hmmm

#

it's best you apply as soon as possible, the wait times are quite long

fervent cradle
#

I thought it would get enforced after the 1.9.2022

fervent cradle
cyan quail
#

hmm hold on

fervent cradle
#

ok thanks

cyan quail
#

it will be enforced in september but ApiV10 requires the intent, if you go down to v9 you should be able to go without...?
at the start of your file after imports, set discord.http.API_VERSION = 9

fervent cradle
#

ok imma try

cyan quail
#

it's probably best to gradually encourage your users to migrate to slash though; if you do get prefix commands working, i recommend having some sort of warning message about the transition

fervent cradle
cyan quail
#

luckily, discord implemented command suggestions so if they do use ? the slash commands will still show up

fervent cradle
#

the issue is that "older servers" didn't give the bot "create commands" (or however it is called) permission so it won't show up for them but generally thats nice

#

and it works now thanks a lot, no way I would have been able to fix that without you

cyan quail
#

all good, i believe discord is rolling out a notification that will allow admins to easily grant bots the required scope

fervent cradle
#

oh that would be nice

cyan quail
#

so it should be easier in due time

#

hmm doesn't seem like it, are you getting any errors?

#

what version?

#

hmmmmmmm

#

i... don't think so? the code itself looks fine, i'll try testing it

#

ok wow that was hard to see

#

unindent the callback function by one level

#

your callback is defined inside the init

#

when it should be outside

grim canopy
#
@bot.message_command(name="Testing Message Command", guild_ids=[995976950541729793])
async def testing(ctx: discord.ApplicationContext, message:discord.Message):
    await ctx.respond("Test")

bot.add_application_command(testing)
#
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 1: Application command names must be unique

why tf is it saying my cmd name isn't unique

#

I tried different names and this still occurred

#
Ignoring exception in on_connect
Traceback (most recent call last):
  File "C:\Users\harro_zke1lyz\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 382, in _run_event    
    await coro(*args, **kwargs)
  File "C:\Users\harro_zke1lyz\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1041, in on_connect      
    await self.sync_commands()
  File "C:\Users\harro_zke1lyz\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 643, in sync_commands    
    registered_guild_commands[guild_id] = await self.register_commands(
  File "C:\Users\harro_zke1lyz\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 528, in register_commands
    registered = await register("bulk", data, _log=False)
  File "C:\Users\harro_zke1lyz\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 360, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 1: Application command names must be unique

full

#

name param or func name

#

Both tried, still not working

#

some nsfw behind it lmaocry_hd

grim canopy
#

that's a ModalEU_hmmm

#

EU_hmmm ig not

#

Maybe ApplicationContext

severe storm
#

how can i play an mp3 file in a voice chat? i have all the logic done except for playing the mp3 file.

fervent cradle
#

How can i edit message?

severe storm
fervent cradle
severe storm
fervent cradle
#

thanks

vital blade
#

get the channel first
then do await channel.send

worldly schooner
#

im getting crazy

#

can someone help me on #1001085374157824030?

fading granite
#

is there anyway to simplify this code 😅

worldly schooner
#

how do I load a .env from cogs file (test) to an outer folder like venv?

fading granite
#

ye

#

except the button interacted

fervent cradle
#

how can i get message id when i press button

ashen pulsar
#

how can i edit the message the button is on?

hollow heath
#

This isn't normal right?

#
Command raised an exception: TypeError: '_FakeBool' object is not iterable
Ignoring exception in on_command_error
Traceback (most recent call last):
  File "/home/container/discord/client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/bot.py", line 58, in on_command_error
    return await error_embed(ctx, "Error, something failed on our side.", f"The error that occured was: {error}, if this continues, please report it to Skezza#1139,")
  File "/home/container/utils.py", line 39, in error
    await ctx.send(embed=embed)
  File "/home/container/discord/abc.py", line 1443, in send
    allowed_mentions = state.allowed_mentions and state.allowed_mentions.to_dict()
  File "/home/container/discord/mentions.py", line 124, in to_dict
    data["users"] = [x.id for x in self.users]
TypeError: '_FakeBool' object is not iterable
#

It only happens in the last 5 commits

worldly schooner
#

anyway to simplify this?

try:
  if timestamp == None:
      if users[str(ctx.author.id)]['seepercent']['enabled']:
         users[str(ctx.author.id)]['seepercent']['enabled'] = not users[str(ctx.author.id)]['seepercent']['enabled']
         await ctx.send("See percentages *disabled*")
      else:
          users[str(ctx.author.id)]['seepercent']['enabled'] = not users[str(ctx.author.id)]['seepercent']['enabled']
          timestamp = users[str(ctx.author.id)]['seepercent']['timestamp']
          await ctx.send(f"See {timestamp+'h' if timestamp==1 or timestamp==24 else timestamp+'d'} percentages *enabled*")
  else:
      if not users[str(ctx.author.id)]['seepercent']['enabled']:
         users[str(ctx.author.id)]['seepercent']['enabled'] = not users[str(ctx.author.id)]['seepercent']['enabled']
         users[str(ctx.author.id)]['seepercent']['timestamp'] = timestamp
         await ctx.send(f"See {timestamp+'h' if timestamp==1 or timestamp==24 else timestamp+'d'} percentages *enabled*")
      else:
         users[str(ctx.author.id)]['seepercent']['enabled'] = not users[str(ctx.author.id)]['seepercent']['enabled']
         await ctx.send("See percentages *disabled*")
except KeyError:
    users[str(ctx.author.id)]['seepercent'] = {}
    users[str(ctx.author.id)]['seepercent']['enabled']=True
    users[str(ctx.author.id)]['seepercent']['timestamp'] = 1
    await ctx.send(f"See 1h percentages *enabled*")
hollow heath
#

auth_id = str(ctx.author_id) and then user that everywhere

#
try:
  auth_id = str(ctx.author.id)
  if timestamp == None:
      if users[auth_id]['seepercent']['enabled']:
         users[auth_id]['seepercent']['enabled'] = False
         await ctx.send("See percentages *disabled*")
      else:
          users[auth_id]['seepercent']['enabled'] = True
          timestamp = users[auth_id]['seepercent']['timestamp']
          await ctx.send(f"See {timestamp+'h' if timestamp==1 or timestamp==24 else timestamp+'d'} percentages *enabled*")
  else:
      if not users[auth_id]['seepercent']['enabled']:
         users[auth_id]['seepercent']['enabled'] = False
         users[str(ctx.author.id)]['seepercent']['timestamp'] = timestamp
         await ctx.send(f"See {timestamp+'h' if timestamp==1 or timestamp==24 else timestamp+'d'} percentages *enabled*")
      else:
         users[auth_id]['seepercent']['enabled'] = True
         await ctx.send("See percentages *disabled*")
except KeyError:
    users[str(ctx.author.id)]['seepercent'] = {'enabled': True, 'timestamp': 1}1
    await ctx.send(f"See 1h percentages *enabled*")
fervent cradle
#

I think its registering the command twice

#

and thats why you are gettin the error

grim canopy
#

ic

fervent cradle
#

could someone explain what the top @s do?

fervent cradle
neon bramble
fervent cradle
neon bramble
#

I think I said that

#

Anyway this is undoubtedly documented somewhere (likely better than I can explain)

limber idol
#

how do i add a role to someone?

#

add_roles doesnt seem to work

neon bramble
#

What're you passing to it?

limber idol
#

just the role

neon bramble
#

The role object?

limber idol
#

yep

fervent cradle
#

or the id

limber idol
#

it doesnt even recognize add_roles

lavish vine
#

my cogs aren't working

neon bramble
fervent cradle
lavish vine
limber idol
fervent cradle
lavish vine
#

right?

#

files

fervent cradle
lavish vine
#

ill try right no

#

it says the command load wasn't found

#

ill try the basic help

#

no commands show up

neon bramble
# limber idol

Why are you re-getting the role? You could just pass the object that you already have

lavish vine
limber idol
lavish vine
#

and then started the bot

#

and it works now

#

so thanks fort the help!!

fervent cradle
#

oh nice

#

np!

fervent cradle
limber idol
fervent cradle
#

is the ID right?

limber idol
#

it just prints None

fervent cradle
#

so it can't get the user

limber idol
#

oh

#

i forgot to thingy the intents

#

is that the problem?

tiny wagon
#

any event listener, that triggers on bot's mesage send?

slow eagle
#

anyway i can add like the letters not as choices?? ```py
async def antitoggle(ctx: discord.ApplicationContext, var: discord.Option(str, 'on or off! ', choices='yn')):

#

nvm i fixed it

vital blade
#

how can i check a member's custom status

vital blade
silver moat
#

b!rtfm pyc status

silver moat
#

I don't think you tried

rugged lantern
#

i tried to read the docs!
...
though i didn't read the section literally named the main keyword for what i'm looking for

waxen whale
worldly schooner
#

how do I treat discord.ext.commands.errors.CommandNotFound as exception?

fervent cradle
#
@bot.event
async def on_member_join(member):
    print('1')
    roleJoin = member.guild.get_role(863696255224643605)
    await member.add_roles(roleJoin, reason=f'{member} (ID: {member.id}) зашёл на сервер')

@bot.event
async def on_member_remove(member):
    dm = bot.create_dm(member)
    dm.send('Нам очень жаль, что вы вышли с нашего сервера, надеюсь мы смогли помочь вам и вашему серверу.\n\n**Если вдруг вы решите вернуться:** \nТакже мы просим вас ответить на несколько вопросов в данной форме: \nФорма для амнистии бана: (если вы были забанены) ')

on_member_join, on_member_remove doesn't work

waxen whale
#

forgot to remove the google forms link :p

fervent cradle
waxen whale
silver moat
#

why tho

silver moat
fervent cradle
full basin
#

Whats the best library that works with pycord to play music?

silver moat
#

but you can just about use anything as shown here #creations message

worldly schooner
silver moat
rugged lantern
#

no reason to 'try, except'

full basin
silver moat
gleaming falcon
#

Sanity check -- the best(/only?) way to watch for messages in a specific channel is to use a global on_message handler and filter by the message.channel.id?

full basin
#

How can I delete duplicated commands? Or do they automatically delete discord just did

worldly schooner
gleaming falcon
#

Oh boy. What am I doing wrong? I'm trying to get the contents of a specific message by ID

Code's fairly simple...

    @commands.command()
    @commands.is_owner()
    async def msg(self, ctx):
        message_id = 998690020435173547
        msg = self.bot.get_message(message_id)
        print(msg)

Yet msg is None. Is get_message() not adequate? The bot has message history permissions (and message intents, even though it shouldn't need it as a private bot)

young bone
#

How can I remove a slash command/disabled?

silver moat
young bone
graceful nebula
#

You can turn it off in the server permissions as well

gleaming falcon
# silver moat message_content intents?

Oh. No, I didn't actually. But it didn't matter - I had to get the channel first, and then channel.fetch_message(message_id). I am guessing get_message() is cache only, but kinda wish there was a way to get an arbitrary message by ID vs caring about the channel (I imagine Discord API limitation)

silver moat
#

ok, glad you figured it out

tiny wagon
#

any event listener, that triggers on bot's mesage send?

silver moat
tiny wagon
#

so you mean by passing an if condition right?

silver moat
#

I mean you can trigger the bot sending a message in a million ways

#

not sure about what event you are looking for

tiny wagon
#

if message.content.author== bot.user

silver moat
#

wait so you want an event to be triggered if your bot sent a message?

tiny wagon
# silver moat not sure about what event you are looking for

see, i have rolled some updates in my bot but i dont have any bot support server, so what i want is advertisement of that thing

i thought i will first create a listener that will trigger when bot sends message, then use random moddule to send the message along with the message bot sends

silver moat
#

how is the random module related?

tiny wagon
#

so to avoid this i will use random.random() and check if its value is smaller than 0.25, then send message

silver moat
#

ok but still create a support server

tiny wagon
#

so 25% chance

tiny wagon
#

also it takes lot of time to fill support server, so how should i tell ppl about updates? i am confused

silver moat
#

so your bot runs on commands and just add an embed on every command

#

and only display that embed if the user hasn't seen it before

tiny wagon
silver moat
#

so store that value in your database

silver moat
tiny wagon
silver moat
#

b!rtfm on_application_command

dire spadeBOT
# silver moat b!rtfm on_application_command

I couldn't find a documentation with the name on_application_command! Maybe you used to command wrong? Correct Usage: <prefix>rtfm <docs> [<term>] (eg. b!rtfm py cool)
List of Documentations you can search:
python
pycord
discord.py
yarsaw
nextcord
disnake

silver moat
#

b!rtfm pyc on_application_command

silver moat
#

do you want to learn python

fervent cradle
#
@bot.event
async def on_member_join(member):
    print('1')
    roleJoin = member.guild.get_role(863696255224643605)
    await member.add_roles(roleJoin, reason=f'{member} (ID: {member.id}) зашёл на сервер')

@bot.event
async def on_member_remove(member):
    dm = bot.create_dm(member)
    dm.send('Нам очень жаль, что вы вышли с нашего сервера, надеюсь мы смогли помочь вам и вашему серверу.\n\n**Если вдруг вы решите вернуться:** \nТакже мы просим вас ответить на несколько вопросов в данной форме: \nФорма для амнистии бана: (если вы были забанены) ')```
silver moat
fervent cradle
silver moat
cyan quail
#

and like mentioned above, you should make sure you specify intents= when defining your bot

silver moat
#

I think the actual issue is that the event is dispatched

cyan quail
#

i wonder if specifying intents should be required for 2.1

#

so many people just don't know about them

silver moat
#

wait I think I forgot about intents in the migration guide

worldly schooner
#

why when hosting with heroku my cog files dont load?

proud pagoda
worldly schooner
#

but no errors about cogs

lost lodge
#

guys how can i edit a message on button click

proud pagoda
worldly schooner
#

here how i load

worldly schooner
proud pagoda
worldly schooner
proud pagoda
#

Yes

worldly schooner
#

ok

lost lodge
proud pagoda
worldly schooner
#

oh now it gave me a error @proud pagoda

#

it is not finding the requests package

lost lodge
worldly schooner
#

i will figure out how to put it in requirements

#

thanks for the help

proud pagoda
proud pagoda
lost lodge
#
            await view.remove_item
            await interaction.response.edit_message(embed=embed2)```
proud pagoda
lost lodge
#

ok so the button just do nothing

#

is that wright?

proud pagoda
#

So you have the button stored in a variable right?

lost lodge
#
            view.remove_item
            await interaction.response.edit_message(embed=embed2,view=view)```
proud pagoda
#

So do view.remove_item(var_name)

lost lodge
#

ah

#

same as before

proud pagoda
#

Wdym?

lost lodge
#

so the button just stops working but it doesn't diapers from the message

proud pagoda
#

Hm send all of ur code

#

For the command

lost lodge
proud pagoda
#

Your issue is that youre doing view.remove_item(view)

#

You must supply the button var

#

So for u it would be view.remove_item(button)

lost lodge
#

ah works thanks

#

!!!

proud pagoda
#

You're welcome

rugged lantern
#

you should class buttons- it is MUCH easier to read and use

proud pagoda
#

Wdym class buttons?

rugged lantern
#

views, not the actual buttons*

proud pagoda
#

Subclass?

#

Yeah u should subclass if you're going to reuse that same view somewhere else

#

For example a confirmation view

rugged lantern
#

even if it is a singular instance, having it separate from the command looks better and is easier to work with

proud pagoda
#

Yeah that's true

lost lodge
#

so i added a feature now to switch between embed and every time i hit a button hit removes the other one and send the new embed but this only works on time per button

#

how can i make that this feature not only works one time

#

?

coarse canyon
#

For me there seems to be no message content however there definitely is message content

#

Well the bot just returns empty string

#

Does anyone know why

#

I’m using pycord 2.0

silver moat
#

?tag message_content

obtuse juncoBOT
#

dynoError No tag message_content found.

silver moat
#

?tag message-content

obtuse juncoBOT
#

As of Pycord Beta 5, Discord API v10 requires message content intent to receive message content. This affects the traditional commands. Not enabling this intent will result in the messages' content, embeds, and components being empty.

You will need to enable the intent on the developer portal, as well as in your code:

intents = discord.Intents.default()
intents.message_content = True
bot = discord.Bot(intents=intents)

Docs: https://docs.pycord.dev/en/master/api.html#discord.Intents.message_content

silver moat
#

@coarse canyon

coarse canyon
#

Thanks

lost lodge
#

ok wait

silver moat
# lost lodge ok wait

when you mean it doesn't work, does it say "this interaction failed" or "the application did not respond"?

worldly schooner
#

How do I treat the circunstance of a misspelled parameter, like:

command hi only accept 1 or 2 parameters: !Hi Joseph (or !Hi Joseph Mila)

but I want the bot to add a reaction if the user dont give a parameter or give more than 2

lost lodge
silver moat
lost lodge
#

no

silver moat
#

so if you click the button on discord what happens?

lost lodge
#

wait i make a video

silver moat
worldly schooner
#

thanks

silver moat
#

It was just cropped off

lost lodge
#

stay safe 😷 xD

silver moat
#

I saw everything but the button

#

_>

lost lodge
#

?

silver moat
#

I couldn't see the button itself lol

lost lodge
#

in the video or code?

silver moat
#

the video

lost lodge
#

ah

#

sorry 😦

silver moat
#

good no virus

#

ok so the button is just gone

lost lodge
#

yes

#

haha

silver moat
#

you defined view2 and view1 as just an empty view

lost lodge
#

it is defined on top of the command

silver moat
#

ok, now in the button callbacks put print(view1.children) and vise versa

silver moat
#

print(view1.children) in button1 and print(view2.children) in button2 callback

#

if I'm right, then these should be None

lost lodge
#
[<Button style=<ButtonStyle.success: 3> url=None disabled=False label='More information' emoji=None row=None>]
[<Button style=<ButtonStyle.success: 3> url=None disabled=False label='Less information' emoji=None row=None>]```
silver moat
#

this is displayed after you clicked each one twice?

silver moat
#

this is the problem

lost lodge
#

ah

silver moat
#

you straight up removed it

meager heron
#

My modal field's max_length doesn't seem to be honored.

self.add_item(
    discord.ui.InputText(
        label="Scene Location",
        placeholder="The location of the current scene",
        value=current_header.location,
        max_length=max_location_len,
    ),
)

Any ideas?

silver moat
#

and it's just gone

meager heron
#

Can I just set it to 0?

silver moat
lost lodge
meager heron
#

Okay. That's odd, but thanks

silver moat
lost lodge
#

ah thanks

#

works all

silver moat
#

glad I could help

lost lodge
#

bro i have a question

silver moat
#

yeah

lost lodge
#

what do you work on every day on vs code

#

i see you every day doing that

silver moat
lost lodge
#

ok xD

woeful spindle
#

wait how do i edit my interaction message with a callback?

#

is it await interaction.response.edit_message?

silver moat
#

if application has already been responded. use interaction.edit_original_message

woeful spindle
#

ty

meager heron
#

Is there a way I can disable application commands? I have some long-running commands I don't want to interrupt with a restart, so it would be nice to prevent new ones from being run in order to give any current processes time to complete before shutdown

#

on_application_command() seems to fire after the commands, not before, so I can't prevent it that way

meager heron
#

Ah, perfect, thank you

#

Is there a way to determine if the interaction is specifically a command invocation?

meager heron
#

Awesome, thank you

woeful spindle
silver moat
woeful spindle
#

same time?

#

what?

silver moat
#

auto correct

woeful spindle
#
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/ui/view.py", line 371, in _scheduled_task
    await item.callback(interaction)
  File "/home/container/main.py", line 54, in select_callback
    await interaction.edit.original_message("owner option test")
AttributeError: 'Interaction' object has no attribute 'edit'
Ignoring exception in view <HelpView timeout=180.0 children=1> for item <Select placeholder='Please select a category:' min_values=1 max_values=1 options=[<SelectOption label='Owner' value='Own' description='Select to view our Owner commands.' emoji=<PartialEmoji animated=False name='CL_AzielOwner' id=1000907171959161023> default=False>, <SelectOption label='Moderation' value='Mod' description='Select to view our Moderation commands.' emoji=<PartialEmoji animated=False name='CL_AzielMod' id=1000909301927395358> default=False>, <SelectOption label='Information' value='info' description='Select to see our infomational commands.' emoji=<PartialEmoji animated=False name='CL_Book' id=1000145556204691536> default=False>, <SelectOption label='Fun' value='Fun' description='Select to view our Fun commands.' emoji=<PartialEmoji animated=False name='CL_AzielGames' id=1000908640263344178> default=False>] disabled=False>:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/ui/view.py", line 371, in _scheduled_task
    await item.callback(interaction)
  File "/home/container/main.py", line 56, in select_callback
    await interaction.edit.original_message("mod option test")
AttributeError: 'Interaction' object has no attribute 'edit'
#

i wasn’t using interaction.edit

silver moat
#

interaction.**edit_**original_message

woeful spindle
#

i am using that?

silver moat
#

with an underscore

#

not a period

woeful spindle
#

oh

#

whoopsy

#

sorry ty

young bone
woeful spindle
#

yes lol

#

what are the arguments for edit_original_message()?

woeful spindle
#

ty

#

uh what

#
Ignoring exception in view <HelpView timeout=180.0 children=1> for item <Select placeholder='Please select a category:' min_values=1 max_values=1 options=[<SelectOption label='Owner' value='Own' description='Select to view our Owner commands.' emoji=<PartialEmoji animated=False name='CL_AzielOwner' id=1000907171959161023> default=False>, <SelectOption label='Moderation' value='Mod' description='Select to view our Moderation commands.' emoji=<PartialEmoji animated=False name='CL_AzielMod' id=1000909301927395358> default=False>, <SelectOption label='Information' value='info' description='Select to see our infomational commands.' emoji=<PartialEmoji animated=False name='CL_Book' id=1000145556204691536> default=False>, <SelectOption label='Fun' value='Fun' description='Select to view our Fun commands.' emoji=<PartialEmoji animated=False name='CL_AzielGames' id=1000908640263344178> default=False>] disabled=False>:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/ui/view.py", line 371, in _scheduled_task
    await item.callback(interaction)
  File "/home/container/main.py", line 54, in select_callback
    await interaction.edit_original_message(content="owner option test")
  File "/home/container/.local/lib/python3.9/site-packages/discord/interactions.py", line 378, in edit_original_message
    data = await adapter.edit_original_interaction_response(
  File "/home/container/.local/lib/python3.9/site-packages/discord/webhook/async_.py", line 211, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
silver moat
daring tendon
#

i recently swtiched to slash commands and the ctx.message.created_at doesnt work anymore

#

can you still get the timestamp for an embed

#

if so how?

woeful spindle
daring tendon
#

thcx

fluid crystal
#

Cane anyone Tell we why is this not working?

#

My Status is dnd and not offline

full basin
#

members intent?

fluid crystal
meager heron
# silver moat also set a min_length

I'm back! I did this:

self.add_item(
    discord.ui.InputText(
        label="Scene Location",
        placeholder="The location of the current scene",
        value=current_header.location,
        min_length=1,
        max_length=max_location_len,
    ),
)

The length restriction still isn't being honored

wicked helm
#

How do I stop the command prefix error.. I don't want to see it pop up every time someone write a message in the server

#

Can I just disable command prefix commands?

full basin
#

Command prefix error?

wicked helm
#
Traceback (most recent call last):
  File "C:\Users\david\AppData\Local\pypoetry\Cache\virtualenvs\brvns-discord-IEfoc-tc-py3.9\lib\site-packages\discord\client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\david\AppData\Local\pypoetry\Cache\virtualenvs\brvns-discord-IEfoc-tc-py3.9\lib\site-packages\discord\ext\commands\bot.py", line 384, in on_message
    await self.process_commands(message)
  File "C:\Users\david\AppData\Local\pypoetry\Cache\virtualenvs\brvns-discord-IEfoc-tc-py3.9\lib\site-packages\discord\ext\commands\bot.py", line 380, in process_commands
    ctx = await self.get_context(message)
  File "C:\Users\david\AppData\Local\pypoetry\Cache\virtualenvs\brvns-discord-IEfoc-tc-py3.9\lib\site-packages\discord\ext\commands\bot.py", line 286, in get_context
    prefix = await self.get_prefix(message)
  File "C:\Users\david\AppData\Local\pypoetry\Cache\virtualenvs\brvns-discord-IEfoc-tc-py3.9\lib\site-packages\discord\ext\commands\bot.py", line 240, in get_prefix
    raise TypeError(
TypeError: command_prefix must be plain string, iterable of strings, or callable returning either of these, not BrvnsBot
Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\david\AppData\Local\pypoetry\Cache\virtualenvs\brvns-discord-IEfoc-tc-py3.9\lib\site-packages\discord\ext\commands\bot.py", line 233, in get_prefix
    ret = list(ret)
TypeError: 'BrvnsBot' object is not iterable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\david\AppData\Local\pypoetry\Cache\virtualenvs\brvns-discord-IEfoc-tc-py3.9\lib\site-packages\discord\client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\david\AppData\Local\pypoetry\Cache\virtualenvs\brvns-discord-IEfoc-tc-py3.9\lib\site-packages\discord\ext\commands\bot.py", line 384, in on_message
    await self.process_commands(message)
  File "C:\Users\david\AppData\Local\pypoetry\Cache\virtualenvs\brvns-discord-IEfoc-tc-py3.9\lib\site-packages\discord\ext\commands\bot.py", line 380, in process_commands
    ctx = await self.get_context(message)
  File "C:\Users\david\AppData\Local\pypoetry\Cache\virtualenvs\brvns-discord-IEfoc-tc-py3.9\lib\site-packages\discord\ext\commands\bot.py", line 286, in get_context
    prefix = await self.get_prefix(message)
  File "C:\Users\david\AppData\Local\pypoetry\Cache\virtualenvs\brvns-discord-IEfoc-tc-py3.9\lib\site-packages\discord\ext\commands\bot.py", line 240, in get_prefix
    raise TypeError(
TypeError: command_prefix must be plain string, iterable of strings, or callable returning either of these, not BrvnsBot

I get this when I write a plain text message in my server that uses / commands

full basin
#

Do you use prefixed commands?

wicked helm
#

Nope, none at all

full basin
#

What bot instance are you using?

wicked helm
#

from discord.ext.commands import Bot and then using cogs for the / commands

#

Is it because I am importing Bot from commands?

full basin
#

Use discord.Bot if you don't want prefixed commands

wicked helm
#

That gives me this:

Traceback (most recent call last):
  File "D:\Visual Code Git Clones\BRVNS-Discord-Bot\main.py", line 23, in <module>
    Bot: BrvnsBot = BrvnsBot(debug_guilds=["id"])
  File "D:\Visual Code Git Clones\BRVNS-Discord-Bot\src\brvns_bot.py", line 21, in __init__
    super().__init__(self, debug_guilds=debug_guilds)
  File "C:\Users\david\AppData\Local\pypoetry\Cache\virtualenvs\brvns-discord-IEfoc-tc-py3.9\lib\site-packages\discord\bot.py", line 1021, in __init__
    self.description = inspect.cleandoc(description) if description else ""
  File "C:\Users\david\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 632, in cleandoc
    lines = doc.expandtabs().split('\n')
AttributeError: 'BrvnsBot' object has no attribute 'expandtabs'
raven island
#

One quick question. I want to do a check to see if the current server my bot is in, if that is equal to a certain server id. As in if my bot is in alot of servers, and i only want this one command to execute on my home server, how would i go about doing that?

wicked helm
#

main:

        token: str = environ['TOKEN']
        Bot: BrvnsBot = BrvnsBot(debug_guilds=["id"])
        Bot.run(token)

BrvnsBot:

"""
BRVNS Bot API
"""
import logging
from os import environ

from discord import Bot

logger = logging.getLogger(environ['LOGGER_NAME'])
print(environ['LOGGER_LEVEL'])
logger.setLevel(environ['LOGGER_LEVEL'])


# pylint: disable=too-many-ancestors
class BrvnsBot(Bot):
    """
    BRVNS Bot
    """

    def __init__(self, debug_guilds):
        super().__init__(self, debug_guilds=debug_guilds)

        self.load_extension("src.cogs", recursive=True)

        logger.info("Cogs added")

    async def on_ready(self):
        """
        Bot On Ready
        """
        logger.info(f"""
            ____ READY ____
            Bot: {self.user.name}
            Guilds: {self.guilds}
            Cogs: {self.cogs}""".strip())
wicked helm
# full basin Code

Do not worry - I found a way to stop them being ugly..

I just added an on message event that does nothing

#

For now it works. I can deal with this better at a later date

fervent cradle
#

Ok so im just creating a new bot and i need to know how to make a welcome messgae event

#

how

#

like event

full basin
fervent cradle
#

like under events?

fervent cradle
#

import discord
from discord.ext import commands

embed_color = 0x301934


class welcome(commands.Cog):
    def __init__(self, client):
        self.client = client

    async def on_member_join(self, member, ctx):
        await ctx.send(f"welcome {member}")


def setup(client):
    client.add_cog(welcome(client))

so i was fucking arround but i cant get this to work

fervent cradle
fresh gust
#

Hi, could someone tell me how to apply command cooldowns on my commands, but conditionally?
Like apply the call inside an if statement :p
Heres what ive been using so far

@commands.cooldown(rate = 1, per = 30, type=commands.BucketType.user)

fervent cradle
#
Traceback (most recent call last):
  File "/Volumes/Danya disk/coding/Py-cord/HFD/main.py", line 36, in <module>
    bot = Bot(intents = discord.Intents.all())
TypeError: Bot.__init__() got an unexpected keyword argument 'intents'```

How can i fix it?
fresh gust
fresh gust
fresh gust
fervent cradle
#
@bot.event
async def on_member_join(member):
    print('1')
    roleJoin = member.guild.get_role(863696255224643605)
    await member.add_roles(roleJoin, reason=f'{member} (ID: {member.id}) зашёл на сервер')

@bot.event
async def on_member_remove(member):
    dm = bot.create_dm(member)
    dm.send('Нам очень жаль, что вы вышли с нашего сервера, надеюсь мы смогли помочь вам и вашему серверу.\n\n**Если вдруг вы решите вернуться:** \nТакже мы просим вас ответить на несколько вопросов в данной форме: \nФорма для амнистии бана: (если вы были забанены) ')```

on_member_join, on_member_remove doesn't work
rugged lantern
#

people have already provided you solutions and you've just ignored it completely

marsh moth
#

serverList = [###########] @client.slash_command(guild_ids=serverList,name='message_delete') async def messageDelete(ctx):
Theres apparently a daily app command limit of 200, when running the script when the command is already in the server count towards that limit?

round rivet
#

it shouldn't

#

I believe it's 200 command creations

devout anvil
#

does this work in @bot.slash_command()

marsh moth
round rivet
devout anvil
round rivet
#

you have to pass it to the input_type param of Option

marsh moth
#

plun, so does syncing count as creations

round rivet
#

I've been able to restart my bot about 30 times a day and it works fine

marsh moth
#

hmm

marsh moth
# round rivet I've been able to restart my bot about 30 times a day and it works fine
@client.slash_command(guild_ids=serverList,name='enable_slash_commands')
async def enableSlashCommands(ctx):
    print(ctx.guild.id)
    slashCommandList = [messageDelete,purgeChannel,emergencyLockdown,reactionRole,restrictedEmojis,emojiRestrict,topic,youtubeListen,setLivePingRole,roleClear,xpEvent,xpGet,xpAdd,xpRemove,xpLevelSet,levelingChannel,levelingRewardAdd,levelingRewardRemove,statusKick]
    msgResponse = await ctx.respond('Working...',ephemeral=True)
    await client.sync_commands(commands=slashCommandList,guild_ids=[ctx.guild.id],force=True)
    await msgResponse.edit(content='Slash commands enabeld!')

Would this cause it to go over 200 if the command was ran 13 times?

round rivet
#

with force=True I believe it would

marsh moth
round rivet
#

it forces all the commands to re-register

marsh moth
#

but they werent appearing in server if I didnt

marsh moth
marsh moth
#

@round rivet if I update the description of the command, does it count for one of the 200?

round rivet
#

it should just update the command

#

so no

marsh moth
#

What if its a global command

round rivet
#

still no

marsh moth
#

but it would take an hour to update if it was global, rigjt?

round rivet
#

as long as force is set to False (default) it should be normal

round rivet
marsh moth
#

oh, really?

marsh moth
round rivet
#

but I do have a thing that removes all commands then syncs them again

marsh moth
#

hm ok, I may have been doing ti wrong then fixed it, thanks!

marsh moth
round rivet
#

something I'm doing

marsh moth
#

alr, ty

tiny wagon
#

how to ask user for a list of channels from slash command input boxes

marsh moth
#

What is guild_only if u can’t add bots to groupchats

lost lodge
#

hello

#

can anyone say me how to limit uses of a button

fervent cradle
#

hello

#
class botinfoButton(discord.ui.View): 
        @discord.ui.button(label = "Click me!", style = discord.ButtonStyle.primary, emoji = "😎")
        async def button_callback(self, button, interaction):
            await interaction.response.send_message("You clicked the button!") 

    @slash_command(
         description = "Shows you a whole list of information about the bot."
    )
    async def botinfo(self, ctx):
        await ctx.respond("im a bot lol", view = botinfoButton())
        ```
its saying botinfoButton is not defined :/
#

File "/home/container/cogs/Information.py", line 38, in botinfo await ctx.respond("im a bot lol", view = botinfoButton()) NameError: name 'botinfoButton' is not defined

fervent cradle
lost lodge
cyan quail
#

yes...?

#

either that or use self, but you shouldn't really be defining a command inside a view subclass

fervent cradle
#

what are indents again

cyan quail
#

bruh

fervent cradle
#

im pretty sure code is correct tho.

marsh mesa
fervent cradle
#

every other command works in that file

cyan quail
#

the tab level

fervent cradle
#

MY INDENTS ARE CORREXTC

marsh mesa
#

You need indentation to be correct in python as otherwise it won't recognize functions and variables correctly

fervent cradle
#

dies.

marsh mesa
#

It doesn't look correct from the copy paste 🙈

cyan quail
#

yeah but you can't call your own class inside the class

fervent cradle
cyan quail
#

you can use self but why on earth would you define a command inside a view

fervent cradle
#

maybe the pycord guide is incorrect

#

jk

cyan quail
fervent cradle
#
        class botinfoButton(discord.ui.View): 
            @discord.ui.button(label = "Click me!", style = discord.ButtonStyle.primary, emoji = "😎")
            async def button_callback(self, button, interaction):
                await interaction.response.send_message("You clicked the button!") ```
what about now..
cyan quail
#

what about it

marsh mesa
#

much better

fervent cradle
#

nevermind same error

#

💀

cyan quail
#

though you should probably have an init function and super().__init__() to give it everything required

#

i didn't mean those indents, i assumed the command should be outside the view class... because of course it should

fervent cradle
#

maybeeeeeee

cyan quail
#

what does your file actually look like?

fervent cradle
#

im new to python and pycord..

fervent cradle
cyan quail
#

then why don't you put the command in the cog class?

fervent cradle
#

i d i d..

cyan quail
#

but... it isn't...

fervent cradle
#

w..a...t

#

oh

cyan quail
#

yeah

fervent cradle
#

nevermind

#

i dont understand

#

i cant put a class inside a cog!?!?!

cyan quail
#

im assuming your file has a cog class and a view class, right?

fervent cradle
#

yes

cyan quail
#

and inside the cog class, you defined a ton of commands?

fervent cradle
#

exactly

cyan quail
fervent cradle
#

ok..

cyan quail
#

this is your view class

fervent cradle
#

yes!

cyan quail
#

and you defined a command inside it

#

why?

fervent cradle
#

why not?!?!

cyan quail
#

because it won't work

fervent cradle
#

o h

cyan quail
#

put it in the cog class with the other commands

fervent cradle
#

alright

#

d o n e

cyan quail
#

ok now try

fervent cradle
#

IT WORKED

#

THANKS!!1

#

omgg

marsh moth
fervent cradle
#

es

#

yes\

marsh moth
#

Dang, thank you for letting me know

fervent cradle
#

np

marsh moth
#

So how would u create slash commands for a certain user?

#

Like userid

fervent cradle
#

i dont think u can

#

do that

lost lodge
cyan quail
#

well you could disable it in the callback

#

so long as you remember to edit the original message

lost lodge
#

Ok

marsh moth
cyan quail
#

you can set permissions inside guilds for a specific user to use a command, but that can't be done via the api; has to be the integrations menu

#

you can't sync commands to a specific user/DM

marsh moth
cyan quail
#

yes, unless you set the guild_only attribute

fervent cradle
cyan quail
#

set guild_only=True inside your slash command decorator

fervent cradle
#

alr cool

lost lodge
fervent cradle
#

will it take time

cyan quail
#

global commands take up to an hour to update

cyan quail
#

i don't think it rolled out fully

lost lodge
cinder pilot
lost lodge
cyan quail
lost lodge
#

so problem is now i wanna use it one time but now i can't use it

fervent cradle
#

hmm

cinder pilot
fervent cradle
#

they still didnt disapear from dms..

#

and i can use them

cyan quail
#

im not saying they don't, im saying that update hasn't fully rolled out

cinder pilot
cinder pilot
#

Slash command autocomplete isn't working for me

cyan quail
cyan quail
lost lodge
cyan quail
#

sure

cinder pilot
cyan quail
#

well i meant, what's wrong with it

#

errors? something else?

cinder pilot
#

Nop

lost lodge
cinder pilot
#

It doesn't show up

cyan quail
#

can you also show your code

cinder pilot
#

Might be confusing but I'll send

cyan quail
cinder pilot
#
async def stop_searcher(ctx: discord.AutocompleteContext):
    return [stop['name'] for stop in rtadubai.StopFinder.findstop(ctx.value)]


@client.slash_command()
@discord.option(name="from", value='from_stop', description="From stop", autocomplete=stop_searcher)
@discord.option(name="to", value='to_stop', description="To stop", autocomplete=stop_searcher)
async def journey(ctx, from_stop, to_stop):
    from_stop = Stop(name=from_stop)
    to_stop = Stop(name=to_stop)
    journey = JourneyPlanner.findroute(from_stop, to_stop)
    await ctx.respond(json.dumps(journey, indent=4))
cyan quail
#

hmm you might need to change a bit more

#

define the view above the callback, do edit_message instead of send_message and pass in view=view

lost lodge
cyan quail
cinder pilot
cyan quail
#

though i'm not completely sure, i just don't like the option decorator syntax and prefer to typehint it instead

cyan quail
#

yeah

cinder pilot
#

I'll try

cyan quail
#

fair enough i guess

lost lodge
cyan quail
# lost lodge .......

define the view above the callback, do edit_message instead of send_message and pass view=view into it

lost lodge
# cyan quail define the view above the callback, do `edit_message` instead of `send_message` ...
Traceback (most recent call last):
  File "Development/Python/AKIRU/akiru-public/venv/lib/python3.10/site-packages/discord/ui/view.py", line 375, in _scheduled_task
    await item.callback(interaction)
  File "Development/Python/AKIRU/akiru-public/cogs/fun/fun-slash.py", line 110, in button_callback
    await interaction.response.edit_message(f"Hacking _**{member.name}**_ now.", view=view)
TypeError: InteractionResponse.edit_message() takes 1 positional argument but 2 positional arguments (and 1 keyword-only argument) were given```
#

error

cyan quail
#

ah change the text to content=f"..."

cinder pilot
lost lodge
cyan quail
#

your hacker text

lost lodge
cyan quail
# cinder pilot Still doesn't work

not sure then, your code i think looks fine?
maybe you could try typehinting but it shouldn't change anything

journey(ctx, from_stop: discord.Option(str, "From stop", autocomplete=stop_searcher), ...)``` and so on
cyan quail
#

i.e. edit_message(content="Hacking...", view=view)

lost lodge
#

ah

#

works thank you so much

cyan quail
#

allgood

cinder pilot
#

Why doesn't it work with decorator?

#

Bug?

fervent cradle
#

ok i need help

#
class botinfoButton(discord.ui.View): 
    @discord.ui.button(label = "Bot Stats", style = discord.ButtonStyle.primary)
    async def button_callback(self, button, interaction):
        statsembed = discord.Embed(
                 title = "Bot Stats",
                 description = "Here are my currect stats",
                 color = 0x717ac9
        )
        statsembed.add_field(name = "Servers", value = f"`{len(bot.guilds)}`", inline = True)
        statsembed.add_field(name = "Members", value = f"`{sum([len(guild.members)])}`", inline = True)
        statsembed.set_thumbnail(url=str(self.bot.user.display_avatar.url))
        await interaction.response.send_message(embed = statsembed) 

how do i define bot in this..

cyan quail
#

I have no clue lol, people have troubles with decorator more often than they should... maybe I'll check it out but it shouldn't be failing

lost lodge
#

is it possible to make to interaction responses?

cyan quail
fervent cradle
#

ok

cyan quail
lost lodge
# cyan quail Wdym make
            await interaction.response.edit_message(content=f"Do you really want to hack {member.name}", view=view)
            hack = await interaction.response.send_message(content=f"Hacking _**{member.name}**_ now.")```
cyan quail
#

Uhhhhhw

#

So a confirmation?

lost lodge
#

no

#

so the code we made last had the problem that the button message got edited but in wannted that a second message will get eddited but i would like it that a new message says hacking now...

cyan quail
#

Don't you already have that

#

Your ip variable

#

Just change the first message then add another edit

fervent cradle
#
from datetime import timedelta
import discord
from discord.ui import *
from discord import Option
from core import bd, lib, embeds
from loguru import logger
import asyncio


b = bd.HFD
logger.add("./main.log", rotation="500 MB")
bt = b.open(self=b)

ban_link = ["", ""]

class Bot(discord.Bot):
    def __init__(self):
        super().__init__()
        intents = discord.Intents.all()
        intents.message_content = True
        intents.members = True
        intents.presences = True
        self.persistent_views_added = False
    
    async def on_ready(self):
        if not self.persistent_views_added:
            self.add_view(view=PersistentView())
            self.add_view(view=RolesUs())
            self.add_view(view=RolesCst())
            self.add_view(view=RolesBot())
            self.persistent_views_added = True

        print(f"Logged in as {self.user} (ID: {self.user.id})")
        print("------")

bot = Bot()
@bot.event
async def on_message(message):
    if any([link in message.content.lower() for link in ban_link]):
        await message.delete()
        

@bot.event
async def on_member_join(member):
    print('1')
    rj = member.guild.get_role(863696255224643605)
    await member.add_roles(rj)

@bot.event
async def on_member_remove(member):
    
    member.send('):')

What can i make wrong?

Bot doesn't see member and message content

cyan quail
#

You defined the intents but you never actually applied them

fervent cradle
#

bot = Bot(intents=intents)

cyan quail
#

Yeah

fervent cradle
#
  File "/Volumes/Danya disk/coding/Py-cord/HFD/main.py", line 38, in <module>
    bot = Bot(intents=intents)
TypeError: Bot.__init__() got an unexpected keyword argument 'intents'```
cyan quail
#

Ah it's because your init isn't accepting any kwargs

#

Instead of in the bot call, you can do it in the super

cinder pilot
cyan quail
#

Ahh

fervent cradle
cyan quail
#

Come to think of it, where did you even get value from?

cinder pilot
cyan quail
fervent cradle
cyan quail
#

...inside super.init

cinder pilot
cyan quail
#

Rip

#

Well if it works

cinder pilot
fervent cradle
#

right?

cinder pilot
marsh mesa
#

and also self.intents.members = True
I think

fervent cradle
#

Thanks

cyan quail
#

no if you have intents.all, that's literally all

cinder pilot
marsh mesa
#

Yeah, I know. But if you do define them like that (eg. with .default()),,then it would need to be with self, no?

#

Actually, nvm

cyan quail
#

well yeah if you're using default it isn't included

marsh mesa
#

Yeah, I was just aiming at the fact that right there, the intents is local

#

Anyway, doing it like that is fine

fervent cradle
#

But on_message doesn't work

@bot.event
async def on_message(message):
    for link in ban_link:
        if link in message.content:
            await message.delete()```

Bot doesn't read message.content
full basin
#

?tag idk

obtuse juncoBOT
#

dynoError No tag idk found.

full basin
#

?tag idw

obtuse juncoBOT
#

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

gilded niche
#

How can i check if a channel is empty??

marsh mesa
marsh mesa
gilded niche
fresh gust
pallid trench
#

docs exist

fresh gust
#

OKAY!

#

ill do that

pallid trench
#

you basically just have to write a function that returns a cooldown object

fresh gust
#

aight
thanks!

marsh mesa
#

Most welcome

fresh gust
#

could you tell me how to trigger the cooldown?

ive never actually figured out how to call async funcs

#

do i just call it? like you do a normal function?

#

okay i actually need a bit of help
i cant make sense of the docs 😦

fervent cradle
#

in change_presence
await self.ws.change_presence(activity=activity, status=status_str)
AttributeError: 'NoneType' object has no attribute 'change_presence'

#

How to get total members from every server combined..

fervent cradle
lost lodge
#

hey

#

my prefixed commands don't work anymore

#

but slash commands work

marsh mesa
#

Probably you don't have the message_content intent enabled in code / dev portal

fervent cradle
#

Cool

lost lodge
fervent cradle
#

My code is setting presence

#

With client.change_prdense

lost lodge
marsh mesa
fervent cradle
lost lodge
marsh mesa
# lost lodge yes

Can you create a thread and paste your code so we can take a look?

marsh mesa
#

If those intents are set up correctly, it will be a more complicated issue 😄

daring tendon
#

How do I edit messages from slash commands, ctx.edit doesn't work for me

cyan quail
#

you mean the original response message? ctx.edit should work fine...

marsh mesa
cyan quail
#

yeah that's the shortcut for it

daring tendon
#

works thx

lost lodge
#

is it possible to stop commands stop working (maintenance mode)

cyan quail
#

well

#

for message commands, you could just have a check in your on_message

lost lodge
#

and slash commands?

cyan quail
#

for slash commands you could have a check at the start of each command, or maybe use before invoke across cogs... hmmm

cyan quail
#

i mean you already overrode on message

#

just have an if/else there

marsh mesa
#

Couldn't you unload the cog in maintenance?

fervent cradle
#
        perms = {
                guild.default_role: discord.PermissionOverwrite(view_channel=False),
                # team_role: discord.PermissionOverwrite(view_channel=True),
                # supporter_role: discord.PermissionOverwrite(view_channel=True),
                interaction.user: discord.PermissionOverwrite(view_channel=True),
                user: discord.PermissionOverwrite(send_messages=True),
                user: discord.PermissionOverwrite(attach_files=True),
                user: discord.PermissionOverwrite(embed_links=True),
            }
        support_channel = await guild.create_text_channel(name=f"{user.id}", overwrites=perms)```

Want to create a channel wich only the user that clicked the button can see but it does not work
lost lodge
cyan quail
#

you should use a single PermissionOverwrite object for all three permissions

fervent cradle
#

Oh ok

lost lodge
fervent cradle
cyan quail
#

just pass all of them into the same object

fervent cradle
#

This gives me an error

marsh mesa
#

you create several permission overwrites

#

add them as parameters to the first

#

discord.PermissionOverwrite(embed_links=True, attach_files=True, ..... ),

fervent cradle
#

Oh Ok

fervent cradle
#

How does it have anything to do with knowing basic python

#

I literally send you what you were looking for

lost lodge
#

is it like that:

bot.unload_extension("music")```
marsh mesa
#

Yeah, if your cog is "music"

#

and not for example "cogs.music"

lost lodge
#

ah

marsh mesa
#

Actually, I think it is "bot.cogs.music" anyway

serene spindle
#

does the "on_member_join" function work?

marsh mesa
marsh mesa
lost lodge
woeful spindle
#

how do i get the author name & discriminator while in an interaction? i can’t use the ctx param so that won’t work? my only params are self, select, and interaction

serene spindle
# marsh mesa Yes, but it's an event

well this is how my code is looking, but it's not working, what am I doing wrong?

@bot.event
async def on_member_join(member):
    channel = bot.get_channel(965600413376200726)
    emb = discord.Embed(title=f"Welcome {member.mention} to ClearFly", description=f"Read the #965610363842351144 to become a member and gain full access to the server. Thanks for joining!", color = 0x57a4cd)
    await channel.send(embed=emb)
cyan quail
#

do you have the members intent

serene spindle
#

if that's this line of code, yes

intents.members = True
cyan quail
#

and on the dev portal im assuming

serene spindle
#

the server one, yes

#

all of them actually

cyan quail
#

or just checking, you definitely passed intents=... into your bot creation right

fervent cradle
#
await client.change_presence(activity=discord.Game(name=f"in {len(client.guilds)}"))```AttributeError: 'NoneType' object has no attribute 'change_presence'
cyan quail
#

when you defined your bot

#

you have to pass intents into that

serene spindle
#

I think I was using the wrong defined line, let me try

marsh mesa
fervent cradle
#

intents = discord.Intents.all()
client = commands.Bot(command_prefix="?", intents=intents)

fervent cradle
#

gives u the user object of the author

woeful spindle
#

ty

fervent cradle
#

so interaction.user.discriminator

woeful spindle
#

interaction.user works alone aha

#

it gives both

#

in the format User#Discrim

#

which is what I was looking for

full basin
serene spindle
marsh mesa
#

Happy to hear!

fresh gust
marsh mesa
fresh gust
cyan quail
#

i don't think there's an easy way to just trigger the cooldown without actually running into it

fervent cradle
#
msg = await ctx.respond()
await msg.edit()``` why doesnt this work?
cyan quail
#

because respond returns an interactionresponse

fervent cradle
#

what code should i put if i want to edit after response then

fresh gust
cyan quail
#

im saying there isn't a method to trigger it

fresh gust
#

oh

fervent cradle
#

yo\

#

how to get the user id of the guy who clicked the button

cyan quail
#

interaction.user

#

.id

fervent cradle
#

or should i do

fervent cradle
# cyan quail .id

ok i knew that, then how to get id of the guy who used the slash command

#

msg.edit_original_message

cyan quail
fervent cradle
cyan quail
#

oh

fervent cradle
#

y e s

fresh gust
# cyan quail im saying there isn't a method to trigger it

what im trying to do is create a dynamic countdown for a currency cog

for example, if a user tries to display someone else's money, and the second user doesnt exist, i dont want the cooldown to trigger

how would i fix that?

the @commands.cooldown(rate = 1, per = 30, type=commands.BucketType.user) wrapper triggers the cooldown no matter the outcome of sending a command

i want the cooldown to be more conditional

cyan quail
#

then subclass the button and add a new argument to the init so you can access it

fervent cradle
#

example..pls..

cyan quail
fresh gust
fervent cradle
#

mongo db

#
  • datetime.
cyan quail
#

when a user uses the command, store the current unix timestamp they used in a db or other file, then on every command run compare that time to the cooldown you want

fervent cradle
#

exactly

#

now nelo pls help me before i die

fresh gust
#

ouuu okay
lots of learning coming up 💀

fervent cradle
cyan quail
fervent cradle
#

i mean

#

yes

#
if interaction.user.id != button.user.id:
            await interaction.response.send_message("You cant use these buttons", ephemeral = True) ```
#

im basically tring to do this

cyan quail
#

show me your whole button code

fervent cradle
#

ok

#
class botinfoButton(discord.ui.View): 
    @discord.ui.button(label = "Bot Stats", style = discord.ButtonStyle.primary)
    async def button_callback(self, button, interaction):
        if interaction.user.id != button.user.id:
            await interaction.response.send_message("You cant use these buttons", ephemeral = True) 
        statsembed = discord.Embed(
                 title = "Bot Stats",
                 description = "Here are my currect stats",
                 color = 0x717ac9
        )
        statsembed.add_field(name = "Servers", value = f"`{len(interaction.client.guilds)}`", inline = True)
        statsembed.add_field(name = "Members", value = f"`{sum([len(interaction.guild.members)])}`", inline = True)
        statsembed.set_thumbnail(url=str(interaction.client.user.display_avatar.url))
        await interaction.response.send_message(embed = statsembed) ```
fresh gust
#

            def __init__(self, ctx)
                self.ctx = ctx```
fervent cradle
#

dies

fresh gust
#

does this help?

fervent cradle
#

yes

#

tysm

fresh gust
#

no worries 😄

fervent cradle
#

i totally forgor that exists

fresh gust
fervent cradle
#

buttons are very complicated in discord.js

woeful spindle
#

So I have this "rate" command, but how do I make it so the mentions actually work?

cyan quail
#

yeah you basically just need the init, then you can create more arguments to pass in

fresh gust
fervent cradle
#

dies

woeful spindle
woeful spindle
fresh gust
woeful spindle
woeful spindle
# full basin code
@commands.command()
    async def rate(self, ctx, *, thing: commands.clean_content):
        """ Rates what you desire """
        rate_amount = random.uniform(0.0, 100.0)
        if thing == "chaze":
            await ctx.send("instant 110/100 :heart:")
        elif thing.lower() == "malachi":
            await ctx.send("i'd rate him a 69/100")
        elif thing.lower() == "arie":
            await ctx.send("arie is a 0/100 bozo, L")
        else:
            await ctx.send(f"I personally decide to rate **{thing}** a **{round(rate_amount, 2)} / 100** :CL_WorryShrug:")
fresh gust
#

send the code, maybe?
I dont really understand what you mean

fresh gust
full basin
#

Why dont you use a member objct

woeful spindle
fresh gust
#

i wouldve added member to the params
and then used member.mention to mention the user

full basin
#

and make the checks adecuate for that, giving you also the option to mention the user

fresh gust
#

exactly

fervent cradle
#
class botinfoButton(discord.ui.View):
    @discord.ui.button(label = "Bot Stats", style = discord.ButtonStyle.primary)
    async def button_callback(self, button, interaction):
        def __init__(self, ctx):
            self.ctx = ctx
        if interaction.user.id != self.ctx.user.id:
            await interaction.response.send_message("You cant use these buttons", ephemeral = True) 
        statsembed = discord.Embed(
                 title = "Bot Stats",
                 description = "Here are my currect stats",
                 color = 0x717ac9
        )
        statsembed.add_field(name = "Servers", value = f"`{len(interaction.client.guilds)}`", inline = True)
        statsembed.add_field(name = "Members", value = f"`{sum([len(interaction.guild.members)])}`", inline = True)
        statsembed.set_thumbnail(url=str(interaction.client.user.display_avatar.url))
        await interaction.response.send_message(embed = statsembed) 

is this correct the self.ctx

woeful spindle
fresh gust
fervent cradle
#

AttributeError: 'botinfoButton' object has no attribute 'ctx'

full basin
fervent cradle
#

?

woeful spindle
full basin
# fervent cradle ?
async def interaction_check(interaction):
    if interaction.user != self.user:
        await interaction.response.send_message("You cant use this")
        return False
    return True```

And pass user after creating the class

view = MyView()
view.user = ctx.author
fresh gust
full basin
#

you could also do it in the callback itself

#

but whatever you decide

fresh gust
rare ice
fresh gust
fervent cradle
#

SO INTERACTION_CHECK IS PRO?

fresh gust
full basin
#

its not unnecessary lmao. it is doing checks right

fresh gust
fervent cradle
fresh gust
fervent cradle
#

OK

#

ok error

#
Ignoring exception in view <botinfoButton timeout=180.0 children=1> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='Bot Stats' emoji=None row=None>:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/ui/view.py", line 367, in _scheduled_task
    allow = await self.interaction_check(interaction)
TypeError: 'Button' object is not callable```
fresh gust
#

                        def __init__(self, ctx):
                            super().__init__(timeout = 10)
                            self.ctx = ctx

                        async def interaction_check(self, interaction):
                            if interaction.user != self.ctx.author:
                                embED = Embed(description= 'Hey! Those buttons aren\'t for you >:(', color= discord.Color.random())
                                await interaction.response.send_message(embed = embED, ephemeral= True)
                                return False #you dont need this
                            else:
                                return True #or this (i copypasted my own code)
fervent cradle
#

OK

fresh gust
full basin
fresh gust
fervent cradle
#
    async def interaction_check(interaction):
        if interaction.user != self.ctx.author:
            await interaction.response.send_message("You cant use these buttons", ephemeral = True)
            return False
        return True```
#

is this cool

#

i have py def __init__(self, ctx): super().__init__(timeout = 10) self.ctx = ctx above of it

#

note: im removing timeout

fresh gust
pallid trench
fervent cradle
#

do i put it on above or below py @discord.ui.button(label = "Bot Stats", style = discord.ButtonStyle.primary)

fresh gust
fervent cradle
#

ok!

#
class botinfoButton(discord.ui.View):
    @discord.ui.button(label = "Bot Stats", style = discord.ButtonStyle.primary)
    def __init__(self, ctx):
        self.ctx = ctx
    async def interaction_check(interaction):
        if interaction.user != self.ctx.author:
            await interaction.response.send_message("You cant use these buttons", ephemeral = True)
            return False
        return True```
correct?
fresh gust
#

no
the wrapper goes after the defs

fervent cradle
pallid trench
#

the interaction check has to be in the class

fervent cradle
#

IT IS A DAM CLASS

pallid trench
#

it has to be a child of the class

fervent cradle
#

I WILL DIE

pallid trench
#

which it is

#

pardon me

fresh gust
#

how about you dm me

fervent cradle
fresh gust
#

ill send you the way i did it

fervent cradle
#

o k

rare ice
#

#help-rules rule 1

fervent cradle
#

ok!!!!!!!!!

fluid crystal
#

How i cane report a pycord bug?

shrewd dome
#

on the github

serene spindle
#

how do you make a slash command only work for a specific role?

rare ice
#

If the author doesn’t have the role it will error

serene spindle
amber shale
#

my slash command is not working but text command is working while using bridge command

#

dont know what is the problem here 😦

silver moat
amber shale
#

yeah

silver moat
#

so the slash command is not appearing or what?

amber shale
#

yes

#

slash command command not appearing

silver moat
#

where are you loading your cog?

amber shale
#

in a Bot class

silver moat
#

and where is that called?

amber shale
#

sorry i dont know how could i share the code (github is having discord.py code)

silver moat
#

I don't see where you load the cogs

amber shale
silver moat
#

ok

amber shale
#

just expand no need to download 🙂

silver moat
#

slash commands sync in on_connect which occurs before on_ready

#

you load the cogs in on_ready so the commands are not synced

amber shale
#

oh 🤦

young bone
wicked helm
#

I know I can prevent a non admin from using a command - but can I set a command to be visible to admins only? Or do I have to do that through discord..

vital blade
#

im trying to check in "on_message" event if the user has manage server permission but i get this error

wicked helm
vital blade
#

so it would be return if the person has the permission

silver moat
vital blade
#

same error tons of times

silver moat
#

yeah, so message.author can return a discord.User or a discord.Member

vital blade
#

on dm it returns discord.User?

silver moat
#

you can check it with

if isinstance(message.author, discord.User):
  pass
silver moat
vital blade
#

oh

#

if i do like

if (not message.guild):
 return

its okay?

silver moat
#

that works

#

so you want it to be in a DM?

vital blade
silver moat
#
if (not None):
    return
#

that looks like you want it to be in a DM, right?

#

oh nvm I'm just stupid

vital blade
#

but i dont want admin's message to be deleted

#

i tried it and still get the same error

vital blade
silver moat
#

yw

worldly schooner
#

Can someone explain to me what are clusters and shards?

#

Or give me something like a tutorial vid

round rivet
lone quail
#

How can I get my config file from the main file in a cog? I need the guild ID for the slash command decorator?

#

@discord.slash_command(guild_ids=[config["guild_ID"]], description="Times out a member") I need config in here

silver moat
#

so your file structure is something like:

main.py
config.json
cogs folder
- cog1
- cog2
```?
lone quail
#

yep

#

i use yml for config but the same applies

silver moat
#

so how do you access config from main.py?

lone quail
#

I haven't got that far yet xD

silver moat
#

what python yaml lib are you using?

lone quail
#

i didn't really want to copy the import code but if i have to i can

cinder pilot
#

Is it possible to make certain slash commands show up only for admins like eg (/ban) but other users wouldn't be able to see it

silver moat
lone quail
#

oh, i have all this...

def loadConfig():
    configFile = ""

    try:
        with open('config.yml', "r") as f:
            configFile = yaml.load(f, Loader=yaml.FullLoader)
    except:
        defaultConfig = open('defaultConfig.yml', "r")
        f = open('config.yml', 'w')
        f.write(defaultConfig.read())
    finally:
        with open('config.yml', "r") as f:
            configFile = yaml.load(f, Loader=yaml.FullLoader)
    
    return configFile
#

ah, that's because of the default config

#

i copied it from an old project blindly

silver moat
cinder pilot
#

This won't work if you want only users with specific roles to be able to see right?

silver moat
cinder pilot
#

thanks for your help

silver moat
#

np

fervent cradle
#

Why i've got this error

discord.errors.Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user

fervent cradle
#

):