#discord-bots

1 messages · Page 1069 of 1

slate swan
#

imagine

#

you cant declare a constant inside an object like that.

#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OperationalError: no such column: arg

#

????

paper sluice
slate swan
#

please go to djs server, thats the correct place to ask the question, as you can see the server name its python.

slate swan
#

they want you to learn js before using discord.js, and so do we

slate swan
paper sluice
#

um then learn them. It would be easier for you to do what you want

sick birch
#

We don’t help with JavaScript here, as mentioned

slate swan
#

Ok. But if the arg is in the str of query , should it throw that error?

sick birch
#

No need to insult them

#

And that doesn’t change the fact that you’re not getting help here

paper sluice
#

well they are not wrong, you are supposed to learn js b4 using djs just like ur supposed to know python b4 making discord bots

sick birch
#

Again, we don’t help with JavaScript

#

I suggest you stop asking because the answer is no

paper sluice
#

ask in a js server :p

granite parcel
#

hi

#
    @commands.Cog.listener()
    async def on_message(self, message):
        db = sqlite3.connect('afk.db')
        cursor =  db.cursor()
        cursor.execute(f"SELECT user FROM afk WHERE user = {message.author.id}")
        result = cursor.fetchone()
        if result is not None:
            cursor.execute(f"DELETE FROM afk WHERE user = {message.author.id}")
            await message.channel.send(f"Welcome Back **{message.author}**, I removed your AFK. You were afk")
            db.commit()```
granite parcel
#

how to fix'

zealous jay
#

I have a few commands inside a cog, how do I make subcommands? Im using slash commands with discord.py

warped mirage
#

first try and it works , i guess the best thing is to try ur best

slate swan
#

seems nice, there can be improvements

warped mirage
slate swan
#
class welcomesystem: 
# should be pascalcase
class WelcomeSystem:
async with aiosqlite.connect("wm.db") as db:
``` instead of making connections  each time, you can have a single connection througout the cog or the file using `cog_load` method

```py
async def cog_load(self) -> None:
  self.db = await aiosqlite.connect("wm.db")

and simply use self.db to get the database whenever you want to

warped mirage
#

can u help me fixed that please?

slate swan
#

begin with the first part, change the class name's case

warped mirage
#

i never do that i always keep em lower case

slate swan
warped mirage
#

oh so for the welcome make it WelcomeSystem?

#

anyways @slate swan lets continue

young pendant
#

hey guys, how to send message in channel every 5 minutes for example

slate swan
#

how to send file AND message with requests module (im using webhook) i dont want other module/library so dont say plz

slate swan
# warped mirage anyways <@456226577798135808> lets continue

next instead of making connections multiple times you can use single connection

class MyCog(commands.Cog):
  async def cog_load(self):
    self.db = await aiosqlite.connect("wm.db")

  @commands.command()
  async def foo(self, _):
    database = self.db
warped mirage
#

so can u help me edit mine

#

if possible?

unkempt canyonBOT
#

requests.post(url, data=None, json=None, **kwargs)```
Sends a POST request.
slate swan
young pendant
slate swan
#

no thats a very bad way of doing it

slate swan
young pendant
warped mirage
slate swan
young pendant
shrewd apex
pliant gulch
#

To handle closing the connection gracefully

slate swan
#

!d discord.ext.commands.Cog.cog_unload

unkempt canyonBOT
#

await cog_unload()```
This function *could be a* [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

A special method that is called when the cog gets removed.

Subclasses must replace this if they want special unloading behaviour.

Changed in version 2.0: This method can now be a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine "(in Python v3.10)").
slate swan
#

oh, never knew this existed

warped mirage
#

@slate swan I have many connections and it confuses me lmao

shrewd apex
slate swan
young pendant
slate swan
#

making requests in on_ready is bad, you should use bot.wait_until_ready() for the cache to get loaded first, then start the task

young pendant
slate swan
unkempt canyonBOT
#

discord/http.py lines 522 to 531

async def get_from_cdn(self, url: str) -> bytes:
    async with self.__session.get(url) as resp:
        if resp.status == 200:
            return await resp.read()
        elif resp.status == 404:
            raise NotFound(resp, 'asset not found')
        elif resp.status == 403:
            raise Forbidden(resp, 'cannot retrieve asset')
        else:
            raise HTTPException(resp, 'failed to get asset')```
slate swan
pliant gulch
warped mirage
#

I need help

slate swan
#

dpy moment

shrewd apex
pliant gulch
#

You should probably not use the internal session

slate swan
#

agreed, playing with internals is not a noice idea

pliant gulch
#

Don't they embed your bot's token into the headers?

slate swan
#

since that may have ur headers

pliant gulch
#

That's really the only problem

slate swan
#

yes

warped mirage
#

Damn

slate swan
#

wot if i do bot.http.__session.get("url", headers={}) pithink

pliant gulch
slate swan
#

oh it was a double underscore and i was trying to ctrl+f http._HTTPClient_session 😔

pliant gulch
#

Yea just editted cause I realised I only put one

#

Not really sure why discord.py decided to use name mangling, as pep8 says somewhere iirc that name mangling isn't meant for private access. Rather used for subclassing stuff

warped mirage
#

@slate swan can u please help me then or nah

#

ok

slate swan
#

How can I make an Cooldown for an command only for an server that recently used the command?

zealous jay
#

!d discord.ext.commands.cooldown

unkempt canyonBOT
#

@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.

A command can only have a single cooldown.
zealous jay
#

Example:

@commands.cooldown(1, 30, commands.BucketType.guild)

Can only be used once every 30 seconds and the cooldown applies for the entire guild

zealous jay
#

no problem

warped mirage
#

can someone here help me

zealous jay
#

what do you want to do?

warped mirage
#

i coded a multi guild welcome system , can i send code and then explain what i want?

zealous jay
#

sure

#

altough I can't help you rn

warped mirage
#

i need to code a set message and delete message command

#

if u know how

sly hamlet
#
    await interaction.response.send_message(f'This command is on cooldown. Please wait {error.retry_after:.2f}s')
    ^
SyntaxError: 'await' outside async function

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

Traceback (most recent call last):
  File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\echo.py", line 53, in <module>
    asyncio.run(main())
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
    return future.result()
  File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\echo.py", line 44, in main
    await bot.load_extension('cogs.admin')
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 990, in load_extension
    await self._load_from_module_spec(spec, name)
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 915, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.admin' raised an error: SyntaxError: 'await' outside async function (admin.py, line 36)``` ```py
    async def error():
        def on_command_error(interaction: discord.Interaction, error):
            if isinstance(error, commands.CommandOnCooldown):
                await interaction.response.send_message(f'This command is on cooldown. Please wait {error.retry_after:.2f}s')

            elif isinstance(error, commands.MissingPermissions):
                await interaction.response.send_message('You do not have the permissions to use this command.')``` I am trying to create a general error that will work with all my command although I do seem to be having a problem and doing this morning, fix it can someone help me?
tawdry perch
sly hamlet
#

yea

tawdry perch
#

That's the error I guess

sly hamlet
#

how do i fix it

warped mirage
#

can someone help me code

paper sluice
sly hamlet
#

cant use bot.event i am in a cog and on 2.0

tawdry perch
#

Use listener then

slate swan
#

commands.Cog.listener

sly hamlet
#

so ```py
@commands.Cog.listener()
def on_command_error(interaction: discord.Interaction, error):
if isinstance(error, commands.CommandOnCooldown):
await interaction.response.send_message(f'This command is on cooldown. Please wait {error.retry_after:.2f}s')

    elif isinstance(error, commands.MissingPermissions):
        await interaction.response.send_message('You do not have the permissions to use this command.')```
warped mirage
paper sluice
paper sluice
#

ya

#

are you trying to handle errors in slash commands?

sly hamlet
#

i am using slash commads but the error i am making is only one

slate swan
sly hamlet
#

how??????

slate swan
slate swan
sly hamlet
#

ok thx

warped mirage
sly hamlet
slate swan
#

as i said, the code was correct, but there can be improvements

warped mirage
#

I made a multi guild system , u can select the channel / remove the channel for ur welcome system . Now I need to code a message to the so set message welcome to server {member.mention} in discord or smth like that and msg del

#

Something like that if it makes sense

warped mirage
#

Ur own message

sly hamlet
#

Interesting because it doesn't seem to be working

warped mirage
#

I am using it and I coded half

#

now i need to continue

placid skiff
#

What you want it's a bit confusing tbh...

warped mirage
#

i have wm_set (chooses welcome channel) wm_del (removes the channel) now i want to code a msg_set (welcome message) msg_del (remove welcome message)

#

does this make more sense?

slate swan
#

in simple words -> you want to display custom greeting messages

warped mirage
#

so for msg_set eg = {prefix}msg_set welcome {member.mention} to server

maiden fable
#

Lmao

slate swan
warped mirage
#

well i need help xd

sly hamlet
slate swan
sly hamlet
#

Yes

slate swan
sly hamlet
#

What would that be?

warped mirage
#

anyways if someone can help me just ping me that would be great!

keen mural
#

how could i check if someone has a role in a specific guild

slate swan
#
from discord import Interaction
from discord.app_commands import AppCommandError

bot = commands.Bot(...)
tree = bot.tree

@tree.error
async def on_app_command_error(interaction: Interaction, exc: AppCommandError):
    ...```
slate swan
dense swallow
#

is there a way i can disable a button after a certain period of time, like a timeout.. i searched thru the docs, couldnt find a timeout function for buttons..

slate swan
keen mural
slate swan
# keen mural wdym
def my_custom_check():
    def predicate(ctx):
        # a function that takes ctx as it's only arg, that returns a truethy or falsey value, or raises an exception
    return commands.check(predicate) 

The predicate can be a coroutine, the indentaion might be a bit weird since im on phone

slate swan
keen mural
warped mirage
#

Actually wait

slate swan
slate swan
#

!d discord.ext.commands.has_role

unkempt canyonBOT
#

@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

If the message is invoked in a private message context then the check will return `False`.

This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
warped mirage
slate swan
#

and use the role id and not the name

keen mural
#
guild = ctx.guild
  booster_role = discord.utils.get(guild.roles, name = 'Server Booster・₊˚‧')
  if booster_role in ctx.author.roles:```
i have this rn
#

ok

maiden fable
warped mirage
#

Ye

#

I’m 1/2 done

maiden fable
#

What about it

warped mirage
slate swan
maiden fable
#

I'm here for another 10, maybe 15 min then I gotta sleep

warped mirage
# maiden fable What about it

i have wm_set (chooses welcome channel) wm_del (removes the channel) now i want to code a msg_set (welcome message) msg_del (remove welcome message)

warped mirage
#

But idk how lmao it confuses me the more I code into the system

#

I need help making it I guess

maiden fable
#

Do you have a db set up?

warped mirage
#

Yes

slate swan
maiden fable
#

What's ur db structure

warped mirage
#

Multiple connections tho 💀

slate swan
#

the reason im not helping you anymore is you wont ever listen to my advice

keen mural
keen mural
#

idk why

maiden fable
maiden fable
warped mirage
#

Damn I had a stroke reading that xd

slate swan
slate swan
warped mirage
#

I just need help editing my code

keen mural
#

brb

sly hamlet
#

i fixed it but have this problum py Traceback (most recent call last): File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\tree.py", line 933, in wrapper await self.call(interaction) File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\tree.py", line 1097, in call await self.on_error(interaction, e) File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\echo.py", line 57, in on_app_command_error if isinstance(error, commands.CommandOnCooldown): NameError: name 'error' is not defined

maiden fable
#

Rip my SQL skills

warped mirage
sly hamlet
# maiden fable Code
@tree.error
async def on_app_command_error(interaction: Interaction, exc: AppCommandError):
    if isinstance(exc, commands.CommandOnCooldown):
        await interaction.response.send_message(f'This command is on cooldown. Please wait {error.retry_after:.2f}s')

    elif isinstance(exc, commands.MissingPermissions):
        await interaction.response.send_message('You do not have the permissions to use this command.')```
maiden fable
slate swan
#

dude

warped mirage
#

E.g = msg_set hello welcome {member.mention} then msg_del

sly hamlet
#

ok thx

slate swan
#

fml, I hate helping here now

maiden fable
#

And yea, learn some basic Python

maiden fable
keen mural
# slate swan no errors?

it only works in the guild the role is in, otherwise it says role (id) is required for the command

warped mirage
#

Damn u don’t get the point alright it’s fine

maiden fable
#

Ah wait I get it

slate swan
maiden fable
#

So when the msg_set command is ran u want the bot to set the welcome msg

keen mural
#

ok

warped mirage
warped mirage
maiden fable
#

I got a stroke reading that

warped mirage
#

Then msg_del deletes it

maiden fable
slate swan
warped mirage
#

Well I showed my code

maiden fable
#

And set the field as welcome_msg

sly hamlet
#

So when using the error handler I don't get anything back. But I also don't get an error inside of my side on my panel

keen mural
#

its only checking the ctx.authors guild

maiden fable
#

Oh, hm

#

Bro, why u overcomplicating this wtf

warped mirage
#

Idk

slate swan
maiden fable
#

U just need to make sure no one is inputting any eval or smth then u can easily do it

#

Just use the UPDATE statement to update the text msg

keen mural
maiden fable
#

DELETE statement to delete the text msg

#

And so on

keen mural
#

and i want the cmd to work from any guild

warped mirage
#

Umm

maiden fable
#

Ngl welcome message system is one of the easiest one to make

warped mirage
#

Makes no sense but thanks for that I’ll just code something

maiden fable
#

Nvm I'mma just go

slate swan
warped mirage
#

That’s correct

#

3 lines of code

maiden fable
#

U just need basic DB knowledge

maiden fable
#

then its a piece of cake

dense swallow
dense swallow
slate swan
lethal moat
#
bot = nextcord.Client()
bot_guild = bot.get_guild(GUILD ID)
whitelisted_role = bot_guild.get_role(WHITELIST ROLE ID)
waitlist_role = bot_guild.get_role(WAITLIST ROLE ID)

why is it not working? isnt that how its supposed to be??

#

the bot IS in the guild whos id I entered
the id IS correct

dense swallow
#

use discord.utils.get

slate swan
#

bot_guild is None

lethal moat
#

ye but h O W

dense swallow
#

is there a get_role in bot obj?

slate swan
lethal moat
#

the code is right above the screenshot

slate swan
#

Either guild id is wrong, or it's not cached

lethal moat
#

guild id is right, and its cached

slate swan
#

How do you know it is cached?

dense swallow
slate swan
lethal moat
wet crystal
#

How can I send a dm with ctx

slate swan
#

You called the get_* function just after initializing the bot..?

slate swan
wet crystal
lethal moat
#

ahh yes I am dumb I forgot the main FOKEN part of the entire code

wet crystal
#

of a command

lethal moat
#

the on_ready function

dull terrace
#

How do you decide whether to scrap all your code and start again or try to clean up very old code

slate swan
wet crystal
lethal moat
slate swan
dull terrace
#

I think im gonna have to, it was the first bot i made

maiden fable
#

Okay the discord app hates me smh

wet crystal
dull terrace
#

saved everything in pickle files and have some obtuse code and it's all using message content sadcat

wet crystal
#

not send to the channel

#

send a dm

slate swan
#

wth

maiden fable
#

Fetch same thing*

dull terrace
#

2.5k lines of code to rewrite, here we goooo 😤

slate swan
#

anyways, best of luck

maiden fable
#

I have also started procrastinating my bot rewrite for some reason again pithink

slate swan
#

my case was way worse, I re-wrote my bot for the third time and i never pushed it to github, and my laptop just....died, now im writing it for the 4th time

maiden fable
#

U haven't enabled Auto Save?

slate swan
#

me who saves code after writing like every 4-5 lines

maiden fable
#

Lmao my code is saved on every key press

#

I press K, the code is saved. I press Enter, the code is saved

slate swan
maiden fable
#

And for some reason I still press Ctrl S every 2 min

dull terrace
#

after every 4 lines i press ctrl+s about 4 times just to double check it has saved KEKW

slate swan
maiden fable
#

Same

maiden fable
#

Even when it's already saved and formatted automatically

sly hamlet
warped mirage
#

lol

sly hamlet
#
@tree.error
async def on_app_command_error(interaction: Interaction, exc: AppCommandError):
    if isinstance(exc, commands.CommandOnCooldown):
        await interaction.response.send_message(f'This command is on cooldown. Please wait {error.retry_after:.2f}s')

    elif isinstance(exc, commands.MissingPermissions):
        await interaction.response.send_message('You do not have the permissions to use this command.')```
warped mirage
#
commands.command()
    async def set_msg(self, ctx):
        async with aiosqlite("wm.db") as db:
            cursor = await db.cursor()
            await cursor.execute("SELECT * FROM wm WHERE guild_id = ?", (ctx.guild.id,))
            data = await cursor.fetchone()

            if data is None:
                await cursor.execute("INSERT INTO wm(guild_id, channel_id) VALUES(?,?)", (ctx.guild.id, ctx.channel.id,))
                await db.commit()
                await ctx.send("Welcome Message has been set")
                return
            if data is not None:
                await cursor.execute("SELECT channel_id FROM wm WHERE guild_id = ?", (ctx.guild.id,))
                await cursor.fetchone()
                result = data[0]
                await ctx.send(f"WelcomeMessage is already set", delete_after = 10 )
                return``` can someone tell me if this would work'
dull terrace
#

i'd change if data is not None: to else: and remove both return statements for clarity but otherwise i see nothing obviously broken

#

ohhh

warped mirage
#

well i need help because , i coded wm_set (set welcome channel) wm_del (remove welcome channel ) now i need help doing the welcome message and removing it

dull terrace
#

result = (await cursor.fetchone())[0]

dull terrace
#

right now you're fetching the cursor but not defining the data you're fetching as anything

warped mirage
#

could u please help me with them 2 , ill send code

dull terrace
#

idk what you're asking me to help with

warped mirage
#

do u see my code?

dull terrace
#

yes

warped mirage
#

now i wanna code 2 more commands , msg_set (set a welcome message ) msg_del (delete the message)

slate swan
dull terrace
#

so you're asking me to code two functions for you? we don't do that here

#

anyway better stop procrastinating and get back to this rewrite ablobsweats

warped mirage
#

no .....

sly hamlet
slate swan
warped mirage
sly hamlet
#

so i need if isinstance(exc, app_commands.CommandOnCooldown):

regal pulsar
#

hello

slate swan
warped mirage
#

I coded the 2 commands now time to fix it 😂

regal pulsar
#

too bad i suck at sql

warped mirage
#

Damm

wet crystal
#

What is a category channel?
I really don't understand what the docs are trying to tell me.

#

!d discord.CategoryChannel

sly hamlet
#

ok thx

unkempt canyonBOT
#

class discord.CategoryChannel```
Represents a Discord channel category.

These are useful to group channels to logical compartments.

x == y Checks if two channels are equal.

x != y Checks if two channels are not equal.

hash(x) Returns the category’s hash.

str(x) Returns the category’s name.
slate swan
slate swan
#

?

wet crystal
#

!d discord.Guild.categories

unkempt canyonBOT
#

property categories```
A list of categories that belongs to this guild.

This is sorted by the position and are in UI order from top to bottom.
wet crystal
#

oh

#

i just read it
my bad

#

yeah, I thought its like diffrent things but the same idk

warped mirage
#

Anyways can someone help me

wet crystal
#

@slate swan
Do you also know if there is a difference between these two methods?

nextcord.Guild.create_category()
nextcord.Guild.create_category_channel()

slate swan
#

probably aliases

#

!d discord.Guild.create_category

unkempt canyonBOT
#

await create_category(name, *, overwrites=..., reason=None, position=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Same as [`create_text_channel()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.create_text_channel "discord.Guild.create_text_channel") except makes a [`CategoryChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.CategoryChannel "discord.CategoryChannel") instead.

Note

The `category` parameter is not supported in this function since categories cannot have categories.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") instead of `InvalidArgument`.
slate swan
#

!d discord.Guild.create_category_channel

unkempt canyonBOT
#

await create_category_channel(name, *, overwrites=..., reason=None, position=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Same as [`create_text_channel()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.create_text_channel "discord.Guild.create_text_channel") except makes a [`CategoryChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.CategoryChannel "discord.CategoryChannel") instead.

Note

The `category` parameter is not supported in this function since categories cannot have categories.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") instead of `InvalidArgument`.
slate swan
#

yeah aliases

warped mirage
#

Can someone help me

wet crystal
#

Does anyone know if this is going to work?

if nextcord.CategoryChannel.name("Trolls") in nextcord.Guild.categories:
  ...
full lily
slate swan
#

since categorychannel is the baseclass for an object that holds data

warped mirage
warped mirage
#

I need to fix them lol

#

So set msg = set welcome msg , del msg ( deletes the msg)

dense swallow
#

how do i disable a button in one page of help menu, and then enable it in the rest?
eg: home button which redirects to home page should not be in the home, it should be disabled.. whereas in other cogs, it should be enabled so tht users can go to that page

wet crystal
#

I cant use a whole channel object since the channel doesn't exist in the scenario.
So I only use the name

slate swan
wet crystal
slate swan
wet crystal
slate swan
#

yeh

slate swan
#

!d discord.ui.View.interaction_check

unkempt canyonBOT
#

await interaction_check(interaction)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.

This is useful to override if, for example, you want to ensure that the interaction author is a given user.

The default implementation of this returns `True`.

Note

If an exception occurs within the body then the check is considered a failure and [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.on_error "discord.ui.View.on_error") is called.
wet crystal
#

idk tho

slate swan
# unkempt canyon

check the embed, get the view's children, and disable the required button using the disabled property

flint isle
#

does anyone know how i can convert a google firebase code into being able to be stored in .env

zealous jay
#

Hey! Quick question, how do I make subcommands for slashcommands? Using discord.py

#

or commands groups, are they the same thing?

potent spear
potent spear
#

what's your source

#

why do you think discord.Option exists?

flint isle
#

    @commands.command(name='logoff')
    @disnake.ext.commands.is_owner()
    async def logoff(self, inter):
        await inter.send('ATTENTION: Bot is Logging off')
        await self.bot.close()
        print('Bot Logged Off')
        await exit()
    @logoff.error()
        

does anyone know how i can settup the logoff error for if the commanding user is not the owner

potent spear
#

no idea how to use that lib

slate swan
#

on_command_error event, and comparing the error's class with NotOwner

#

the error class is NotOwner right, please correct me if im wrong

young pendant
#

hey guys, i have this code, in func sending_messages i send message in channel. its work but sometimes i have strange warnings and errors and this bot stop sending messages, but program continue working. why it could be?

flint isle
slate swan
flint isle
slate swan
#

yessir

flint isle
#

like a seprate cog or inside a cog

slate swan
#

yes it is, tho you can modify it and use normally

#

making your own code is a better choice

flint isle
#

ok

glass tangle
#

what is a cog?

potent spear
celest marlin
#

Looking to hire someone for a current project, dm me if interested

glass tangle
#

do you have a link?

celest marlin
#

Can you dm me

potent spear
unkempt canyonBOT
#

9. Do not offer or ask for paid work of any kind.

potent spear
#

nah
I want an actual use case

#

i do this, and that happens

glass tangle
#

@potent spearthanks, I'll read that 🙂

potent spear
#

how do you think that command will work?

#

nah, how will you call the command

#

act like you're invoking the command

#

how would you? you can't obviously mention banned users

sly hamlet
#
Ignoring exception in command 'real':
Traceback (most recent call last):
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\commands.py", line 639, in _do_call
    return await self._callback(self.binding, interaction, **params)  # type: ignore
  File "C:\Users\culan\Desktop\3.0.0 echo\cogs\nsfw.py", line 92, in real
    embed.set_image(url = realResponse['url'])
KeyError: 'url'

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

Traceback (most recent call last):
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\tree.py", line 1090, in call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\commands.py", line 665, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\commands.py", line 658, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'real' raised an exception: KeyError: 'url'``` what am i doin worng
sick birch
#

What is realResponse?

sly hamlet
#
@commands.cooldown(1, 5, commands.BucketType.user)
    @app_commands.command(name='',
                       description="")
    async def (self, interaction: discord.Interaction):

            response = requests.get("api linl=k")

            realResponse = response.json()

            embed = discord.Embed(
                title = "",
                color = 0x0000FF
            )
            embed.set_image(url = realResponse['url'])

            await interaction.response.send_message(embed = embed)
        else:
            embed=discord.Embed(title="Error", description=".", color=0xff3333)
            await interaction.response.send_message(embed=embed)``` what i get back from api `{"image":"pic link"}`
potent spear
#

a dict without an url key

wet crystal
#

why is nextcord.Guild.categories returning
<property object at 0x0000029156D2D6C0>
instead of a list of categories?

sly hamlet
vale wing
wet crystal
vale wing
#

Lmfao

#

Man wtf

wet crystal
#

wdym?

potent spear
vale wing
#

I mean you don't copy text straight from docs

wet crystal
vale wing
#

You just made a reference to a method of a class

sick birch
wet crystal
vale wing
#

Idk if I can call properties methods but in fact they use methods

vocal plover
vale wing
#

"Decorated methods that don't require calling" might be a weird definition but probably valid

sly hamlet
vocal plover
#

yes

#

assuming you're getting back the data you think you are

warped mirage
#

guys

wet crystal
#

there is no get_category etc

vale wing
# wet crystal which method?

!e

class Stuff:
    def __init__(self, smth):
        self.something = smth

    @property
    def some_stuff(self):
        return self.something * 420

print(Stuff.some_stuff)  # no object instantiated, we are accessing method of a class
print(Stuff(69).some_stuff) # object instantiated and we can access its property```
unkempt canyonBOT
#

@vale wing :white_check_mark: Your eval job has completed with return code 0.

001 | <property object at 0x7fb0f3f2bbf0>
002 | 28980
vale wing
warped mirage
#

so can someone help me.

potent spear
warped mirage
#

SniperGlitcherz wsg can u help me

wet crystal
vale wing
#

!d discord.CategoryChannel no idea honestly

unkempt canyonBOT
#

class discord.CategoryChannel```
Represents a Discord channel category.

These are useful to group channels to logical compartments.

x == y Checks if two channels are equal.

x != y Checks if two channels are not equal.

hash(x) Returns the category’s hash.

str(x) Returns the category’s name.
potent spear
#

example

vale wing
#

Probably discord API considers categories the channels as well

potent spear
#

hey, I made a command which I expect to do X when I do !shit remove
but actually, it does Y
can anyone tell me why? <command codeblock>

potent spear
unkempt canyonBOT
#

class discord.CategoryChannel```
Represents a Discord channel category.

These are useful to group channels to logical compartments.

x == y Checks if two channels are equal.

x != y Checks if two channels are not equal.

hash(x) Returns the category’s hash.

str(x) Returns the category’s name.
potent spear
#

yes

warped mirage
#

hey i coded a msg_set for my welcome message ```py
@commands.command()
async def set_msg(self, ctx):
async with aiosqlite("wm.db") as db:
cursor = await db.cursor()
await cursor.execute("SELECT * FROM wm WHERE guild_id = ?", (ctx.guild.id,))
data = await cursor.fetchone()

        if data is None:
            await cursor.execute("INSERT INTO wm(guild_id, channel_id) VALUES(?,?)", (ctx.guild.id, ctx.channel.id,))
            await db.commit()
            await ctx.send("Welcome Message has been set")
            return
        if data is not None:
            await cursor.execute("SELECT channel_id FROM wm WHERE guild_id = ?", (ctx.guild.id,))
            await cursor.fetchone()
            result = data[0]
            await ctx.send(f"WelcomeMessage is already set", delete_after = 10 )
            return``` doesnt seem to work , can someone help me fix it
potent spear
#

doesn't seem to work
F

warped mirage
#

well i showed my code

#

should make sense i guess

warped mirage
#

bruh

potent spear
slate swan
#

How can I add a reaction with default discord emoji?

vale wing
warped mirage
#
@commands.command()
    async def set_msg(self, ctx):
        async with aiosqlite("wm.db") as db:
            cursor = await db.cursor()
            await cursor.execute("SELECT * FROM wm WHERE guild_id = ?", (ctx.guild.id,))
            data = await cursor.fetchone()

            if data is None:
                await cursor.execute("INSERT INTO wm(guild_id, channel_id) VALUES(?,?)", (ctx.guild.id, ctx.channel.id,))
                await db.commit()
                await ctx.send("Welcome Message has been set")
                return
            if data is not None:
                await cursor.execute("SELECT channel_id FROM wm WHERE guild_id = ?", (ctx.guild.id,))
                await cursor.fetchone()
                result = data[0]
                await ctx.send(f"WelcomeMessage is already set", delete_after = 10 )
                return``` hey i coded a set welcome message command if u look at it it doesnt seem to look right in my opinion , as of now there arent any errors
#

u cant make it better then that

slate swan
#

You dont need await to execute or fetch

#

you need to.

vale wing
#

You do

#

It's aiosqlite

slate swan
#

Oh

#

I didn't see that

#

My bad

#

I use sqlite which dont need await

warped mirage
#

basically what i did

vale wing
#

Simple sqlite will cause issues

warped mirage
#

is copied the code from wm_set (set welcome channel) and changed some stuff

#

so now i need to uknow make it into what it should be

vale wing
#

Personally I hate aiosqlite but we all gotta use it if we want to keep using sqlite

wet crystal
#

this is odd and my brain cant comprehend that

vale wing
#

I use postgres cuz asyncpg is much more convenient

warped mirage
vale wing
#

@warped mirage do you have a global error handler (on_command_error)?

warped mirage
#

no

vale wing
#

And you get no errors?

potent spear
#

the mosty important question of them all

#

what's "not working" about it?

warped mirage
#

..... one sec

#

File "C:\Users\Dom\Desktop\beta test\cogs\welcomesystem.py", line 68, in set_msg
async with aiosqlite("wm.db") as db:
TypeError: 'module' object is not callable

vale wing
#

self.client.get_channel() with no arguments would definitely cause errors (it's in the listener so can't be caught by on_command_error anyway)

potent spear
#

now we're talking

vale wing
#

aiosqlite.connect() bro

#

Why'd you call a module

warped mirage
#

wait

sick birch
#

Worth putting in that you should have one global aiosqlite.connect()

potent spear
#

preferably a botvar

slate swan
#

async with aiosqlite("wm.db")

vale wing
#

Wrapped into bot subclass

dim wing
#

is possible to add a timer in a cog?

potent spear
vale wing
#

What kind of a timer

slate swan
#

depends on what you mean by timer

vale wing
#

3 persons helping you gg

dim wing
warped mirage
#

Hmm it updates the message it might work

#

We shall see

dim wing
#

just a cooldown/timer, and when we trigger a command it could reset it

#

but in a cog

#

and not in a command

vale wing
#

Yeah just decorate the command

slate swan
#

is it an on_message event?

vale wing
dim wing
#

mmh i don't know how to explain

vale wing
#

Show your code

dim wing
#

i will explain you my project

#

i don't have code yet

slate swan
#

if you could show an example of what you want to do, we can help you

vale wing
warped mirage
#

File "C:\Users\Dom\Desktop\beta test\cogs\welcomesystem.py", line 21, in on_member_join
channel_id = await cursor.fetchone
TypeError: object method can't be used in 'await' expression

#

@potent spear

vale wing
#

Do you even call the method

#

I see no brackets

warped mirage
#

wait

dim wing
#

I want to use paramiko (python library) to connect to my raspberry pi, via a discord bot. And i have to etablish a SSH connection with paramiko. But i want only one user to be able to control my raspberry pi. So i want to etablish a cooldown/timer, so if nobody use a command that uses paramiko, then it stop the connection. But if someone use a command, it reset the timer and the SSH connection continue

vale wing
#

When you get an error just try to understand the error itself and if you didn't, look at the line of traceback that is written by you and find what's wrong

vale wing
warped mirage
#

final = self.client.get_channel()
TypeError: Client.get_channel() missing 1 required positional argument: 'id'

#

next error

potent spear
#

error says it all

warped mirage
#

it id

warped mirage
#

btw this system is meant to be multi guild

vale wing
warped mirage
#

so what do i do

dim wing
#

nice idea

#

thx

warped mirage
dim wing
#

but do you think my little project is possible?

vale wing
#

If this is what you wanted yw

potent spear
vale wing
warped mirage
#

so channel_name?

dim wing
wet crystal
vale wing
#

!d discord.Guild.categories 😉

unkempt canyonBOT
#

property categories```
A list of categories that belongs to this guild.

This is sorted by the position and are in UI order from top to bottom.
warped mirage
#

bruh

#

what do i change

vale wing
#

But to understand the OOP principle

wet crystal
#

come on, isnt there a workaround

vale wing
#

You have a discord.Guild object and that's your ctx.guild and that object has categories attribute

vale wing
wet crystal
#

basically the way you just told me and I really do like it indeed

vale wing
#

Allegory bro

wet crystal
warped mirage
#

@potent spear bro i did say my code is incorrect , the first 2 commands and last 2 almost look the same and have the same function i think , can u check my code?

vale wing
#

Literature term

#

Sry I am confusing you

warped mirage
#

when i did del_msg it removed my system

vale wing
wet crystal
wet crystal
#

thats why I said thanks

vale wing
#

Nice

wet crystal
#

you're a good teller fr

vale wing
#

Thx

flint isle
#

hmm i cant get my error handler to grab the users name

#

how would i do that?

warped mirage
vale wing
flint isle
potent spear
#

just saying "something doesn't work" isn't helping us

#

we want to know what you did, what you expected to happen, and what actually happened

vale wing
warped mirage
#

I CODED 2 commands , wm_set sets welcome channel and wm_del removes the channel then i coded another 2 commands set_msg (SETS THE WELCOME MESSAGE) del_msg ( DELETES THE WELCOME MESSAGE ) when i do set_msg it says its already set , when i do del_msg it turns of the system

#

thats the best detail i can say

potent spear
warped mirage
#

i said what i did , what its meant to do

#

WM_SET(set the channel) wm_del (remove the channel) set_msg(set welcome message) del_msg (delete the welcome message)

#

there u go

potent spear
#

I don't care about those command names

#

just start with 1 command at a time

#

tell me 1 command first

warped mirage
#

bruh

potent spear
#

I just don't have the time to look at it all at once

warped mirage
#

how about u put my code into ur and test it

#

u will understand perfectly

regal pulsar
#

that logic lmao

warped mirage
#

which command is this

vale wing
slate swan
#

imagine not making helper functions

#

How can I make a function, when I verify with this way, the bot to add me a role?

potent spear
#

this event will be called when the user is verified (the member.pending will be True after verification )

slate swan
#

there was a property named pending or is_pending iirc, hm

slate swan
potent spear
slate swan
hollow zealot
#

#bot-commands

flint isle
#

umm i accadentally switched branches in git and my changes are gone is there a way to recover them? i lost 1 hr of coding my bot

slate swan
#

what ide is that

#

I want to make circle image manipulation of member with pillow, but i want the pic to be circular , is there any way to do this?

#

will some one help me make a bot ?

#
import discord
from http import client
import random

TOKEN = 'bot discord token here'

client = discord.Client()


@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

    client.run(TOKEN)

i started but not working

flint isle
slate swan
#

didnt you save your code before switching the branch>

slate swan
flint isle
#

it saves automatically...

#

i didnt mean to switch branches

slate swan
#

so now when you go back to your normal branch it isnt at the state you left?

sick birch
#

It looks like you're following a youtube tutorial, so before you go down that rabbit hole, just don't

slate swan
# slate swan wdym

client.run is inside on_ready function, but it should be on global level

sick birch
#

Also remove from http import client due to namespace conflict

sick birch
#

I only point that out because your code looks suspiciously familiar

slate swan
#

oke im beginner in python i started some weeks ago

sick birch
#

In that case, maybe you should get a better grasp of Python first?

#

That's only going to help you understand concepts easier

slate swan
sick birch
#

Yeah those are usually subpar and not really that good

slate swan
#

but can u accept my friend request i want ask u something ?

sick birch
#

!resources these are some good resources to get started

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

sick birch
slate swan
#

idk how to say it

#

cuz its some people that will laugh

green bluff
sick birch
#

Nobody's laughing, it's all fair questions here

heavy shard
#

certainly not

slate swan
#

oh ok cuz in polish community everyone doing this

green bluff
sick birch
#

Doing what?

slate swan
#

laugh

sick birch
#

Go ahead and ask, we're more than willing to help and we don't judge

still mountain
sick birch
#

There are no stupid questions, as it were

green bluff
sick birch
#

Knowing the concepts of how something works is probably the best way to work with it

slate swan
flint isle
#

@slate swan if i send you a zip of the directory including the .git could you see if the files are still there?

sick birch
slate swan
sick birch
#

In which case, you should probably start looking for other resources

#

We call this "tutorial hell"

sick birch
#

You don't learn and retain anything by just watching someone else code something, then copying it down

green bluff
#

^^ yeah understanding the code is much better

sick birch
#

Same way you don't get better at, say, football just by watching professional athletes play it on TV

slate swan
sick birch
#

!resources books are a very good learning medium

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

sick birch
#

I find that things actually go to my head with books & hands on practice

slate swan
sick birch
#

Your nationality doesn't matter when you're learning

green bluff
sick birch
#

I would recommend against W3schools

slate swan
#

i can english but if i read in english i get nothing in head

sick birch
#

Whatever you do, don't go there

flint isle
green bluff
sick birch
#

I'm not 100% sure but the resources link I sent you earlier, there are tens of resources and one of them may support polish as the language

slate swan
sick birch
#

Yeah, most people do early on

green bluff
#

Just better to know

sick birch
#

The main reason would just be blatant misinformation

sick birch
#

Other reasons include lacking syntax/documentation, subpar examples, pretty bad explanations, list goes on

#

Not to mention they did SEO like hell

slate swan
#

w3schools can be in polish too ?

sick birch
#

Don't know, but again don't use it

flint isle
#

i completely lost my errorhandler file when i caccadentally changed branches

slate swan
slate swan
sick birch
#

!resources

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

slate swan
sick birch
#

There are a bunch if you click on that link

slate swan
#

ik

#

how long u take to learn python ik its difference but asking

flint isle
sick birch
#

I don't know, honestly, one can never really learn a language

#

Every day you learn something new

slate swan
#
        img = Image.open("welcome.png")
        asset = member.avatar_url_as(size=128)
        data = BytesIO(await asset.read())
        pfp = Image.open(data)
        pfp = pfp.resize((177,177))
        img.paste(pfp, (120, 122))
        img.save("welcome2.png")
        await channel.send(file=discord.File("welcome2.png"))``` How can I make this image circular?
slate swan
sick birch
#

Not a problem

slate swan
#

how i can make the tutorials to polish ?

sick birch
slate swan
#

but like click on a book and see if it support polish ?

sick birch
#

Maybe. Some books do print in multiple languages

slate swan
#

i see nothing

#

is this good xd

sick birch
#

I remember doing that for a club 6th or 7th grade year, I thought it was pretty stupid

slate swan
#

so its bad ?

sick birch
#

Maybe. My opinion was that it's bad

slate swan
#

i didnt whant this

#

a game

#

this ??

sick birch
#

Looks useful, though I'm not the right person to ask since I've never used these resources

#

I'm a more hands on person like I mentioned, and I learn by doing rather than reading or watching

sick birch
#

None, I try my best to make projects and learn from them

sick birch
#

different people learn differently ¯_(ツ)_/¯

slate swan
#

but i dont know how it will be best for me to learn python

#

like i want to learn it but if i ask people they tell me differently

sick birch
#

You need to figure that out yourself, since only you know yourself

sick birch
#

Not really, what sort of tips are you looking for?

slate swan
#

learning python

sick birch
#

Well, only one I can really give you is that your mindset is probably the most important thing when it comes to learning

green bluff
#

Which converts all english to polish

slate swan
green bluff
slate swan
#

name

green bluff
slate swan
#

im starting getting no ide now how i will learn python

#

😭

#

Learning "enough" Python isn't super difficult, it just takes some patience and willingness. You can start by learning the basic concepts first (variables, built-in data types, syntax, functions, etc) and attempt different stuff as you progress. What worked for me (this might not work for you) is read a lot of source code; I started out by trying to make discord bots, and it was very unintuitive for me as I knew very little Python. So I read the library's source code and googled stuff up as I went along. Programming languages are literally meant to be human readable, just take time and go slowly and thoughtfully.

sick birch
#

Pretty sure google translate can translate entire sites for you

slate swan
#

Lol read the website

#

It says up there "Read the basics"

#

Look through those links

#

learn

#

Don't worry, it is made as simple as possible for people to understand

heady sluice
slate swan
#

Like all of Python or something?

#

Because you only really need to know what you're using

#

If that makes sense

#

timtoy

#

wheres your cat pfp😾

slate swan
#

its more

#

something for discord with python

#

only i know discord,tools,multitool

lyric apex
#
    @commands.Cog.listener()
    async def on_message(self, message):
        db = sqlite3.connect('afk.db')
        cursor =  db.cursor()
        cursor.execute(f"SELECT user FROM afk WHERE user = {message.author.id}")
        result = cursor.fetchone()
        if result is not None:
            cursor.execute(f"DELETE FROM afk WHERE user = {message.author.id}")
            await message.channel.send(f"Welcome Back **{message.author}**, I removed your AFK. You were afk")
            db.commit() ```
#

This instantly removes my data how to fix it

stone beacon
#

!with

unkempt canyonBOT
#

The with keyword triggers a context manager. Context managers automatically set up and take down data connections, or any other kind of object that implements the magic methods __enter__ and __exit__.

with open("test.txt", "r") as file:
    do_things(file)

The above code automatically closes file when the with block exits, so you never have to manually do a file.close(). Most connection types, including file readers and database connections, support this.

For more information, read the official docs, watch Corey Schafer's context manager video, or see PEP 343.

wet crystal
#

why does ctx.guild.members only show me 1 member and thats the bot himslelf?

slate swan
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

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

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.

wet crystal
#

yeah i forgot the intents=intents in the commands.bot

#

thanks

rocky hornet
#

do i need to create another app in dev portal if i want a test version of my bot?

loud junco
lyric apex
loud junco
rocky hornet
#

i remember always using with_static_format("png") because of apple not supporting webp

#

is this still a thing?

slate swan
#

!d discord.Asset.with_static_format

unkempt canyonBOT
#

with_static_format(format, /)```
Returns a new asset with the specified static format.

This only changes the format if the underlying asset is not animated. Otherwise, the asset is not changed.

Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") instead of `InvalidArgument`.
rocky hornet
#

do i still have to do it?

#

i even made this ugly shortcut

disnake.Asset.compat = property(
    lambda self: self.with_static_format("png")
)
loud junco
#

jesus christ i forgot this 💀

#

its ; ?

rocky hornet
#

wrong language mate

loud junco
#

LOL

#

for i=1 to 3?

rocky hornet
#

for i in range(1, 4):

loud junco
#

alright

#

thanks mate

rocky hornet
#

that is if you actually use i

#

if u just want to iterate 3 times use for _ in range(3):

loud junco
#

alright thanks

rocky hornet
#

can my bot access these assets from dev portal?

wet crystal
#

How can I send a message to the channel if someone tried to invoke a command but didn't enter necessary arguments?

potent spear
#

mind you: always add an else statement in error handlers

#

if not: the error will raise (silently without output) and you won't even notice, since you never handled it

wet crystal
#

thanks

potent spear
#

👍

wet crystal
potent spear
#

Great! So I don’t want to see any discord.Guild.categories etc anymore in your code

wet crystal
wet crystal
potent spear
lyric apex
#

MissingArguement

wet crystal
#

thanks

#

is it possible to make a dismiss button like Clyde has when dm'ing a blocked person or someone who doesn't accept dm's

torn sail
#

You only can when sending a message from an interaction and making it ephemeral

flint isle
#

is there a list of possible bot errors for disnake

stone beacon
#

Well the docs are supposed to tell you of possible exceptions for each function so

#

Bot errors are gonna depend on what the bot is doing

flint isle
#

well lol im trying to work on my error handler

robust fulcrum
#

Guys what's use of cogs.listener
Me not able to understand it from documentation

robust fulcrum
#

Like @client.event

#

Am i right?

torn sail
#

Yes but it would be within a cog

robust fulcrum
#

Ok thank u

#

Actually me usings cogs First time

sick birch
robust fulcrum
#

Guys can anyone help me fix this error

fading marlin
#

it's await bot.add_cog(...) if you're using 2.0

robust fulcrum
#

Ok

robust fulcrum
fading marlin
#

if you're using await inside a function, the function should be async

robust fulcrum
#

Hmmm async def?

fading marlin
#

precisely

robust fulcrum
#

@fading marlin ```py
bot.get_channel

With what we have to replace bot in cogs
fading marlin
#

self.bot ??

robust fulcrum
fading marlin
#

yes

robust fulcrum
#
import discord
from discord.ext import commands
import requests
import json

def get_quote():
  response = requests.get("https://zenquotes.io/api/random")
  json_data = json.loads(response.text)
  quote = json_data[0]['q'] + " -" + json_data[0]['a']
  return(quote)

class quote(commands.Cog):                       
	def __init__(self, bot):                          
		self.bot = bot
		
	@commands.command()
    async def quote(self, ctx):
		quote = get_quote()
		Embed = discord.Embed(title="Quote", description=quote,color=discord.Color.green())
		await ctx.send(embed=Embed)

async def setup(bot):
	await bot.add_cog(quote(bot))

Guys me again and again getting indentation error but my indentation is correct

regal pulsar
#
import discord
from discord.ext import commands
import requests
import json


def get_quote():
    response = requests.get("https://zenquotes.io/api/random")
    json_data = json.loads(response.text)
    quote = json_data[0]["q"] + " -" + json_data[0]["a"]
    return quote


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

    @commands.command()
    async def quote(self, ctx: commands.Context):
        quote = get_quote()
        embed = discord.Embed(title="Quote", description=quote, color=discord.Color.green())
        await ctx.send(embed=embed)


async def setup(bot: commands.Bot):
    await bot.add_cog(Quote(bot))

#

seems fine to me

robust fulcrum
#

!p

unkempt canyonBOT
#
Missing required argument

pep_number

robust fulcrum
#

How to paste code?

slate swan
#

Used client.remove_command(“help”)
And then created my own help command
But it is unresponsive

#

Wait I’ll send code

marsh mulch
slate swan
#
@client.command()
async def Help(ctx):
  await ctx.send(embed=hE)
  button2 = Button(label = "Utility Commands", style = discord.ButtonStyle.blurple, emoji = ":utility:"),
  Button(label = "Fun Commands", style = discord.ButtonStyle.blurple, emoji = ":bug4:"),
  Button(label = "Moderation Commands", style = discord.ButtonStyle.blurple, emoji= ":mod:"),
  Button(label = "Dank Commands", style = discord.ButtonStyle.blurple, emoji = ":dh_pepe_juce:")
  async def button_callback4(interaction):
    if interaction.button.label == "Utility Commands":
          await interaction.response.send_message(embed=UC)
    if interaction.button.label == "Fun Commands":
          await interaction.response.send_message("Currently There Are No Fun Commands")
    if interaction.button.label == "Moderation Commands":
          await interaction.response.send_message(embed=b)
    if interaction.button.label == "Dank Commands":
          await interaction.response.send_message(embed=d)

    button.callback = button_callback4
    view = View()
    view.add_item(button2)
    await ctx.send(embed=hE, view=view)
#

No errors in terminal

slate swan
placid verge
#

Guys i want to make a discord bot that it plays the songs that we uploaded to the bot before , and we can make playlists of those songs, is that possible ?

regal pulsar
#

just fixed his indentation

placid verge
#

did you mean purple ?

torn sail
#

!d discord.ButtonStyle.blurple

unkempt canyonBOT
torn sail
#

It exists

placid verge
#

hm ok

marsh mulch
#

Is it possible to edit already sent embeds?

sick birch
sick birch
placid verge
sick birch
#

Right, any error handlers?

#

Because the first line await ctx.send(embed=hE) should be throwing an error, unless you have a globally defined hE variable

slate swan
#

nope

sick birch
#

You're sure? No on_command_error or on_error anywhere at all?

slate swan
sick birch
#

ah okay

sick birch
#

and the embed won't send?

#

Try printing something:

@client.command()
async def Help(ctx):
  print("help")
  ...
slate swan
#

i had ctx.send(embed=hE at end
when i used it at top of command
the embed is sent but no buttons

sick birch
#

I also believe you're doing the whole button thing wrong

slate swan
#

hmm k

#

wait

robust fulcrum
sick birch
#

Your indentation is messed up quite a bit

#

For one it doesn't seem like they're 4 spaced

robust fulcrum
#

But on replit it's correct

#

Means looking

sick birch
#

If it was correct it wouldn't be giving you the error, would it?

robust fulcrum
#

Maybe replit error

sick birch
#
        @commands.command()
    async def quote(self, ctx):
        quote = get_quote()
        Embed = discord.Embed(title="Quote", description=quote,color=discord.Color.green())
        await ctx.send(embed=Embed)
#

Looks like that part isn't indented properly

#

The first 2 lines have to be on the same indent level

robust fulcrum
#

But i replit it's indented

sick birch
#

Again, if it was indented properly you wouldn't be getting the error

#

Can you send a screenshot of how it looks on replit?

robust fulcrum
#

Ok

sick birch
#

And where exactly is the error saying the problem is?

robust fulcrum
#

Line 17

sick birch
#

Full traceback please

slate swan
#
Traceback (most recent call last):
  File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 200, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\Jaisman's PC\Desktop\ACLib\bot.py", line 367, in Help
    await ctx.send(embed=hE, view=Help12)
  File "C:\Python310\lib\site-packages\discord\ext\commands\context.py", line 700, in send
    return await super().send(
  File "C:\Python310\lib\site-packages\discord\abc.py", line 1521, in send
    with handle_message_parameters(
  File "C:\Python310\lib\site-packages\discord\http.py", line 183, in handle_message_parameters
    payload['components'] = view.to_components()
TypeError: View.to_components() missing 1 required positional argument: 'self'

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

Traceback (most recent call last):
  File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1329, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 995, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 209, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: View.to_components() missing 1 required positional argument: 'self'
#

my buttons are in a class

robust fulcrum
#

@sick birch

sick birch
#

hmm odd

slate swan
#
class Help12(View):
      def __init__(self):
            super().__init__(timeout=None)


            @Button(label = "Utility Commands", style = discord.ButtonStyle.blurple, emoji = ":utility:")
            async def counter(interaction: Interaction, button: Button):
              await interaction.response.send_message(embed=UC),

            @Button(label = "Fun Commands", style = discord.ButtonStyle.blurple, emoji = ":bug4:")
            async def counter2(interaction: Interaction, button: Button):
              await interaction.response.send_message("There are no fun commands."),

            @Button(label = "Moderation Commands", style = discord.ButtonStyle.blurple, emoji= ":mod:")
            async def counter3(interaction: Interaction, button: Button):
              await interaction.response.send_message(embed=b),

            @Button(label = "Dank Commands", style = discord.ButtonStyle.blurple, emoji = ":dh_pepe_juce:")
            async def counter4(interaction: Interaction, button: Button):
              await interaction.response.send_message(embed=d)
robust fulcrum
sick birch
sick birch
robust fulcrum
#

Ok

#

Actually me using replit as me on Android

#

Otherwise windows have best ides

sick birch
#

Technically most are cross platform

#

Except maybe emacs which doesn't want to play nice with windows

slate swan
#
class Help12(View):
  File "c:\Users\Jaisman's PC\Desktop\ACLib\bot.py", line 348, in Help12
    async def counter(interaction: Interaction, button: Button):
TypeError: 'Button' object is not callable

error ^

sick birch
#
  1. They should be un-indented, under the class, not the constructor
  2. it should be discord.ui.button, lowercase b
slate swan
#

and if its a class, shouldnt the first parameter be self?

sick birch
#

that too

regal pulsar
#

!d disnake.ButtonStyle

unkempt canyonBOT
#

class disnake.ButtonStyle```
Represents the style of the button component.

New in version 2.0.
robust fulcrum
slate swan
hidden snow
#

hey after you learn all about python OOP do you have enough knowledge to code a discord bot?

silk fulcrum
#

Cus someone think that if they know that it is Object Oriented Programming and it's about objects they know everything

hidden snow
#

like you understand oop

#

can u code cool bot

hollow zealot
#

how do i make a sleep without the bot not responding to a message

silk fulcrum
#

Uhm, then yes I think, also you need to know how to readthedocs

slate swan
hollow zealot
#

if I use the sleep and someone else ran a command. the bot won't respond until the sleep is finish

silk fulcrum
silk fulcrum
#

import asyncio also

hidden snow
hollow zealot
hollow zealot
#

do i need to import things. just like i did in sleep?

silk fulcrum
#

yes

#

asyncio

hollow zealot
#

ok thks

slate swan
silk fulcrum
#

await?

slate swan
#

await*

silk fulcrum
#

xD

hollow zealot
#

thks

#

UwU

silk fulcrum
#

me searching what is better to store prefixes: json or database

maiden fable
#

JSON according to me but people prefer db

#

Ngl the only reason I love JSON is cz it's easy to edit and highly readable

silk fulcrum
#

MEE6: json

vocal snow
#

Depends on if you already have a db set up and how many prefixes you're planning to store

slate swan
silk fulcrum
silk fulcrum
slate swan
silk fulcrum
#

oh

slate swan
#

or pocket or deta

silk fulcrum
#

Nah i prefer MySQL

vocal snow
silk fulcrum
#

Also it'll be easy to use it in dashboard

silk fulcrum
regal pulsar
regal pulsar
#

lots of limitations tho

hollow zealot
#

@regal pulsar its u........

regal pulsar
hollow zealot
regal pulsar
#

i just saw it in your status

#

got curious

#

then left

hollow zealot
#

ok ig 🤷‍♂️

maiden fable
# regal pulsar lots of limitations tho

What I prefer to do- Store the json content in memory on startup, then close the file (or use a context manager). Then, make a task to save the updated data (from memory) to the JSON every x minutes. This way, u won't really encounter any data corruption issues acc to me

slate swan
#

How can I replace spaces with a percent symbol?