#discord-bots

1 messages · Page 262 of 1

little ether
#

subclass this

#

and then use the subclass in the type hint

silk wasp
#

there is a way to build your own type hint method if that what u want

winter token
#

bruh there was just a indentation error

#

....

slate swan
#

any help?

silk wasp
silk wasp
# slate swan any help?

if u are using client.start(),

In the discord.py docs, it only allows token and reconnect as an argument

await start(token, *, reconnect=True)
This function is a coroutine.

A shorthand coroutine for login() + connect().

Parameters
token (str) – The authentication token. Do not prefix this token with anything as the library will do it for you.

reconnect (bool) – If we should attempt reconnecting, either due to internet failure or a specific failure on Discord’s part. Certain disconnects that lead to bad state will not be handled (such as invalid sharding payloads or bad tokens).

Raises
TypeError – An unexpected keyword argument was received.
naive briar
#

The bot argument was removed a long time ago

thick fulcrum
#

/voice verify

silk wasp
formal basin
#

!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...
silk wasp
#

!e

unkempt canyonBOT
#
Missing required argument

code

formal basin
#

my code here is not being executed

slate swan
#

my lord the indentation

formal basin
#

ok

formal basin
silk wasp
slate swan
#

everything

silk wasp
#

ahhahaha

formal basin
slate swan
#

just reformat your thing and get consistent indentation, then come back

slate swan
#

and all those empty lines, pointless

silk wasp
formal basin
#

there is that better?

silk wasp
#

all those indentation just need 1

#

look for all the indetation

formal basin
#

one tab?

silk wasp
#

it like everything

#

yes one tab]

formal basin
#

ok

formal basin
silk wasp
#

good job but the rest can work abit more too llike those functions and pass statement also but it fine so what the problem>?

#

btw rule of programming eb consistent

#

anyways so what the problem u facing?

formal basin
#

nothing happens

silk wasp
#

can i see the above code?

formal basin
#

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

formal basin
slate swan
silk wasp
#

could u send me the try except also

slate swan
#

More inconsistent than that is hard

formal basin
formal basin
silk wasp
#

nvm

#

i nvr see im blind

silk wasp
#

u only sent until line 744

formal basin
#

you want whole on_message?

silk wasp
#

yes

formal basin
#

ok

silk wasp
#

Btw you need to make sure things are consistent in programming if not things will fall apart

Unnecessarily parenthesis in if (message.author.bot), remove that

Unnecessary pass statement you dont really needed

Improper try-except block

your try-except block is place wrongly, It should wrap around the specific code that might raise an exception.

#

In your case, it should wrap around the code inside theif profanity.contains_profanity(message.content):condition.

#

@slate swan can i fix his code for him? ahahahah

formal basin
#

no but It needs to check if the guild id is in r (r=db) and then check for bad words

slate swan
silk wasp
#

yes please

slate swan
#

To be fair before fixing anything should fix indentation

silk wasp
#

i see the indent and it an indent error

slate swan
#

Because every indentation line different than the previous

silk wasp
#

this:

 try:                   
    if f'2 {message.guild.id}' not in r:
            pass
    else:
    
     if profanity.contains_profanity(message.content):
      await message.delete()
      embed = discord.Embed(title="No bad words please")
     embed.set_footer(text="Censored by profanity_filter")
     await message.channel.send(f"{message.author.mention}", embed=embed)
 except:
   pass 

is not same indent as this:

 if message.author.id == client.user.id:
        return 
   
   global author_msg_counts
   
   author_id = message.author.id
    # Get current epoch time in milliseconds
   curr_time = datetime.datetime.now().timestamp() * 1000

    # Make empty list for author id, if it does not exist
   if not author_msg_times.get(author_id, False):
        author_msg_times[author_id] = []

    # Append the time of this message to the users list of message times
   author_msg_times[author_id].append(curr_time)

    # Find the beginning of our time window.
   expr_time = curr_time - time_window_milliseconds

    # Find message times which occurred before the start of our window
   expired_msgs = [
        msg_time for msg_time in author_msg_times[author_id]
        if msg_time < expr_time
    ]

    # Remove all the expired messages times from our list
   for msg_time in expired_msgs:
        author_msg_times[author_id].remove(msg_time)
    # ^ note: we probably need to use a mutex here. Multiple threads
    # might be trying to update this at the same time. Not sure though.

   if len(author_msg_times[author_id]) == max_msg_per_window:
     
     try:
        +1
        minutes = r.get(f"1 {str(message.guild.id)}")
        min = int(minutes.decode("utf-8"))
        if f'1 {message.guild.id}' not in r:
            pass
        else:
            
            duration = datetime.timedelta(minutes=min)
            await message.author.timeout(duration)
            embed = discord.Embed(title="User muted", description=f" {message.author.mention} has been muted", color=discord.Color.blue())
            embed.add_field(name = "Reason",value = "spamming")
            embed.add_field(name = "Mute duration",value = f"{min} minutes")
            await message.channel.send(f"{message.author.mention} no spamming allowed")
            log = r.get(f"log {str(message.guild.id)}")
            log2 = int(log.decode("utf-8"))
            logging_channel = client.get_channel(log2) or await client.fetch_channel(log2)
            await logging_channel.send(embed=embed)
     except KeyError:
         pass
slate swan
#

And then leads to some stuff like that

silk wasp
#

it not in the same indent

formal basin
slate swan
#

But I mean that's what happens when people don't learn python

#

Probably a mix between self-made and pasted code

silk wasp
#

can i just end this hell ahahaha?

slate swan
#

And the pasted code uses proper indentation like the second code block above

silk wasp
#

dam

#

python bot ask me paste in in pastebin zzz

#

wait not python bot thought i was advertising nooooo

#

nooooooooo whyyy anyways

slate swan
#

What I specifically love are these 6 useless empty lines

#

Nevermind, they have some spaces/tabs

silk wasp
#

discord bot im not advertising ahh fine i paste bin

#

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

silk wasp
formal basin
#

ok.

silk wasp
#

for ur indent\

slate swan
#

And also seeing that makes the code already 10 times worse than it can ever be

silk wasp
#

but then eh

slate swan
#

global shouldn't be used at all

silk wasp
#

true true

slate swan
#

Especially if the variable is never used afterwards

buoyant quail
#

It just looks cool

#
global author_msg_counts

and your code becomes very pretty

glad cradle
#

tf

dense barn
#

Is there really no other way of making 2x2 fields without making this ugly empty field using \u200b?

buoyant quail
#

!d discord.Embed.add_field

unkempt canyonBOT
#

add_field(*, name, value, inline=True)```
Adds a field to the embed object.

This function returns the class instance to allow for fluent-style chaining. Can only be up to 25 fields.
buoyant quail
#

just pass inline

slate swan
#

this will make it one per row

buoyant quail
#

On second field

slate swan
#

thats not how inline works

#

when inline is True then this field will be the only one on this row

buoyant quail
#

ah yeah

slate swan
#

using inline you can create one column

#

without you can create 3 columns

#

and here comes problem how to make 2

dense barn
#

who do I talk to for changing this? sadboihours

#

fine i'll work around it, thanks :>

glad cradle
#

blud really thinks that he can ask for changes to the discord api dev team

winter token
#

so what should I learn for database shits in bot

slate swan
#

depends what database you want to use

#

Can anyone recommend a discord bot thats free and will remove anyone that hasn't posted in a server for 30 days?

shrewd apex
#

make ur own

slate swan
#

i dont think there are discord bots that do that stuff but you can code your own

slate swan
shrewd apex
#

lmao rip

buoyant quail
buoyant quail
#

With that your bot will need to exist on server these 30 days

shrewd apex
#

if u want to start from rn else yeah read from history

slate swan
#

Iterate through every channel and see if a member has a message timestamp within 30 days but if not, kick.

shrewd apex
#

for each member

winter token
slate swan
#

And then if someone didnt occur in any event for 30days

#

Boom gone

buoyant quail
slate swan
#

Well then you gotta have it running for 30days before it starts working

winter token
#

also a quick question, does ```py
bot.fetch_user(id)

slate swan
#

its awaitable its all i know

winter token
buoyant quail
#

If it was fetch_member, then not

winter token
winter token
slate swan
#

If you are new to this should go with MySQL or mongodb

buoyant quail
slate swan
slate swan
buoyant quail
#

same actually

#

and write to file as variable

slate swan
#

In js you can at least import from json file

buoyant quail
slate swan
#

I know

formal basin
#

could I make list like this:

  list2 = ["test", f"1{str(list)}2"]
#

so like 1t2 is in list2

#

or 1a2

naive briar
#

Not relevant to the channel's topic

thick fulcrum
#

Hi I made a discord py code for an Image generator it generates using /imagine and generates 6 photos under 3 seconds it gives high quality photos with so much more I am making more commands is the bot good

shrewd apex
thick fulcrum
#

Mine I made.

#

I swear it’s not copyrighted

#

Okay

naive briar
thick fulcrum
#

Can you do it with high graphics from Nvidia

winter token
#
except commands.ChannelNotFound:
            await ctx.send('Please mention a valid channel to lock.')
#

why does this dont work

thin raft
#

and try to understand what you copied / coded

winter token
#
async def lock(self, ctx, channel: discord.TextChannel, duration: converter = None, *, reason = "Not Specified"):

        description = f"**Locked:** <#{channel.id}>\n**Locked by:** {ctx.author.mention}\n**Reason:** {reason}"
        embed = discord.Embed(title = "Channel Locked Successfully!", description = description, colour = colour)
        guild = ctx.guild
        everyone_role = guild.default_role

        try:
            if channel.overwrites_for(everyone_role).send_messages is True:
                await channel.set_permissions(everyone_role, send_messages = False)
                await ctx.send(embed = embed)

                if duration == True:
                    await asyncio.sleep(duration)
                    await channel.set_permissions(everyone_role, send_messages = True)
                    await ctx.send('Channel has been unlocked.')

            else:
                await ctx.send('The given channel is already locked.')

        except commands.ChannelNotFound:
            await ctx.send('Please mention a valid channel to lock.')
naive briar
#

Do you really don't see anything wrong

#

The bot is trying to convert the channel argument before calling the command callback, so your try-except cannot catch it

thin raft
#

but why is it sending the message tho

#

I dont understand it

winter token
naive briar
#

That's even worse

#

It's hard to get a sense of where an error occurred if you can't see the traceback

silk wasp
#

btw u wanna make sure that the author has manage_channels permission.

#

also

winter token
silk wasp
#

nvm

thin raft
#

!d discord.TextChannel

unkempt canyonBOT
#

class discord.TextChannel```
Represents a Discord guild text channel.

x == y Checks if two channels are equal.

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

hash(x) Returns the channel’s hash.

str(x) Returns the channel’s name.
silk wasp
#

@winter token try commands.BadArgument instead

winter token
winter token
#
total = 0
        duration_pattern = r"(\d+)([dhms])"
        duration_values = re.findall(duration_pattern, duration)

        for value, unit in duration_values:
            value = int(value)
            if unit == "d":
                total += value * 86400
            elif unit == "h":
                total += value * 3600
            elif unit == "m":
                total += value * 60
            elif unit == "s":
                total += value
        return total
``` converter
winter token
unkempt canyonBOT
shrewd apex
#

!pypi time-str

unkempt canyonBOT
shrewd apex
#

there are libs for stuff like this

winter token
#

oh damn didnt know, I will study abt them later

formal basin
#
@client.event
async def on_member_update(before, after):
    if f'2 {after.guild.id}' not in r:
           return
    
     
    if after.id == client.user.id:
        return
``` ive got this code and it is a bad word filter for nicknames but once it changes the nickname it loops it
winter token
#

anyways u know the reason for that error?

shrewd apex
formal basin
shrewd apex
#

!d discord.ext.commands.Converter

unkempt canyonBOT
#

class discord.ext.commands.Converter(*args, **kwargs)```
The base class of custom converters that require the [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") to be passed to be useful.

This allows you to implement converters that function similar to the special cased `discord` classes.

Classes that derive from this should override the [`convert()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Converter.convert "discord.ext.commands.Converter.convert") method to do its conversion logic. This method must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.11)").
shrewd apex
#

u inherit from this class

winter token
shrewd apex
#

yeah dosent work that way

winter token
shrewd apex
#

when someone changes nickname the event triggers then bot changes it again then the event may trigger again that might be a case

shrewd apex
#

after.id is id of user whose name was changed iirc

#

print and check

formal basin
#
@client.event
async def on_member_update(before, after):
    if f'2 {after.guild.id}' not in r:
           return
    
     
    if after.id == client.user.id:
        return
    if after.nick == "Bad word name":
       pass
    else:
     
     badword = f"{profanity}"
    if any (word in after.nick for word in badword):
       new_nickname = "Bad word name"  
       await after.edit(nick=new_nickname) 
       log = r.get(f"log {str(after.guild.id)}")
       embed = discord.Embed(title="nickname changed", description=f"{after.mention}'s nickname was changed")
       embed.add_field(name="Reason", value="contained bad words")
       log2 = int(log.decode("utf-8"))
       logging = client.get_channel(log2) or await client.fetch_channel(log2)
       await logging.send(embed=embed)
#
Traceback (most recent call last):
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "/Users/zagzag/vscode/zagzag/zagzag.py", line 72, in on_member_update
    if any (word in after.nick for word in badword):
UnboundLocalError: local variable 'badword' referenced before assignment```
#
badword = f"{profanity}"
    if any (word in message.content.lower() for word in badword):
      await message.delete()
      embed = discord.Embed(title="No bad words please", description=None)
      embed.set_footer(text="Censored by better_profanity")
      log = r.get(f"log {str(message.guild.id)}")
      await message.channel.send(f"{message.author.mention}", embed=embed, delete_after=20)
      embed = discord.Embed(title="Message Deleted", description=f"{message.author}'s message was deleted")
      embed.add_field(name="Reason", value="contained bad words")
      log2 = int(log.decode("utf-8"))
      logging = client.get_channel(log2) or await client.fetch_channel(log2)
      await logging.send(embed=embed)
        ``` I have this code for an on_message event for anti swear {profanity} is better_profanity and if someone types anything it gets deleted
#

why is it deleteing any word or letter typed

buoyant quail
#

Because you are iterating over string badword characters

#

!e

badword = "something"
print([word for word in badword])
unkempt canyonBOT
#

@buoyant quail :white_check_mark: Your 3.11 eval job has completed with return code 0.

['s', 'o', 'm', 'e', 't', 'h', 'i', 'n', 'g']
buoyant quail
#

And checking if any characters from this word are in the message

winter token
shrewd apex
#
class CustomConverter(commands.Converter):
  async def convert(self, ctx: commands.Context, argument: str):
    return ur_data
dense barn
#

{context.guild.region} Can't find any documentation relating to this, has this been removed/changed?

shrewd apex
#

its interaction if slash command

dense barn
#

For a serverinfo command.

shrewd apex
#

why not i often use a duration converter

buoyant quail
slate swan
#

No need to over-engineer, especially for their use case where you just care about the argument and context is pointless

formal basin
buoyant quail
formal basin
#

i tried profanity.split

dense barn
#

for word in badword iterates through badword with its letters being the values.

shrewd apex
#

eh ur preference ig its not that simple for a duration converter u need to handle edge cases like errors and bad spam input as well

formal basin
#

there lots of words in it

shrewd apex
#

plus i reuse mine in a bunch of places so subclassing is better

formal basin
slate swan
#

If their converter works (at least in some cases according to messages), no point in telling them it's wrong and not the way to do it, but rather fix the issue they have with their actual converter

formal basin
#

and not the letters

buoyant quail
buoyant quail
unkempt canyonBOT
#

@buoyant quail :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | ['s', 'o', 'm', 'e', 't', 'h', 'i', 'n', 'g']
002 | ['something']
slate swan
#

basics of python

buoyant quail
slate swan
#

Why bother learning if you can ask here gigachad

scarlet snow
winter token
#

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

finite imp
#

Exception has occurred: AttributeError
partially initialized module 'discord' has no attribute 'Client' (most likely due to a circular import)

i can't find anything on google how do i solve this?

slate swan
#

did you name your file discord.py?

finite imp
#

im so fucking stupid i didn't notice my bad 😭

slate swan
#

yeah you cant name files like module names cause they will stop working

#

now you know 👍

finite imp
#

i just checked it omg im dumb

#

well thanks

slate swan
#

👍

reef fractal
#
async def profile(interaction,member: discord.Member):
   
    user = interaction.member```

With this, when someone is using the command, in the embed I am getting the user who is using the command, and the username of the person someone is wanting to see. Can someone tell me how to add that? Where the username in the embed is shown of the person who is being mentioned
formal basin
vocal laurel
#

Also what’s interaction.member??

#

Cuz iirc it’s interaction.user for the person using slash command and member for the selected member

slate swan
#

!d discord.Interaction.user

unkempt canyonBOT
vocal laurel
reef fractal
#
async def profile(interaction,member: discord.Member):
   
    user = interaction.user```

this was the code, sorry, I was just trying to understand when doing that
formal basin
slate swan
#

user is the person who invoked the command while member is the person specified in the command param

reef fractal
#

Ohh, how do I invoke that tho? getting the information of the member?

slate swan
#

!d discord.Member

unkempt canyonBOT
#

class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").

This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").

x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.

x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.

hash(x) Returns the member’s hash.

str(x) Returns the member’s handle (e.g. `name` or `name#discriminator`).
slate swan
#

here you have all attributes and methods it has

#

the names are self explainatory

#

if not there is description as well

reef fractal
# formal basin what type of info?

Like when the user uses the slash command, gives a members name, then the username of the member is shown and ID, that's what I want rn

reef fractal
slate swan
formal basin
reef fractal
#

oh

#

I am so dumb

#

Thank you so much, both of you

formal basin
#

...

#

!d

unkempt canyonBOT
slate swan
#

random symbols does not exist

#

!d discord.on_message

unkempt canyonBOT
#

discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") is created and sent.

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

Warning

Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
buoyant crescent
#

!d discord.Interaction

unkempt canyonBOT
#

class discord.Interaction```
Represents a Discord interaction.

An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.

New in version 2.0.
hasty pike
#

Dumb question but
Can i replace this

def blacklist_check():

    def predicate(ctx):
        with open("blacklist.json") as f:
            data = json.load(f)
            if str(ctx.author.id) in data["ids"]:
                return False
            return True

    return commands.check(predicate) 

With this

def blacklist_check(ctx):
        with open("blacklist.json") as f:
            data = json.load(f)
            if str(ctx.author.id) in data["ids"]:
                return False
            return True

To use like

@bot.command()
@blacklist_check()
async def check(ctx):
slate swan
#

thats why you return it already as commands.check so you dont need to do that

slate swan
#

you need to have Member class object not a Member class

#

well discord bot isnt a good project for a beginner you need to know basics and maybe some more of python to know what you are doing

#

you need to gather Member object and use this method on it

hasty pike
slate swan
#

how is is supposed to know what member to give/remove roles

unique gorge
#

Hello Guys!

#

@grizzled tundra

grizzled tundra
#

hello

unique gorge
#

: D

hasty pike
#

async def say(interaction, user: discord.Member, ......)

slate swan
#

why steal avatar

hasty pike
slate swan
#

impersonating

hasty pike
winter token
#

the lock cmd works only if I give 1s as duration input

slate swan
#

and what is the converter

#

ok its below

#

does it even work when you annotate it as function?

#

did you try printing what it outputs?

buoyant quail
buoyant quail
#

Ah well i see

#

Your duration is an integer

#

Why are you comparing it with True...

onyx bison
#

I’m very new to python but I want to create a discord bot where should I start

slate swan
#

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

shrewd apex
hasty pike
#

ctx.guild.icon_url doesn't work?

coarse geyser
#
embed.add_field(
        name="OSINT", value="  ⤷ Open-Source-Intelligence", inline=False
)```

The two spaces infront of the arrow `  ⤷` get deleted in the actual embed
coarse geyser
crimson horizon
#

Hi guys

hasty pike
coarse geyser
hasty pike
crimson horizon
#

I used stable diffusion to generate images on discord. But my problem is that when one image is generating and someone else uses the command, my bot responds with „this application did not respond“. I also made like a queue so it adds the user who wants to generate an image to a queue and then generates the images. So why does it not respond?

slate swan
#

You need to respond to interactions within 3 seconds

crimson horizon
#

I know

slate swan
#

If you can't, then defer the response and you can then respond within 15 minutes

crimson horizon
#

But It adds the user to the queue and responds directly

slate swan
#

Most likely not, Discord doesn't lie

crimson horizon
#

Then generates images for all users in the queue in a loop

#

It works when a user enters the command

#

But someone else has to wait until the first image is generated

#

Even though that is in the loop and not the command

hasty pike
#

Seems like you didn't try

hasty pike
slate swan
#

if you really want bigger space before this arrow you need to use some sort of invisible character

pure sparrow
ocean trench
#

Hey, I just wanted to say I successfully migrated my Replit bot to a DigitalOcean VPS after receiving advice to do so on this server a week ago. So thank you to those who showed me the way, it wasn't easy but I finally made it 🙂

slate swan
unkempt canyonBOT
#

class discord.Guild```
Represents a Discord guild.

This is referred to as a “server” in the official Discord UI.

x == y Checks if two guilds are equal.

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

hash(x) Returns the guild’s hash.

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

docs are here for a reason check what attributes it has

kindred iron
#
    async def lock(self, ctx : commands.Context,
                    channel : Optional[Union[discord.TextChannel, discord.VoiceChannel, discord.CategoryChannel, discord.StageChannel, discord.ForumChannel]],
                    duration : Optional[TimeConverter]):
        
        print(duration)```

Hi , anyone know why I'm getting discord.Message? ( The return type of TimeConverter is int | None)
slate swan
#

what is the definition of TimeConverter

kindred iron
#

It's subclass of commands.Converter

slate swan
#

yeah but what is the definition

kindred iron
#

It's supposed to return int or none but

slate swan
#

give code

kindred iron
#
class TimeConverter(commands.Converter):
    def __init__(self, * , min : int = None, max : int = None):
        self.min = min
        self.max = max



    async def convert(self, ctx : commands.Context, arg : str) -> int:
        try:

            time_ls : list = []
            time_str : str = ''

            for i in arg:
                try:
                    int(i)
                    time_str += i
                except ValueError:
                    time_ls.append(i)

            try:
                time_ls.append(int(time_str))

            except:
                return await ctx.send(":no: The provided time is invalid", delete_after = 15)


            time_mapping : dict = {
            "w" : 604800,
            "d" : 86400,
            "h" : 3600,
            "m" : 60,
            "s" : 1
            
        }
            
            

            new_time = time_ls[1]
            unit = time_ls[0]
                
            time = time_mapping[unit] * new_time

            if self.max or self.min:
                if time > self.max:
                    return await ctx.send(f"invalid time, maximum time is {self.max} seconds.")
                
                if time < self.min:
                    return await ctx.send(f"invalid time, minimum time is {self.min} seconds.")


            return time

        except Exception:
            await ctx.send(f'{unit} is not valid time unit')
            return```
stuck cosmos
#

hey

#

anyone know why cooldown command isnt working on the latest version of discord.py

#

@commands.cooldown(1, 10, commands.BucketType.user) is the current code i added

slate swan
#

and you said it returns Message

kindred iron
#

arg : TimeConverter(min, max)

slate swan
#

well you are doing return await ctx.send

kindred iron
#

Smart

slate swan
#

thats why you get Message

kindred iron
#

But I'm not giving anything

#

It's optional right?

slate swan
#

what is optional

#

the min and max?

slate swan
#

yes it is optional

kindred iron
#

Let me test first

slate swan
stuck cosmos
kindred iron
#

Ok so

stuck cosmos
#

im looking at the docs rn, tryna figure it out

kindred iron
#

Didn't work

#

from discord.ext import commands

class TimeConverter(commands.Converter):
    def __init__(self, * , min : int = None, max : int = None):
        self.min = min
        self.max = max



    async def convert(self, ctx : commands.Context, arg : str) -> int:
        try:

            time_ls : list = []
            time_str : str = ''

            for i in arg:
                try:
                    int(i)
                    time_str += i
                except ValueError:
                    time_ls.append(i)

            try:
                time_ls.append(int(time_str))

            except:
                await ctx.send(":no: The provided time is invalid", delete_after = 15)
                return


            time_mapping : dict = {
            "w" : 604800,
            "d" : 86400,
            "h" : 3600,
            "m" : 60,
            "s" : 1
            
        }
            
            

            new_time = time_ls[1]
            unit = time_ls[0]
                
            time = time_mapping[unit] * new_time

            if self.max or self.min:
                if time > self.max:
                    await ctx.send(f"invalid time, maximum time is {self.max} seconds.")
                    return
                
                if time < self.min:
                    await ctx.send(f"invalid time, minimum time is {self.min} seconds.")
                    return


            return time

        except Exception:
            await ctx.send(f'{unit} is not valid time unit')
            return```
#

Now return type should be just int or None right?

#

But still discord.Message somehow

naive briar
#

But still what?

#

That message doesn't make sense

kindred iron
#

Lol

#

My brain

#

Ig command problem

shrewd apex
#

is everyone making a converter today 👀

slate swan
shrewd apex
unkempt canyonBOT
shrewd apex
#

also instead pf ctx.send why not raise some error and handle it at once in the error handler

kindred iron
#

I'm lazy lol

shrewd apex
#

no ur doing more hard work that way

kindred iron
#

Not that much difference

shrewd apex
#

all u need is raise commands.BadArgument("Invalid Time") as long as u have a decent error handler u dont need any of those if statements

kindred iron
#

Just writing ctx.send * 4 then usual lol

shrewd apex
#

try:
return
except:
raise

#

thats it

kindred iron
#

Thanks, will try it

shrewd apex
# slate swan progress

lets write a gist for these features maybe a comprehensive guide seems like a good project 👀

#

wanna try it out?

slate swan
#

like converters and stuff

shrewd apex
#

we can include modals paginators and all that stuff

shrewd apex
#

all features with examples

kindred iron
shrewd apex
#

best practices i suppose

slate swan
#

i know but you are like 4th person who asks about them

shrewd apex
#

as well as making handy components

slate swan
#

and im here for a long time

kindred iron
#

Lol

shrewd apex
#

down is like master oogway been here for a loooong time 👀

#

change pfp when? oogway way cooler than current pfp turtle guy

slate swan
#

turtle is my symbol now

buoyant quail
slate swan
shrewd apex
#

hmm think I'll start writing one from tomorrow

blazing flint
#

!d discord.Attachment

blazing flint
#

how can I get the text contained in an inputted discord.Attachment

shrewd apex
#

aight cool a repo or a gist i think we can have a repo examples and a gist explaining

slate swan
stuck cosmos
#

will @commands.cooldown(1, 10, commands.BucketType.user) work for the latest py version?

#

dpy*

shrewd apex
#

either that or we make something like a GitHub pages that would be cool too

stuck cosmos
#

i got no clue why its not working then

#

does it change up for slash commands?

shrewd apex
#

u need to handle cooldown error in ur error handler tho

blazing flint
stuck cosmos
#

the cooldown just doesnt work, still allows me to use the command

slate swan
shrewd apex
#

on application command error or on command error

buoyant quail
stuck cosmos
#

yh 1 sec

buoyant quail
#

!d discord.app_commands.checks.cooldown

unkempt canyonBOT
#

@discord.app_commands.checks.cooldown(rate, per, *, key=...)```
A decorator that adds a cooldown to a command.

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns are based off of the `key` function provided. If a `key` is not provided then it defaults to a user-level cooldown. The `key` function must take a single parameter, the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") and return a value that is used as a key to the internal cooldown mapping.

The `key` function can optionally be a coroutine.

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandOnCooldown "discord.app_commands.CommandOnCooldown") is raised to the error handlers.

Examples

Setting a one per 5 seconds per member cooldown on a command:
shrewd apex
#

time to check docs

buoyant quail
#

this ?

shrewd apex
#

disnake has same for both pithink

shrewd apex
stuck cosmos
#

doesnt cooldown unfortantly

shrewd apex
stuck cosmos
#

ok 1 sec

blazing flint
#

@slate swan it is txt

stuck cosmos
#

would i just replace it with the old one?

shrewd apex
unkempt canyonBOT
#

class discord.Attachment```
Represents an attachment from Discord.

str(x) Returns the URL of the attachment.

x == y Checks if the attachment is equal to another attachment.

x != y Checks if the attachment is not equal to another attachment.

hash(x) Returns the hash of the attachment.

Changed in version 1.7: Attachment can now be casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") and is hashable.
blazing flint
#

I can't find anything on the docs either

shrewd apex
#

calm down lol i was checking docs

slate swan
#

!d discord.Attachment.read

unkempt canyonBOT
#

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

Retrieves the content of this attachment as a [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.11)") object.

New in version 1.1.
shrewd apex
#

yeah use the read method

blazing flint
#

it does not work

shrewd apex
#

how does it not work?

slate swan
#

what does that mean

blazing flint
#

is .read() enough

slate swan
#

what do you get?

shrewd apex
#

await file.read()

blazing flint
#

yeah

shrewd apex
#

if file is the param name

blazing flint
#

await file.read()

shrewd apex
#

u will get the data in bytes

slate swan
#

and to get them to string you need to use .decode

#

!d bytes.decode

unkempt canyonBOT
#

bytes.decode(encoding='utf-8', errors='strict')``````py

bytearray.decode(encoding='utf-8', errors='strict')```
Return the bytes decoded to a [`str`](https://docs.python.org/3/library/stdtypes.html#str "str").

*encoding* defaults to `'utf-8'`; see [Standard Encodings](https://docs.python.org/3/library/codecs.html#standard-encodings) for possible values.

*errors* controls how decoding errors are handled. If `'strict'` (the default), a [`UnicodeError`](https://docs.python.org/3/library/exceptions.html#UnicodeError "UnicodeError") exception is raised. Other possible values are `'ignore'`, `'replace'`, and any other name registered via [`codecs.register_error()`](https://docs.python.org/3/library/codecs.html#codecs.register_error "codecs.register_error"). See [Error Handlers](https://docs.python.org/3/library/codecs.html#error-handlers) for details.

For performance reasons, the value of *errors* is not checked for validity unless a decoding error actually occurs, [Python Development Mode](https://docs.python.org/3/library/devmode.html#devmode) is enabled or a [debug build](https://docs.python.org/3/using/configure.html#debug-build) is used.

Note

Passing the *encoding* argument to [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") allows decoding any [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) directly, without needing to make a temporary `bytes` or `bytearray` object.
shrewd apex
slate swan
#

yeah
``

blazing flint
#

so await file.read.decode(encoding='utf-8)

shrewd apex
#

no

slate swan
#
b'hello'.decode('utf-8')```
### or
```py
str(b'hello', 'utf-8')```
shrewd apex
#

str(await file.read())

blazing flint
#

ok

slate swan
#

@shrewd apex we need to create a list of features to explain 👀

blazing flint
#

I keep getting the same error with .read()

#
  File "/home/runner/translator-bot-20/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 827, in _do_call
    return await self._callback(self.binding, interaction, **params)  # type: ignore
  File "/home/runner/translator-bot-20/cmds/translate.py", line 20, in translate
    print(translator.detect(str(await file.read())))
  File "/home/runner/translator-bot-20/venv/lib/python3.10/site-packages/googletrans/client.py", line 255, in detect
    data = self._translate(text, 'en', 'auto', kwargs)
  File "/home/runner/translator-bot-20/venv/lib/python3.10/site-packages/googletrans/client.py", line 78, in _translate
    token = self.token_acquirer.do(text)
  File "/home/runner/translator-bot-20/venv/lib/python3.10/site-packages/googletrans/gtoken.py", line 194, in do
    self._update()
  File "/home/runner/translator-bot-20/venv/lib/python3.10/site-packages/googletrans/gtoken.py", line 62, in _update
    code = self.RE_TKK.search(r.text).group(1).replace('var ', '')
AttributeError: 'NoneType' object has no attribute 'group'

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

Traceback (most recent call last):
  File "/home/runner/translator-bot-20/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/translator-bot-20/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/translator-bot-20/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 846, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'translate' raised an exception: AttributeError: 'NoneType' object has no attribute 'group'```
shrewd apex
#

we have 3 options

  • gist
  • repo with bunch of readme and examples
  • a github pages sites with like some docs lib like mkdocs
slate swan
#
  • error handling
  • global
  • per command
  • converters
  • custom context
shrewd apex
#

we should take this to another server for discussion ig

slate swan
shrewd apex
#

3 rd is also I'll set up the repo tmrw we can get a nuce ui

blazing flint
#

can someone help me with my error

shrewd apex
blazing flint
#
import discord
from discord.ext import commands
from discord import app_commands
import googletrans
from googletrans import Translator

class Translate(commands.Cog):

  def __init__(self, client):
    self.client = client

  @app_commands.command(name="translate", description="Translate a file to English")
  @app_commands.describe(file="The file to translate")
  async def translate(self, interaction: discord.Interaction, file: discord.Attachment):
    if file.content_type[0:4] != 'text':
      interaction.response.send_message("Please input a valid text file", ephemeral=True)

    translator = Translator()

    print(translator.detect(str(await file.read())))
    
async def setup(client):
  await client.add_cog(Translate(client))
shrewd apex
#

he is trying to detect the language that the text inside the text file is

#

yeah its a issue with the translator library

blazing flint
#

oh

shrewd apex
#

can u try printing the text

slate swan
#

maybe the content is empty

shrewd apex
#

also keep in mind that some languages may not have same encoding as English so when decoding u will have to specify

buoyant quail
#

That's a google translate library issue
Google it, there is a solution

shrewd apex
#

like i worked on some translation stuff for webnovels some time back like chinese has codec cp 499 or 599 or something so u have to decode with those specific values than utf-8

blazing flint
slate swan
blazing flint
#

the content is not empty

#

I meant to respond to the other messgae

slate swan
#

try printing the str(await file.read()) and see whats inside

buoyant quail
# buoyant quail That's a google translate library issue Google it, there is a solution
shrewd apex
#

!pypi deep-translator

unkempt canyonBOT
#

A flexible free and unlimited python tool to translate between different languages in a simple way using multiple translators

shrewd apex
#

i use this its smexy google rate limited me very often when i used googletrans ;-;

slate swan
#

!source pip

unkempt canyonBOT
#
Command: pypi

Provide information about a specific package from PyPI.

Source Code
shrewd apex
#

also btw u would need to run this in an executor to not block they use requests internally i think

#

definitely need to add the concept of blocking or not in the guide

blazing flint
#

the content is b'el gato'

#

the file content is just 'el gato' for testing

shrewd apex
#

is that enough content for detection of a language pithink

blazing flint
#

hmm

#

lemme try with a big chinese file

buoyant quail
buoyant quail
shrewd apex
#

try it out ig no harm altho look into the error if its lib specific

slate swan
#

ah

blazing flint
#

I get the same error as before

shrewd apex
#

mute the group :p

shrewd apex
blazing flint
#

do you know another library

shrewd apex
blazing flint
#

ty

dense barn
#

Hello, suppose I use my Command Prompt to run the bot and host it on my PC but I want to hide the Command Prompt Console but still keep the bot running on the background, would that be possible? And is it possible to close it through Task Manager or something?

#

It's just obstructing to Alt+Tab and see a cmd console just sitting there.

#

I see some solutions online that is to change the extension to .pyw, but unsure if it would break things.

slate swan
#

its \u200e

hasty pike
#

Look as per my knowledge we have 3 steps
1.

value="** **space"
space=" " 
value=f"{space} ok"

And last one what downie said @coarse geyser

#

All three works for me

slate swan
#

_ _ _ _ _ _ blah

#

works fine

#

For me it does

hasty pike
#

Are you replit user

#

_ _ _ _ _ _ blah

slate swan
#

Probably the encoding of something or whatever else blocking it

#

Because encoding is different on machines duh

#

For the third time, it's called encoding

#

Yes, your computer also uses encoding to save files - very mind-blowing

#

And depending on that, it doesn't matter to whom you send - it will be sent with the encoding YOUR computer has used to save the file

hasty pike
#

Back to primary school topics

slate swan
#

You don't send data to discord based on their encoding, they handle your data later on

#

And as mentioned above, it may be because of encoding, could be something else

#

Change your encoding or make sure it's sent with proper encoding

hasty pike
#

He doesn't know about it

slate swan
#

?????????

hasty pike
#

Bro being racist Bg_pikachu

slate swan
#

Field Name: yes
Field Value: _ _ _ _ _ _ yes

#

So it's definitely something on your end

#

And the way you send the data to discord

#

Proposes some nonsense
Says thanks to own nonsense proposition
Will continue blaming others
...
Profit???

#

Ok.

#

Cool.

hasty pike
slate swan
#

<@&831776746206265384> thank you ^-^

#

See context above as well with the user being racist

hasty pike
#

pain meanwhile Russians brute forcing your accounts

hollow osprey
#

!cban 1116437317360554064 racism and trolling

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied ban to @coarse geyser permanently.

slate swan
#

Thanks

hollow osprey
#

carry on

hasty pike
#

Thanks

formal basin
#

why do I get this error?

slate swan
#

Because you did

message = message.content.lower()
#

So message is no longer a message object but just a string

formal basin
#

I didnt realise that i did message as the name

#
if f'2 {message.guild.id}' not in r:
            return
    

    message_content2 = message.content.lower()
    words = message_content2.split(",.!?;:=+_-*%&!/\><~  ")
    for word in words:
       if word in profanity.CENSOR_WORDSET:
        await message.delete()
        embed = discord.Embed(title="No bad words please", description=None)
        embed.set_footer(text="Censored by better_profanity")
        log = r.get(f"log {str(message.guild.id)}")
        await message.channel.send(f"{message.author.mention}", embed=embed, delete_after=20)
        embed = discord.Embed(title="Message Deleted", description=f"{message.author}'s message was deleted")
        embed.add_field(name="Reason", value="contained bad words")
        embed.set_footer(text="Censored by better_profanity")
        log2 = int(log.decode("utf-8"))
        logging = client.get_channel(log2) or await client.fetch_channel(log2)
        await logging.send(embed=embed)
      ``` I have this code here to check if theres special characters in between words but its not doing anything
#

profanity.CENSOR_WORDSET is a set of bad words

#

no error

slate swan
hasty pike
slate swan
#

ah what a nice guy

hasty pike
#

Ikr

slate swan
#

😭

flint heart
#

I play for a league that uses mystatsonline.com as a place to store all of our league's stats, but I was wondering if there would be a (relatively) simple way to scrape the info off the site to use for a discord bot aswell. I already checked, and sadly, there is no api for the site

fair vapor
#

someone can help me, i need a simple bot for my discord server, only 3 basic commands, but i dont understand too much, y alredy got a base code, can someon help me?

#

i only need this commands: $generatecode, $deletecode and $reclaim 'code', generate a 6 digits code that will be stored on codes.txt and $reclaim code will get 1 gift from a list, $deletecode will delete the code from the codes.txt

thin raft
#

those are 4 commands

fair vapor
#

ammm no, $generatecode $deletecode and $reclaim 'code'

thin raft
#

well 3

#

!code

unkempt canyonBOT
#
Formatting code on discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

fair vapor
#

@thin raft can u help me?

#

i need help :/

thin raft
fair vapor
tacit prawn
#

I need to import a fail safe incase someone tries to scam me, how can I delete all of the files of a bot across all servers?

#

So say I give a bot to someone, then they block me, ban me, etc without paying, I want to be able to run a command in my server, which the bot is still in, to destroy all of its files across all servers. I don't care if it destroies all of the files of the one I sent the command in, as I will have it backed up on a totally separate file.

#

Would this do the trick?

path = os.getcwd()
        for file in path:
            os.remove(file)
hasty pike
#

What if they just copy paste somewhere else or backup it

#

Also command wouldn't run if bot is offline

#

I don't think you have any luck

sick birch
tacit prawn
sick birch
#

Another option is to host their bot for them so you're in control of the bot (if they don't pay, you can simply shut off the bot)

tacit prawn
sick birch
#

Charge users for the hosting shrug

tacit prawn
#

I got an old laptop I don't use

sick birch
#

You can also charge users the cost of the product (the bot) + labor costs as a profit

#

So it's a net gain for you

tacit prawn
#

Genius

sick birch
#

Well you need to make a profit, otherwise there's no point

tacit prawn
#

True

tacit prawn
sick birch
#

Fiverr or Upwork

tacit prawn
#

Got it

swift edge
#

guys
im trying to make making a command easier, heres a ex

@commands.command()
async def ping(self, ctx):
    await ctx.send("pong")

remake

def cmd(title, send)
@commands.command()
async def title(self, ctx):
await ctx.send(send)

so basically whatever is put in the title is basically gonna be the command name
send is for sending a message to the specified text

hasty pike
swift edge
#

so u know lua

#

function button(title, send)

guititle = title
guiresponse = send

for example

function button(game, hello)

guititle = title
guiresponse = send

command
app title is game and the cmd prints hello

#

@hasty pike heres a example

hasty pike
#

Is it my not working or you aren't telling me what do you need

hasty pike
swift edge
#

okay

swift edge
swift edge
hasty pike
#

No need for self modifications

#

It's already alot simpler

sick birch
swift edge
#

i just dont know what to do

#

i want to code, but code what

#

?

sick birch
#

Make the triggers into keys and the responses into values, check in on_message

winter token
#

I want my bot to send some msg like "Failed" when someone tries to mute a user who has admin perms. How do I do it

swift trench
#
Traceback (most recent call last):
  File "/home/runner/zio-accounts/venv/lib/python3.10/site-packages/discord/client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 58, in on_message_delete
    snipe_channel = message.content.channel
AttributeError: 'str' object has no attribute 'channel'
slate swan
#

tree = discord.app_commands.CommandTree(client)
^^^^^^^^^^^^^^^^^^^^
AttributeError: module 'discord' has no attribute 'app_commands'

swift trench
#
    await client.commands_proccess()
#

this right?

#

got it nvm

tacit prawn
#

How can I get like a few set args, then after that an infinite number of args that are put together into an array, and only the inf number of args are put into the array

#

For example:

async def info(self, context: Context, eventtype: str, notes: str, attendees: str):

I want to keep the first two, and I want an infinite number of attendees args, which are all put together into an array

hasty pike
#

Like

#
async def ban(ctx, user: discord.Member, *, reason=None)

@tacit prawn

hasty pike
#

try:
mute function goes here
except:
await ctx.send("unable to mute this member")

tacit prawn
#

Don't quite get it...

tacit prawn
#

I need to have two args, then after that I will have an infinite number of args

naive briar
#

!e

def a(*args):
    print(*args)

a(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

0 1 2 3 4 5 6 7 8 9
naive briar
#

!e or this

def a(first, second, *args):
    print(first, second)
    print(*args)

a("uwu", "owo", 0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | uwu owo
002 | 0 1 2 3 4 5 6 7 8 9
winter token
slate swan
#

@winter token you'll have to use an if condition ```py
if other_member.guild_permissions.administrator:
# member is admin

quick gust
#

or maybe just handle BotMissingPermissions or MissingPermissions

#

also what is that profile sarth 🤔

vocal snow
#

You mean Aditi

quick gust
#

you don't need infinite args for that....

hasty pike
#

Cat explained it all

quick gust
#

Yeah they were right

winter token
#
async def timeout(self, ctx, member:discord.Member, duration: converter, *, reason = "Not Specified"):
        description = f"**Timed out:** {member.mention}\n**Timed out by:** {ctx.author.mention}\n**Reason:** {reason}"
        embed = discord.Embed(title = "Timed out Successfully!", description = description, colour = colour)

        if member.mention == ctx.author.mention:
            await ctx.send("You can't timeout yourself.")
        else:
            try:
                if member.is_timed_out() == True:
                    await ctx.send("The member is already timed out.")
                else:
                    await member.timeout(until = duration, reason = reason)
                    await ctx.send(embed = embed)
#

Error occured: Command raised an exception: TypeError: Member.timeout() got some positional-only arguments passed as keyword arguments: 'until'

#

how do i use until thingy

naive briar
#

Learn to read errors

#

TypeError: Member.timeout() got some positional-only arguments passed as keyword arguments: 'until'

winter token
#

what do i dooo

quick gust
#

remove until=

winter token
#

it tells me to use datetime module

slate swan
#

So use it

winter token
#

so i was trying to use my TIME converter

slate swan
#

The .timeout method takes only datetime.timedelta

#

!d discord.Member.timeout

unkempt canyonBOT
#

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

Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.11)").

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

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
slate swan
#

O can be datetime.datetime as well

#

In your case datetime.timedelta will be the best

#

!d datetime.timedelta

unkempt canyonBOT
#

class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)```
All arguments are optional and default to `0`. Arguments may be integers or floats, and may be positive or negative.

Only *days*, *seconds* and *microseconds* are stored internally. Arguments are converted to those units...
winter token
slate swan
#

No

#

That's why you have your converter

#

To convert it

winter token
slate swan
#

Would be best if the converter would already return timedelta

formal basin
#
 ok_words = "assesment", "assasin", "pass", "rass", "lass"
    words = message.content.lower()
    for word in profanity.CENSOR_WORDSET:
     if word in words:
      if words == ok_words:``` the ``if words == ok_words:`` doesnt work
slate swan
slate swan
#

What does your converter output

winter token
slate swan
#

so why dont you do something=datetime.timedelta(seconds=your_converter_output)

slate swan
#

and then pass something to .timeout method

#

or give it better name

slate swan
naive briar
#

I just think that they're trolling at this point

slate swan
#

🦆 Maybe

formal basin
#

profanity.CENSOR_WORDSET is a set of words

slate swan
#

Define topggpy in your main file and set it as bot variable

#

!botvar

unkempt canyonBOT
#
Bot variables

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!

formal basin
#

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

formal basin
#

this code is deleting anything

#

when a message is edited

#

it should only be deleting profanity.CENSOR_WORDSET

sturdy peak
#

Hi there, im trying to get more proficient with discord bots, right now getting familiar with cogs.
I've managed to get the hang of using commands in cog files, but trying to get certain attributes still doesnt work like it would in the main.py file:

import discord
from discord.ext import commands
from discord import app_commands

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

    @commands.command() # Actually introducing a command.
    async def hello(self, ctx:commands.Context):
        await ctx.send(f'Hello {ctx.author}')
        #working
    
    @commands.command()
    async def shutdown(self, ctx:commands.Context):
        await ctx.send("Shutting down the bot...")
        await self.client.close()
        #working
    
    @commands.command(aliases=['uinfo', 'whois'])
    async def userinfo(self, ctx:commands.Context, member): #member:discord.Member=None
        #if member == None:
        #    member = ctx.author
        embed = discord.Embed(title="User info", description=f"Here is the user info on the user{member.name}", color = discord.Color.green(), timestamp  = ctx.message.created_at)
        embed.add_field(name="ID", value=member.id)
        embed.add_field(name="Name", value = f"{member.name}#{member.discriminator}")
        embed.add_field(name="Nickname", value = member.display_name)
        await ctx.send(embed=embed)

async def setup(client:commands.Bot) -> None:
    await client.add_cog(Greetings(client))```

Its about the third @commands.command , how do i correctly get the name, member, author when .userinfo is called?
Getting *Context' object has no attribute 'name'* error and i roughly know why just not familiar with cogs enough yet to fix it :/

Any help is appreciated ![prayge](https://cdn.discordapp.com/emojis/806672915499319317.webp?size=128 "prayge")
sharp whale
#

hello, how would i make it so even after restarting the bot, the button interaction works?

unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

slate swan
sturdy peak
# naive briar !traceback <:ducky_sus:987918033504854066>
  File "/home/alias/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "/home/alias/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 1029, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "/home/alias/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 244, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'name'```
vocal snow
#

embed.add_field(name="Name", value = f"{member.name}#{member.discriminator}")

#

look at the function signature, the member parameter has no typehint so discord.py will pass it as a string

raw rain
#

!rpc

unkempt canyonBOT
#
Relative path

A relative path is a partial path that is relative to your current working directory. A common misconception is that your current working directory is the location of the module you're executing, but this is not the case. Your current working directory is actually the directory you were in when you ran the python interpreter. The reason for this misconception is because a common way to run your code is to navigate to the directory your module is stored, and run python <module>.py. Thus, in this case your current working directory will be the same as the location of the module. However, if we instead did python path/to/<module>.py, our current working directory would no longer be the same as the location of the module we're executing.

Why is this important?

When opening files in python, relative paths won't always work since it's dependent on what directory you were in when you ran your code. A common issue people face is running their code in an IDE thinking they can open files that are in the same directory as their module, but the current working directory will be different than what they expect and so they won't find the file. The way to avoid this problem is by using absolute paths, which is the full path from your root directory to the file you want to open.

raw rain
#

!sa

slate swan
#

@raw rain please use #bot-commands for random commands

winter token
#

is there a way to set the footer at right side

slate swan
#

no

#

You can set timestamp on the right side

winter token
slate swan
#

!d discord.Embed.timestamp

unkempt canyonBOT
#

The timestamp of the embed content. This is an aware datetime. If a naive datetime is passed, it is converted to an aware datetime with the local timezone.

winter token
#

guess i need to learn this module

slate swan
#

Yeah you have to

#

As you can see its needed everywhere

drifting arrow
#

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

lean harbor
turbid condor
#

As far as i know discord bot can't listen or record voice in a vc

slate swan
#

Guys any tutorial suggestions to build discord bots?

turbid condor
slate swan
#

Oh okay thank u

#

Btw and smth else dont want to bother

#

I keep getting stuck even after finishing python bootcamps

#

When it gets to actual code

#

I blame a bit and my adhd but still

#

Any suggestions

turbid condor
#

Keep on practicing I'd say it's not easy to write a code

slate swan
#

Yeah i guess lol

slate swan
turbid condor
#

Don't know but might be interesting if it is

vocal snow
#

you can, however it's an undocumented part of the api and most python dapi wrappers do not have proper support for it (only some RFCs and forks which are experimental)

#

py-cord used one of discord.py's voice receive forks, but I'm not sure how much that has been polished

slate swan
#

the only way to output a final message with information from three different forms is to use global variables, but if two people fill out the form at the same time then its possible for them to receive the wrong message. is there a way to avoid this

formal basin
#
  host='redis-11943.c56.east-us.azure.cloud.redislabs.com',
  port=11943,
  password='pass')``` 
im using redis but its not working for example

```py
@client.tree.command(name="anti-discord-servers-on", description="blocks discord servers from your server")
@app_commands.default_permissions(manage_guild=True)
async def antiservers_on(interaction: discord.Interaction):
    if f'{interaction.guild.id}' in r:
        pass
        await interaction.response.send_message("Anti discord servers is already on")
    else:
        r.set(f'{str(interaction.guild.id)}', 'on')
  
        await interaction.response.send_message("Anti discord servers is on")
        
``` this doesnt work like it stores it but doesnt get it
sharp whale
#

command not working even after syncing:

@bot.tree.command(name="verify", description="Sends the verification button")
async def verify(interaction):
  verifybutton = ui.Button(label="Verify", style=discord.ButtonStyle.green, custom_id="verifybutton", emoji="✅")
  viewVerify = ui.View()
  viewVerify.add_item(verifybutton)
  await interaction.response.send_message(view=viewVerify)```
dense barn
#

Is anyone familiar with sir Kryptox's bot template? I wanted to add a Welcome {member} feature and I opted to put it in bot.py, but upon testing it doesn't work. I think my code's right, but I dunno.

client = discord.Client(intents=intents)

@client.event
async def on_member_join(member):
    channel = client.get_channel(...)
    messages_title = [f"Hiya {member.name}!", f"Bom Bom Bakudan, {member.name}!", f"Let's go fish blasting, {member.name}!", f"Let's play, {member.name}!'"]
    embed = discord.Embed(
        title = random.choice(messages_title),
        description = f"Welcome to {member.guild.name}! Say hello to everyone at {channel.mention}!",
        color = 0x752C18)

    embed.set_thumbnail(url=member.avatar_url)
    embed.set_image(url=...")

    await channel.send(embed=embed)
slate swan
#

Make sure the members intent is set

dense barn
#

it is,

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

also on developer portal

slate swan
#

Then likely have some error, for the channel use

channel = client.get_channel(...) or await client.fetch_channel(...)

instead

dense barn
#

or like this?

slate swan
#

Like that

dense barn
#

hmmm it's still not working

#

no error on console too

slate swan
#

member.avatar_url is not a thing, it's member.avatar.url

#

await client.send() is not a thing either, you probably want to either send in channel with await channel.send(...) or in another channel that you get by ID again similarly to channel = ...

hasty pike
#

Paginator help?
Is there any official documentation?

dense barn
slate swan
#

Well there's a built-in thing

#

No real need to install yet another library

dense barn
#

It's still not working :< and console is so clean

#

I've been leaving and entering with another account for a few times

hasty pike
#

One pagination works for description, field and all or i need separate for them?

dense barn
#

I also have on_member_remove set up and there's no effect too

slate swan
#

Also, what if you just add a print at the beginning

dense barn
#

uhm yeah haha, all commands work just fine.

hasty pike
#

try:

except Exception as e:
print(e)

slate swan
#

And what's the rest of your file

hasty pike
#

Always do this while testing commands

dense barn
slate swan
#

E.g. do you have some error handler eating everything

slate swan
dense barn
#

Thoughhhh I do have another bot in another console running, would that interfere?

slate swan
#

Well my template doesn't use client

#

So you heavily edited it

dense barn
slate swan
dense barn
#

aahh

slate swan
#

I meant client

#

And yes, if you have both - it will not work

#

Only have one, you can do everything with one

dense barn
#

yeah yeah I thought I should use client cause it's the one this tutorial i read used haha

slate swan
#

Bot is pretty much Client with more things

#

So you can remove all client things and replace with bot e.g. @bot.event

dense barn
#

hmm okay i'll try

slate swan
#

And then you'll at least get errors if something goes wrong

dense barn
#

never thought I'd be happy seeing errors on my code TT

slate swan
#

Errors are more useful than nothing krHappy

dense barn
#

it finally works TT thanks very much guys

brisk bluff
#

if i have a python program that prints on terminal can i make a discord bot that does that work?

hasty pike
brisk bluff
hasty pike
#

Like

brisk bluff
#

uk python idle right

#

u click f5 on ur program and it just prints

#

the white screen

hasty pike
#

ramramji didn't know that but thanks to you now i do

brisk bluff
#

idk what its called

swift acorn
#
class approvedmodal(ui.Modal, title = "Approve Sponsor Request"):
    message = ui.TextInput(label="Message", style=discord.TextStyle.long, placeholder="Your sponsor has been accepted!", required=True, max_length=2000)

    async def on_submit(self, interaction : discord.Interaction):
        user_id = int(interaction.message.embeds[0].footer.text)
        message = self.message.value
        creator_to_dm = interaction.guild.get_member(user_id)
        if creator_to_dm == None:
            await interaction.response.send_message("The user was not found as a member in the server.", ephemeral=True)
            return
        try:
            await creator_to_dm.send(message)
            await interaction.response.send_message("The Creator was successfully DMed. This request has been approved.", ephemeral=True)
            for button in self.children:
                button.disabled = True
            await interaction.message.edit(content=f"This request was approved by {interaction.user.mention}", view=self)
        except:
            await interaction.response.send_message("Unable to DM the creator. Their DMs are closed.", ephemeral=True)

I am getting this error on the edit function when this modal is submitted

Error:
File "/home/container/creator_bot.py", line 3658, in on_submit
await interaction.message.edit(content=f"This request was approved by {interaction.user.mention}", view=self)
File "/home/container/.local/lib/python3.11/site-packages/discord/message.py", line 2275, in edit
data = await self._state.http.edit_message(self.channel.id, self.id, params=params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/http.py", line 745, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).

dense barn
#

what permissions does bot need to be able to autorole someone who joins? is it only manage roles?

thin raft
dense barn
#

is there somewhere that I can see what permissions a permission integer checked?

#

I want to see if I missed something

thin raft
#

what

sharp whale
#

Hi, i wanted to check for roles in the user executing the slash command

#

how would i do it?

thin raft
#

!d discord.app_commands.checks.has_role

unkempt canyonBOT
#

@discord.app_commands.checks.has_role(item, /)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_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.

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

New in version 2.0...
thin raft
#

this¿

sharp whale
#

hmm

hasty pike
#
@commands.hybrid_group(name='test')
async def _test(ctx):

@test.command()

Is that the Right way to make hyrbid group

#

Because i can't see my commands in slash commands

sharp whale
#

i want to restrict a role from using the command

sharp whale
hasty pike
sharp whale
#

and if they do have it, then they cant use the command

hasty pike
#

fetch role id

thin raft
sharp whale
thin raft
hasty pike
#

Read documentations first

sharp whale
#

how do i use the decorator

hasty pike
thin raft
#

Smh

hasty pike
#

Everything you need is given in documentation always

sharp whale
hasty pike
#

Use predicate

sharp whale
hasty pike
#

Smh

hasty pike
# sharp whale how
def ignore_check():
    def predicate(ctx) -> bool:
        if role in ctx.author.roles:
            return False
        return True
    return commands.check(predicate)
#

Try documentation next time

#

It would give you bunch of knowledge

swift edge
#

eshaan after your done helping him can u help me with a command/embed please

#

everything works except for this 1 things

#

thing*

hasty pike
swift edge
#

im using cog by the way, im getting no errors too

sharp whale
hasty pike
swift edge
#

yeah, for embed for some reason

#

ping command works except for embed command

sharp whale
swift edge
#

embed name was originally called test, that didnt work too

hasty pike
#

That's what predicate do

#

@commands.command()
@ignore_check()
async def xd(self, ctx):

hasty pike
swift edge
#

ohhh

swift edge
hasty pike
#

It's always better to read docs properly and understand things on your own

hasty pike
sharp whale
hasty pike
hasty pike
hasty pike
swift edge
#

guys how to make a url text in embed.set_footer thingy

#

ive done this
embed.set_footer(text="[hello](not tryna get banned)")

#

before this the () came first then [] right after

hasty pike
swift edge
#

but i switched

#

doesnt work

swift edge
hasty pike
hasty pike
swift edge
#

no?

hasty pike
swift edge
swift edge
hasty pike
#

Footer you can't

#

Use other ways

#

Like last line of description

swift edge
#

ok

reef plank
#

How can I remove the hello and say command even though they aren't anywhere in the code anymore?

merry cliff
#

Should just work if you sync the command tree again but without the code for those two commands

reef plank
#

Got it! Thank you both! 🙂

slate swan
#

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

Traceback (most recent call last):
File "/home/runner/UnacceptableWittyAxis/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/UnacceptableWittyAxis/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/UnacceptableWittyAxis/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'whitelistrole' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction

@bot.tree.command(name="whitelistrole")
@commands.has_permissions(administrator=True)
async def whitelistrole(interaction: discord.Interaction, role: discord.Role):
if not interaction.response.is_done():
update_whitelistrole(role.name)
await interaction.response.send_message("Whitelist role successfully updated.")

turbid condor
#

This error is occurring because the interaction isn't being completed in the standard 3 sec therefore u need to defer it which inc the completion time to 15 min

torn solar
#

can i ask what ctx stands for

fading marlin
#

usually "context", as in the class

torn solar
#

ty

turbid condor
# slate swan How do i do that 😭

The defer response, defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
When deferring, you get up to 15 minutes to respond instead of the normal 3 seconds.

This response is only supported if the interaction is an application command, component/view, or a modal.

Because deferring counts as a response, you can't use the typical response.send_message method afterwards. Instead we can use something called followup. We can use followup.send to send one or more followup messages.
Example:

await interaction.followup.send(...)```



Something to note: when deferring, if you set ephemeral to True, your first followup will be ephemeral regardless of what you pass to the ephemeral kwarg of followup.send. If you have ephemeral set to False, your first followup won't be ephemeral.

Docs on deferring: https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.InteractionResponse.defer
Docs on followup: https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.Interaction.followup
winter hare
#

I have voice channel lock and unlock commands, but i dont want just anyone to use these commands.

I want to have it to where:

  1. The person who first joins the vc can use the commands
  2. Once that person leaves, it will either go the the next person who joined or reset it for someone else to use it(if that makes sense)

For example, if i joined a vc and left and someone else joins, they will be able to use those commands and i will be no longer able to because i wasnt the first one who joined.
https://paste.pythondiscord.com/ucepegufus
if anyone can could you send a link to a referred documentation.?

naive briar
#

What documentation

turbid condor
#

U can just make a check to see wether the user is in the vc or not

winter hare
#

i fixed my previous problem but now i have another one for channel.overwrites_for() how do i add a role to this

echo wasp
#

how do i fetch a guild in a cog? ```py
self.client.get_guild(id)

Seems to not be anything and shown as any
hollow osprey
#

!d discord.Client.get_guild

unkempt canyonBOT
#

get_guild(id, /)```
Returns a guild with the given ID.

Changed in version 2.0: `id` parameter is now positional-only.
hollow osprey
#

this returns the guild from the cache, I think?

#

!d discord.Client.fetch_guild

unkempt canyonBOT
#

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

Retrieves a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") from an ID.

Note

Using this, you will **not** receive [`Guild.channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.channels "discord.Guild.channels"), [`Guild.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.members "discord.Guild.members"), [`Member.activity`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.activity "discord.Member.activity") and [`Member.voice`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.voice "discord.Member.voice") per [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member").

Note

This method is an API call. For general usage, consider [`get_guild()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_guild "discord.Client.get_guild") instead...
hollow osprey
#

have you tried using this?

winter token
#
embed.add_field(name = "Bot Creation Date", value = f"{self.bot.created_at}", inline = True)
        ```
#

Error occured: Command raised an exception: AttributeError: 'Bot' object has no attribute 'created_at'

#

but in the docs there is

winter token
winter token
winter token
#
 async def nuke(self, ctx, channel: discord.TextChannel = None):
        
        if channel:
            await channel.clone()
            await channel.delete()

        else:
            await ctx.channel.clone()
            await ctx.channel.delete()

        await ctx.send("Channel Nuked!")
#

how do I make the bot send msg in the newly created channel

vocal snow
#

!d discord.TextChannel.clone

unkempt canyonBOT
#

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

Clones this channel. This creates a channel with the same properties as this channel.

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

New in version 1.1.
vocal snow
#

Return type

abc.GuildChannel
#
target = channel or ctx.channel
new = await target.clone()
await target.delete()
``` and those if statements and repeated code is quite unnecessary
vocal laurel
dense barn
#

How do I exclude certain cogs in the Slash Sync process?

#

Or does a Slash Command hide itself from you if you don't have the proper permissions to use it?

#

Because I want to hide my moderation commands in the Slash of my other normal users.

slate swan
#

!d discord.app_commands.default_permissions

unkempt canyonBOT
#

@discord.app_commands.default_permissions(**perms)```
A decorator that sets the default permissions needed to execute this command.

When this decorator is used, by default users must have these permissions to execute the command. However, an administrator can change the permissions needed to execute this command using the official client. Therefore, this only serves as a hint.

Setting an empty permissions field, including via calling this with no arguments, will disallow anyone except server administrators from using the command in a guild.

This is sent to Discord server side, and is not a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check"). Therefore, error handlers are not called.

Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
dense barn
#

Setting an empty permissions field, including via calling this with no arguments, will disallow anyone except server administrators from using the command in a guild.

So if I just use @discord.app_commands.default_permissions() that would do the trick, right?

slate swan
#

I suppose

#

Note the warning though

#

You'll still have to check if the user has permissions to execute the command, e.g. with a decorator

#

Those are default permissions which can be edited at any time in the server settings, so you definitely want to add a has_permissions decorator

left dew
#

hi, ive made a program so that a user cannot press a button too quickly before it responds with Slowdown!, and adds them to usersoncooldown = [], however when the cooldown ends, the user isnt removed from the cooldown and therefore cannot reclick the button

#

i have no clue why

quick gust
#

you'll have to show what ure doing

slate swan
#

Because you're not removing the user

#

That's all we can say based on what you gave us

dense barn
#

@discord.app_commands.checks.has_permissions(administrator=True)

So if a member is not an administrator the Slash Command won't appear right?

naive briar
#

Why don't just test it

dense barn
#

Also, and I just now thought I could check the code myself, this already does the trick?

left dew
quick gust
#

then ull have to show us the most important part of all of this, your code

slate swan
#

You'll have to handle the permission error in an error handler if you want to give an error message back

slate swan
glad cradle
#

wow so many decorators 😞

slate swan
#

You haven't seen the average Java program then

dense barn
#

okay default persmissions did the trick, thanks so much!

slate swan
left dew
#

how do i make this print the date, month, year and time without the day?
f"<t:{int(member.created_at.timestamp())}:F>

slate swan
#

Just use the default one, remove :F

left dew
#

okay thanks

formal basin
#

!paste