#Basic Pycord Help (Quick Questions Only)

1 messages · Page 75 of 1

solemn idol
#

Organizable Code ig...

regal agate
#

are json files bad for realtime data?

candid coral
#

It is in the class of buttons

regal agate
#

oooohhh

#

but like the question

#

can i use a json file or not?

neon bramble
#

what are you storing

#

you probably want to use something like sqlite

regal agate
#

its just static data

neon bramble
#

then sure

candid coral
regal agate
#

im defining static as being made and barely changing

#

idk if i should

neon bramble
neon bramble
neon bramble
#

once you have the message you can just get the message author's id

candid coral
#

Can I find out an author of the message inside this function?

full basin
#

You pass the author to the view

#

This is why you should know python basics

#

#help-rules

candid coral
#

When learning Python I didn't meet it

full basin
#

Then learn about classes now.

#

Because pycord is an oop library

#

You deal with classes at all times

neon bramble
full basin
#

itd be the bot

#

self.message in a view is the message the view is in

cyan quail
#

you should override __init__ to allow yourself to pass in your own arguments and access them from the view

neon bramble
cyan quail
#

e.g. in the link example @ https://github.com/Pycord-Development/pycord/blob/master/examples/views/link.py, they've made it so you can call this view with a url py class Google(discord.ui.View): def __init__(self, query: str): super().__init__() # We need to quote the query string to make a valid url. Discord will raise an error if it isn't valid. self.query = quote_plus(query) ... await ctx.respond(view=Google(query))

neon bramble
#

probably wanna make it self.query here since you're accessing it from on_timeout

cyan quail
#

indeed

candid coral
#

Thank you for your patience, The Nelo, kaede, dark and free. I realized what I need to improve, so I will learn the classes in a few days

rare ice
#

Error:

Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/ui/view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "/home/container/cogs/ads.py", line 32, in appeal_button_callback
    await interaction.response.send_modal(modal)
  File "/home/container/.local/lib/python3.9/site-packages/discord/interactions.py", line 1056, in send_modal
    await self._locked_response(
  File "/home/container/.local/lib/python3.9/site-packages/discord/interactions.py", line 1090, in _locked_response
    await coro
  File "/home/container/.local/lib/python3.9/site-packages/discord/webhook/async_.py", line 217, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.1: The specified component exceeds the maximum width

Code causing the error: ```py
# in a button callback
modal = BasicModal(title='Warning Appeal', children=[discord.ui.InputText(style=discord.InputTextStyle.long, label="Appealing reason", placeholder="Why are you appealing?"), discord.ui.InputText(style=discord.InputTextStyle.long, label="Your Advertisement", placeholder="Provide what you sent", min_length=200)])
await interaction.response.send_modal(modal)

**BasicModal** code
```py
class BasicModal(discord.ui.Modal):
  def __init__(self, title: str, children: list):
    super().__init__(title=title)
    for child in children:
      self.add_item(child)
    self.interaction = None
    self.response = None
  async def callback(self, interaction):
    self.interaction = interaction
    self.response = self.children
    self.stop()```
copper pine
#

Hello, does anyone know how I can retrieve this Spotify activity status information using PyCord?

cyan quail
worn void
#

with my on_message cog I want to reply to the message if it contains something, but I also want it to be an ephemeral?

    @commands.Cog.listener()
    async def on_message(self, message):
      if item in message.content:
        await reply_to_message(reply, ephemeral=True)          
      await self.bot.process_commands(message)
#

how do I do this?

silver moat
#

ephemeral messages can only be used as a response to interactions

full basin
#

Your function makes no sense

light kettle
#

I'm new to all of this so that' sprobably accurate

full basin
#

Something must be the trigger to send the message

#

You can't just fly a message without telling it

#

Unless you wanna do it on startup or something

light kettle
#

I was hoping I could trigger a function to send an embedded message to a channel once incoming data was received from another app.

full basin
#

Uh well

#

That's a thing

#

How do you recive that data

light kettle
full basin
#

I mean

#

Wherre does it come from

#

Some http request? Or idk

light kettle
full basin
#

I assume you're using some app that listen to your domain and the request and bla bla bla stuff

#

I think you might need ipc

#

?tag ipc

obtuse juncoBOT
#

dynoError No tag ipc found.

full basin
#

Ig it still works

light kettle
full basin
#

Np

spice oyster
#

Hi! Do you have a migration guide for the upcoming Discord nickname change?

cyan quail
#

main things to look out for:

  • Avoid using User.discriminator
  • Avoid using ClientUser.edit
    apart from that we don't know any other changes
spice oyster
#

Thanks!

fervent cradle
#

Is it a good idea to handle the exceptions that occour withing a commands using try and except or use the on_error handler?

proud mason
#

on_command_error would be a better approach as it handles errors from all commands

#

on_application_command_error for app cmds

fervent cradle
#
    @commands.hybrid_command(name="verify", with_app_command=True)
    async def verify(self, ctx: commands.Context, game_name: str):
        try:
            obj = User()
            await obj.set_client()
            found = await obj._User__find_username(username = game_name)
            if found:
                await ctx.send(found, ephemeral=False)
            else:
                await ctx.send("Not Found", ephemeral=False)
        except Exception as error:
            # await ctx.send("An error occoured" + str(error))
            self.logger.log_error(class_name="testing", function_name="verify", message=str(error))
            raise Exception(error)

is this a good idea or a super bad one?
the part in except

#

self.logger is a logger i made myself so should i intrupt the flow like this or use the logger in the on_error handlers

full basin
#

That doesn't look like pycord

fervent cradle
#

it is

#
from discord.ext import commands
from discord.ui import TextInput, View, Button, Select
from database.User import User
from Logs import logevents

class testing(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.logger = logevents()
    
    @commands.hybrid_command(name="verify", with_app_command=True)
    async def verify(self, ctx: commands.Context, game_name: str):
        try:
            obj = User()
            await obj.set_client()
            found = await obj._User__find_username(username = game_name)
            if found:
                await ctx.send(found, ephemeral=False)
            else:
                await ctx.send("Not Found", ephemeral=False)
        except Exception as error:
            # await ctx.send("An error occoured" + str(error))
            self.logger.log_error(class_name="testing", function_name="verify", message=str(error))
            raise Exception(error)

async def setup(bot):
    await bot.add_cog(testing(bot))
#

whole file

full basin
#

We don't have hybrid_command

#

We have bridge_commands

valid spruce
#

How to fix this question?

proud mason
weak violet
#

Hi, im having an issue with this if someone can help me 🙂

The turn on and execute commands but its always display this error, and something doesnt register the news slash commands

Traceback (most recent call last):
  File "C:\Users\deadz\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 352, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\deadz\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 793, in on_connect
    await self.register_commands()
  File "C:\Users\deadz\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 460, in register_commands
    await self.http.bulk_upsert_command_permissions(
  File "C:\Users\deadz\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 338, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 405 Method Not Allowed (error code: 0): 405: Method Not Allowed```
patent knoll
weak violet
patent knoll
#

well the get thread is underlined which is usually not good

proud mason
#

They should be an int

weak violet
proud mason
#

Also check if you have app cmd scope in all of them

fervent cradle
#

wait did i, lemme check

proud mason
valid spruce
proud mason
valid spruce
#

But panel can’t start

full basin
valid spruce
#

Host panel

full basin
#

Don't tell me you're using replit

valid spruce
#

No

valid spruce
sand beacon
#

do i have to nest classes to have a button inside a cog?

proud mason
fervent cradle
#
bot = bridge.Bot(command_prefix="$", help_command=None, strip_after_prefix=True, intents=discord.Intents.all())

@bot.event
async def on_ready():
    obj = logevents()
    await obj.log_restart()
    await bot.tree.sync()
    print("Ready for code execution")

Error :

  File "main.py", line 23, in on_ready
    await bot.tree.sync()
AttributeError: 'Bot' object has no attribute 'tree'

Earlier i was using commands.bot but since i wanted to use hybrid commands thought to use bridge.bot() but this
and if i cant use bot.tree.sync() then what is to be used to sync application commands?

patent knoll
#

i am converting a bridge-command to a slash-only bot, how exactly do i need to change this?

proud mason
patent knoll
#

and how is this different from just messages? or am i remembering wrong

proud mason
patent knoll
#

ah yes

patent knoll
proud mason
proud mason
#

so use commands.Bot

#

prefix could be when_mentioned

#

.rtfm when_mentioned

winter condorBOT
proud mason
#

but you would need the messages intent

weak violet
round rivet
#

view channel is required to do literally anything with a channel

weak violet
jaunty lantern
#

how is that possible that bot has slash commands on one guild and doesn't on another? yes, I used same invite link for both guilds and i don't limit slash commands with guild ids

jaunty lantern
#

i don't think i do

proud mason
jaunty lantern
#

in the one commands work in, 5?
in the one i try to sync commands with, 25+... that explains it i guess

proud mason
#

.slashnoshow

winter condorBOT
#

Checklist for Application Commands Not Showing Up:
• Does your bot have the application.commands scope?
• Are you loading cogs before on_ready and on_connect?
• Is on_connect not overridden?
• Did you update to the newest version of py-cord (tag: install)?
• Is User Settings > Accessibility > Chat Input > Use legacy chat input turned off?
• Did you share your code and errors?
• Do you still have libraries that conflict with the discord namespace (e.g. discord.py)?

proud mason
#

check those

lethal nexus
#

Am I able to separate my commands and functions into different files without using cogs?

soft girder
#

I wrote a code to constantly update the message. But I need this code to work constantly after the bot is restarted.

#
class TlB(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
    @discord.ui.button( label="Update",custom_id="button-  
3",emoji="🔄",style=discord.ButtonStyle.primary,row=3)
      async def second_button_callback(self, button: discord.ui.Button, interaction):
        #
        if interaction.user.guild_permissions.administrator==True:
            await interaction.response.defer()
            while (1):#<------------------------------------------------------------------------------
                guild = interaction.guild_id

                data1=f"..."

                cursor.execute(data1)
                item2 = cursor.fetchmany(4)
                db.commit()
                b = ""
                i = 0
                for el in item2:
                    i+=1
                    b += f"**{i}**.{el[5]}__{el[1]}__ | {el[2]} | <@{el[3]}>\n"

                data2=f"...."

                cursor.execute(data2)
                item = cursor.fetchmany(28)
                db.commit()

                a = ""
                f=4
                for el in item:
                    f+=1
                    if 4<f<17:
                        a += f"**{f}**.{el[5]}__{el[1]}__ | {el[2]} | <@{el[3]}>\n"    
                    if f>16:
                        a += f"Res.🔴**{f}**.{el[5]}__{el[1]}__  | {el[2]}  | <@{el[3]}>\n"

                await interaction.edit_original_response(content=f":scroll: __**TEAM LIST**__ :scroll: \n**🕐Time: 21:00 Moscow **\n \n{b}{a}\n \n``•To confirm participation, click on :white_check_mark:\n•1-4 vip slots.``")
        else:
            await interaction.response.defer()
            await interaction.followup.send("Only Admin button",ephemeral=True)
#

The class itself is already restarting. But how to make the loop "while "reload automatically instead of on button click

lethal nexus
proud mason
agile dust
#

hi, how do i get the server name when an interaction (button) was clicked? interaction.guild does not work

soft girder
#

@proud mason Are you suggesting to start a cycle "while" on reboot using a database?

#

I explain more simply. How to make it so that while cycle ,which will run when the bot is restarted.

proud mason
#

But be aware that on_ready can be fired multiple times

#

Use @client.listen(once=True) if you are on master branch

lethal nexus
proud mason
#

I think the docs tell you how to do that

lethal nexus
#

Ahhhh

#

and I guess the name of the extension is whatever the file is (except the .py)

#

is there any way to stuff all the extension files in a folder?

agile dust
agile dust
#

it just crashed, not even an error message

#

weird

proud mason
proud mason
#

First time I've heard that

#

Can you show the pip list

#

And python version

lethal nexus
lethal nexus
#

ah wait, this is what i should be reading isn't it

#

So like? bot.load_extension('foldername.hello')

proud mason
lethal nexus
proud mason
proud mason
lethal nexus
#

what does recursive do?

proud mason
#

Loads all extensions from folders and subfolders

#

No need to hardcode each one

soft girder
#

Let's take the path of least resistance.

lethal nexus
proud mason
#

Yes

soft girder
#

How to make a button that, when pressed once, will turn on (for example, auto-update), and turn it off again. You can just throw the code if it's hard to explain.

#

.rtfm button_role

winter condorBOT
#

Target not found, try again and make sure to check your spelling.

lethal nexus
errant craneBOT
#

Here's the reaction roles example.

agile dust
zealous kelp
#

I have question i want to create a bot with the function to banning members ,if they use bad words. but it's don't work and i don't have any idea, how can i fix this problem.

lethal nexus
#

@proud mason how am I able to "import" a python function rather than a command?

zealous kelp
#

ich will meinen Eigenen haben

vast sun
#

P3evilsmile 🇩🇪

young bone
#

you also need the intents for messages

zealous kelp
#

It's also not working

young bone
zealous kelp
#

I know the basic

lethal nexus
#

How can I do that?

cyan quail
#

that's why we have cogs

#

or, make it so your function accepts the bot object as an argument

plain cove
#

Hello how would I make a prefix code for my discord bot? new to coding

cyan quail
#

just add it to your function args

plain cove
lethal nexus
lethal nexus
plain cove
plain cove
# cyan quail can you elaborate?

so i'm trying to make a prefix to where when it use the bot will like say it back. For example, if i type "!dad", my bot would response back with "searching for your dad". The prefix would be "!" but I don't know how to define a prefix or to even to get it work.

cyan quail
lyric parrot
#

why are errors still being thrown after i catched them in on_application_command_error()?

this is only in master branch, it's not like that in 2.4.1

#

did anything change that is not in the changelog?

cyan quail
#

probably not

lyric parrot
#

is this intended or should i create a github issue for that?

cyan quail
cyan quail
minor monolith
#

how can i make a command which doesnt require positional argument

cyan quail
#

oh wait

lyric parrot
# cyan quail could you elaborate more on what's happening
    @slash_command()
    @commands.check(test)
    async def hey(self, ctx):
        await ctx.respond("Hey")

    @commands.Cog.listener()
    async def on_application_command_error(self, ctx, error):
        if isinstance(error, discord.CheckFailure):
            await ctx.respond(f"Test!")
            return

so basically, in 2.4.1 only "test" is responded, but in master branch an error is thrown like in the screenshot

cyan quail
#

ok yeah that might have been an accidental change

#

let's see...

cyan quail
# lyric parrot ```py @slash_command() @commands.check(test) async def hey(self, ctx...

in /discord/bot.py (click the first blue link in your traceback) inside on_application_command_error, can you try adding this line https://github.com/pycord-development/pycord/blob/master/discord/bot.py#L1168 py if self._event_handlers.get("on_application_command_error", None): returnwhile you SHOULD be registering it as a cog error handler, it doesn't change the fact that this functionality was removed without warning

#

if that fix works then i'll make a pr for it

lyric parrot
cyan quail
#

nice

candid coral
#

Is it worth "global" and "nonlocal"?

cyan quail
#

i'd... heavily avoid using those

candid coral
#

Articles say so too

cyan quail
#

you can, i just wouldn't recommend it; it's not a great practice, and it'll cause you headaches down the line

candid coral
#

I understand that "self" is just the name of the first argument?

cyan quail
#

self is the instance of the current class

candid coral
#

Can there be only one "__init__" in a class?

cyan quail
patent knoll
#

function overloading b like

cyan quail
#

I was considering mentioning overloads but most people don't need it

fervent cradle
#

Is ctx.author.public_flags a correct form of getting the user flags?

#

Im having trouble getting them and im not sure if im doing it right

#

Nevermind i fix it,

Using user_flags = ctx.author.public_flags.all()

frail spade
#

how?

proud mason
#

.guide

winter condorBOT
novel yacht
#

Traceback (most recent call last):
File "C:\Users\misha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "C:\Users\misha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\bot.py", line 1164, in on_connect
await self.sync_commands()
File "C:\Users\misha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\bot.py", line 719, in sync_commands
registered_commands = await self.register_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\misha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\bot.py", line 599, in register_commands
registered = await register("bulk", data, _log=False)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\misha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\http.py", line 371, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In options.2: Required options must be placed before non-required options
Mikis#6365 is ready and online!

trying set send webhook

frail spade
coarse spire
#

seems like you have discord.py installed maybe, instead of pycord

frail spade
#

oh

coarse spire
#

and also, never share your token with anyone. Make sure to reset it now

frail spade
#

how to install pycord?

coarse spire
#

just do pip uninstall discord.py in the terminal, and then pip install py-cord

frail spade
#

ok

coarse spire
#

remove discord.py from requirements.txt if you have it in there, and replace it with py-cord

frail spade
#

hey

#

when i install pycord it says requirements alr satisfied

coarse spire
#

did you install py-cord, and not pycord?

frail spade
#

yes

#

py-cord

coarse spire
frail spade
#

no

coarse spire
#

ok, try to reinstall py-cord

frail spade
#

ok

#

in requirements.txt right

coarse spire
#

yeah, and if that doesn't work, try in the terminal

frail spade
#

not working

#

yet

#

getting this error token must be of type str, not NoneType

coarse spire
#

in your .env file, you need to do this:

DISCORD_TOKEN = your_token

and then in the code:


load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
bot.run(TOKEN)```
frail spade
#

alr

#

in your_token i have to put my bot token?

coarse spire
#

yep

frail spade
#

alr

#

hey

#

** [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992)')]**

frail spade
#

yes

proud mason
# frail spade yes

Go to Applications/Python 3.x and double click the Install Certificates files

#

3.x is your python version

frail spade
#

do uk which file name?

frail spade
#

ok

#

donep

#

problem solved ty

fervent cradle
#

In Main

bot = commands.Bot(command_prefix="$", help_command=None, strip_after_prefix=True, intents=discord.Intents.all())

Inside of cog

from discord.ext import commands, bridge

class testing(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
    
    @bridge.bridge_command(name="verify", aliases=['Verify', 'store', 'Store'], description="Command used to verify and add account to your discord username")
    async def verify(self, ctx: bridge.BridgeContext, game_name: str):
        #Some Logic

def setup(bot):
    bot.add_cog(testing(bot))

error
'cogs.testing' raised an error: AttributeError: 'Bot' object has no attribute 'bridge_commands'

#

can someone tell me whats wrong with this

coarse spire
#

you need to define the bot in main as bridge.Bot instead of commands.Bot

fervent cradle
#

ahhh okay

#

thank you

fervent cradle
#

Can a file have multiple cog classes?

coarse spire
fervent cradle
#

If somone has implemented bridge_commands in your bot, can you share their git repo's link?

I need to see some reference idk whats happening with my bot anymore

coarse spire
#

sure, I guess. one sec

#

otherwise, take a look at this:

errant craneBOT
#

Here's the bridge commands example.

green hinge
#

Is there a way to reload a cog while the bot is running without having to restart the entire bot to keep the systems running?

coarse spire
#

.rtfm reload_extension

green hinge
coarse spire
#

Yeah, so for example:

bot.reload_extension('cogs.example')```

(if you have a folder named "cogs" with the cog "example" in it)
green hinge
coarse spire
#

yeah. Everything will be reset then. And you could do:

@bot.command()
async def reload(ctx, cog):
  bot.reload_extension(f'cogs.{cog}')```

for example
green hinge
coarse spire
#

you would need to add the reload command to the main file

green hinge
#

Ah okay

proud mason
green hinge
#

Do I just have to enter the cog name !reload rules or e.g. !reload rules.py

coarse spire
#

just the cog name

green hinge
#

Ok

#

Why can't I respond to the message to send it ephemeral?

@bot.command()
async def reload(ctx, cog):
    bot.reload_extension(f'cogs.{cog}')
    await ctx.respond(f"Reloaded {cog}!", ephemeral=True)```
fervent cradle
#

This button should work after the is restarted right? But it's not working after restarting

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

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

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

    @discord.slash_command()
    async def button(self, ctx):
        await ctx.respond("This is a button!", view=MyView())
tribal girder
#

how to access bot_runtime variable?

"""main.py"""

bot_runtime = datetime.utcnow()

def loader():
    for extension in initial:
        bot.load_extension('cogs.utils')
        print(f'Loading Extension')

loader()

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name}'

"""utils.py"""

class Utility(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.process = psutil.Process()
        self.bot_runtime = bot_runtime

    @commands.command()
    async def uptime(self, ctx):
        delta = datetime.utcnow() - self.bot_runtime
fervent cradle
coarse spire
fervent cradle
#

in the cog?

coarse spire
fervent cradle
#
from discord.ext import bridge, commands

bot = bridge.Bot(command_prefix=commands.when_mentioned_or('$'), help_command=None, strip_after_prefix=True, intents=discord.Intents.all())

@bot.bridge_command()   
async def reload(ctx: bridge.BridgeContext, cog:str):
    if ctx.author.id in [782252708685414470]:
        try:
            bot.reload_extension(f"cogs.{cog}", package='BOTAPRILUPDATE.database')
            await ctx.reply(f"{cog} has been reloaded successfully",ephemeral=True)
        except Exception as e:
            obj = logevents()
            errorid = await obj.log_error(class_name="Main", function_name="ReloadCommand", message=str(e))
            print(f'An error occoured in the Main class wtihin the {cog} cog, check error logs with id {errorid} for more details')

This is my command in my main.py but for some reason its not getting synced with the server idk why

obtuse juncoBOT
#

Need to keep track of a variable between functions? No problem!

⚠️ Careful what you name it though, else you might overwrite something ⚠️

Just add it to your commands.Bot or discord.Client instance like so:

bot = commands.Bot(...)
bot.my_variable = 0

async def foo():
    bot.my_variable += 1

# In a cog
@commands.command()
async def counter(self,ctx):
    await ctx.send("Current Counter is at {}".format(ctx.bot.my_variable))

This also allows you to access this from other cogs/extensions/functions. Anywhere you have access to the bot instance

winter condorBOT
# fervent cradle ```python from discord.ext import bridge, commands bot = bridge.Bot(command_pre...

Checklist for Application Commands Not Showing Up:
• Does your bot have the application.commands scope?
• Are you loading cogs before on_ready and on_connect?
• Is on_connect not overridden?
• Did you update to the newest version of py-cord (tag: install)?
• Is User Settings > Accessibility > Chat Input > Use legacy chat input turned off?
• Did you share your code and errors?
• Do you still have libraries that conflict with the discord namespace (e.g. discord.py)?

fervent cradle
#

but will cogs loading of cogs affect the commands that are in the main file

proud mason
fervent cradle
fervent cradle
#

Can I use on_thread_join() event listener for forum?

full basin
#

.tag tias

winter condorBOT
fervent cradle
#

knew that i would get a response like that, but ok

soft girder
#

How will the new discord rules affect the work of bots.

#

Discriminators do not play an important role

patent knoll
silver moat
#

unless your bot for some reason depends on them

spring hare
#

(timecode)

young bone
#

isn't it really bad to use the names in the code if you have the user id?

patent knoll
#

If your bot uses discrims for anything you made your bot wrong

silver moat
young bone
#

I only use the user id

patent knoll
silver moat
#

displaying stuff like just a squid#2777

patent knoll
#

oh, yea

#

but that doesnt need much changing
change it to use the username and thats it, in outputs

spring hare
#

Mb add Deprecation message when using user.discriminator?

silver moat
#

#discussion

patent knoll
#

p sure everyone is aware lol

young bone
spring hare
#

oof

fervent cradle
#

I am trying to make a persistent button that deletes the response, it worked without any error before the bot was restarted, but after restarting it throws the following exception:

          ^^^^^^^^
NameError: name 'response' is not defined```
Code:
```py
# Imported necessary modules here

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

    @discord.ui.button(label="Delete", custom_id="delete", style=discord.ButtonStyle.red)
    async def callback(self, button, interaction):
        await response.delete()

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

    @commands.Cog.listener()
    async def on_ready(self):
        self.bot.add_view(deleteButton())

    @commands.message_command(name="Translate Message")
    async def translate_message_context(self, ctx, message: discord.Message):
        [...] # Some code here that doesn't matter for this question
        result = discord.Embed(
            title = f"Translated from {source_language}",
            color = 0x4BB060
        )
        result.add_field(name="Here is your translated message:", value=f"{translated_content}")
        global response
        response = await ctx.respond(embed=result, view=deleteButton(), ephemeral=True)
spring hare
#

change response to interaction.message

spring hare
fervent cradle
#

sweet, thanks!

sinful pivot
#

I want to blacklist certain users from using commands on my bot, I tried to do that with the on_application_command event but the actual response from the bot does still happen, how would I go about doing this?

waxen whale
proud mason
sinful pivot
#

I tried to do ```py

@app_commands.check()```

#

but that doesnt exist, so what is it in pycord?

proud mason
#

hmm one sec

sinful pivot
#

also how would my check look like?


def blacklist_check(ctx: discord.ApplicationContext):
    if ctx.author.id in []: # list of blacklisted users
        return False # i think it should be?

    return True```
#

Or do I do ```py

def blacklist_check(ctx: discord.ApplicationContext):
if ctx.author.id in []: # list of blacklisted users
raise SomeCustomError()

return True```
#

I want to also give a response to the user saying that they are blacklisted

cyan quail
#

there's tons of examples on custom checks in the docs

proud mason
cyan quail
#

(also, isn't app_commands dpy or is that a group name?)

proud mason
#

yea ig they were just giving an example

sinful pivot
cyan quail
#

you'd probably be better off asking them since idk if they've altered their check system

sinful pivot
#

anyone wanna tell me whats the deco called

sinful pivot
proud mason
#

@commands.check(...) will work for app cmds too
but commands is discord.ext.commands, and not discord.commands

cyan quail
#

oh i see

#

^

sinful pivot
#

got that, thanks!

cyan quail
#

read through the docs i linked above, it'll help a ton

sinful pivot
#

I did

#

I can raise, and then what should I do, use a on_application_command_error event? As I don't know if I can check for custom checks in there

cyan quail
#

use isinstance to check what class the error is

sinful pivot
cyan quail
#

you can also set individual error handlers for specific commands or cogs

sinful pivot
#

yeah ik that

#

but its all global so

cyan quail
#

fair enough

sinful pivot
cyan quail
#

that would be bot_check

sinful pivot
#

uhh wym

#

Can you gimme an example

cyan quail
#

either:

  • in your main file, use the @bot.check() decorator
  • in a cog, use the @Cog.bot_check() decorator
#

async is optional

sinful pivot
#

I wanna use it in my main file btw, I suppose that applies to all cogs

cyan quail
#

both apply to everything

#

the first is if you want to define it in your main file, e.g. like in some examples you see @bot.event

sinful pivot
#

id wanna do it in my main file so its nice and tidy

cyan quail
#

then go with that

sinful pivot
cyan quail
#

i was just using that as a generic example

#

as in, in some examples you'll see people overriding events using @bot.event

#

in the same manner, you can set a bot check with @bot.check()

sinful pivot
cyan quail
#

mhm

sinful pivot
#

Okay did that

#

Oh okay

candid coral
#
class Test(discord.ui.View):
    @discord.ui.button(label="+", style=discord.ButtonStyle.blurple)
    async def left(self, button, interaction):
        x = Test1()
        x.page += 1
        await interaction.response.send_message(x.page)

    @discord.ui.button(label="-", style=discord.ButtonStyle.blurple)
    async def right(self, button, interaction):
        x = Test1()
        x.page -= 1
        await interaction.response.send_message(x.page)

class Test1():
    def __init__(self, name, page):
        self.name = name
        self.page = page

@client.command()
async def test(ctx):
    Test1(ctx.author, 1)
    await ctx.send("Text", view=Test())

My unsuccessful attempt to pass data to buttons to use and change...

candid coral
#

I learned how classes work, but didn't solve the problem that made me decide to learn them...

cyan quail
#

you don't need the Test1 class, but rather you define the __init__ in your original Test class

#

apart from that, all you need to do is use super().__init__(...) inside the said function, which will take what you would pass into your original View class (e.g. timeout)

candid coral
#

I'll try to fix it, thank you

patent knoll
#

How the hell does ctx.guild.owner return none

proud mason
#

What intents do you have?

patent knoll
#

guilds

#

ah..

#

no, the other stuff works fine too, e.g. membercount

#

weird. for some reason first fetching the owner via the ID works

#

fixed that, but now I'm too stupid to convert a created_at to UNIX timestamp

lyric parrot
#

how can i use disable_on_timeout=True, but only if the message still has buttons? sometimes i edit the buttons out the message, but on timeout, they are disabled and added back into the message

full basin
lyric parrot
full basin
#

Try fetching the message

cyan quail
patent knoll
#

i hate time stuff ok :C

lyric parrot
gleaming falcon
#

What's the way to get the Member from a User instance? on_user_update gives a User, but I can't ban from that.

#

Even bot.get_user only provides a User instance? 🤔

cyan quail
#

they belong to guilds

#

and you can ban with a user instance, assuming you have the guild object

gleaming falcon
#

Well the on_user_update event doesn't pass guild context.

Just trying to be as dead-simple as possible

cyan quail
#

because it's a different event

#

if you're trying to do username bans, then you have to know which guild you want to ban from pre-emptively

#

and then use bot.get_guild

gleaming falcon
#

mmkay. I am capturing it elsewhere in the method, so hardcoded it is.

Appreciate the sanity check

candid coral
#

I spent several hours yesterday trying to solve problems with __init__, so as not to sound stupid when I return here, but i'm still here

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Test.__init__() takes 1 positional argument but 2 were given```

This error appears, what arguments are mentioned here? I don't understand...
candid coral
# spring hare Please, send your `class Test`
class Test(discord.ui.View):
    def __init__(self, name):
        self.name = name
        self.page = 1

    @discord.ui.button ...

@client.command()
async def test(ctx):
    await ctx.send("Text", view=Test(ctx.author))
#

I tried to fix it but now another error

#

All my new skills about classes doesn’t apply when I start writing code for the bot

proud mason
#

Can you send full traceback for both errors

proud mason
candid coral
#
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 1560, in send
    components = view.to_components()
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 215, in to_components
    children = sorted(self.children, key=key)
AttributeError: 'Test' object has no attribute 'children'

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

Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 347, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 950, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 187, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Test' object has no attribute 'children'```
proud mason
#

Yep. Call super().__init__() at the first line of your init

candid coral
spring hare
#

Inhertence

proud mason
candid coral
#

It turns out super() necessarily?

proud mason
#

candid coral
#

If I use __init__ in a View, is the line with super() required?

proud mason
#

You don't always need to call super init. Depends from case to case

The view class has some initializer code which needs to be called

#

So yes. You need that when subclassing View and overriding the init

spring hare
candid coral
#

AWESOME

#

Thank you

proud mason
#

🎉

fervent cradle
#

I wonder, if you pass a embed raw that has components, how are these buttons/select menus going to attach in the embed?

proud mason
#

"embed" themselves dont have buttons. embeds and views are part of a "message". the message can have embeds and/or view. the view will be attached to the message

candid coral
#

I discovered a new problem. I need the button to be disabled under certain conditions before sending the message

#

I cannot substitute a variable with the value "True" in "disabled=...", because the button doesn't see it

#
@discord.ui.button(label="<", style=discord.ButtonStyle.blurple, disabled=self.flag)
NameError: name 'self' is not defined
proud mason
#

smth like so

class MyView(...):
  def __init__(...):
    ...
    self.my_button.disabled = True/False

  @button(...)
  async def my_button(...):
    ...
candid coral
proud mason
candid coral
#

Oh

candid coral
proud mason
#

no? it will be determined when creating the view

#

i suggest you tias

#

.tias

winter condorBOT
candid coral
#

Tias 🫶

#

O-ops, I was inattentive, I'm sorry

#

I understood, thank you

proud mason
#

np lol

signal topaz
#

how can you add space in-between command name

tired crag
#

yo guys I just need very quick help. How would I make an enum argument in a command

tired crag
proud mason
errant craneBOT
#

Here's the slash groups example.

#

Here's the slash cog groups example.

tired crag
proud mason
#

Hmm. What happens when you typehint the parameter with the enum class

tired crag
#

uh

#

idk

#

ive never tried it, idk the syntax to make it work

#

I only started pycord recently lol

#

I used to use one called hikari

proud mason
tired crag
#

and it would let the user select an option from the enum?

tired crag
#

how would I do that 😅

#

yeah can someone help me with the enum thing, I need to know how to make the enum

proud mason
#

Google

tired crag
#

i still dont know what to do :/

proud mason
tired crag
#

wait wdym

proud mason
#

No need for enum just to show choices

errant craneBOT
#

Here's the slash options example.

proud mason
#

See that

tired crag
#

I looked at that but idk how to add my own options

proud mason
errant craneBOT
#

examples/app_commands/slash_options.py line 15

@option("gender", description="Choose your gender", choices=["Male", "Female", "Other"])```
tired crag
#

tysm

proud mason
#

Specify them in the choices parameter

tired crag
#

i didnt see that

#

wait but where tf do I put that

#

under bot.command?

proud mason
#

Uh

#

Read the whole example

tired crag
#

ye I did

#

they have it under bot.command but mine is being weird

signal topaz
tired crag
signal topaz
#

why not

#

seems better than underscore

tired crag
#

because its way more complicated

signal topaz
#

but it's better, so it's good

tired crag
#

and its easier to type

#

if you say so

signal topaz
#

but many good bots use spaces

tired crag
#

and ive been on discord for 4 years

#

nvm you're right lmao they do exist

#

but they dont use the space for the name

#

its just for subcommands

#

they do it if there's multiple options under highlight

#

wait wtf is @bot.slash_command

#

im using @bot.command

signal topaz
#

what

#

isnt that for commands with prefix

tired crag
#

I use bot.command and it works perfectly fine

signal topaz
#

ima stick with underscore-

tired crag
#

yeah probably a good idea

#

bro i'm just so confused why my thing isnt working

signal topaz
#

what thing

tired crag
#

options for slash commands

signal topaz
tired crag
#

the docs are so confusing

#

my head hurts

tired crag
#

I have this

signal topaz
#

im not sure if From works

#

I think its from

tired crag
#

yeah its lowercase

#

it just got cut off lol

proud mason
tired crag
#

wait hold up

signal topaz
#

does ur code look like this

tired crag
#

guess the chapter's the one that I want

signal topaz
#

i thjnk @option does not work

proud mason
proud mason
tired crag
#

leaked db

proud mason
#
@bot.command()
async def ping(ctx, member: discord.Option(...):
  ...
@bot.command()
@option(...)
async def ping(ctx, member: discord.Member):
  ...
#

notice the difference

#

Option vs option

#

both are valid

#

personal preference

tired crag
#

ok now im getting very long error

#

but here's typeerror

#

issubclass() arg 1 must be a class

proud mason
tired crag
#

@bot.command(name='guesschapter', description='Guess the chapter from these Valve games!') @option("gender", description="Choose your gender", choices=["Male", "Female", "Other"]) async def guesschapter(ctx, game : option(name='game')): pass
this?

#

im so confused 💀

proud mason
#

also, you remove the option part from this game : option(name='game')

#

make it game: str

tired crag
proud mason
tired crag
#

from the list of games

proud mason
#

change the name to game

#

and put your choices in the list

tired crag
#

oh crap it works

proud mason
#

also change the description

tired crag
#

idk how it works but it works lol

proud mason
#

💀

tired crag
#

lmao

#

ty lmao

proud mason
#

kden 👍

winged ravine
#

According to https://docs.pycord.dev/en/stable/intents.html#member-intent & https://docs.pycord.dev/en/stable/api/data_classes.html#discord.Intents.members I need to activate the members privileged intent in order to access the roles of a member (Member.roles), yet my code which does so does not subscribe to this intent and it still works?

winged ravine
# proud mason show the (relevant) code
@discord.slash_command(
    name="writeroles",
    description="Populates #roles with the correct messages."
)
async def write_roles(self, ctx: ApplicationContext):
    ctx.defer()

    guild: Guild | None = self.bot.get_guild(settings["DISCORD_GUILD_ID"])
    if guild is None:
        await ctx.respond(
            f"""⚠️There was an error when trying to send messages:⚠️️\n`Server with id \"{settings["DISCORD_GUILD_ID"]}\" does not exist.`""",
            ephemeral=True
        )
        return

    roles_channel: TextChannel | None = discord.utils.get(guild.text_channels, name="roles")
    if roles_channel is None:
        await ctx.respond(
            "⚠️There was an error when trying to send messages:⚠️️\n`Text channel with name \"roles\" does not exist.`",
            ephemeral=True
        )
        return

    guild_member: Member | None = await guild.fetch_member(ctx.user.id)
    if guild_member is None:
        await ctx.respond(
            "⚠️There was an error when trying to send messages:⚠️️\n`You must be a member of the Discord server to run this command.`",
            ephemeral=True
        )
        return

    committee_role: Role | None = discord.utils.get(guild.roles, name="Committee")
    if committee_role is None:
        await ctx.respond(
            "⚠️There was an error when trying to send messages:⚠️️\n`Role with name \"Committee\" does not exist.`",
            ephemeral=True
        )
        return

    if committee_role not in guild_member.roles:
        await ctx.respond(
            "⚠️There was an error when trying to send messages:⚠️️\n`You must have the \"Committee\" role to run this command.`",
            ephemeral=True
        )
        return
    ...

The line if committee_role not in guild_member.roles: seems to work perfectly fine for me even without the privileged intent?

cyan quail
#

well

#

you're checking "not in"

#

so it'll always be true if the list is empty

#

you should actually print guild_member.roles to see what it outputs

#

also py guild_member: Member | None = await guild.fetch_member(ctx.user.id)this fetch is completely useless, ctx.author already gives you the Member object

#

though i guess the advantage is letting you run the command outside the guild so fair enough

winged ravine
silver moat
#

can’t you first try to get the member through cache then try to fetch it?

cyan quail
#

if they have intent off then no

silver moat
winged ravine
winged ravine
cyan quail
#

oh interesting

#

then fair enough

#

hm actually

winged ravine
#

im glad it works but it feels weird that it does, surely it shouldnt?

cyan quail
#

this is likely because it's using the roles recieved from the interaction?

#

if you tried to fetch a random other member and print roles it probably won't work

winged ravine
#

ohhh gotcha, well seen as i'm never going to be requesting another user's roles (only the triggering user to validate them) i guess it's fine to have the intent off & it will still work, cool! Cheers for your help!

candid coral
#

I'm sorry, I fixed it

winged ravine
#

how long are message IDs? (are they always a fixed length?)

silver moat
#

?tag snowflake

silver moat
#

this is how IDs are made

winged ravine
#

that implies theyre always 18 digits? or am i misunderstanding cos I have guild, application/client & message IDs all with 19 digits?

silver moat
winged ravine
#

ohh gotcha, I should just ask the actual question: is there a good way for me to regex to validate an integer is a snowflake ID?

silver moat
#

probably just anywhere from 6 to 14 digits for a weak check

#

or use the abc.Snowflake class to see if it has a valid creation date

winged ravine
#

I thought it wasnt possible to directly create snowflake instances?

candid coral
#

How can I check if a message has been deleted or not? "on_timeout" continues to count down and then executes the code that raises an error

glass gulch
#

was greedy function/class removed? it i reinstalled my module couple of times and couldn't find it and what are the alternatives

proud mason
candid coral
proud mason
#

yes

candid coral
#

I will use it, thank you

solemn idol
#

Uh

coarse cargo
#

It's possible to create a command only if the user set an option to true in a config or i can't?

proud mason
proud mason
#

i believe a simple way would be to use a bot wide check

#

that would raise an error if command is disabled

#

you can handle this in your error handler, and even choose to ignore it

#

but commands also have a way to disable them

#

you could set this, but this will be bot wide, an not per guild

coarse cargo
proud mason
coarse cargo
proud mason
#

unless you have made one yourself

#

that isnt necessary tbh

#

oh but yeah. they will show up in the slash menu

#

so there is a way

#

but it is not that elegant

coarse cargo
#

Sorry if i forgot to specify.

proud mason
#

it is fine

#

lol

coarse cargo
proud mason
#

so this config is per-guild right?

coarse cargo
#

no it's just a private bot

proud mason
#

oh then it should be easy

#

one sec

coarse cargo
#

oke

proud mason
#

hmm

#

ok what i thought is not possible

#

slash cmds dont have a way to be disabled

#

there is another way. but it is kinda hacky

#

each cmd would be in a separate extension. to remove the cmd, you unload the extension and then call bot.sync_commands()

#

im not sure if this would work tho

coarse cargo
#

Well, i think i will just handle the error and say something like "Enable the command in the config". Probably creating a whole extension just for it isn't a good idea.

#

Thanks anyway

proud mason
#

np lol

proud mason
coarse cargo
#

xD

proud mason
#

so the thing is, you can just do bot.remove_application_command

but then you wont be able to add it back with bot.add_application_command, as you dont have the cmd object

patent knoll
#

If I use ctx.defer(), can i still use ctx.respond() later on?

coarse cargo
proud mason
proud mason
#

but thats on startup

#

you would also need to do it before ready

coarse cargo
#

You're right

proud mason
proud mason
coarse cargo
#

Also the command is in a group inside a cog

proud mason
#

use that. it takes the name

proud mason
coarse cargo
#

Oh ok thanks very much

coarse cargo
proud mason
#

you need to specify the full name

coarse cargo
#

oh let me try

proud mason
#

like group subcmd

coarse cargo
#
helpcmd = bot.get_application_command('ticket help', guild_ids=get_serverinfo('guild_id'))
print(helpcmd)
proud mason
#

or is it a global one?

coarse cargo
#

In the group i specify the guild id

proud mason
#

like do you have guild_ids specified in the decorator

#

ah

proud mason
coarse cargo
#

for testing i tried it in the setup function, i guess this is the problem?

proud mason
#

hmm

#

but after bot.add_cog right

coarse cargo
proud mason
#

what does get_serverinfo('guild_id') return?

#

it should be an int. not a string

coarse cargo
#

It's an integer

proud mason
#

then idk blobpain

coarse cargo
#

so this is not the problem

#

i also tried with /ticket help as name

coarse cargo
proud mason
#

alr sure

coarse cargo
#

thank you so much for the effort to help me

proud mason
#

you could also try and print the qualified names of all the cmds in the bot

proud mason
coarse cargo
#

probably im just doing something wrong

fervent cradle
#

I wonder why it didn't send the message in ephemeral 🤔

await ctx.respond("An error occured.", ephemeral=True)
fervent cradle
#

of what? the code?

#

or the response?

young bone
#

The message

fervent cradle
coarse cargo
#

@proud mason So, actually if i try to do bot.get_application_command in the on_ready it returns the command but it's useless as i can't remove the command after the bot starts.

clear vault
#

Can anyone help me? I have no loop in my event?

proud mason
#

if you want, then you can play around with internal attributes of the bot

#

specifically pending_application_commands

#

but you are kinda on your own

#

i havent deal with that stuff

proud mason
solemn idol
#

can you provide more information of how your command works, like is that the only part of your command which uses ephemeral... or did you define True to False somewhere LOL

coarse cargo
proud mason
#

you should highlight this issue in #discussion. it should be made better

young bone
proud mason
proud mason
young bone
#

Is that the pip or github one?

proud mason
fervent cradle
cyan quail
#

uhh

cyan quail
#

or they set the image

fervent cradle
cyan quail
#

then just do that

fervent cradle
#

idk how to

cyan quail
#

embed.set_image(url=...)

clear vault
clear vault
fervent cradle
#

oh ok

cyan quail
cyan quail
#

if you're try/excepting you're cog load then temporarily remove that

clear vault
#

ok wait

#

@cyan quail:

cyan quail
clear vault
#

Whats the command?

cyan quail
#

pip install -U ...

#

(whatever your pip command is, may vary on versions etc.)

clear vault
#

Nope

cyan quail
#

how about dblpy?

clear vault
#

Version 0.4.0?

#

Update via pip install -U dblpy doesnt work

cyan quail
#

i think it was never updated to support 3.10

#

last release late 2020. 3.10 released late 2021

clear vault
#

I cant remove topgg

cyan quail
#

theoretically you can go edit dbl/http.py yourself and remove loop=self.loop but idk if that'll fix it

#

you could try installing a lower python version

clear vault
#

Nonono

cyan quail
#

then you're more or less out of options then

#

would have to modify the package yourself

clear vault
#

...

#

Thanks anyway for your help

candid coral
#

I know what problem I will meet next. To pass information from one View to another, I need:

class Name1(discord.ui.View, Name2)
    def __init__(...):
        super().__init__(...)
#

Right?

fervent cradle
#

how can i create restrictions for my slash command options? I dont want to have a set value of options but rather not accept some specific values as input

silver moat
fervent cradle
#

i dont think that will solve it, what im looking for is that i want the input to be a timestamp something like 20:00 so i want to make some kind of validation so that it doesnt accept anything that is not on this format

coarse cargo
#

So guys, i want to make a slash command that takes an option but it should be selected from a list of selected values for example, answers=[Hi, Hello, Bye] and i want the user to select an option from this list how can i do this?

errant craneBOT
#

Here's the slash options example.

coarse cargo
#

Ty ^^

candid coral
#

How can I pass data from two classes at once?

silver moat
candid coral
#
class Name1(discord.ui.View)
    def __init__(self, ...)
        super().__init__(timeout=...)
        self. ...
        self. ...

class Name2(discord.ui.View)
    def __init__(self, ...)
        super().__init__(timeout=...)```
silver moat
#

?tag xy

obtuse juncoBOT
#

An XY problem is when you're trying to ask about your attempted solution, rather than your actual problem.

You are trying to solve problem X, using solution Y. Instead of asking for help with X, you ask about Y. This only results in frustration as whoever is trying to help you needs to ask several questions before even beginning to help you with your actual issue, wasting both their own, and your time. Always include as much information as you can about your problem, including attempted solutions. If there are solutions you've ruled out, include them along with an explanation as to why you've ruled them out.

candid coral
silver moat
#

What is the problem you are trying to solve?

candid coral
silver moat
candid coral
#

When a certain button is pressed, the View class changes to another subclass, it is necessary to save arguments from the previous class

full basin
#

Then pass those variables to the new class when you create the instance

restive scarab
#

how to add a custom button to a paginator that has its own function not related to the paginator?

glossy forum
#

Hey, I've got problem with my cog's task loop, which is supposed to post messages in a preselected channel, which ID is stored in a database
Any idea why

channel = self.bot.get_channel(channel_id)
print(f"{channel_id = }, {channel = }")
```this always returns None?
the channel_id is correct as when surrounded with `<#id>` it properly shows the channel, like on the pic
`self.bot` is what would you expect it to be inside a Cog
young bone
glossy forum
young bone
#

in which type of function?

glossy forum
#

Besides, it's None just after the assignment

glossy forum
# young bone in which type of function?

I described it above, it's inside a cog

@tasks.loop(minutes=10)
async def check_for_feed(self):
  # some code
  channel = self.bot.get_channel(channel_id) # it runs each and every time the function is called
  print(f"{channel_id = }, {channel = }")
  # prints channel_id = 1102548337187635240, channel = None
  # more code
young bone
#

you can use await self.bot.fetch_channel()

glossy forum
silver moat
glossy forum
silver moat
glossy forum
#

👍
I already implemented all the checks, I like my software to be reliable :)

young bone
#

or just use get_or_fetch_channel

silver moat
glossy forum
#

Thanks, but I believe the problem was caused by lack of guilds intent. And I'd rather deal with a programming error than discord support (to remove being ratelimited)

proven mantle
#

How can i load Views when i restart the Bot? Old Views wont work anymore then

proven mantle
#

i see. Thanks

fervent cradle
fervent cradle
silver moat
plain cove
#

Hello Why is my command not working when it shows no errors?

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
#

?tag intents

obtuse juncoBOT
#

https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents

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)
Discord Developer Portal

Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.

fervent cradle
# silver moat could you show code?
    @commands.message_command(name="Translate Message")
    async def translate_message_context(self, ctx, message: discord.Message):
        """Context menu for translating a message to english."""
        try:
            message_content = message.content
            if len(message_content) > 4096:
                await ctx.respond(f"Sorry {ctx.author.name}, but this message is too long for me to show here. I can only translate messages less than `4096` characters.")
                return
            load_dotenv()
            api_key = str(os.environ.get("detectlanguage_api_key"))
            await ctx.defer()
            source_language = single_detection(message_content, api_key)
            translated_content = GoogleTranslator(source='auto', target='en').translate(message_content)
            result = discord.Embed(
                title = f"Translated from {source_language}",
                description = f"{translated_content}",
                color = 0x4BB060
            )
            global response
            response = await ctx.respond(embed=result, view=deleteButton(), ephemeral=True)
        except:
            await ctx.respond("An error occured.", ephemeral=True)
silver moat
#

so add the ephemeral kwarg to your defer

fervent cradle
#

hm

#

ephemeral=True in the parenthesis?

silver moat
#

side-note. Don’t use bare excepts

silver moat
fervent cradle
silver moat
#

you should except a specific exception

silver moat
fervent cradle
# silver moat yes

thanks, it worked 😄 also if a defer is ephemeral, wlll other responses be ephemeral too even I don't set ephemeral=True in the response? For example:

await ctx.defer(ephemeral=True)
[...] # Do something time consuming here
await ctx.respond("Hello World!") # Will this response be ephemeral?
fervent cradle
#

and won't be ephemeral if i set ephemeral=False in the response?

silver moat
#

whatever the defer is, the followup will get

fervent cradle
#

so what if i want it not to be ephemeral?

silver moat
#

then send two messages

#

this is a discord limitation

fervent cradle
#

got it

#

thanks

plain cove
full basin
signal topaz
#

how to set timeout for buttons,select menus etc?

proud mason
#

in seconds

signal topaz
proud mason
#

timeout is a parameter of the view class init. Not related to subclassing

signal topaz
#

like view = View(select_menu/button)

proud mason
#

Yea so just pass timeout=10 or whatever

signal topaz
#

got it

proud mason
#

👍

signal topaz
#

did not work

spring hare
#

Is there any guide on how to transfrom prefixed commands into bridge commands?

signal topaz
#

how to remove the view after timeout?

proud mason
#

Subclassing is recommended for this

#

But you can do it using other ways too

signal topaz
proud mason
#

example without subclassing?

#
view = View()

async def on_timeout():
  ...

view.on_timeout = on_timeout

...
#

like that

signal topaz
#

ohk

winged ravine
#

Is there any way for me to create 2 slash commands with the same name but different Options arguments & one is guild only & the other is DMs only?

proud mason
#

Nope. Not possible

winged ravine
# proud mason Nope. Not possible

ok, cheers. Alternative question: if they have different names can I make one of them guild only & the other DMs only? (& if i can will the DMs only one show in the list of possible commands in a guild but just not work?)

proud mason
#

You can make commands guild-only

#

But I'm not sure about dm-only

winged ravine
winged ravine
proud mason
winged ravine
proud mason
#

Btw

#

Any particular reason why the guild version won't just directly work in dms?

#

Just asked in ddevs server

winged ravine
obsidian ermine
#

How am I able to get the description of a application command?

#

no description attribute? bigbigflushed

#

nvm it works with the description attribute, its just not documented

cyan quail
#

ApplicationCommand and SlashCommand are different; other types of ApplicationCommand such as MessageCommand and UserCommand don't have descriptions.

plain cove
proud mason
#

I'm not sure if that works either

winged ravine
coarse cargo
#

what is the slash command limit a bot can have?

proud mason
proud mason
#

Each of these can have 25 subgroups

#

Each of those can 25 further subcommands

#

So 100*25*25
Which means 62500 commands

#

This is for global commands

#

Same for guild commands

#

So for a guild, the bot can do 125000 commands

winged ravine
# proud mason Oof

yh the only way i can think is doing some hackery with behind the scenes on how pycord adds the different available options to a slash command, but i dunno if thats even possible and seems a bit complex

proud mason
#

But this sounds like too much effort for small gain

winged ravine
#

hehe might just get my bot actually working first lol, add it to the feature requests

patent knoll
#

In short:
I have a command that lists members based on their acc creation date
It works perfectly fine, but it just doesnt work with one member on my server. I have zero idea why

#

The missing 0 is no problem because it also works with me (with a 01 08 creation date) and i have no idea why it doesnt work on that particular one member

solemn idol
#

wait no

cyan quail
#

then in your command use TextChannelConverter

winged ravine
solemn idol
cyan quail
#

GuraShrug the specialised slash options will only ever work in the current context

patent knoll
patent knoll
#

yea i dont know

#

has to be timezone related somehow

solemn idol
#

oh maybe discord rounds up days

cyan quail
#

discord does everything in UTC so yes

solemn idol
#

or that

cyan quail
winged ravine
cyan quail
#

you set the autocomplete logic yourself

#

so if you want then yeah

winged ravine
#

so i can always autocomplete from a given guild?

cyan quail
#

assuming it's always from 1 specific guild, just use ctx.bot.get_guild

young bone
cyan quail
#

autocomplete is probably the best feature slash commands have because you have full control over the output

winged ravine
#

fabulous! i presume i will also need to write my own validation that the entered channel is valid? (i heard that autocomplete does not ensure valid data)

cyan quail
#

yes

#

though that's straightforward enough

winged ravine
#

just do another check that the entered channel exists in the guild?

cyan quail
#

mhm

winged ravine
#

thanks for ur help!!!!!

cyan quail
#

autocomplete supports the discord.OptionChoice object, so you have a separate name and value

#

name is what's shown on the UI, while value is the actual object you recieve in your callback (always string)

#

so you'll want something like OptionChoice(name=channel.name, value=str(channel.id))
return a list of those through iteration and then back in your callback, you can instantly validate it with guild.get_channel

winged ravine
#

wonderful! that really helps

winged ravine
cyan quail
#

then you can validate stuff like view_channel

winged ravine
#

👍🏻

fervent cradle
#

is there a event that listens to every executed command so I can save it in my logs?

fervent cradle
#

can you give me a example

grizzled sentinel
#

prefix or slash commands?

fervent cradle
#

slash

grizzled sentinel
#

on_application_command

fervent cradle
#

thanks

grizzled sentinel
#

.rtfm on_application_command

grizzled sentinel
#

docs^ (first link)

fervent cradle
#

🙏🏿

winged ravine
cyan quail
#

autocomplete is always str

winged ravine
#

gracias

cyan quail
#

OptionChoice will always return whatever value is

#

so e.g. if your args were ctx, channel: Option(str, autocomplete=...) and your autocomplete function returned a list of OptionChoice, the channel variable would be OptionChoice.value

cyan quail
unkempt moss
#

Does anybody else currently have a problem with their bots never connecting to voice (channel.connect() hanging forever)?

unkempt moss
#

Oh dang - apparently just doing pip install -Ur requirements.txt is not enough sometimes. thanks!

winged ravine
cyan quail
#

uhh i think it needs to match?

#

though

#

it seems there's a hidden parameter_name kwarg you can try using

#

which would be the target argument name

#

TIL

winged ravine
#

ooooooooo fabuloussss

#

Will send_messages permission always be false if view_channel is false?

cyan quail
#

not necessarily

dapper pasture
#

does py-cord have this? i've tried searching docs but i don't know name of that form

errant craneBOT
#

Here's the modal dialogs example.

dapper pasture
#

ty