#discord-bots

1 messages ยท Page 186 of 1

spice jewel
#

this is killing me

upbeat otter
#

no, I personally don't have a solution, we're in the same boat peepocry

spice jewel
#

should I uninstall and install sqlite again

#

and try stuff like that

shrewd fjord
#

U using aiosqlite

spice jewel
#

yeah

shrewd fjord
#

.....

upbeat otter
#

I mean you could try but I'd prefer making a single connection first and trying, so many unclosed connections may mess up the file and corrupt it at the end of the day pepe_exit

shrewd fjord
shrewd fjord
#

Use db visualizer to inspect the db file

spice jewel
#

ive tested this all before

#

it all worked and now all of a sudden there is an error

#

(I didnt change anything)

spice jewel
shrewd fjord
#

await cursor.close()
await db.close()

upbeat otter
#

just make a single connection

shrewd fjord
upbeat otter
#

so many connections is resource consuming and makes the file prone to corruption

naive briar
#

It auto-closes after the context manager ends

upbeat otter
#

yes

shrewd fjord
#

๐Ÿ’€i forgor totally

#

with open(file....) as ash:
Do the same lol

upbeat otter
#

,

shrewd fjord
#

...

#

I saw dat Peepo_UwU

upbeat otter
wraith meteor
#

hey Catgal, type pip install invoke, i am not weard, i am a yang PetoNYst:)

pastel basin
#

May someone explain this to run the slash commands>

    await client.tree.sync()
``` I cant find it in the docs
#

Code?

steep estuary
#

what is the problem here?

#

the process is terminated because it's using too much memory?

naive briar
unkempt canyonBOT
#

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

Syncs the application commands to Discord.

This also runs the translator to get the translated strings necessary for feeding back into Discord.

This must be called for the application commands to show up.
vocal hollow
#

how to turn off @ everyone but allow mentioning of specific roles?

pastel basin
static thunder
#

async for entry in g.audit_logs(limit=1,after=datetime.datetime.now() - datetime.timedelta(minutes=2),action=discord.AuditLogAction.bot_add):

#

why isnt this working nothing is logged

vocal hollow
pastel basin
#

Then go to the role that you want others to mention

pastel basin
vocal hollow
#

does community automatically disable everyone

static thunder
#

help me also

vocal hollow
#

oh ok

pastel basin
#

@vocal hollow
Check the second option if you want a specific role that can be @ by anyone

static thunder
#

ignore,,,

shrewd fjord
#

Hewo

wraith meteor
#

who is from which country?

shrewd fjord
#

!d discord.Guild.audit_logs

unkempt canyonBOT
#

async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the guildโ€™s audit logs.

You must have [`view_audit_log`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.view_audit_log "discord.Permissions.view_audit_log") to do this.

Examples

Getting the first 100 entries:

```py
async for entry in guild.audit_logs(limit=100):
    print(f'{entry.user} did {entry.action} to {entry.target}')
```...
shrewd fjord
timid spade
#

anyone familiar with sqlite?

shrewd fjord
#

Ye?

timid spade
wraith meteor
#

wodgenzi_ test your sql request on sql console....

#

whan wright request code..

heady verge
#

how to check if a user who is using the cmd has a banner or guild avatar

shrewd fjord
unkempt canyonBOT
#

property default_avatar```
Equivalent to [`User.default_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.default_avatar "discord.User.default_avatar")
shrewd fjord
#

!d discord.Member.banner

unkempt canyonBOT
#

property banner```
Equivalent to [`User.banner`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.banner "discord.User.banner")
shrewd fjord
#

!d discord.Guild.icon

unkempt canyonBOT
shrewd fjord
#

Check this 3 prooerties

#

Properties*

heady verge
#

okay

grizzled crown
#

to find if a bot on discords is open source should one search on github

#

or are there other ways to know if the bot is free or more info on it

#

I am also curious if Discords has access to source code of all bots?

vale wing
grizzled crown
#

idk, just wondering

#

hope not but just wanted to be sure

vale wing
grizzled crown
#

sometimes I see link to bot on profile

#

but other times I dont

vale wing
#

Most of mega-popular bots like dyno and mee6 aren't open-sourced yk

shrewd fjord
#

Mhm

vale wing
grizzled crown
#

so I wonder what if the bot didn't have link to info or github source code, how to get info on it?

vale wing
grizzled crown
#

so no way to get info or source code on it?

vale wing
#

Why are you so obsessed with that

grizzled crown
#

I like different bots from different servers

vale wing
#

There are tons of open-source bots just search until you find one

shrewd fjord
#

Just make one yourself :)

grizzled crown
#

I hope to create my own server soon but dont know if I can do all the bots I want

#

I think its faster if I can copy them but sometimes I dont see info on it

shrewd fjord
grizzled crown
#

but from what I am understanding, discords bot is actually similar to twitter bot

#

it seems a lot of bots use python

vale wing
#

Platform sends events to app, app sends requests to platform

#

Not a surprise, everything functions like that

grizzled crown
#

I see, so seems learning discords bot skill will translate to other kind of bots

vale wing
#

If you learn principle, not only library

grizzled crown
#

python principle or others?

vale wing
#

API interactions principle

#

Webhooks, requests and websockets

grizzled crown
#

hmm do most API use python?

#

discords API is python or could it also work with others, not sure actually

#

but yes I do think I need to learn more about API interactions principle as I plan to use bots and API in general

#

one great thing about this field is since code can be on your own private server, maybe it can't be copied as easy as javascript

#

I remember debating someone about this, but I think they mention javascript had their own server backend so not sure, I guess all languages are similar in a way, but I chose python for now

shrewd fjord
grizzled crown
#

oh interesting, didn't know that, thanks

#

so some discords bots may be harder to manipulate if programmed in a language you dont know

shrewd fjord
#

Yes

#

If u r wondering there is several python libraries, where they parsed all informations from the API and made it usable for normal users

grizzled crown
#

I see, I am now wondering if someone got in trouble for copying someone bot and server? is it okay to do that I hope

slate swan
#

depends on how you define copy

#

if you straight up take their source and shit yeah. that can prob get it taken down

grizzled crown
#

discords has ban users for that?

#

I think this is why we need decentralized discords to become more popular

#

once things are decentralized, no one owns them and can ban people

shrewd fjord
#

If the bot owner gives you the source or make it public or give you perms, then u good to go

slate swan
#

You can steal bot code lol?

shrewd fjord
#

Like making a same type of support server as apollo

#

Copying their bot's pfp etc

shrewd fjord
#

Lol

rare echo
#

they wont ban if its just a mimic but if its for malicious intent thats different, either for users or towards the real bot

shrewd fjord
#

Intention hm

slate swan
spice jewel
#
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/nextcord/ext/commands/core.py", line 165, in wrapped
    ret = await coro(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/myname/Custom bot/cogs/add.py", line 20, in add
    await cursor.execute('SELECT id FROM users WHERE guild = ?', (ctx.guild.id,))
                                                                  ^^^^^^^^^
AttributeError: 'AddCog' object has no attribute 'guild'

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

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/nextcord/ext/commands/bot.py", line 1381, in invoke
    await ctx.command.invoke(ctx)
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/nextcord/ext/commands/core.py", line 948, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/nextcord/ext/commands/core.py", line 174, in wrapped
    raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'AddCog' object has no attribute 'guild'```
#
nextcord.utils.format_dt(datetime.utcnow(), style="R")

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

    @commands.command()
    async def add(self, ctx, member:nextcord.Member):
        async with aiosqlite.connect("callisto.db") as db:
            async with db.cursor() as cursor:
                await cursor.execute('SELECT id FROM users WHERE guild = ?', (ctx.guild.id,))
                data = await cursor.fetchone()
                if data:
                    await cursor.execute('UPDATE users id = ? WHERE guild = ?', (member.id, ctx.guild.id,))
                else:
                    await cursor.execute('INSERT INTO users (user_name, id, guild) VALUES (?, ?, ?)', (f"{member.name}#{member.discriminator}", member.id, ctx.guild.id,))
            await db.commit()
                
def setup(callisto):
    callisto.add_cog(AddCog(callisto))```
spice jewel
shrewd fjord
#

And since self is required

spice jewel
#

OH

rare echo
#

haha

spice jewel
#

omg

shrewd fjord
#

So
async def add(self, ctx...)

#

Need to add self xd

spice jewel
#

ahh thats embarrassing

rare echo
#

quick delete all evidence

shrewd fjord
#

Nah np lol

spice jewel
shrewd fjord
#

Yes fast Peepo_Gun

spice jewel
#

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

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/nextcord/ext/commands/bot.py", line 1381, in invoke
    await ctx.command.invoke(ctx)
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/nextcord/ext/commands/core.py", line 948, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/nextcord/ext/commands/core.py", line 174, in wrapped
    raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: OperationalError: near "id": syntax error```
#

but theres no syntax error

slate swan
#

Does anyone know reasons why a discord bot wouldn't work when printing that it's online and not giving any error?

shrewd fjord
#

And '' on values

spice jewel
slate swan
#

nvm I fixed it

slate swan
#

I think it was do to me having an on_message event that only had pass inside of it

shrewd fjord
#

Huh?

#

I get syntax errors always on quotations lol

rare echo
tough lance
#

How to set dynamic cooldown in a cog?
Can't get access to self arg

naive briar
heady verge
#
bbutton.style = discord.ButtonStyle.gray, disabled = True

any way how to get this to work, it doesnt disable the button

tough lance
naive briar
#

Why do you need that anyway

heady verge
#

oh ty

tough lance
heady verge
#
if user.banner == None:
                bbutton.style = discord.ButtonStyle.gray
                bbutton.disabled = True``` even though i have a banner it disables the button
pulsar kettle
#

Working on an action log command, it works as intended but it doesn't pick up on messages that are only attached images or a hybrid of text and image. How can I edit my code so it also detects attached files?

@bot.event
async def on_message_delete(message):
    if message.author.bot:
        return
    embed = discord.Embed(description = f"**A message sent by {message.author.mention} has been deleted in <#{message.channel.id}>**\n{message.content}", color = 0xf6ff00)
    embed.set_author(name = f"{message.author.name}#{message.author.discriminator}", icon_url = message.author.avatar)
    embed.set_footer(text = f"User ID: {message.author.id} โ€ข Message ID: {message.id}")
    channel = bot.get_channel(<the action log channel>)
    await channel.send(embed = embed)```
naive briar
unkempt canyonBOT
#

cog_check(ctx)```
A special method that registers as a [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") for every command and subcommand in this cog.

This function **can** be a coroutine and must take a sole parameter, `ctx`, to represent the [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context").
tough lance
#

Actually, I already found the fix

#

!d discord.ext.commands.Context.bot

unkempt canyonBOT
naive briar
#

I guess ๐Ÿคท

wraith meteor
#

anyone gave example how to write voice data from channel to buffer queue?

#

while True: data = q.get() -NICE:)

heady verge
#

how to fetch a user in cogs

vale wing
wraith meteor
#

yes i am using nextcord

#

i need RawInputStream from channel ID ๐Ÿ™‚ to the buffer, now i am using sounddevice for this but this is not right way

heady verge
#

buser = await bot.fetch_user(member.id)
doesnt fetch the user in cogs should i define bot in cogs too?

vocal snow
heady verge
#

okay ty

shrewd fjord
#

;-;?

tawny junco
#

No tracebacks? Spooky

#

Did you check the db for the data?

shrewd fjord
tawny junco
#

That's the stuff of nightmares

#

The worse bug has to be the invisible one

shrewd fjord
#

Yep lmao

vale wing
#

Just an advise โ€” don't create new connection for every query. Have one connection established on bot launch and close it on bot shutdown

#

UPDATE users id = ? WHERE guild = ? is invalid

#

What are you even trying to achieve

cloud dawn
#

Monin pandaHappy

cold sonnet
#

fill in the blank:
mo_ning

naive briar
#

a

vale wing
#

It's definitely a

#

!e print("mo_ning".replace("_",import("string").ascii_lowercase[int(import("math").log(1,69420)69(420+6+ 9**6))]))

unkempt canyonBOT
#

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

moaning
vale wing
#

Tbh outside of code block it looks even more sus

limber bison
#
with open("image.png", "rb") as f:
    data = f.read()```
how i convert this data to png ?
#

and then png to discord file ?

vocal snow
#

data to png? what do you mean

#

what is your actual goal? Do you want to send image.png to a discord channel?

winged linden
#

How do I change a global variable from within a tree.command

slate swan
#

use botvars

#

!botvar

unkempt canyonBOT
#

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

slate swan
#

that way you can use interaction.client.<var> to update it anytime

vale wing
pastel basin
#

Is there any command for cogs?

#

!cogs

pastel basin
winged linden
#

How can I stop a tree.command from continuing to run at a specific point in it?
I thought about using break but thats only for loops

slate swan
#

return?

winged linden
#

the moment i posted my code i saw the error lol

slate swan
#

hello I have a little question, Ive been tryint to import discord_components

but its saying:
Traceback (most recent call last): File "c:\Users\Kynhogat\Desktop\kyn_end\main.py", line 12, in <module> import discord_components ModuleNotFoundError: No module named 'discord_components'

I tried to install it using pip but:

ERROR: Could not find a version that satisfies the requirement discord-components (from versions: none) ERROR: No matching distribution found for discord-components

I hope someone can help with it, ty!

slate swan
vocal snow
#

discord.py has components, you don't need a seperate package

slate swan
#

thank you very much ๐Ÿ™

timid spade
#

i have few functions in my bot
they are not commands but they are just like normal functions like in basic python
They are just randomly lying around in my code
is there any better way to write them?

vocal snow
#

you could put them in a separate module and/or utilize classes

timid spade
#

i can try classes

slate swan
#
await ctx.send(embed=hell.main, components=[[Button(style=ButtonStyle.blue, label="Main", disabled=True),
                                                     Button(style=ButtonStyle.blue, label='test'),
                                                     Button(style=ButtonStyle.blue, label='Games')],
                                                    [Button(style=ButtonStyle.blue, label='Lock'),
                                                     Button(style=ButtonStyle.red, label='test'),
                                                     Button(style=ButtonStyle.green, label='Admin')]])```

is this the right use of the buttons?

because I am getting the error: Button isnt defined
vocal snow
#

are you sure you imported it?

#

!d discord.ui.Button

unkempt canyonBOT
#

class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.

New in version 2.0.
vocal snow
#

this is the class ^

slate swan
#

thank you

timid spade
#

can i somehow make the member argument optional? like if the user doesnt provide a vailed member it jumps to amount
what i mean is the command should work in both ways
^ <- prefix
^set @wodgenzi_#2586 100
set 100

#

is it possible ?

cedar talon
timid spade
#

okay thanks

flat marsh
#

Hello, how can I get the author who used this slash command?

async def test_command(interaction:Interaction, minutes:str):```
slate swan
#

interaction.user

#

!d discord.Interaction.user

unkempt canyonBOT
simple plume
#

Anyone have any idea why this code isn't working?

stray carbon
simple plume
stray carbon
#

Does the bot have proper permissions?

simple plume
stray carbon
#

Oh wait

stray carbon
simple plume
vale wing
#

Just quotes around ID so it looks like this

if message.channel.id == 123456789012345678```
simple plume
gentle nova
#

Hello, someone can help me to make my bot work? I cant get command working , that command should edit channel permission for specific user, its possible to do it ?

#

@vagrant crescentHello, do you understand python and nextcord things ?

vagrant crescent
#

nope

gentle nova
#

@vagrant crescentWho from staff knows ?

sick birch
gentle nova
#

@sick birchusually staff knows things

sick birch
#

also I recommend showing your code, errors, expected vs actual behavior to maximize your chance of getting help

gentle nova
#

im new here, and second day trying create one command

#

@sick birchi opened forum with code

sick birch
#

It's hard for people to answer questions with minimal information

gentle nova
#

and what im trying to do

slate swan
gentle nova
simple plume
#

Anyone knows how to solv it?

vocal snow
simple plume
vocal snow
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

vocal snow
#

please paste the code, I cannot tell from screenshot

cold sonnet
#

I can see there's a nested on_message

#

no deco just an on_message

vocal snow
#

and no code inside the function

simple plume
sullen river
#

yo could anyone help me with permissions?

#

wait nvm i thik i figured it out

simple plume
vocal snow
#

well why do you just have a blank function there?

still heron
#

what i can do

vocal snow
#

you could do what it says

#

or are you looking for an alternative

still heron
vocal snow
still heron
vocal snow
#

you're using both? in the same code/

still heron
#

what i can do

vocal snow
#

which discord.py functions do you require that are not present in nextcord?

vocal snow
#

and which nextcord functions do you need that are not in discord.py?

vocal snow
vocal snow
#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if itโ€™s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
vocal snow
#

looks like you don't need nextcord

still heron
#

๐Ÿ‘

still heron
vocal snow
#

no, because nextcord was designed as an alternative for dsicord.py

still heron
#

ok thx

vocal snow
#

you shouldn't ever need to use both together, because they support the same things

#

just in different ways

simple plume
vocal snow
#

sure

#

you put it there, idk why lol

simple plume
arctic fiber
#

nothing comes up there? should i follow the discord py guide thing

vocal snow
arctic fiber
vocal snow
#

sure

#

but you already know intermediate python, right?

arctic fiber
#

i'm new to python

#

i don't know anything

vocal snow
#

then you should learn python first

arctic fiber
#

where do i do that?

vocal snow
#

!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.

arctic fiber
vocal snow
vocal snow
arctic fiber
# vocal snow

could you send me the first one and the third one?

vocal snow
terse bobcat
#

I have my python installed weirdly which is preventing me from using pip (which doesn't allow me to download pip install discord)

#

which channel should I be using for help

vocal snow
terse bobcat
#

I have pip (and discord) installed on my python install

#

however I cant change the version of python

#

I am currently forced to use Anocanda

#

do I need to update this?

vocal snow
vocal snow
#

looks like your command has user parameter which you didn't pass when invoking the command in discord

graceful ermine
#

Hey guys how do I make it so that the bot fines the user that deleted a channel?

#

this is what I have currently

sick birch
#

!e discord.on_guild_channel_delete

#

!d discord.on_guild_channel_delete

unkempt canyonBOT
#

discord.on_guild_channel_delete(channel)``````py

discord.on_guild_channel_create(channel)```
Called whenever a guild channel is deleted or created.

Note that you can get the guild from [`guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.guild "discord.abc.GuildChannel.guild").

This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
sick birch
#

note the arguments

vocal snow
#

smart, make people pay if they delete a channel and ban them if they don't

neat basin
#

I want my discord bot to send a message to the person running the command how do I do it?

vocal snow
neat basin
vocal snow
#

are you in a slash command?

neat basin
vocal snow
#

then you would use interaction.user

neat basin
#

interaction.user.send ?

neat basin
vocal snow
neat basin
#

no

vocal snow
#

can you show your code/

neat basin
#
@bot.tree.command(name="tc")
async def tc(interaction: discord.Interaction, tc:str):
    await interaction.response.send_message(f"{interaction.user.name} said: '{tc}' ")

    print("1")
    cur.execute("SELECT * FROM `data` WHERE `TC` = %s", (tc,),"")

    print("2")
    sonuc = cur.fetchall()

    print("3")
    for x in sonuc:
        print(tuple(y.decode() if isinstance(y, (bytes, bytearray)) else str(y) for y in x))
        await interaction.user.send(tuple(y.decode() if isinstance(y, (bytes, bytearray)) else str(y) for y in x))```
#

@vocal snow

vocal snow
#

so it's executing that print statement but not sending anything?

neat basin
#

yes

vocal snow
#

do you have any error handlers?

#

or have you set up logging?

neat basin
#

no

#

opss

#

sorry bro i getting error

#
2023-01-27 02:38:38 ERROR    discord.app_commands.tree Ignoring exception in command 'tc'
Traceback (most recent call last):
  File "C:\Users\2k\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 862, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\2k\Desktop\proje\deneme.py", line 34, in tc
    await interaction.user.send(tuple(y.decode() if isinstance(y, (bytes, bytearray)) else str(y) for y in x))
  File "C:\Users\2k\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\abc.py", line 1538, in send
    data = await state.http.send_message(channel.id, params=params)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\2k\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\http.py", line 738, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user

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

Traceback (most recent call last):
  File "C:\Users\2k\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\2k\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\2k\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'tc' raised an exception: Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user```
vocal snow
#

their DMs are closed probably

neat basin
vocal snow
#

its crazy how plausible it is

neat basin
vocal snow
#

why are you calling a Member object

#

did you forget the .send

neat basin
#

gave an error

sick birch
sick birch
neat basin
#
2023-01-27 02:46:03 ERROR    discord.app_commands.tree Ignoring exception in command 'tc'
Traceback (most recent call last):
  File "C:\Users\2k\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 862, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\2k\Desktop\proje\deneme.py", line 34, in tc
    await interaction.user.send(tuple(y.decode() if isinstance(y, (bytes, bytearray)) else str(y) for y in x))
  File "C:\Users\2k\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\abc.py", line 1538, in send
    data = await state.http.send_message(channel.id, params=params)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\2k\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\http.py", line 738, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user

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

Traceback (most recent call last):
  File "C:\Users\2k\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\2k\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\2k\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'tc' raised an exception: Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user```
vocal snow
#

yeah, so their dms must be closed

neat basin
#

no

neat basin
vocal snow
#

interaction.channel.send / interaction.response.send_message if you haven't responded to the interaction /

graceful ermine
vocal snow
#

interaction.response.defer + interaction.followup.send if you are unable to respond to the interaction within 3 seconds

vocal snow
#

and you can set ephemeral=True so only the command author will see the message. like a dm

smoky sinew
#

@vocal snow

vocal snow
smoky sinew
#

good night

pulsar kettle
#

Trying to log when a member joins the server and it displays their account age (e.g. 1 year, 5 months... NOT the account creation date) and I get this error message when someone joins TypeError: can't subtract offset-naive and offset-aware datetimes

@bot.event
async def on_member_join(member):
    now = datetime.utcnow()
    delta = now - member.created_at
    embed = discord.Embed(description = f"**{member.mention} joined the server**", color = 0xf6ff00, timestamp = embed.created_at)
    embed.add_field(name = "Account Age", value = delta, inline = False)
    embed.set_thumbnail(url = member.avatar.url)
    embed.set_author(name = f"{member.name}#{member.discriminator}", icon_url = member.avatar)
    embed.set_footer(text = f"User ID: {member.id}")
    channel = bot.get_channel(1067413418597953637)
    await channel.send(embed = embed)```
#

I think it's something to do with the line delta = now - member.created_at

vocal snow
#

use discord.utils.utcnow instead of datetime.utcnow to get an aware datetime

naive briar
#

!d discord.utils.utcnow

unkempt canyonBOT
#

discord.utils.utcnow()```
A helper function to return an aware UTC datetime representing the current time.

This should be preferred to [`datetime.datetime.utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow "(in Python v3.11)") since it is an aware datetime, compared to the naive datetime in the standard library.

New in version 2.0.
pulsar kettle
#

Works better now, it displays the account age in days but it also shows 1:23:45.678910 after, so how can i remove that AND convert the days into years, months and days?

vocal snow
#

We can't help with music bots here

#

!ytdl

unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeโ€™s robots.txt file; (b) with YouTubeโ€™s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
jaunty hare
#

oh, sorry

slate swan
#

you can help with music bot's as long as it isn't against any of the stuff listed above.

#

@vocal snow

#

alot of ppl do radio bots and i even seen one guy doing local files with beats he made for like rap cyphers

vocal snow
#

Yes, but the code mentions youtube

jaunty hare
#

so i have to censor it?

#

the word youtube?

vocal snow
#

No, we won't help with anything that utilizes ytdl or other such libraries

jaunty hare
#

F

vocal snow
#

If it's a music bot that obtains music legally then it's fine

pulsar kettle
#

How can i make it so it displays the account age as "x years, y months and z days", and remove the 1:23:45.678910 that appears after it?

now = discord.utils.utcnow()
delta = now - member.created_at 
embed = discord.Embed(description = f"**{member.mention} joined the server**", color = 0xf6ff00, timestamp = member.joined_at)
embed.add_field(name = "Account Age", value = delta, inline = False)```
slate swan
#

!d discord.utils.format_dt

unkempt canyonBOT
#

discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") for presentation within Discord.

This allows for a locale-independent way of presenting data using Discord specific Markdown...
slate swan
#

use a timestamp

smoky sinew
pulsar kettle
#

Tried installing humanize and it wasnt working so i uninstalled python and reinstalled, then tried humanize again and it worked, but now my import discord and from discord.ext import commands wont install even if i type pip install discord in the temrinal since it just repeats requirement already satisfied...

#

Ill try restarting my pc, see if tha thelps

naive briar
pulsar kettle
#

Yeah restarting my pc didnt help

pulsar kettle
#

When i run the code i get ModuleNotFoundError: No module named 'discord'

naive briar
naive briar
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

pulsar kettle
#

So just run pip install discord and copy whats there?

austere prairie
#

ah, another python/pip mismatch

austere prairie
pulsar kettle
austere prairie
#

check the interpreter version (bottom right of your IDE) and see if the version matches output from pip --version

pulsar kettle
#

pip --version = 3.11
interpreter version = 3.10.9

austere prairie
#

then change the interpreter version to 3.11

#

click on the interpreter version and select 3.11 from the list that shows up

pulsar kettle
#

Tyyyy

#

Cant belive it was that simple ๐Ÿ˜ญ

austere prairie
slate swan
#

the relative timestamp style exists

#

but even if you want to use a timedelta humanize is definately not the best way

#

well, it works ๐Ÿคทโ€โ™‚๏ธ

pulsar kettle
#

Humanize works, but is it possible to round the seconds? age = humanize.precisedelta(delta)

#

Looking at the website and im not seeing anything on rounding

naive briar
#

You better off making your own than keep finding

smoky sinew
#

i don't know if that one has been updated try pip install discord.py

smoky sinew
# slate swan ?

where exactly do you see months or days in the relative timestamp

#

if my account was created on jan 26 2020 you will just see "3 years ago"

slate swan
smoky sinew
#

and?

pulsar kettle
#

I could add milliseconds so there's no decimals ig

slate swan
#

you can't get it to work properly "according to your will" without making a custom parser

shrewd fjord
#

sarthh Peepo_UwU

pulsar kettle
#

Thx for ur help though guys <3

slate swan
shrewd fjord
#

Y not round it?

#

Altho idk what's the prob PU_PeepoLeaveExit

shrewd fjord
glad palm
#

is pycord or discordpy recommended over the other? is there a difference?

naive briar
hushed galleon
#

discord.py is the most popular python library for handling the discord API, and i think its decently organized (specifically the newer features since thats where most forks of d.py deviate the most), but i cant say anything about the architecture of pycord and both libraries seem to be actively maintained

pulsar kettle
#

Is it possible for a bot to return "None" for their member.display_name if they do not have a nickname or will it always return their username UNLESS they have a nickname? (sorry if unclear)

hushed galleon
#

!d discord.User.display_name

unkempt canyonBOT
#

property display_name```
Returns the userโ€™s display name.

For regular users this is just their username, but if they have a guild specific nickname then that is returned instead.
hushed galleon
#

well the property says the return type is str, so None shouldnt be expected

slate swan
#

but in general opinion dpy is more preferable

glad palm
#

ok thank you @hushed galleon and @slate swan!

slate swan
slate swan
#

can anyone help with this?

vocal snow
#

can you share your code?

austere prairie
#

^

slate swan
unkempt canyonBOT
#

Hey @slate swan!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

slate swan
#

can you see that?

#

not my code helping for a freind

#

@austere prairie ^^^^

vocal snow
#

yeah we can't help with that, definitely breaks riot games tos

slate swan
austere prairie
#

!rule tos

unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

austere prairie
#

yeah what zeffo said

slate swan
slate swan
#

just need help fixing the error code

austere prairie
austere prairie
slate swan
austere prairie
#

still, rules are rules

slate swan
austere prairie
#

I don't even know what the error is, I haven't seen that before

viral fulcrum
#

This seems to be a common issue I cant find the right answer for: I can get my bot to run its just that the @ bot.command() does not work. How can I resolve this?

vocal snow
austere prairie
#

make sure message content is enabled in the dev portal as well

viral fulcrum
#

In my file and in the portal

#

I wonder if it has to do something with the order. But at the same time, the ide isn't throwing any errors

#

Order of my code*

vocal snow
viral fulcrum
sick birch
#

Great time to segue to something...
So y'all might know by know I'm the project lead for migrating pins from this channel to site
Additionally I'm also tasked with a few tags that could be useful in situations like these
For instance, a tag explaining why on_message blocks your command handler: !on_message
Or generally common pitfalls like these
I'm looking for some volunteers to help doing that, if you haven't contributed to our repos this would be a great first step.
Let me know if you're interested and I'll CC you in a formal announcement that I'm about to put together ๐Ÿ™‚
The work will be relatively easy as we want to tags to be pretty short

slate swan
sick birch
slate swan
#

as i am using the newest version right now but this was coded some time ago

sick birch
slate swan
#

this is what i got back

sick birch
#

What command are you running?

slate swan
sick birch
#

That needs to go inside your code

#

Then you run the code

slate swan
sick birch
#

Yes

#

inside on_ready

slate swan
#

sorry i am very new to coding

sick birch
#

Np

slate swan
#

i cant find where you mean?

sick birch
#

!pastebin your code please

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

slate swan
sick birch
#

We can't help you without seeing your code

sick birch
#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

slate swan
pulsar kettle
#

Attempting to polish my bot's audit log, however whenever I ban someone it sends both on_member_ban AND on_member_remove. Is there anyway I can make it so it's like "if member was banned, don't send the on_member_remove"?

@bot.event
async def on_member_ban(guild, member):
    embed = discord.Embed(description = f"**{member.mention} has been banned**", color = discord.Color.red(), timestamp = discord.utils.utcnow())
    embed.set_thumbnail(url = member.avatar.url)
    embed.set_author(name = f"{member.name}#{member.discriminator}", icon_url = member.avatar)
    embed.set_footer(text = f"User ID: {member.id}")
    channel = bot.get_channel(1067413212955426877)
    await channel.send(embed = embed)

@bot.event
async def on_member_remove(member):
    now = discord.utils.utcnow()
    delta = now - member.created_at
    age = humanize.precisedelta(delta)
    embed = discord.Embed(description = f"**{member.mention} left the server**", color = discord.Color.red(), timestamp = discord.utils.utcnow())
    embed.add_field(name = "Account Age", value = age, inline = False)
    embed.set_thumbnail(url = member.avatar.url)
    embed.set_author(name = f"{member.name}#{member.discriminator}", icon_url = member.avatar)
    embed.set_footer(text = f"User ID: {member.id}")
    channel = bot.get_channel(1067413418597953637)
    await channel.send(embed = embed)```
#

(For clarification the on_member_remove is for when members are kicked or leave the server themselves)

sick birch
#

Personally I'd just leave it as it's pretty easy to infer

quick gust
sick birch
#

Do we know which comes first?

quick gust
#

it will still dispatch the event though

quick gust
sick birch
#

Sure can

shrewd fjord
#

If it would exisg ๐Ÿ’€

#

Exist*

slate swan
#

?

shrewd fjord
#

Nothing

#

!d discord.Guild.fetch_ban

unkempt canyonBOT
#

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

Retrieves the [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry") for a user.

You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") to get this information.
shrewd fjord
#

Hm this may work

slate swan
#

nah

#

well maybe

#

it depends like robin said which event comes first

#

and if it's constant

shrewd fjord
#
try:
 await fetch_ban(user)
except discord.NotFound:
   #rest of the code
shrewd fjord
slate swan
#

yea but he is explicitly trying to only do one and not the other so if try fails that will still trigger both events

shrewd fjord
#

Yep lol

slate swan
#

that's actually something I never thought of with the ban/remove events

shrewd fjord
#

Just incase if member get bans first then this code should work

#

If remove triggers first then ๐Ÿ’€

#

Maybe u can use asyncio module too to give some delay, but idk if it would work lol

#

!d discord.Member.ban

unkempt canyonBOT
#

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

Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.ban "discord.Guild.ban").
shrewd fjord
#

Meh

fresh fern
#

helppp

upbeat otter
fresh fern
#

`@client.command()
async def setup(ctx, wlcmC: discord.TextChannel, byeC: discord.TextChannel, guildID: discord.Guild):
global wlcm
wlcm = wlcmC
global bye
bye = byeC
global guild
guild = guildID
print(wlcm, bye, guild)

@client.event
async def on_member_join(member):
await guild.get_channel(wlcm).send("Hello")`

#

this is not working

#

NameError: name 'guild' is not defined error

fresh fern
#

this is not working

upbeat otter
#

read the error

fresh fern
#

i kknow

upbeat otter
#

learn python

fresh fern
#

but i made the guild a global variable

upbeat otter
#

so

fresh fern
#

ohh

#

i knew it

upbeat otter
#

๐Ÿ’€ then why ask

fresh fern
#

BRUHH i mean i knew that im making the vars wrong way

upbeat otter
#

!botvar use these

unkempt canyonBOT
#

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

fresh fern
#

for me?

upbeat otter
#

yeah

#

don't use globals

fresh fern
#

oh yea ok

#

i tried that also it didnt work lemme show

#

`wlcm: discord.TextChannel
bye: discord.TextChannel
guild: discord.Guild

@client.command()
async def setup(ctx, wlcmC: discord.TextChannel, byeC: discord.TextChannel, guildID: discord.Guild):
wlcm = wlcmC
bye = byeC
guild = guildID
print(wlcm, bye, guild)

@client.event
async def on_member_join(member):
await guild.get_channel(wlcm).send("Hello")
@client.event
async def on_member_leave(member):
await guild.get_channel(wlcm).send("Bye")`

fresh fern
#

ohhhh

#

never knew that

upbeat otter
#

ok

#

read the example

fresh fern
#

what does this do anyways

upbeat otter
#

makes the variables global, in a better way

fresh fern
#

ohhhhhhh

#

thankss alot

upbeat otter
#

welcome

fresh fern
#

ayoo

#

AttributeError: 'Bot' object has no attribute 'guild'

pulsar kettle
#

Code works, but is there any way I can make it significantly shorter? I'm going to do similar types of code for other commands and I would like to know if there's a way I can save lines and time: https://paste.pythondiscord.com/oruyufopev

#

More specifically, embeds with varying images and titles depending on the random number landed on

unkempt canyonBOT
#

random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
naive briar
#

Pick a string from a list then put it in the embed

fresh fern
#

`client.wlcm: discord.TextChannel
client.bye: discord.TextChannel
client.guild: discord.Guild

@client.command()
async def setup(ctx, wlcmC: discord.TextChannel, byeC: discord.TextChannel, guildID: discord.Guild):
client.wlcm = wlcmC
client.bye = byeC
client.guild = guildID
print(client.wlcm, client.bye, client.guild)

@client.event
async def on_member_join(member):
await client.guild.get_channel(client.wlcm).send("Hello")
@client.event
async def on_member_leave(member):
await client.guild.get_channel(client.wlcm).send("Bye")`

#

this doesnt work

shrewd fjord
#

on_member_remove

fresh fern
#

Ohhhhhh thanks alot man

#

ill try and let u know soon......

naive briar
#

You already have the channel object

#

Why would you getting it again

slate swan
#

!e print ("hello world")

unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.10 eval job has completed with return code 0.

hello world
slate swan
#

omg wow

fresh fern
#

!e print("Hello Hello")

unkempt canyonBOT
#

@fresh fern :white_check_mark: Your 3.11 eval job has completed with return code 0.

Hello Hello
fresh fern
#

yo this is cool

upbeat otter
#

@fresh fern @slate swan
use #bot-commands please

slate swan
#

k

fresh fern
#

sorry

upbeat otter
#

I genuinely read that as "I am sorry" ๐Ÿ’€ wtf

still heron
#

doesn't work what I can do

#

@upbeat otter

vocal snow
slate swan
#

Hello, How would i make my bot status say watching number of ticket

vocal snow
#

!d discord.Client.change_presence

unkempt canyonBOT
#

await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Changes the clientโ€™s presence.

Example

```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
```   Changed in version 2.0: Removed the `afk` keyword-only parameter...
slate swan
vocal snow
#

yes, so you use that method to change the status to say whatever you want it to say

slate swan
vocal snow
#

you could change it whenever a ticket is created

slate swan
#

Surely, there is a way to do it automatically

vocal snow
#

how much more automatic can it be

#

user creates ticket --> bot changes status

slate swan
#

So can i not make it change automatically

vocal snow
#

it is automatic

#

you have a function or command to create a ticket, right

slate swan
#

Nope, i was just thinking it could count the number of channel names with tickets

vocal snow
#

sure, but how is a ticket created

#

do you have a button, a command or something for it

slate swan
#

A button

vocal snow
# unkempt canyon

so in the button callback, calculate the number of tickets, and then use this method to change the status

slate swan
#

Could you maybe help me do that, I'm not very good at python

vocal snow
#

do you know the code which is executed when the button is pressed

slate swan
#

There 2 dif bots, do they have to be the same?

#

One isn't mine the one what i want to change the status on is

vocal snow
#

so the ticket creator bot is not yours?

slate swan
#

nope, it's ticket tool

vocal snow
#

that would've been good to know earlier

#

anyways, you can still detect when a ticket is created

slate swan
#

Perfect

vocal snow
#

using an event like on_guild_channel_create

#

are the tickets normal text channels?

slate swan
#

Yes

vocal snow
slate swan
#

Err nope

vocal snow
#

ok, do you have any code so far?

slate swan
#

yeah

#

I just have a few random things what i found of stackoverflow

vocal snow
#

so you probably defined a bot or client variable?

slate swan
#

Yeah, bot

vocal snow
#

now, you can use the .listen() decorator to listen for an event; ```py
@bot.listen()
async def on_guild_channel_create(channel):
...

#

that function will be called whenever a channel is created

#

you can access the guild via channel.guild

#

and then the text channels of the guild via guild.text_channels

slate swan
#

So would it be something like

@bot.listen()
async def on_guild_channel_create(channel):
      await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="IDk what goes here"))
vocal snow
#

right

#

and you'll need to add the code to calculate the number of tickets, and pass that number to the discord.Activity name

static holly
#

Hi , why i dont have anny error and the code dont work?

import discord
from discord.ext import commands
import os
from dotenv import load_dotenv

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


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


    @commands.Cog.listener()
    async def on_message(self, message):
        liste = ("Bonjour", "bonjour", "Bonsoir", "bonsoir")

        
        nombre_mention=len(message.mentions)

        if nombre_mention== 0 and message.content.startswith(liste):
            await message.channel.send (f"Salut {message.author.mention} ")
            
        if nombre_mention >= 1 and message.content.startswith(liste):
            await message.channel.send (f"Salut" + ",".join([mention.mention for mention in message.mentions]))
flat marsh
#

can i do these 4 functions in one

#

they are essentially the same but idk how to make them one, so its flexible

naive briar
#

Subclass a view

flat marsh
#

?

#

So.. any help?

naive briar
#

What even is do these 4 functions in one

flat marsh
#

because these 4 functions are hard code

#

do you know what hard code means

pliant gulch
#

!e ```py
for i in range(4):
print(i)

unkempt canyonBOT
#

@pliant gulch :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 0
002 | 1
003 | 2
004 | 3
pliant gulch
#

Use this for the index then keep everything else the same

flat marsh
#

functions in a for loop?

heady verge
#

nvm used url for icon_url Facepalm

flat marsh
tough lance
#

self, button obj, interaction

pliant gulch
flat marsh
#

the function only gets i as 3.. somehow

pliant gulch
#
for i, button in enumerate(button_list):
    Embed(value=button)

    buttons[i].callback = ...
flat marsh
#

what does this change?

#

and what is the Embed line

pliant gulch
#

It's an example following where you create the embed

#

It doesn't change much, it just enumerates the button list

#

So it gives index and the element itself

#

I'm not quite sure if it'll fix but try it out first

#

I mean, it's quite odd your only getting 3 for i as well

flat marsh
#

bro enumerate and range wont change a thing, this is like saying praying to god will make you a millionaire

#

cuz enum is range but with 1 more element which u get from it

flat marsh
heady verge
#

how do i create subcommands for slash commands in pycord?

#

i tried @suggest.subcommand(name='approve')
but i get this error
discord.errors.ExtensionFailed: Extension 'cogs.modal' raised an error: AttributeError: 'SlashCommand' object has no attribute 'subcommand'

naive briar
naive briar
heady verge
#

discord.errors.ExtensionFailed: Extension 'cogs.modal' raised an error: AttributeError: 'SlashCommand' object has no attribute 'command'

#
    @slash_command(name='suggest')
    async def suggest(self, ctx: discord.ApplicationContext):
        modal = MyModal()
        await ctx.send_modal(modal)

    @suggest.command(name='approve')
    async def approve(self, ctx, id:int, *, reason=None):
        if id is None:
            return
        chnl = await self.bot.fetch_channel(1068521772191846460)
        if chnl is None:
            return
        msg = await chnl.fetch_message(id)
        embed = discord.Embed(
            color=discord.Colour.random(),
            title='Approved!'
        )
        await msg.edit(embed = embed)```
naive briar
#

Show the code

heady verge
#
class MyModal(Modal):
    def __init__(self) -> None:
        super().__init__(title='Suggest!') #title of the modal up top
        self.add_item(
            InputText(
                label= "Suggestion", 
                value= "", #sort of like a default
                style=discord.InputTextStyle.long, #long/short
            )
        )

    async def callback(self, interaction: discord.Interaction):
        embed = discord.Embed(color=discord.Color.green())
        embed.add_field(name="Suggestion -", value=self.children[0].value, inline=False)
        embed.set_author(name=f'{interaction.user.name}#{interaction.user.discriminator}', icon_url=f'{interaction.user.avatar.url}')
        chnl = await self.bot.fetch_channel(1068521772191846460)
        msg = await chnl.send(embeds=[embed])
        await msg.add_reaction('![loki_yes](https://cdn.discordapp.com/emojis/1068526769629577276.webp?size=128 "loki_yes")')
        await msg.add_reaction('![loki_no](https://cdn.discordapp.com/emojis/1068526731629166634.webp?size=128 "loki_no")')```
upbeat otter
naive briar
heady verge
#

okay ty

flat marsh
#

im talking SPECIFICALLY about the i element

naive briar
#

What are you even talking about

flat marsh
#
for i, button in range(something)```
andy said that this might change something, but it wouldnt (obviously)
heady verge
#

how do i fetch a channel in a modal callback i tried using this py chnl = await ctx.bot.fetch_channel(1068521772191846460) but it doesnt work i get this error TypeError: MyModal.callback() missing 1 required positional argument: 'interaction'

naive briar
heady verge
#
async def callback(self, ctx, interaction: discord.Interaction):
        embed = discord.Embed(color=discord.Color.green())
        embed.add_field(name="Suggestion -", value=self.children[0].value, inline=False)
        embed.set_author(name=f'{interaction.user.name}#{interaction.user.discriminator}', icon_url=f'{interaction.user.avatar.url}')
        chnl = await ctx.bot.fetch_channel(1068521772191846460)
        msg = await chnl.send(embeds=[embed])
        await msg.add_reaction('![loki_yes](https://cdn.discordapp.com/emojis/1068526769629577276.webp?size=128 "loki_yes")')
        await msg.add_reaction('![loki_no](https://cdn.discordapp.com/emojis/1068526731629166634.webp?size=128 "loki_no")')```
#
Ignoring exception in modal <cogs.modal.MyModal object at 0x000001F44F02BED0>:
Traceback (most recent call last):
  File "C:\Users\LOKESH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\modal.py", line 341, in dispatch
    await value.callback(interaction)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: MyModal.callback() missing 1 required positional argument: 'interaction'```
naive briar
#

Choose one

heady verge
#

if i use interaction.bot.fetch_channel it gives another error

naive briar
#

THEN SEND THE ERROR

heady verge
#
Ignoring exception in modal <cogs.modal.MyModal object at 0x000002EF9D83B810>:
Traceback (most recent call last):
  File "C:\Users\LOKESH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\modal.py", line 341, in dispatch
    await value.callback(interaction)
  File "C:\Users\LOKESH\Desktop\Pycord\cogs\modal.py", line 28, in callback
    chnl = await interaction.bot.fetch_channel(1068521772191846460)
                 ^^^^^^^^^^^^^^^
AttributeError: 'Interaction' object has no attribute 'bot'
naive briar
#

I'm going out before causing any trouble

slate swan
#

interaction.client

pulsar kettle
#

Changing the Position of a role sends an update from EVERY role that got its position adjusted, rate limiting the bot and overall spamming messages I don't want. How can I fix this?

@bot.event
async def on_guild_role_update(before_role, after_role):
    embed = discord.Embed(description = f"**Role Updated: <@&{after_role.id}>**", color = 0xf6ff00, timestamp = discord.utils.utcnow())
    if before_role.name != after_role.name:
        embed.add_field(name = "Name before", value = before_role.name, inline = False)
        embed.add_field(name = "Name after", value = after_role.name, inline = False)
    if before_role.color != after_role.color:
        embed.add_field(name = "Color before", value = before_role.color, inline = False)
        embed.add_field(name = "Color after", value = after_role.color, inline = False)
    if before_role.position != after_role.position:
        embed.add_field(name = "Position before", value = before_role.position, inline = False)
        embed.add_field(name = "Position after", value = after_role.position, inline = False)
    if before_role.hoist != after_role.hoist:
        embed.add_field(name = "Hoist before", value = before_role.hoist, inline = False)
        embed.add_field(name = "Hoist after", value = after_role.hoist, inline = False)
    if before_role.permissions != after_role.permissions:
        embed.add_field(name = "Permissions before", value = before_role.permissions, inline = False)
        embed.add_field(name = "Permissions after", value = after_role.permissions, inline = False)
    if before_role.mentionable != after_role.mentionable:
        embed.add_field(name = "Mentionable before", value = before_role.mentionable, inline = False)
        embed.add_field(name = "Mentionable after", value = after_role.mentionable, inline = False)
    embed.set_footer(text = f"Role ID: {after_role.id}")
    channel = bot.get_channel(1067413212955426877)
    await channel.send(embed = embed)```
winged coral
#

You could cache the previous positions somehow, maybe on cog load or in setup hook

#

When one role is edited, this should theoretically be the one that was actually manually changed

#

Then modify the cache and compare to it next time to make sure the event hasn't already been handled

#

Although I wouldn't rely on the API sending through the initial edit first

#

From my bots this seems to happen most of the time though so should be good

pulsar kettle
#

I can live with the other roles appearing (does what code says technically, plus can be useful) but the role position change in in a separate embed from all the other role changes. How can I merge them into one embed?

@bot.event
async def on_guild_role_update(before_role, after_role):
    embed = discord.Embed(description = f"**Role Updated: <@&{after_role.id}>**", color = 0xf6ff00, timestamp = discord.utils.utcnow())
    if before_role.name != after_role.name:
        embed.add_field(name = "Name changed:", value = f"{before_role.name} -> {after_role.name}", inline = False)
    if before_role.color != after_role.color:
        embed.add_field(name = "Color changed:", value = f"{before_role.color} -> {after_role.color}", inline = False)
    if before_role.position != after_role.position:
        embed.add_field(name = "Position changed:", value = f"{before_role.position} -> {after_role.position}", inline = False)
    if before_role.hoist != after_role.hoist:
        embed.add_field(name = "Hoist changed:", value = f"{before_role.hoist} -> {after_role.hoist}", inline = False)
    if before_role.permissions != after_role.permissions:
        embed.add_field(name = "Permissions changed:", value = f"{before_role.permissions} -> {after_role.permissions}", inline = False)
    if before_role.mentionable != after_role.mentionable:
        embed.add_field(name = "Mentionable changed:", value = f"{before_role.mentionable} -> {after_role.mentionable}", inline = False)
    embed.set_footer(text = f"Role ID: {after_role.id}")
    channel = bot.get_channel(1067413212955426877)
    await channel.send(embed = embed)
abstract owl
#

is there a way i can make the whole code sleep for a specific period of time? and then it should start working again?

gentle nova
#

Hello guys, yesterday i found out few new things, today i tryed my code, and i need somehow to make if chances to work properly, so code

        await interaction.response.send_message(f'Nuplake')
        await channel.set_permissions(interaction.user, send_messages = False)
        await interaction.channel.send(f'{interaction.user.mention} smeigฤ— gerฤ… bankฤ™ ฤฏ {user.mention} uลพverdamas jo kakarynฤ™ {minutes} min.')
        await asyncio.sleep(minutes)
    if chance < 7:
        await interaction.response.send_message(f'Nusiplake')
        await channel.set_permissions(user, send_messages = False)
        await interaction.channel.send(f'{interaction.user.mention} paslydo ir neuลพtaikฤ™s pliauskos prisiplojo snukiu ฤฏ ลพemฤ™. Dabar gulฤ—s pavฤ—syje {minutes} min.')
        await asyncio.sleep(minutes)```

If chance > 7: adding permissions to both users, message author and to user which was mentioned , with If chance < 7 all good , how to do it properly
abstract owl
#

yea

#

i mean the bot stays on but its functions etc doesnt work

gentle nova
#

@abstract owli think so with asyncio.sleep you can try

naive briar
#

Yeah, it should be fine

gentle nova
#

Better help me with my problem now ๐Ÿ˜„

abstract owl
#

so like i wish for it to be off and on every specified time

naive briar
#

You can make a attribute for the bot instance then check if it's true

abstract owl
#

basically i want it to stay on for 1 hour then go off then come back after hour

naive briar
#

Like

bot.respond_to_cmd = False
await asyncio.sleep(100)
bot.respond_to_cmd = True
abstract owl
#

hmm that's the issue ๐Ÿ’€

#

i cant get my head

#

tried searching for module came across scheduler but not quite sure if it serves the purpose

naive briar
#

You can use tasks extension

#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
abstract owl
#

so i put the whole bot in there? yert

naive briar
#

Loop every 1 hour then revert the value

abstract owl
#

it'll loop it but it wont be alive for 1 hour

naive briar
#

It can stay looping as long as your program still running

#

Or haven't stopped yet

abstract owl
#

now like for ex
i have a function print("hello world")
if i loop it, it'll send this every x seconds but i wont the bot to send this for 1 hour continually then sleep for 1 hour

#

run for x hours
sleep for x hours
repeat

naive briar
#

Uh, sooooo, maybe not exactly

abstract owl
#

yea

pulsar kettle
#

How can I edit the message so instead of it saying <Permissions value=0> -> <Permissions value=1024 I can make it simpler and say smth like value = 0 -> value = 1024?

If before_role.permissions != after_role.permissions:
        embed.add_field(name = "Permissions changed:", value = f"{before_role.permissions} -> {after_role.permissions}", inline = False)```
#

Nevermind

#

Tried smth random and it worked lmao

abstract owl
#

woah

naive briar
pulsar kettle
#

Changed before_role.permissions to before_role.permissions.value

naive briar
#

Kinda close, yeah

pulsar kettle
#

Using an f string i can get what i want

abstract owl
naive briar
gentle nova
#

or you can do minutes = 60

#

and then asyncio.sleep (minutes)

vale wing
#

That's funny

slate swan
#

someone can tell me why i have 0 synced commands ?

golden portal
#

what is your code for the sync?

slate swan
#
@bot.event
async def on_ready():
    print(pyfiglet.figlet_format("BOT ONLINE", font="slant"))
    try:
        synced = await bot.tree.sync()
        print(f"Synced {len(synced)} command(s)")
    except Exception as e:
        print(e)```
golden portal
slate swan
#

bcz im breaking the rule 5

#

!rule5

velvet compass
upper root
#

Hello guys I have created a command handler inside a cog although it is not working. I don't know what I've done wrong. Basically, im trying to make the bot send "Missing role" if a user use the command and has not the role.
Thats the code:

class error(commands.Cog):
    def __init__(self, bot: commands.Bot) -> None:
        self.bot = bot

    @commands.command()
    async def echo(self, interaction: discord.Interaction, arg):
        await interaction.response.send_message(arg)

    @echo.error
    async def echo_error(self, interaction: discord.Interaction, error):
        print("There was an error")
        if isinstance(error, commands.MissingAnyRole):
            await interaction.response.send_message("Missing Role")
        else:
            raise error
sick birch
upper root
sick birch
#

@commands.command() leads me to believe it is a prefix command
However interaction leads to me to believe it is an app command

#

What is your intention?

upper root
#

not a !command

sick birch
#

Should be @app_commands.command() then, once you've from discord import app_commands

cold sonnet
upper root
velvet compass
upper root
#
class error(commands.Cog):
    def __init__(self, bot: commands.Bot) -> None:
        self.bot = bot

    @app_commands.command()
    async def echo(self, interaction: discord.Interaction, arg):
        await interaction.response.send_message(arg)

    @echo.error
    async def echo_error(self, interaction: discord.Interaction, error):
        print("There was an error")
        if isinstance(error, commands.MissingAnyRole):
            await interaction.response.send_message("Missing Role")
        else:
            raise error

and thats the error I get

    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.error' raised an error: TypeError: parameter 'arg' is missing a type annotation in callback 'error.echo'
#

weird..

cold sonnet
stray carbon
#

arg: str

Also, assuming your error is raised if user is missing some role but you are not checking it in the command?

upper root
stray carbon
#

No

upper root
#

and btw I still get no message while running

class error(commands.Cog):
    def __init__(self, bot: commands.Bot) -> None:
        self.bot = bot

    @app_commands.command()
    async def echo(self, interaction: discord.Interaction, arg: str):
        await interaction.response.send_message(arg)

    @echo.error
    async def echo_error(self, interaction: discord.Interaction, error):
        print("There was an error")
        if isinstance(error, commands.MissingAnyRole):
            await interaction.response.send_message("Missing Role")
        else:
            raise error
stray carbon
#

Yeah, this should work

upper root
#

I import it tho as a cog

stray carbon
#

What did you run?

#

It is a slash command, you have to sync it

sick birch
upper root
sick birch
#

Inside your echo_error, do print(type(error)) and see what it says

upper root
#

its like the cog isnt imported correctly

#
class error(commands.Cog):
    def __init__(self, bot: commands.Bot) -> None:
        self.bot = bot

    @app_commands.command()
    async def echo(self, interaction: discord.Interaction, arg: str):
        await interaction.response.send_message(arg)

    @echo.error
    async def echo_error(self, interaction: discord.Interaction, error):
        print(type(error))
        print("There was an error")
        if isinstance(error, commands.MissingAnyRole):
            await interaction.response.send_message("Missing Role")
        else:
            raise error


async def setup(bot: commands.Bot) -> None:
    await bot.add_cog(
        error(bot),
#

and here

        self.initial_extensions = [
            "cogs.test",
            "cogs.seb",
            "cogs.error"
        ]

stray carbon
#

why is there a ,

upper root
slate swan
#

I made slow mode on my discord channel but it works only for messages and not commands is there any fix for that?

upper root
vocal snow
upper root
# vocal snow Could you resend the error?

it does not print anything tho except

2023-01-27 19:25:55 ERROR    discord.app_commands.tree Ignoring exception in command 'solebox'
Traceback (most recent call last):
  File "C:\Users\lysde\Desktop\Mind FnF\venv\Lib\site-packages\discord\app_commands\tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\lysde\Desktop\Mind FnF\venv\Lib\site-packages\discord\app_commands\commands.py", line 883, in _invoke_with_namespace
    if not await self._check_can_run(interaction):
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\lysde\Desktop\Mind FnF\venv\Lib\site-packages\discord\app_commands\commands.py", line 1021, in _check_can_run
    return await async_all(f(interaction) for f in predicates)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\lysde\Desktop\Mind FnF\venv\Lib\site-packages\discord\utils.py", line 672, in async_all
    for elem in gen:
  File "C:\Users\lysde\Desktop\Mind FnF\venv\Lib\site-packages\discord\app_commands\commands.py", line 1021, in <genexpr>
    return await async_all(f(interaction) for f in predicates)
                           ^^^^^^^^^^^^^^
  File "C:\Users\lysde\Desktop\Mind FnF\venv\Lib\site-packages\discord\app_commands\checks.py", line 232, in predicate
    raise MissingRole(item)
discord.app_commands.errors.MissingRole: Role 1054565979394412544 is required to run this command.
#

this*

vocal snow
#

So the error is with the solebox command

#

What happens when you use the echo slash command?

#

And the error cog is in a module called error.py right?

upper root
upper root
vocal snow
#

Or you could make a Global one in the error cog with on_application_command_error event

vocal snow
#

The same way you're doing it for echo command

upper root
stray carbon
upper root
# stray carbon you need to make a function somewhere and then do this: ```pt bot.tree.on_error ...

okay so holdon I've fixed the problem, now it just doesn't send the message

class error(commands.Cog):
    def __init__(self, bot: commands.Bot) -> None:
        self.bot = bot

    @app_commands.command()
    @app_commands.checks.has_role(1054565979394412544)
    async def echo(self, interaction: discord.Interaction, arg: str):
        await interaction.response.send_message(arg)

    @echo.error
    async def echo_error(self, interaction: discord.Interaction, error):
        print(type(error))
        print("There was an error")
        if isinstance(error, commands.MissingAnyRole):
            await interaction.response.send_message("Missing Role")
        else:
            raise error

<class 'discord.app_commands.errors.MissingRole'>
There was an error

#

This is what it prints

#

is commands.MissingAnyRole correct?

#

import discord
from discord import app_commands
from discord.ext import commands
I import this btw

rapid jetty
#

Why people use cogs when using decorators is so easier

rapid jetty
#

Using @client.command() is so much easier than using cogs to make comands

hushed galleon
#

cogs combined with extensions give you the ability to hot-reload your code, easily add/remove features, and more neatly organize your project

fading marlin
rapid jetty
#

Ik, but its different

hushed galleon
#

learning it might be confusing part, but afterwards using it is pretty simple: ```py

main.py

from discord.ext import commands

class MyBot(commands.Bot):
async def setup_hook(self):
await self.load_extension("path.to.my_feature")

bot = MyBot(...)
bot.run(...) py

path/to/my_feature.py

from discord.ext import commands

class MyCog(commands.Cog):
@commands.command(name="my-special-command")
async def my_command(self, ctx): ...

async def setup(bot):
await bot.add_cog(MyCog())```

slate swan
#

Any1 can check that error please?

fading marlin
#

Show your check

slate swan
#

I have a syntax error line 7

#

i removed the () after bot.event i tought it was due to that but no

magic forge
slate swan
#

lol

#

maybe line 2 i forgot .ext

#

i try

#

nop it's not because of that

rapid jetty
#

@slate swan from discord.ext import commands

#

That's probably the error

#

Send us a print of the error

upper root
gentle nova
#

hey guys

#

how to add embed

slate swan
#

How to like put in discord embed (description) x(x litteraly has to stay behind number)random number 1-50.random number 1-50

sick birch
slate swan
gentle nova
#

await interaction.response.send_message(embed = embed)
add to this code await interaction.channel.send(f'{interaction.user.mention} megino tvot per veidฤ… {user.mention}')

#

cuz i cant embed = embed put

#

There is any way to put embed before await interaction.channel.send ?

#

Or do embed only for gif

slate swan
sick birch
slate swan
sick birch
#

By not taking more than 3 seconds to respond to an interaction

slate swan
#

It must take more then 3 secounds

#

so can i handle the error by anychance ?

sick birch
#

Defer & followup then

slate swan
#

How i can do it please ;?

gentle nova
#

How to put embed after interaction ?

#

Cant get it work .. Nextcord pytho

sick birch
slate swan
# sick birch ```py await interaction.response.defer() # do long task that takes more than 3 s...
Task exception was never retrieved
future: <Task finished name='CommandTree-invoker' coro=<CommandTree._from_interaction.<locals>.wrapper() done, defined at C:\Users\kacpe\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\tree.py:1089> exception=NotFound('404 Not Found (error code: 10062): Unknown interaction')>
Traceback (most recent call last):
  File "C:\Users\kacpe\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\kacpe\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\commands.py", line 883, in _invoke_with_namespace
    if not await self._check_can_run(interaction):
  File "C:\Users\kacpe\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\commands.py", line 1021, in _check_can_run
    return await async_all(f(interaction) for f in predicates)
  File "C:\Users\kacpe\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\utils.py", line 674, in async_all
    elem = await elem
  File "C:\Users\kacpe\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\checks.py", line 407, in predicate
    raise CommandOnCooldown(bucket, retry_after)
discord.app_commands.errors.CommandOnCooldown: You are on cooldown. Try again in 2.41s

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\kacpe\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\tree.py", line 1091, in wrapper
    await self._call(interaction)
  File "C:\Users\kacpe\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\tree.py", line 1246, in _call
    await self.on_error(interaction, e)
  File "d:\Programowanie\discordbot\spotfiyclaim\main.py", line 67, in on_app_command_error
    else:
  File "C:\Users\kacpe\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\interactions.py", line 769, in send_message
    await adapter.create_interaction_response(
  File "C:\Users\kacpe\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\webhook\async_.py", line 218, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```
slate swan
sick birch
#

No

upper root
#

@sick birch Man i love you hahah, thanks for the help really. It solved it, by the way as I realized im better doing it now. How do I turn this in order to make a cog that will affect all the commands and not only this command

sick birch
upper root
slate swan
#

@sick birch You checked it ?

gentle nova
#

await interaction.send(embed = embed);


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

nextcord.errors.ApplicationInvokeError: Command raised an exception: UnboundLocalError: cannot access local variable 'embed' where it is not associated with a value```
#

any solutions ?

slate swan
gentle nova
#

but can i use ctx if im using interactions ?

slate swan
#

just change the ctx to interaction

gentle nova
#

a

#

and discord to nextcord ?

#

In embed box should be a gif

#

so if i put embed = embed

#

it not gonna work ?

slate swan
#

@sick birch So would you help ?

sick birch
#

No offense but that code is really shoddy and I see a lot of blocking

slate swan
sick birch
#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

sick birch
#

We're not going to help you automate spotify

#

That's in violation of their terms of service

gentle nova
#

@sick birchAnyone will help me to create custom command were im going to use for my server purpose and time by time adding more features and just keep learning something good in this cruel world

sick birch
#

I'm not quite understanding what you're saying

slate swan
sick birch
#

@gentle nova

gentle nova
#

@sick birchIm trying to code a simple command which have to be like /slap but with penalties, but dont understand why my code struggling to do what i want

sick birch
#

Since I don't know what your code looks like or what the error is

gentle nova
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

gentle nova
#

code like that , dont get errors

#

but code wont respond with other stuff

sick birch
#

Ah, I don't use nextcord, sorry

gentle nova
#

:/

slate swan
#

Robin

#

Can u help me?

pulsar kettle
#

Role update sends embeds for other roles despite them not changing, I think its because embed = discord.Embed(description = f"**Role Updated: <@&{after_role.id}>**", color = 0xf6ff00, timestamp = discord.utils.utcnow()) isnt in an if but how can i fix this?

@bot.event
async def on_guild_role_update(before_role, after_role):
    embed = discord.Embed(description = f"**Role Updated: <@&{after_role.id}>**", color = 0xf6ff00, timestamp = discord.utils.utcnow())
    if before_role.name != after_role.name:
        embed.add_field(name = "Name changed:", value = f"{before_role.name} -> {after_role.name}", inline = False)
    if before_role.color != after_role.color:
        embed.add_field(name = "Color changed:", value = f"{before_role.color} -> {after_role.color}", inline = False)
    if before_role.hoist != after_role.hoist:
        embed.add_field(name = "Hoist changed:", value = f"{before_role.hoist} -> {after_role.hoist}", inline = False)
    if before_role.permissions != after_role.permissions:
        embed.add_field(name = "Permissions changed:", value = f"Value = {before_role.permissions.value} -> Value = {after_role.permissions.value}", inline = False)
    if before_role.mentionable != after_role.mentionable:
        embed.add_field(name = "Mentionable changed:", value = f"{before_role.mentionable} -> {after_role.mentionable}", inline = False)
    embed.set_footer(text = f"Role ID: {after_role.id}")
    channel = bot.get_channel(1067413212955426877)
    await channel.send(embed = embed)```
potent spear
#

something has changed between the roles which you're not comparing

#

you can check EVERY attribute, you'll see which one changed

pulsar kettle
#

I think I know of a fix but that'll double the amount of lines of code so I just wanted to see if there's one that's more compact

#

Wait nvm my fix would just repeat the embed description for EVERY change

potent spear
pulsar kettle
potent spear
#

Youโ€™ll seeโ€ฆ itโ€™s an easy fix. Gl!

pulsar kettle
#

When you change one role position, it changes all the subsequent ones, so my bot spams those messages too (and gets rate limited grr)

potent spear
#

You can just skip the whole message if the position change is the only changeโ€ฆ and I think changes only happen one at a time, nvm, this is not the case as I see in your embed example . so maybe just (positionB != positionA) return
Would fix that

slate swan
#

just check for which one has changed it's position out of order

pulsar kettle
#

How do I do that?

exotic maple
#

Can someone help?

smoky sinew
exotic maple
#

how do i find out

smoky sinew
#

what

#

did you install nextcord or discord.py or something else

exotic maple
#

discord.pu

#

py

smoky sinew
#

use this instead

slate swan
#

@upper root mind checking dms?

exotic maple
smoky sinew
#

no problem

exotic maple
#

@smoky sinew do you have the documentation to manipulate text on pillow

smoky sinew
#
pulsar kettle
#
@bot.tree.command(name = "roleedit", description = "Changes the features of a role")
@discord.app_commands.checks.has_permissions(manage_roles = True)
async def roleedit(interaction:discord.Interaction, role: str, name: str = None, color: str = None, hoist: str = None, position: str = None, permissions: str = None, mentionable: str = None):
    await role.edit(name = name, color = color, hoist = hoist, position = position, permissions = permissions, mentionable = mentionable)
    embed = discord.Embed(title = f"**Edited the role <@&{role.id}**", color = 0xf6ff00)
    await interaction.response.send_message(embed = embed)```
Returns `discord.app_commands.errors.CommandInvokeError: Command 'roleedit' raised an exception: AttributeError: 'str' object has no attribute 'edit'` upon execution. Any fixes I can do?
pulsar kettle
# sick birch Typehint `role: discord.Role`

Changed role: str = None to role: discord.Role now I get the error:
Discord.app_commands.errors.CommandInvokeError: Command 'roleedit' raised an exception: TypeError: '<=' not supported between instances of 'NoneType' and 'int'

sick birch
#

Can you paste the full traceback?

potent spear
#

tbh, I don't see why you would even make such a command, discord's built-in UI is great for this...

pulsar kettle
# sick birch Can you paste the full traceback?

2023-01-28 08:38:34 ERROR discord.app_commands.tree Ignoring exception in command 'roleedit'

  File "C:\Users\ichirpy\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 862, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "d:\!Chirpy\Discord Bot Coding\Stardust\main.py", line 552, in roleedit
    await role.edit(name = name, color = color, hoist = hoist, position = position, permissions = permissions, mentionable = mentionable)
  File "C:\Users\ichirpy\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\role.py", line 454, in edit
    await self._move(position, reason=reason)
  File "C:\Users\ichirpy\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\role.py", line 358, in _move
    if position <= 0:
       ^^^^^^^^^^^^^
TypeError: '<=' not supported between instances of 'NoneType' and 'int'

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

Traceback (most recent call last):
  File "C:\Users\ichirpy\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\ichirpy\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ichirpy\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 876, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'roleedit' raised an exception: TypeError: '<=' not supported between instances of 'NoneType' and 'int'
pulsar kettle
potent spear
#

aight

#

so your main problem here has to do with datatypes

#

you're passing most arguments as strings in the command, but in role.edit(...) most arguments need to be specific datatypes (not strings), for example, position needs to be an int

naive briar
#

Who would have thought

pulsar kettle
potent spear
pulsar kettle
#

Yeah idk how to do the permissions part xd

potent spear
#

I hope you're starting to understand the redundancy of this command

potent spear
pulsar kettle
#

I might just remove the permissions part entirely because doesnt it have to be like the permissions value interger or smth

potent spear
#

you'd have to type a shit ton to set that up

#

(as a member using that command)

#

sure, you do you

graceful ermine
#

Hey guys

tired notch
#
def find_user_info(ctx, user: discord.Member, command):
    info = get_user_info(user.id)
    if info:
        def wrapper(*args, **kwargs):
            return command(*args, **kwargs)
    else:
        def wrapper():
            embed = discord.Embed(title="Error",
                                  description="This person has not created an account yet. Start the game with `/start`.",
                                  color=discord.Color.red())
            embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar)
            await ctx.send(embed=embed)
    return wrapper``` i know this code doesn't work but is there a way to do something similar to this?
#

i use that in most of my commands and i want to make it reusable

hushed galleon
# tired notch i use that in most of my commands and i want to make it reusable

id write a check that tries getting the user info, if it succeeds then its assigned as an attribute on ctx, otherwise it raises some custom error that you can catch in a handler: ```py
class NoAccountCreatedError(commands.CheckFailure): ...

def with_account():
async def predicate(ctx):
info = ...
if info is None:
raise NoAccountCreatedError

    ctx.account_info = info
    return True
return commands.check(predicate)

To use:

@bot.command(...)
@with_account()
async def my_command(ctx):
info = ctx.account_info
...```

tired notch
#

oh wow that is very clean

#

i didnt know you could do that with ctx

#

dang you can just assign attributes like that?

hushed galleon
#

sure, its one of their few classes that doesnt specify __slots__ so you're free to add new attributes to it

#

though it is perhaps not a type-safe way to do it, so you might prefer making a function that raises the same error if their account doesnt exist, only difference in error handling would be having to unwrap CommandInvokeError

tired notch
#

wait what is the point of class NoAccountCreatedError(commands.CheckFailure):?