#discord-bots

1 messages ยท Page 258 of 1

naive briar
#

Without it, you can't get the results in real-time

#

I meant can't

drifting arrow
#

Because "identifier" doesnt need choices.. I was using it to just update a global variable lol.

naive briar
#

You'd only be able to do it once the command is sent

drifting arrow
#

So then if I cant dynamically change the choices for a param I might as well as take a different route.

naive briar
#

You can if you just use the autocomplete ๐Ÿคท

#

What's even a problem with it

#

If you don't need to return choices for it, then just return an empty list

drifting arrow
#

i think you're focusing on the wrong paramater..

#

which paramater do you think I am having an issue with?

naive briar
#

Identifier?

drifting arrow
#

No

naive briar
#

Then that's because you didn't specify it, how do you think I'd know

drifting arrow
#

I've been specifying it..

naive briar
#

Where

spiral swan
#

gimme cookie

drifting arrow
spiral swan
#

COOKIE

drifting arrow
spiral swan
#

thanks

drifting arrow
#

I got two autocomplete functions for my code.
The first autocomplete functions job isn't to return anything, it's just to update a global variable and grab data from an API.
The second autocomplete functions job is to return the list of choices.

The list of choices changes based on what the first paramater was input as, the identifier. So if identifier is A, it grabs data based on A, if it's B it grabs data based on B. Etc.

I want the "serverbans" choices to dynamically change based on what the identifier is, and to do that I need the first autocomplete to run. It is currently running and setting the list correctly (To a list of choices).

The second autocomplete is not running correctly, it's not loading any of the choices, even when I set it to a basic static choice.

naive briar
#

I just told you to combine the two autocomplete decorators

#

!d discord.app_commands.autocomplete

unkempt canyonBOT
#

@discord.app_commands.autocomplete(**parameters)```
Associates the given parameters with the given autocomplete callback.

Autocomplete is only supported on types that have [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)"), [`int`](https://docs.python.org/3/library/functions.html#int "(in Python v3.11)"), or [`float`](https://docs.python.org/3/library/functions.html#float "(in Python v3.11)") values.

[`Checks`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check") are supported, however they must be attached to the autocomplete callback in order to work. Checks attached to the command are ignored when invoking the autocomplete callback.

For more information, see the [`Command.autocomplete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command.autocomplete "discord.app_commands.Command.autocomplete") documentation.

Warning

The choices returned from this coroutine are suggestions. The user may ignore them and input their own value...
north kiln
#

why do you even need to autocomplete the first parameter

#

and how does steam token relates to unmuting a person on the server

vernal folio
#

ERROR : 103 no route to host

vernal folio
sonic vapor
#

Pls tell best python book

potent spear
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.

wispy pewter
#

Hi all!
Hope you can help me to figure out the best way to handle some OAuth redirects.
I want to "link" or "verify" the Discord account with another application (MyAnimeList) using OAuth, once a command is invoked, it gives the user an URL for the authorization that redirects to the application page, and once the user clicks "allow", the application has to redirect to another page with the authorization code, and here is where I'm stuck.
In a normal scenario I would create a Web application to handle that, but, is it possible to configure somehow the bot so that it receives the redirection with the auth code? Or what can I do in this scenario?
Thanks in advance.

sonic vapor
sonic vapor
potent spear
sick birch
sonic vapor
sonic vapor
wispy pewter
potent spear
sonic vapor
potent spear
potent spear
sonic vapor
potent spear
sonic vapor
#

Bokk

#

?

#

I will find

wispy pewter
sonic vapor
potent spear
potent spear
sonic vapor
slate swan
#

you can use a local DB file with aiosqlite or get a free MongoDB plan

sonic vapor
#

But I understand

slate swan
#

none of which cost money

sonic vapor
#

Oo

potent spear
sonic vapor
#

I message here daily I ask questions daily but I can't create bot From 2 month ๐Ÿ˜ฅ

sonic vapor
potent spear
potent spear
sonic vapor
#

Hm

slate swan
#

blocked = ["1", "2", "-3", "4", "5", "discord.gg"]

How can i make it so you can do !changeblocked 4,5,6,7,8

Then it would charge the things in the array

sonic vapor
#

Oo

#

I will try

slate swan
potent spear
#

if yes is your answer, you should consider using a database instead of just a variable to store this info

potent spear
# slate swan example ?

you update the bot
you restart it
all the info in blocked will be gone or "reset" to what you set it to first

#

but if you had a database, when the bot restarts, it will still have to blocked set to what you last changed it to
(thanks to a db)

slate swan
slate swan
#

I don't know how to use MongoDB is there a video on how to ?

potent spear
#

in short, you want to strive for best practice.
not something that "works"
you can eat soup with a fork, but is it made for that? no

potent spear
slate swan
#

pymongo/motor docs

slate swan
#

how would u add permissions for app commands for server owners, or certain permissions for admins, mods?

formal basin
slate swan
#

ty!
and for hybrid commands it would just be the
@commands.guild_only()
@commands.is_owner()
@commands.has_permissions(administrator=True)

slate swan
#

gotcha. tyvm

formal basin
#

await interaction.original_response.edit

#
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/ui/view.py", line 427, in _scheduled_task
    await item.callback(interaction)
  File "/Users/zagzag/vscode/zagzag/zagzag.py", line 164, in button_callback2
    await interaction.original_response.edit(content=f"we both picked {paper} so it is a tie {interaction.user.mention}", view=view)
AttributeError: 'function' object has no attribute 'edit'
formal basin
winter token
#

guys I wanna learn abt discord moderation methods but idk where it is in the docs. Can anyone lend me a helping hand

fading marlin
unkempt canyonBOT
#

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

Fetches the original interaction response message associated with the interaction.

If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message "discord.InteractionResponse.send_message") or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer "discord.InteractionResponse.defer"), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).

Repeated calls to this will return a cached value.
fading marlin
#

You have to call it

formal basin
vocal snow
winter token
vocal snow
#

what about them?

winter token
vocal snow
#

discord.VoiceChannel probably

#

depends on what you are actually trying to do

winter token
slate swan
#

average 572287th multipurpose discord bot

reef charm
#

Hey is there a channel for webscrapping?

Trying to scrape a site so it returns me the title of every deal posted but only thing i get is an empty channel in my terminal if anyone could help would appreciate it

from bs4 import BeautifulSoup
import time

url = 'https://www.mydealz.de/new'

# Define headers to mimic a browser-like behavior
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
    'Accept-Language': 'en-US,en;q=0.9',
}

# Function to scrape the website and print the titles of the last 5 deals
def scrape_deals():
    # Send a GET request to the website with headers
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        # Parse the HTML content using BeautifulSoup
        soup = BeautifulSoup(response.content, 'html.parser')

        title_element = soup.find('a', class_='cept-tt thread-link linkPlain thread-title--list js-thread-title')
        title = title_element.get('title')

        print(title)```
unkempt canyonBOT
#

5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.

#

7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.

fading linden
#

is scraping not allowed?

fast stone
#

hi guys, so i'm trynna host my bot on ovh but is it not possible if i'm not from uk? (still from EU)

naive briar
fading linden
#

rule 5 was referred so idk

naive briar
#

Web scraping itself is legal, but you should read the website's ToS to make sure if they allow it or not

#

And maybe the website's robots.txt ducky_wizard

winter token
#
@purge.error
async def purge_error(ctx, error):
    embed = discord.Embed(title = "Syntax Error!", description = "Correct Usage: `$purge (no. of msgs)`", colour = discord.Colour.red())
    embed1 = discord.Embed(title = "Bot Missing Required Permissions!", description = "Please give the bot `manage_messages` permissions!", colour = discord.Colour.red())
    embed2 = discord.Embed(title = "Missing Required Permissions!", description = "You need `manage_messages` permission to execute this command, Please try again later!", colour = discord.Colour.red())
    if isinstance(error, commands.BadArgument):
        await ctx.send(embed=embed)
    elif isinstance(error, commands.BotMissingPermissions):
        await ctx.send(embed=embed1)
    elif isinstance(error, commands.MissingPermissions):
        await ctx.send(embed=embed2)
    elif isinstance(error, commands.MissingRequiredArgument):
        await ctx.send(embed=embed)

Bot is not sending error msg if the bot/user don't have perms

slate swan
#

did you check if the error handler fires?

winter token
slate swan
winter token
slate swan
#

did you try printing anything

#

for example printing error to see what error actually happens

slate swan
#

yeah

winter token
#

idk why it is not being called

slate swan
#

so its not being called

winter token
#

other errors works just fine

winter token
slate swan
winter token
#
async def purge(ctx, amt:int):
    embed = discord.Embed(title = "Purged Messages!", description = f"**Purged by:** {ctx.author.mention}\n**Amount:** {amt}",colour = discord.Colour.red())
    await ctx.channel.purge(limit = amt+1)
    await ctx.send(embed=embed, delete_after = 3) ```
slate swan
#

no other decorators?

winter token
#

nope

#

@command.haspermissions or something needed?

slate swan
#

well then no way the MissingPermissions wont throw since you dont check if user has this permissions

#

!d discord.ext.commands.has_permissions

unkempt canyonBOT
#

@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.

Note that this check operates on the current channel permissions, not the guild wide permissions.

The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions").

This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
slate swan
#

!d discord.TextChannel.purge

unkempt canyonBOT
#

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.

You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") to delete messages even if they are your own. Having [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") is also needed to retrieve message history.

Changed in version 2.0: The `reason` keyword-only parameter was added.

Examples

Deleting botโ€™s messages...
slate swan
#
Raises
Forbidden โ€“ You do not have proper permissions to do the actions required.

HTTPException โ€“ Purging the messages failed.```
#

!d discord.ext.commands.bot_has_permissions

unkempt canyonBOT
#

@discord.ext.commands.bot_has_permissions(**perms)```
Similar to [`has_permissions()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.has_permissions "discord.ext.commands.has_permissions") except checks if the bot itself has the permissions listed.

This check raises a special exception, [`BotMissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BotMissingPermissions "discord.ext.commands.BotMissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
winter token
#

alright thanks

#

and also what do u prefer? making on_command_error or making seperate handlers for each cmd

slate swan
#

next time try to debug it a little
see if its being called
if it does what param values are etc

slate swan
#

i belive there are cases to use per command but i never needed that

#

depends on case

winter token
#

hm

tidal folio
#

Hello.
Can anyone help me?

gusty shard
unkempt canyonBOT
#

class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.

async with x Asynchronously initialises the client and automatically cleans up.

New in version 2.0.

A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
slate swan
#

!intents

unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

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

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

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

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

gusty shard
#

this code looks like some self bot stuff

tidal folio
#

He said and i did.

thin raft
slate swan
#

message.client ?

meager chasm
tidal folio
slate swan
#

you sure this exists

naive briar
slate swan
thin raft
tidal folio
# slate swan where did you get this odd attribute

Learn how to code a Discord bot using Python and host it for free in the cloud using Repl.it.
๐ŸšจNote: At 16:43, Replit now has a new method for environment variables. Check the docs: https://docs.replit.com/programming-ide/storing-sensitive-information-environment-variables

Along the way, you will learn to use Repl.it's built-in database and cr...

โ–ถ Play video
naive briar
#

Is the message.client even ever existed

thin raft
#

2 years ago

naive briar
slate swan
#

maybe

thin raft
#

just stick to the docs it is well documented

naive briar
#

That's already suspicious from the title

tidal folio
slate swan
#

doing a discord bot from youtube PainChamp

gusty shard
tidal folio
#

Can anyone help me?

gusty shard
#

this wont solve your problem tho

slate swan
#

you cant even rewrite from youtube video skull

thin raft
slate swan
thin raft
#

you've been told to do so countless times

tidal folio
naive briar
#

(and not from YouTube)

slate swan
#

doesnt look like

tidal folio
slate swan
#

i dont use youtube for coding i dont know any

naive briar
#

You can use YouTube for coding!?!?

slate swan
#

you can code in comments

tidal folio
#

I can watch this?

slate swan
#

well you can do anything but you wont learn python from it

#

nor how to make a discord bot

gusty shard
#
intents = discord.Intents.default()
intents.messages = True```
#

try adding this to your code

naive briar
#

messages is already included in default()

slate swan
#

its message_content first of all

#

!d discord.Intents.default

unkempt canyonBOT
#

classmethod default()```
A factory method that creates a [`Intents`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents "discord.Intents") with everything enabled except [`presences`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.presences "discord.Intents.presences"), [`members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members"), and [`message_content`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.message_content "discord.Intents.message_content").
gusty shard
#

also change the client part

naive briar
#

That's very vague

gusty shard
#
client = discord.Client(intents = intents,help_command=None)```
slate swan
#

commands.Client

naive briar
#

commands.Client?

slate swan
#

odd

gusty shard
#

client = discord.Client()

naive briar
#

Did you get this from YouTube, also?

gusty shard
#

i just woke up.

slate swan
gusty shard
slate swan
#

PEP 8 cried

naive briar
#

There's no help_command kwarg in that class

slate swan
#

yeah help_command is only for Bot since it supports prefixed commands

gusty shard
#

this removes the default help command ig

slate swan
#

so there are any you can list on help page

gusty shard
#

i aint a professional but im pretty sure this exists

slate swan
#

it does in commands.Bot yeah

naive briar
#

Not for the discord.Client

slate swan
#

not in Client

gusty shard
#

ohh

#

ima sleep back

#

๐Ÿค“

slate swan
slate swan
#

how would u get a channels lowest role?

thin raft
#

the ones with the least permissions?

slate swan
#

right.

thin raft
#

Why would you want this?

molten skiff
#

hey,
how to check if discord id is member in the guild or not
also how to send private message to discord id member

thin raft
#

!d discord.User.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
slate swan
#

for temporary voice channel generators. I only want to grab the lowest role with permissions to see/ join, talk etc.
I was looking to test it w/ a slash command for interactions to make new channels that way as well.

thin raft
#

lowest permissions would be a mess to check

slate swan
#

im guessing get a list, then check the hoist positions

#

based on the list of role id's

thin raft
#

you could loop through roles and check for discord.Role.position

#

and check the higher role position

slate swan
#

right cause the highest role has the least permissions

thin raft
slate swan
thin raft
#

what do you mean by that

#

role position starts at 0 and ends at n

proper thicket
#

can someone please help me with this error i am getting i added a setup function and it still gives me problems

slate swan
#

ur setup function is indented.

slate swan
proper thicket
slate swan
#

how are you going to create a cog in a method that needs a cog to be created

proper thicket
#

and it works perfectly

slate swan
proper thicket
slate swan
#

i want you to see the difference

#

i know what the problem is

slate swan
# thin raft what do you mean by that

I want the role w/ the least amount of permissions that are listed in the channels permissions. so like... roles that just see/talk/etc... if that channel has multiple roles w/ permissions to view it.. 0 would be like owner, bots, admins right?

proper thicket
slate swan
#

and do you see difference between those two functions

#

and where they are located?

proper thicket
#

and

slate swan
slate swan
proper thicket
buoyant quail
#

Also i'd suggest to use the same indenting everywhere
Having 8 spaces in one place and 1 space in another hurts my eyes

slate swan
#

!e ```py
def setup():
print("Setup working")

setup()

unkempt canyonBOT
#

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

Setup working
slate swan
#

!e ```py
class A:
def setup():
print("Setup working")

setup()

unkempt canyonBOT
#

@slate swan :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 5, in <module>
003 |     setup()
004 |     ^^^^^
005 | NameError: name 'setup' is not defined
slate swan
#

indentation matters

proper thicket
#

Oh cause it doesnt read it

#

oh i understand now

slate swan
#

if u hover over it it also says it won't get called in vscode

#

setup function exists but in A class scope so it does not see that outside or without A class instance

proper thicket
slate swan
#

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

slate swan
#

especially read the bottom bold text

#

pastebins so useful

proper thicket
proper thicket
proper thicket
#

still responding in a error

proper thicket
buoyant quail
#

Show your new code

#

Or maybe you didn't save it

proper thicket
buoyant quail
buoyant quail
proper thicket
#
import discord
from discord.ext import commands

class Moderation(commands.Cog):
    def init(self, client):
        self.client = client
        @commands.Cog.listener()
        async def on_Ready(self):
            print("Moderation.py is online.")

            @commands.command()
            @commands.has_permissions(manage_messages=True)
            async def clear(self, ctx, count: int):
                await ctx.channel.purge(limit=count)
                await ctx.send(f"(count) messag(s) have been deleted.")
                    
        async def setup(client):
            await client.add_cog(Moderation(client))```
buoyant quail
#

It's still inside the class

#

Even in the __init__

proper thicket
slate swan
#

unindent it all the way

unkempt canyonBOT
#
Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

slate swan
# naive briar What

I j wanted to know how I can get a channels role w/ least permissions. whether it's the current channel(voice) or if inserting the channel obj

buoyant quail
#

If you have a role with permission only to connect and one with permission only to talk, which you will choose and why?

#

Same question if there is a role that has only 1 permission admin and a role that has a lot of permissions but no admin

#

Anyways you'd loop over them and select the minimum by comparing them as you want

naive briar
#

!d max - or literally just this

unkempt canyonBOT
#
max

max(iterable, *, key=None)``````py

max(iterable, *, default, key=None)``````py

max(arg1, arg2, *args, key=None)```
Return the largest item in an iterable or the largest of two or more arguments.

If one positional argument is provided, it should be an [iterable](https://docs.python.org/3/glossary.html#term-iterable). The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned.

There are two optional keyword-only arguments. The *key* argument specifies a one-argument ordering function like that used for [`list.sort()`](https://docs.python.org/3/library/stdtypes.html#list.sort "list.sort"). The *default* argument specifies an object to return if the provided iterable is empty. If the iterable is empty and *default* is not provided, a [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "ValueError") is raised.
slate swan
slate swan
naive briar
#

!d min - or this if you want the lowest one

unkempt canyonBOT
#
min

min(iterable, *, key=None)``````py

min(iterable, *, default, key=None)``````py

min(arg1, arg2, *args, key=None)```
Return the smallest item in an iterable or the smallest of two or more arguments.

If one positional argument is provided, it should be an [iterable](https://docs.python.org/3/glossary.html#term-iterable). The smallest item in the iterable is returned. If two or more positional arguments are provided, the smallest of the positional arguments is returned.

There are two optional keyword-only arguments. The *key* argument specifies a one-argument ordering function like that used for [`list.sort()`](https://docs.python.org/3/library/stdtypes.html#list.sort "list.sort"). The *default* argument specifies an object to return if the provided iterable is empty. If the iterable is empty and *default* is not provided, a [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "ValueError") is raised.
slate swan
#

so i'd pass in the role positions to find the min/max?

buoyant quail
#

If you want to compare them by positions. As we said, role permissions don't depend on their position

naive briar
#

No, just the roles

slate swan
#

oh it compares obj not just ints

slate swan
#

!d discord.Role

unkempt canyonBOT
#

class discord.Role```
Represents a Discord role in a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild")...
fringe lake
#

whats the best choice for hosting a bot online?

unkempt canyonBOT
#
Discord Bot Hosting

Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.

See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.

You may also use #965291480992321536 to discuss different discord bot hosting options.

fringe lake
#

@turbid condor why using free hosting is bad

#

i dont thnk i can afford a vps, and my laptop will get destroyed if i used it for hosting ;-;

formal basin
#

how can i check if a user is timed out in the on_message event?

turbid condor
turbid condor
#

multiple users are using the same ip address

fringe lake
#

ooh

#

if the ip got blocked my bot will go offline ?

turbid condor
#

tho if u still want a free hosting u can check discloud.com i believe it has a free tier

turbid condor
fringe lake
#

but i can restart it right?

turbid condor
#

u can but then u will need a new vps

fringe lake
#

is 100 enough ? ๐Ÿ’€

turbid condor
#

depends on what you are doing with your bot

#

if its a small bot then this should be enough

fringe lake
#

like moderation and some utis ?

#

util*

turbid condor
#

then it should be ok

fringe lake
#

but what if used some apis or databases

turbid condor
#

again it depends on what the bot is doing

#

so u should try and see if it works or not

fringe lake
#

oh ok

#

thanks a lot for these informations

formal basin
#

how can i check if a user is timed out in the on_message event?

slate swan
#

!d discord.Member.is_timed_out

unkempt canyonBOT
naive briar
#

!d discord.Member.is_timed_out just read the docs for once

slate swan
#

I didnt even know is there a util function but took me 20s to check

#

Docs are for a reason there

molten skiff
# thin raft if you have a member object you know it's in a guilg

this code doesn't work โ†“

    guild = interaction.guild
    receiver_member = guild.get_member(receiver_id.id)
    if receiver_member:
      await receiver_id.send(embed=embed)

how to check if receiver_id.id is member in guild or not & is he enabled Direct Messages in Privacy Settings or not

slate swan
#

I am assuming that adding code to a discord bot to kick members based on when they last posted is against discords ToS?

formal basin
#

can I make a message be sent once

#

cause its sending it twice

slate swan
# naive briar What <:ducky_sus:987918033504854066>

The prune method to get rid of ghost members, is just awful cause it only goes off whether they are active in discord itself or not, not the server. So I am wondering if creating a script to remove members that havent posted in 30days will be against ToS cause it will get rid of a lot.

formal basin
#

can I make a message be sent once
cause its sending it twice

slate swan
#

Uhhh, don't know whether to risk or not :>

naive briar
#

Why would it be

slate swan
#

Could be seen as a form of nuking?

naive briar
#

Since Discord already has a kind of a similar thing (prune, like you said) built-in

formal basin
#

can I make a message be sent once
cause its sending it twice

naive briar
#

Stop repeating your question

formal basin
#

sorry

buoyant quail
#

If you send the message once, it will be send once.
If you send the message twice, it will be send twice.
discord.py doesn't send two messages instead of one for you.

molten skiff
naive briar
#

Is that sarcasm

#

Because it's so overkill that I can't tell

molten skiff
#
    guild = interaction.guild
    receiver_member = guild.get_member(receiver_id.id)
    # Send private message to receiver_id
    if receiver_member and receiver_member.guild_permissions.send_messages and receiver_member.bot == False:
            try:
                await receiver_member.send(embed=embed)
            except discord.Forbidden as e:
                print("\nFailed to send a direct message to the member.\n")
                print(f"Reason: {e}")

i tried this code and it doesn't work .
i'm trying to send private message only if receiver_id.id is member in the guild & receiver_id.id enabled Direct Messages in Privacy Settings
because when i run this code directly : await receiver_member.send(embed=embed) i get error The application did not respond if receiver_id.id not member / disabled Direct Messages in Privacy Settings

slate swan
#

How to solve a bot sending twice a same message:

drakeNo Check why your bot sends messages twice, e.g. your bot is running twice by mistake

drakeYes Store all the messages the bot sends in a database and double check every time before sending a new message

buoyant quail
naive briar
#

Is it inside an app command and you didn't respond to its interaction?

molten skiff
#

this code is working without The application did not respond error

        try:
            await receiver_id.send(embed=embed)
        except Exception as e:
            print(f"An error occurred: {str(e)}")
#output
An error occurred: 403 Forbidden (error code: 50007): Cannot send messages to this user

slate swan
molten skiff
#

hey, i need example of message with link button to add it here

        try:
            await receiver_id.send(f"{interaction.user.mention} tried to send you points, but you haven't registered on our website yet. To register, visit the website from {site_link}")
        except Exception as e:
            print(f"An error occurred: {str(e)}")
            
prime solar
#

ro

#

Okay thx

fringe lake
#

i heard that pycord is better for ui thank discord.py

#

isnt it forked from discord.py? how it could be better

cloud dawn
#

I wouldn't recommend py-cord.

#

I'd recommend discord.py or Hikari for more advanced Python programmers.

ocean trench
#

Hi, I'm working on making a discord bot, it's hosted on replit as a private bot, and today I got an error 429 message saying I'm making too many requests.

But that's really weird, I'm basically the only one using the bot and I do some testing but not more than like a few requests here and there, nothing major.

I'm not doing anything super special, not using any http requests or whatever, just bot commands and bot events. I do use reactions as a way to interact with my bot, and I did see there's something about emojis that's special but it's all very obscure to me.

I'm trying to figure out what's going, on. The doc mentions checking headers and stuff, but doesn't explain how to do it, so I'm a bit lost. I'm using discord.py and from what I've heard I shouldn't be worrying about those things with that library.

Is the logical deduction of all this that my token was compromised? How can I verify that? Who can I contact to understand why I've been locked out?

sick birch
#

Replit isn't meant as a hosting platform so many many users can "share" the same machine

cloud dawn
ocean trench
#

but it's a private replit

sick birch
#

Using replit as a host is not recommend BTW

ocean trench
cloud dawn
sick birch
#

That only controls the "visibility"

#

Someone else is still sharing the same machine as you

ocean trench
sick birch
#

No your token shouldn't be compromised that way

#

But it can get your bot banned off Discord if it keeps happening

ocean trench
#

ok, so if replit is not recommended, where else could I host my bot?

sick birch
#

Platforms like AWS and GCP have free tiers that's good enough for Discord bots

#

Old machines are also great
I run all my bots on an old raspberry PI

cloud dawn
#

Everywhere that offers a dedicated IP to a VPS or container host like Azure.

ocean trench
#

ok I'll look into that then. I'm completely new to all this, I just wanted to make a bot and now I'm down the rabbithole ๐Ÿ˜„

ocean trench
#

@cloud dawn a quick search found me Heroku, is that one fine?

north kiln
#

no

ocean trench
cloud dawn
ocean trench
#

what IDE would you recommend for coding?

cloud dawn
slate swan
sick birch
#

have not - but that would be an interesting proposition sip

#

Just a docker container, after all

slate swan
#

haha

#

thats what i thought

#

here i am with about 6 hours of issues

sick birch
#

Why do you ask? Using Snekbox for one of your own projects by chance?

slate swan
#

yes, correct

cloud dawn
#

Can't you just run snexbox inside a container?

sick birch
slate swan
sick birch
#

Azure app service I believe

slate swan
#

and how much does it cost

cloud dawn
#

Azure is expensive.

slate swan
#

ive been trying to get it up and running on my raspberry pi, but it isnt working i've asked a couple minutes ago in #unix but eh

cloud dawn
#

But reliable

sick birch
#

Actually I'm not entirely sure it's on App Service
@feral timber can you confirm?

slate swan
# cloud dawn But reliable
snekbox.nsjail |     INFO | Executing code...
2023-06-26 16:21:34,969 |     9 |                 snekbox.nsjail |     INFO | Found 0 files.
2023-06-26 16:21:34,970 |     9 |                 snekbox.nsjail |    ERROR | Couldn't open '/sys/fs/cgroup/NSJAIL.11/memory.max' for writing: No such file or directory
2023-06-26 16:21:34,971 |     9 |                 snekbox.nsjail |  WARNING | Could not update memory.max
2023-06-26 16:21:34,971 |     9 |                 snekbox.nsjail |    ERROR | Couldn't initialize cgroup 2 user namespace for pid=11
2023-06-26 16:21:34,972 |     9 |                 snekbox.nsjail |    ERROR | Launching child process failed
2023-06-26 16:21:34,974 |     9 |                 snekbox.nsjail |     INFO | nsjail return code: 255``` i just get these errors
#

yet theres no mention of anything with cgroups

cloud dawn
#

Ah yeah you need to authorize that in linux.

slate swan
#

wdym

#

can we move over to dms?

cloud dawn
slate swan
#

no worries

cloud dawn
#

@slate swan Meaning you need to give write permission to that process.

slate swan
#

right, and how would that work? how do i give it write permissions

cloud dawn
slate swan
#

yeah but how, thats logs from the docker container

hybrid minnow
cloud dawn
slate swan
#

which part to be more specific

cloud dawn
#

You'd need to change the permission before the process starts.

slate swan
#

i really dont know what i need to edit, i havent got much experience with docker

blissful sundial
#

I am in need of small help here. I want to convert my google collab py file to discord bot output. I have already written the file

slate swan
#

okay so somewhere in the dockerfile i need to do chmod 600 on that file

slate swan
cloud dawn
slate swan
#

so chmod 600 /?

slate swan
# cloud dawn Preferably everything inside the project just to make sure.

at the bottom i added RUN chmod 600 /
now i get:

2023-06-26 17:35:20,798 |     9 |                 snekbox.nsjail |     INFO | Executing code...
2023-06-26 17:35:20,888 |     9 |                 snekbox.nsjail |     INFO | Found 0 files.
2023-06-26 17:35:20,889 |     9 |                 snekbox.nsjail |    ERROR | Couldn't open '/sys/fs/cgroup/NSJAIL.11/memory.max' for writing: No such file or directory
2023-06-26 17:35:20,891 |     9 |                 snekbox.nsjail |  WARNING | Could not update memory.max
2023-06-26 17:35:20,891 |     9 |                 snekbox.nsjail |    ERROR | Couldn't initialize cgroup 2 user namespace for pid=11
2023-06-26 17:35:20,892 |     9 |                 snekbox.nsjail |    ERROR | Launching child process failed
2023-06-26 17:35:20,894 |     9 |                 snekbox.nsjail |     INFO | nsjail return code: 255``` so thats not an error with permissions, its simply not there
cloud dawn
slate swan
#

Isn't that RUN chmod 600 .

#

i can try

cloud dawn
#

It's also a bit weird that there isn't a default amount of percentage it can use.

slate swan
#

where do u configure that then? in the snekbox.cfg?

cloud dawn
#

It's prob not in the cfg but it's trying to open a file there that didn't get created since by default docker containers cannot write.

slate swan
#
root@08c3a6408ecc:/snekbox# ls /sys/fs/cgroup/
cgroup.controllers      cgroup.subtree_control  cpu.weight.nice         io.stat
cgroup.events           cgroup.threads          cpuset.cpus             pids.current
cgroup.freeze           cgroup.type             cpuset.cpus.effective   pids.events
cgroup.kill             cpu.idle                cpuset.cpus.partition   pids.max
cgroup.max.depth        cpu.max                 cpuset.mems             pids.peak
cgroup.max.descendants  cpu.max.burst           cpuset.mems.effective   
cgroup.procs            cpu.stat                init/                   
cgroup.stat             cpu.weight              io.max ``` NSJAIL.11 isnt even there
cloud dawn
#

Porb gets created when the procerss is ran.

slate swan
#

theres no memory.max tho

#
cgroup.controllers      cgroup.procs            cpu.max          cpuset.cpus.effective  pids.current
cgroup.events           cgroup.stat             cpu.max.burst    cpuset.cpus.partition  pids.events
cgroup.freeze           cgroup.subtree_control  cpu.stat         cpuset.mems            pids.max
cgroup.kill             cgroup.threads          cpu.weight       cpuset.mems.effective  pids.peak
cgroup.max.depth        cgroup.type             cpu.weight.nice  io.max
cgroup.max.descendants  cpu.idle                cpuset.cpus      io.stat```
cloud dawn
#

Any issue on the github?

slate swan
#

no

#

theres no issue with memory.max

cloud dawn
#

Are these default settings?

slate swan
#

yes

#

in the snekbox.cfg file i could try setting
cgroup_mem_swap_max: 0 to some higher value

cgroup_mem_max: 52428800
cgroup_mem_swap_max: 0
cgroup_mem_mount: "/sys/fs/cgroup/memory"

cgroup_pids_max: 6
cgroup_pids_mount: "/sys/fs/cgroup/pids"

iface_no_lo: true

exec_bin {
    path: "/usr/local/bin/python"
    arg: "-BSqu"
}```
#

but nope, didnt do anything

cloud dawn
blissful sundial
shrewd vapor
#

Hi, i don't know how to resolve this error

2023-06-26 16:44:50 ERROR    discord.client Ignoring exception in on_message
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/otrobot.py", line 115, in on_message
    role = discord.Object(id=role_id)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/discord/object.py", line 95, in __init__
    id = int(id)
         ^^^^^^^
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'sqlite3.Row'```
#
@bot.event
async def on_message(message):
    user = message.author
    if message.channel.type is discord.ChannelType.private:
        return
    if message.channel.name != "verification":
        return
    if user.bot:
        if not message.embeds:
            await message.delete()
    if len(message.content) > 1024:
         return
    elif not user.bot:
        if message.content != ".verif":
            if (message.author.guild_permissions.ban_members):
                return
            messages = await message.reply("Deleting because it's not .verif")
            await messages.delete(delay = 5)
            await message.delete()
        if ".verif" in message.content:
            guild_id = message.guild.id
            role_id = database_verif.get_role_id(guild_id)
            role = discord.Object(id=role_id)
            await message.author.add_roles(role)
            embed = discord.Embed(title = "You have passed the verification", description = "Role successfully added")
            embed.set_footer(text = f"Added for {message.guild.name}")
            messagess = await message.reply(embed=embed)
            await messagess.delete(delay = 2)
            await message.delete(delay = 2)
            if database_verif_channel.get_channel(guild_id) is None:
                return
            channel_send = database_verif_channel.get_channel(guild_id)
            embed_verif = discord.Embed(title = "Verification Successful Passed", description = f"Verification Successful Passed for:\n<@{message.author.id}> | {message.author}")
            embed_verif.set_footer(text = f"By {message.guild.name}")
            message = await channel_send.send(embed=embed_verif)```
slate swan
#

role_id is of type sqlite3.Row and it shouldn't be, instead of it actually being the role ID it's the entire row in your database - get the right column of that row

cloud dawn
#

Most likely that it's the key that you got.

shrewd vapor
#

I started having this error overnight.

#
def get_role_id(self, guild_id : int):
        cursor = self.con.cursor()
        query = "SELECT role_id FROM verif WHERE guild_id =?;"
        cursor.execute(query, (guild_id,))
        result = cursor.fetchone()
        cursor.close()
        return result```
I get role_id here
#

In the database it's arranged like this

vocal snow
#

fetchone() fetches one row

#

which is why result is an sqlite.Row object

twilit grotto
#

^

shrewd vapor
#

Oh

vocal snow
shrewd vapor
#

If i remove result = cursor.fetchone() its good no ?

slate swan
#

FYI ||{Don't use online IDEs when making discord bots, can be harmful sometimes}||

slate swan
blissful sundial
slate swan
blissful sundial
#

total soldier boy

spring minnow
#

???
???

shrewd vapor
spring minnow
#

The definition of your guide id?

buoyant crescent
#

hi i'm trying to send an embed when someone type "!help" but it's keep telling me this error message : Traceback (most recent call last): File "c:/Users/MYOUSSEF/Desktop/bot/main.py", line 45, in <module> async def help(ctx): File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 1521, in decorator self.add_command(result) File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 246, in add_command super().add_command(command) File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 1356, in add_command raise CommandRegistrationError(command.name) discord.ext.commands.errors.CommandRegistrationError: The command help is already an existing command or alias.

and this is my code : ```python
client = commands.Bot(command_prefix= '!',intents=discord.Intents.all())

@client.event
async def on_ready():
print("The bot is now ready")
print("--------------------")
try:
synced = await client.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print(e)

@client.command()
async def help(ctx):
help = discord.Embed(title="Help", url="", description="Besoin d'aide ?", color=0x7434eb)
await ctx.send(help=help)
```

shrewd vapor
buoyant quail
# buoyant crescent hi i'm trying to send an embed when someone type "!help" but it's keep telling m...

discord.py already provides a default help command for your bot. (you can call help and see) you need to remove it to create yours (or better - subclass)
client.remove_command("help")
https://gist.github.com/InterStella0/b78488fb28cadf279dfd3164b9f0cf96

Gist

Walkthrough guide on subclassing HelpCommand. GitHub Gist: instantly share code, notes, and snippets.

slate swan
buoyant quail
unkempt canyonBOT
#

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

(1,)

failed_file Files with no extension can't be uploaded.

slate swan
#

and also change the command name to something that's not help like

async def helper(ctx)``` 
๐Ÿคทโ€โ™‚๏ธ
buoyant crescent
slate swan
#

^

buoyant crescent
spring minnow
slate swan
#

is there a cap for the app_commands.autocomplete()
for how many items u can see at a time? if it's more than 7 it just gives me an error loading options failed in the slash command area

buoyant quail
slate swan
#

why create a command and remove it if you can just not create it

buoyant quail
#

You won't die from it

slate swan
unkempt canyonBOT
#

@autocomplete(name)```
A decorator that registers a coroutine as an autocomplete prompt for a parameter.

The coroutine callback must have 2 parameters, the [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction"), and the current value by the user (the string currently being typed by the user).

To get the values from other parameters that may be filled in, accessing [`Interaction.namespace`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.namespace "discord.Interaction.namespace") will give a [`Namespace`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Namespace "discord.app_commands.Namespace") object with those values.

Parent [`checks`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check") are ignored within an autocomplete. However, checks can be added to the autocomplete callback and the ones added will be called. If the checks fail for any reason then an empty list is sent as the interaction response.

The coroutine decorator **must** return a list of [`Choice`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Choice "discord.app_commands.Choice") objects. Only up to 25 objects are supported.
slate swan
#

docs are for a reason

slate swan
stuck cosmos
#

see when you move a channel but the channel has a reached the maximum limit would the error code that showed up be discord.errors.HTTPException:?

#

it doesnt specifically say on the docs

slate swan
#

about what action are you talking

  • moving member between channels
  • moving channel between (or outside) category
  • none of above
#

@stuck cosmos ^

stuck cosmos
slate swan
#

and how can it fail

stuck cosmos
#

the limit of channels in a category is 50, i dont have 50 rn and i was wondering what the error code would be if you tried moving a channel to a different category

slate swan
#

there is such limit?

stuck cosmos
#

yeah

#

its 50

#

i presume the error would be httpexception but im not 100% surer

#

try:
B = discord.utils.get(interaction.guild.channels, name="โ”€โ”€โ”€ โ—† complete 1 โ—† โ”€โ”€โ”€")
await interaction.channel.edit(name=f"ยฃ{packamount}-{user.name}",reason=None, category=B)
await interaction.followup.send(f"Category Moved To {B} :)")
except discord.errors.HTTPException:
try:
C = discord.utils.get(interaction.guild.channels, name="โ”€โ”€โ”€ โ—† complete 2 โ—† โ”€โ”€โ”€")
await interaction.channel.edit(name=f"ยฃ{packamount}-{user.name}",reason=None, category=C)
await interaction.followup.send(f"Category Moved To {C} :)")
except discord.errors.HTTPException:

slate swan
#

well you wont know until you try

stuck cosmos
#

thats what ive got rn, but i wont know until the category hits 50 ig ๐Ÿ˜ญ

#

it doesnt specifically say on the docs

slate swan
#
parent_id?    ?snowflake    for guild channels: id of the parent category for a channel (each parent category can contain up to 50 channels), for threads: id of the text channel this thread was created
``` thats all the discord api docs say
#

i cant find anything else

#

and it does indeed say max is 50

stuck cosmos
desert imp
#

so my @bot.event action listener isn't listening to some channels in my server, any idea as to why? it'll react to the action in like 5 channels, regardless of permission, but not for any other channels

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
#

? fix

potent spear
proper thicket
#

hey can someone help me my purge command isnt working like at all
import discord
from discord.ext import commands

    def init(self, client):
        self.client = client
    @commands.Cog.listener()
    async def on_Ready(self):
        print("Moderation.py is online.")

    @commands.command()
    @commands.has_permissions(manage_messages=True)
    async def clear(self, ctx, count: int):
        await ctx.channel.purge(limit=count)
        await ctx.send(f"(count) messag(s) have been deleted.")
            
async def setup(client):
    await client.add_cog(Moderation(client))```
potent spear
proper thicket
potent spear
proper thicket
#

8 ball discord app command

potent spear
#

is that in the same cog?

proper thicket
#

yes same cogs folder

potent spear
#

not the folder, the class

#

is that in the same class as your clear command?

proper thicket
#

yes

potent spear
#

what errors are you getting when trying to run the clear command?
none?

#

can you print something in the command to be sure it even executes in the first place?

winter token
#

why am i getting this

sick birch
sick birch
#

Can you also paste the mod cog?

winter token
winter token
#

@sick birch main error is AttributeError: module 'discord.ext.commands.bot' has no attribute 'has_permissions'

#

how do i import it

sick birch
#

You don't need it since you already have it in the line above

winter token
#

decorator one?

sick birch
#

The @commands.bot.has_permissions one

winter token
#

nvm thx, im dumb

winter token
desert imp
# potent spear !paste

It's just

@bot.event
async def on_reaction_add(reaction, user): # same for on reaction remove
    print('test')```

Not exact code because I'm on my phone rn but it's just basically the event listener and a test print
#

It's annoying because it doesn't pick it up in certain channels

sick birch
desert imp
#

Sorry robin, didn't mean to interrupt ๐Ÿ˜ญ

sick birch
sick birch
#

Both have to be true

winter token
#

and i have exceptions for missing perms so its not the case

sick birch
#

Is it a custom help command?

winter token
#

default

sick birch
#

Though it's printing so surely it's being loaded

slate swan
#

Send, sleep, edit

#

Send message
Sleep x seconds
Edit message

#

!d asyncio.sleep

unkempt canyonBOT
#

coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.

If *result* is provided, it is returned to the caller when the coroutine completes.

`sleep()` always suspends the current task, allowing other tasks to run.

Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.

Example of coroutine displaying the current date every second for 5 seconds:
desert imp
#

Async.sleep?

slate swan
#

No, asyncio.sleep as the documentation says

desert imp
#

Oh nvm sorry my WiFi took too long to send that

winter token
#

@sick birch so is there anything I can do to fix it?

slate swan
#

No, like

x = await ctx.send(...)
await asyncio.sleep(...)
await x.edit(...)
#

Sometimes it's worth reading the documentation that was linked you know?

hasty pike
#

Okay it takes delay time in seconds as a int

slate swan
#

See, reading documentation isn't rocket science

winter token
#

can sm1 help me

hasty pike
winter token
slate swan
#

!d discord.ext.commands.Context.invoke # though it's probably better to have a common function you call in both commands

unkempt canyonBOT
#

await invoke(command, /, *args, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Calls a command with the arguments given.

This is useful if you want to just call the callback that a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") holds internally.

Note

This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function.

You must take care in passing the proper arguments when using this function...
winter token
hasty pike
hasty pike
#

But it would be better for you if you just use cog's name instead of using loop

winter token
#

alright

hasty pike
slate swan
#

Not at all

winter token
slate swan
#

Loading cogs like you did is very fine

winter token
slate swan
#

What if instead of

asyncio.run(main())

you just do

asyncio.run(load())
winter token
#

shows this tho when i execute purge

hasty pike
#

await context.send

winter token
hasty pike
winter token
#

nothing more

#
import asyncio
import discord
from discord.ext import commands

intents = discord.Intents.all()

bot = commands.Bot(command_prefix = '$', intents = intents)

@bot.event
async def on_ready():
    await bot.change_presence(activity = discord.Game("$help"))

@bot.event
async def on_command_error(ctx, error):
    colour = discord.Colour.red()
    if isinstance(error, commands.MissingPermissions):
        embed = discord.Embed(title="Missing Permissions!", description = f"{error}", colour = colour)
        ctx.send(embed = embed)
    elif isinstance(error, commands.BotMissingPermissions):
        embed = discord.Embed(title="Bot Missing Permissions!", description = f"{error}", colour = colour)
        ctx.send(embed = embed)

async def main():
    for files in os.listdir("./cogs"):
        if files.endswith('.py'):
            await bot.load_extension(f"cogs.{files[:-3]}")
   
asyncio.run(main())
bot.run("token")

slate swan
#

Go ahead and await both the send, just like in your cog

hasty pike
#

await it and try

winter token
#

nvm

#

ty all

slate swan
#

what's max upload size for bots on discord?

iron pulsar
slate swan
#

original message is msg and you pass it into the view

winter token
#
    @commands.command()
    @commands.cooldown(1, 3, commands.BucketType.user)
    @commands.has_permissions(kick_members = True)
    @commands.bot_has_permissions(kick_members = True)
    async def kick(self, ctx, member: discord.Member, *, reason: None):
        description = f"**Kicked:** {member.mention}\n**Kicked by:** {ctx.author.mention}\n**Reason:** {reason}"
        embed = discord.Embed(title = "Kicked Successfully!", description = description, colour = self.colour)
        await member.kick(reason = reason)
        await ctx.send(embed = embed)
     
    @kick.error
    async def kick_error(self, ctx, error):
        if isinstance(error, commands.MemberNotFound):
            await ctx.send("Please mention a valid member to kick!")
        elif isinstance(error, commands.BadArgument):
            await ctx.send("Please mention a valid member to kick!")
        elif isinstance(error, commands.MissingRequiredArgument):
            await ctx.send("Please mention a valid member to kick!")````
slate swan
#

can you print error.argument in your error handler

slate swan
#

ah its MissingRequiredArgument

#

then its error.param

#

also error comes from this that you are expecting a reason but you do not provide it

winter token
slate swan
winter token
slate swan
#

did you change command you run

winter token
slate swan
#

it was MissingRequiredArgument before

winter token
#

just the mistake was i wrote reason: None

#

instead of =

slate swan
#

yeah i told you you are expecting reason but you do not provide it

winter token
#

im doing dumb mistakes a lot today lol

tribal sleet
#

Hello how should I learn to make a bot?i kinda know some things but wanna start from start

gusty shard
#

if you know a little python you can make a discord bot, it's not that complicated

#

or you can just watch some youtube vids

slate swan
gusty shard
#

i started with youtube vids 2 years ago

#

its just for learning the basics

slate swan
#

Sure but it can lead to developing bad practices

#

i just want to ask for some advice when is it good to make messages ephemeral should i do moderation responses to commands like kick or ban ephemeral? just need to know when its good idea to use it

#

Itโ€™s good idea to use ephemeral messages when you want a message to only be seen by a specific person

vocal snow
slate swan
#

okay thank you

hasty pike
tribal sleet
naive briar
hasty pike
#

It's kind of like refresh function for beginning message

naive briar
#

And? What's your question

#

What do you mean go back

rare vector
#

I have an issue where only my old commands are showing but i have completely removed the file?

vocal snow
#

you need to sync after you remove them

buoyant crescent
#

hi i trying to run an embed command but it's give me this error message ```python
2023-06-27 13:29:30 ERROR discord.ext.commands.bot Ignoring exception in command aide
Traceback (most recent call last):
File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
File "c:/Users/MYOUSSEF/Desktop/bot/main.py", line 47, in aide
help.set_author(name="Menu Help du bot", url="", icon_url=ctx.author.avatar_url)
AttributeError: 'Member' object has no attribute 'avatar_url'

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

Traceback (most recent call last):
File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Program Files (x86)\Python38-32\lib\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: 'Member' object has no attribute 'avatar_url'


and this is my code :
```python
client = commands.Bot(command_prefix= '!',intents=discord.Intents.all())




@client.event
async def on_ready():
    print("The bot is now ready")
    print("--------------------")
    try:
        synced = await client.tree.sync()
        print(f"Synced {len(synced)} command(s)")
    except Exception as e:
        print(e)



@client.command()
async def aide(ctx):
    help = discord.Embed(title="Liste des commandes", url="", description="Besoin d'aide ?", color=0x7434eb)
    help.set_author(name="Menu Help du bot", url="", icon_url=ctx.author.avatar_url)
    await ctx.send(embed=help)```
hasty pike
#

Don't use url params if you want to leave it blank

buoyant crescent
hasty pike
#

Or else use None

buoyant crescent
buoyant crescent
turbid condor
#

๐Ÿ‘

drifting arrow
#

Is it possible for a discord bot to edit the servers integrations channel? such as the slash commands etc?

raw escarp
#

How do I register Slash commands

sharp whale
sonic vapor
#

i want to learn basics of python from where to learn?

hasty pike
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.

hasty pike
hasty pike
buoyant crescent
#

hi i have a question how can i send image in an embed

#

not in the thumbnail

vocal snow
#

!d discord.Embed.set_image

unkempt canyonBOT
#

set_image(*, url)```
Sets the image for the embed content.

This function returns the class instance to allow for fluent-style chaining.
sharp whale
hasty pike
buoyant crescent
#

ty

buoyant crescent
hasty pike
buoyant crescent
#

ok

hasty pike
#
embed = discord.Embed()
embed.set_image(url='link') 

@buoyant crescent this way

buoyant crescent
buoyant crescent
buoyant quail
sonic vapor
#

can i learn python by w3school website

buoyant crescent
hasty pike
hasty pike
#

But practice is more important than just learning

buoyant crescent
naive briar
#

What error

sonic vapor
hasty pike
#

Visual studio codes?
Sublime?
Pycharm?
Vim?

sonic vapor
hasty pike
sonic vapor
buoyant crescent
#
Traceback (most recent call last):
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:/Users/MYOUSSEF/Desktop/bot/main.py", line 51, in aide
    await ctx.send(file=file, embed=help)
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\ext\commands\context.py", line 1024, in send
    return await super().send(
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\abc.py", line 1562, in send
    data = await state.http.send_message(channel.id, params=params)
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\http.py", line 625, in request
    async with self.__session.request(method, url, **kwargs) as response:
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\aiohttp\client.py", line 1141, in __aenter__
    self._resp = await self._coro
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\aiohttp\client.py", line 508, in _request
    req = self._request_class(
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\aiohttp\client_reqrep.py", line 313, in __init__
    self.update_body_from_data(data)
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\aiohttp\client_reqrep.py", line 505, in update_body_from_data     
    body = body()
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\aiohttp\formdata.py", line 170, in __call__
    return self._gen_form_data()
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\aiohttp\formdata.py", line 163, in _gen_form_data
    self._writer.append_payload(part)
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\aiohttp\multipart.py", line 829, in append_payload
    size = payload.size
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\aiohttp\payload.py", line 379, in size
    return os.fstat(self._value.fileno()).st_size - ```
#
ValueError: I/O operation on closed file

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

Traceback (most recent call last):
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Program Files (x86)\Python38-32\lib\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: ValueError: I/O operation on closed file```
hasty pike
buoyant crescent
#
file = discord.File("pu.gif", filename="pu.gif")
@client.command()
async def aide(ctx):
    help = discord.Embed(title="Liste des commandes :", url=None, description=None, color=0x7434eb)
    help.set_author(name="Menu Help du bot", url=None, icon_url="https://cdn.discordapp.com/attachments/1122145321535930499/1122145393032040519/20230624_142400_0000.png")
    help.add_field(name="Musiques :", value="!join | !play | !stop | !resume | !pause | !music", inline=False)
    help.add_field(name="Modรฉration :", value="!ban | !kick", inline=False)
    help.set_image(url='attachment://pu.gif')
    await ctx.send(file=file, embed=help)```
unkempt canyonBOT
#

class discord.File(fp, filename=None, *, spoiler=..., description=None)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.

Note

File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
naive briar
#

It's not meant to be used more than once

buoyant crescent
#

oh that's why ;-;

digital magnet
#

can someone tell me where is django discussion channel?

buoyant quail
naive briar
unkempt canyonBOT
#

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

Never, ever, watch YouTube tutorials
digital magnet
sonic vapor
sonic vapor
hasty pike
unkempt canyonBOT
#
Missing required argument

code

hasty pike
#

!e

print(" don't play with it")
unkempt canyonBOT
#

@hasty pike :white_check_mark: Your 3.11 eval job has completed with return code 0.

 don't play with it
sonic vapor
hasty pike
#

That's how you write/make code block

sonic vapor
#

thrre?

hasty pike
sonic vapor
#

lol

hasty pike
#

@sonic vapor

sonic vapor
#

thanks bro![incident_actioned](https://cdn.discordapp.com/emojis/714221559279255583.webp?size=128 "incident_actioned")

buoyant crescent
#

can someone can help me again with my embed, i want do display the name of the person who request the command but it give me this error : ```python
ERROR discord.ext.commands.bot Ignoring exception in command aide
Traceback (most recent call last):
File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
File "c:/Users/MYOUSSEF/Desktop/bot/main.py", line 51, in aide
help.set_footer(f"Demandรฉ par :{ctx.author.display_name}")
TypeError: set_footer() takes 1 positional argument but 2 were given

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

Traceback (most recent call last):
File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Program Files (x86)\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Program Files (x86)\Python38-32\lib\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: TypeError: set_footer() takes 1 positional argument but 2 were given```

#

and here is my code : ```Python

@client.command()
async def aide(ctx):
help = discord.Embed(title="Liste des commandes :", url=None, description=None, color=0x7434eb)
help.set_author(name="Menu Help du bot", url=None, icon_url="https://cdn.discordapp.com/attachments/1122145321535930499/1122145393032040519/20230624_142400_0000.png")
help.add_field(name="Musiques :", value="!join | !play | !stop | !resume | !pause | !music", inline=False)
help.add_field(name="Modรฉration :", value="!ban | !kick", inline=False)
help.set_image(url='https://media.discordapp.net/attachments/1120608535672270939/1123258060983509124/pu.gif?width=747&height=312')
help.set_footer(f"Demandรฉ par :{ctx.author.display_name}")
await ctx.send(embed=help)```

naive briar
#

!d discord.Embed.set_footer

unkempt canyonBOT
#

set_footer(*, text=None, icon_url=None)```
Sets the footer for the embed content.

This function returns the class instance to allow for fluent-style chaining.
naive briar
#

The method is keyword-only

buoyant crescent
naive briar
#

It only accepts keyword arguments

#

Like

func(keyword=value)
buoyant crescent
#

oh i forgot the text=

fallen imp
#

sorry if I ask stupid ;-;

vocal snow
#

you cannot do bot.username because that attribute doesn't exist like the traceback says

#

check the docs of discord.ext.commands.Bot object to see what attributes it has

formal basin
fallen imp
#

ohhh

#

tks you guy

buoyant crescent
#

hi i want to make an embed that when someone join it shows his picture but i don't know how i can do that ```python
@client.event
async def on_member_join(member):
channel = client.get_channel(1121386561150386276)
join = discord.Embed(title="Bienvenue dans le serveur de la Neo Destiny ! ", url=None, description=f":tada: Bienvenue {member} :tada:")
join.set_image(url='')

slate swan
#

member.avatar.url

hasty pike
slate swan
#

What on earth are you doing

#

If you assign msg to the original response, then use that message variable to do whatever you want, e.g. editing

#

Passing a message variable in send_response is pointless

hasty pike
hasty pike
#

You mean like this

msg = await ctx.send(embed=vam, view=antinuke(author, guild))
slate swan
#

When i try to change the color nothing works? i don't know if i have to use a hex or

#

ive got more cosmetic questions, should i reply with an embed with just a description or should i reply with

text here
for a one line or maybe 2 lines reply thats lets say like a fact or something?

proper thicket
#
from discord.ext import commands

class Moderation(commands.Cog):
    def init(self, client):
        self.client = client
    @commands.Cog.listener()
    async def on_Ready(self):
        print("Moderation.py is online.")

    @commands.command()
    @commands.has_permissions(manage_messages=True)
    async def clear(self, ctx, count: int):
        await ctx.channel.purge(limit=count)
        await ctx.send(f"(count) messag(s) have been deleted.")
            
async def setup(client):
    await client.add_cog(Moderation(client))```
#

can someone help me with my purge command i am getting errors that when i say it it shows purge is not found

buoyant quail
#

Because you named it clear?

proper thicket
#

didnt even see that

maiden fable
#

Ping?

slate swan
#

Pong

maiden fable
#

Hi Krypton

slate swan
slate swan
tight mica
#

bruh slow internet moment

slate swan
slate swan
tight mica
#

I was talking about myself

tight mica
#

anyway, ```embed.title = ...
embed.color = ...

#

color could be 16711680, 0xff0000, discord.Color.red()(this also returns the same thing)

proper thicket
#

can i get help with this error ERROR discord.client Ignoring exception in on_ready
Traceback (most recent call last):
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/bot.py", line 947, in _load_from_module_spec
await setup(self)
File "/Users/hervans/Downloads/Hervy bot/cogs/kick.py", line 33, in setup
await client.add_cog(Moderation(client))
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/bot.py", line 777, in add_cog
raise discord.ClientException(f'Cog named {cog_name!r} already loaded')
discord.errors.ClientException: Cog named 'Moderation' already loaded

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

Traceback (most recent call last):
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/Users/hervans/Downloads/Hervy bot/main.py", line 19, in on_ready
await load()
File "/Users/hervans/Downloads/Hervy bot/main.py", line 25, in load
await bot.load_extension(f"cogs.{cog_name}")
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/bot.py", line 1013, in load_extension
await self._load_from_module_spec(spec, name)
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/bot.py", line 952, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.kick' raised an error: ClientException: Cog named 'Moderation' already loaded

slate swan
slate swan
tight mica
#

wat

slate swan
#

idk what to do

tight mica
#

what are you doing?

proper thicket
#

But its a moderation command

slate swan
#
    embed.color = color
#

Just don't load the same cog twice

#

Problem solved

tight mica
proper thicket
slate swan
#

You load twice the same cog, don't do it

proper thicket
slate swan
tight mica
slate swan
turbid condor
tight mica
#

what is the user inputting?

slate swan
proper thicket
# slate swan You coded it, you tell me
from discord.ext import commands

class Moderation(commands.Cog):
    def init(self, client):
        self.client = client
    @commands.Cog.listener()
    async def on_Ready(self):
        print("Moderation.py is online.")

    @commands.command()
    @commands.has_permissions(manage_messages=True)
    async def kick(self, ctx, count: int):
          async def kick(self, ctx, member: discord.Member, modreason):
                await ctx.guild.kick(member)
   
   
                conf_embed = discord.Embed(title="Success!" , color=discord.Color.blue())
                conf_embed.add_field(name= "Kicked:" , value=f"{member.mention} has been kicked from the server by{ctx.author.mention},", inline=False )
                conf_embed.add_field(name="Reason:", value=modreason, inline=False)

                await ctx.send(embed=conf_embed)

            
          
          
          
          
            
            
            
async def setup(client):
    await client.add_cog(Moderation(client))```
slate swan
#

Unrelated to loading cogs

tight mica
turbid condor
#

This doesn't explain the problem

slate swan
#

And for your eye's sake, remove those unnecessary empty lines in your code

tight mica
#

so something like #123456

slate swan
#

correct

turbid condor
#

Check if you have 2 moderation classes

proper thicket
slate swan
#

skull

#

A cog contains multiple commands, it's not one command per cog

turbid condor
slate swan
#

So don't have twice the same cog named "Moderation" and two different commands in diffferent files

#

Create one cog/file/class, put both your commands in there

tight mica
# slate swan correct

as as the embed color can only be int, you need to convert the string from user input to int

color = color.replace("#", "") # removing the # part
color = int(color, base=16) # we use base=16 because its hexadecimal
embed.color = color```
slate swan
#

Or just

embed.color = int(color[1:7], base=16)
tight mica
#

not always sure that the input contains a #

tight mica
slate swan
tight mica
#

what error

slate swan
#

AttributeError: 'dict' object has no attribute 'title'

tight mica
#

dont convert embed to dict

#
embed = msg.embeds[0]
...
await msg.edit(embed=embed)```
slate swan
#
@client.command()
async def editembed(ctx, channel: discord.TextChannel, msg_id, title, color):
    msg = await channel.fetch_message(msg_id)
    embed = msg.embeds[0]
    embed.title = title
    color = color.replace("#", "") # removing the # part
    color = int(color, base=16) # we use base=16 because its hexadecimal
    embed.color = color
    await msg.edit(embed=discord.Embed.from_dict(embed))```
tight mica
#

think about it

#

am not spoonfeeding everything to you

#

@slate swan

proper thicket
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
#
if message.author.id == client.user.id:
        return 
  
   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:
      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
            
      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```
#

my bot is spamming the logging_channel.send and the message.channel.send

proper thicket
#

nvm

formal basin
proper thicket
formal basin
proper thicket
#

cause i am using cogs and its not allowing me to use Moderation 2 times

formal basin
#

Moderation?

proper thicket
proper thicket
formal basin
#

oh i see

proper thicket
#

i am just asking for another way to define Moderation

formal basin
proper thicket
formal basin
#

is it not working?

proper thicket
formal basin
proper thicket
# formal basin like what?

ERROR discord.client Ignoring exception in on_ready
Traceback (most recent call last):
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/bot.py", line 947, in _load_from_module_spec
await setup(self)
File "/Users/hervans/Downloads/Hervy bot/cogs/kick.py", line 26, in setup
await client.add_cog(Moderation(client))
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/bot.py", line 777, in add_cog
raise discord.ClientException(f'Cog named {cog_name!r} already loaded')
discord.errors.ClientException: Cog named 'Moderation' already loaded

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

Traceback (most recent call last):
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/Users/hervans/Downloads/Hervy bot/main.py", line 19, in on_ready
await load()
File "/Users/hervans/Downloads/Hervy bot/main.py", line 25, in load
await bot.load_extension(f"cogs.{cog_name}")
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/bot.py", line 1013, in load_extension
await self._load_from_module_spec(spec, name)
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/bot.py", line 952, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.kick' raised an error: ClientException: Cog named 'Moderation' already loaded

proper thicket
proper thicket
formal basin
#

I have no clue

#

I have never used cogs before

proper thicket
#

what about this

proper thicket
# formal basin I have never used cogs before

Traceback (most recent call last):
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/converter.py", line 1236, in _actual_conversion
return converter(argument)
ValueError: invalid literal for int() with base 10: '@rustic shard'

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

Traceback (most recent call last):
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/core.py", line 1021, in invoke
await self.prepare(ctx)
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/core.py", line 938, in prepare
await self._parse_arguments(ctx)
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/core.py", line 845, in _parse_arguments
transformed = await self.transform(ctx, param, attachments)
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/core.py", line 715, in transform
return await run_converters(ctx, converter, argument, param) # type: ignore
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/converter.py", line 1345, in run_converters
return await _actual_conversion(ctx, converter, argument, param)
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/converter.py", line 1245, in _actual_conversion
raise BadArgument(f'Converting to "{name}" failed for parameter "{param.name}".') from exc
discord.ext.commands.errors.BadArgument: Converting to "int" failed for parameter "count".

formal basin
#

hm

#

what is count?

proper thicket
formal basin
proper thicket
# formal basin show me your code
from discord.ext import commands



class Moderation(commands.Cog):
    def init(self, client):
        self.client = client
    @commands.Cog.listener()
    async def on_Ready(self):
        print("Moderation.py is online.")

    @commands.command()
    @commands.has_permissions(manage_messages=True)
    async def purge(self, ctx, count: int):
        await ctx.channel.purge(limit=count)
        await ctx.send(f"Purged {count} Messages.")
            


    @commands.command()
    @commands.has_permissions(manage_messages=True)
    async def kick(self, ctx, count: int):
          async def kick(self, ctx, member: discord.Member, modreason):
                await ctx.guild.kick(member)
   
   
                conf_embed = discord.Embed(title="Success!" , color=discord.Color.blue())
                conf_embed.add_field(name= "Kicked:" , value=f"{member.mention} has been kicked from the server by{ctx.author.mention},", inline=False )
                conf_embed.add_field(name="Reason:", value=modreason, inline=False)

                await ctx.send(embed=conf_embed)

            
async def setup(client):
    await client.add_cog(Moderation(client))```
formal basin
#

your code is right

#

for me

proper thicket
#

this is crazy

buoyant quail
#

what is this lol

formal basin
#

how can I make a bot not send a message because of a message

slate swan
#

how come this part of my code doesn't set the embed description to something went wrong if i have an unhandled exception?

    elif isinstance(error, discord.ApplicationCommandInvokeError):
        if isinstance(error.original, discord.errors.Forbidden):
            embed.description = "error1"
    elif isinstance(error, discord.errors.NotFound):
        embed.description = "error2"
    elif isinstance(error, gdshortener.GDGenericError):
        embed.description = "error3"

    else:
        embed.description = "Something went wrong"```
buoyant quail
formal basin
buoyant quail
#

I don't understand you

formal basin
buoyant quail
#

Don't send it 3 times ยฏ_(ใƒ„)_/ยฏ

formal basin
#

but its anti spam

buoyant quail
#

So you want to punish user that sent 3 messages very fast?

formal basin
slate swan
buoyant quail
# formal basin here

You didn't finish previous runs for some reason maybe.
Check for unfinished processes and kill them (or just restart the pc)

formal basin
#

ok

merry flint
#

guys i am making a project computer in discord i want developers to help
Its discord bot

meager chasm
slate swan
#

also when do u use discord.User and when discord.Member

merry flint
#
from email import message
import discord 
import random
from re import M
from discord.ext import commands

client = commands.Bot(command_prefix = '',)


@client.command()
async def Createaccount(ctx):
    await ctx.message.delete()


guys how do i make it like createaccount username password

merry flint
#

oh thanks

proper thicket
#
await bot.change_presence(game=discord.Game(name="on " + str(len(bot.servers)) + " Servers.", type=0))```
#

is that correct for acivity status to see how much servers is in

#

game is not defined

#

!e @commands.command(name="unban")
@commands.guild_only()
@commands.has_permissions(ban_members=True)
async def unban (self, ctx, userid):
user = discord.Object(id=userid)
await ctx.guild.unban(user)
conf_embed = discord.Embed(title="Success!" , color=discord.Color.blue())
conf_embed.add_field(name= "Unban:" , value=f"<@{userid}> has been unbanned from the server by {ctx.author.mention}.", inline=False )

unkempt canyonBOT
#

@proper thicket :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     @commands.command(name="unban")
004 |      ^^^^^^^^
005 | NameError: name 'commands' is not defined
proper thicket
# slate swan f strings exist

also can you help me with this ```py
@commands.command(name="unban")
@commands.guild_only()
@commands.has_permissions(ban_members=True)
async def unban(self, ctx, userId):
user = discord.Object(id=userId)
await ctx.guild.unban(user)

    conf_embed=discord.Embed(title="Success!", color=discord.Color.blue())
    conf_embed.add_field(name="UnBanned:", value=f"<@{userId}> Has Been Unbanned From The Server By {ctx.author.mention}.", inline=False)

    await ctx.send(embed=conf_embed)```
slate swan
#

userId is not an integer

unkempt canyonBOT
proper thicket
#

target_id?

slate swan
#

id=int(userId) my god

proper thicket
#

instead of userid

slate swan
proper thicket
buoyant crescent
#

hi can someone help me, i'm trying to make a cog but it don't work

import discord
from discord.ext import commands
import os

from apikeys import *


client = commands.Bot(command_prefix= '!',intents=discord.Intents.all())

intents = discord.Intents.default()

intents.members = True

@client.event
async def on_ready():
    await client.change_presence(status=discord.Status.do_not_disturb, activity=discord.Streaming(name="Pokemon Unite", url="https://www.twitch.tv/mysterymom__"))
    print("The bot is now ready")
    print("--------------------")


initial_extensions = []

for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        initial_extensions.append("cogs." + filename[:-3])

if __name__  == '__main__':
    for extension in initial_extensions:
        client.load_extension(extension)



client.run((BOTTOKEN))
#

and this is my cog : ```python
import discord
from discord.ext import commands

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

@commands.command()
async def aide(self, ctx):
    help = discord.Embed(title="Liste des commandes :", url=None, description=None, color=0x7434EB)
    help.set_author( name="Menu Help du bot", url=None, icon_url="https://cdn.discordapp.com/attachments/1122145321535930499/1122145393032040519/20230624_142400_0000.png")
    help.add_field(name="Musiques :", value="!join | !play | !stop | !resume | !pause | !music", inline=False)
    help.add_field(name="Modรฉration :", value="!ban | !kick", inline=False)
    help.set_image(url="https://media.discordapp.net/attachments/1120608535672270939/1123258060983509124/pu.gif?width=747&height=312")
    help.set_footer(text="Demandรฉ par : {}".format(ctx.author.display_name))
    await ctx.send(embed=help)


@commands.command()
async def music(self, ctx):
    await ctx.send("La liste des musiques : black_clover, black_rover, demon_slayer_3, night_dancer")


@commands.Cog.listener()
async def on_member_join(member):
    channel = client.get_channel(1121386561150386276)
    join = discord.Embed(title="Bienvenue dans le serveur de la Neo Destiny ! ", url=None, description=f":tada: Bienvenue {member} :tada:", color=0x7434EB)
    join.set_image(url=member.avatar.url)
    join.set_footer(text=f"Nous sommes dรฉsormais : {member.guild.member_count}")
    await channel.send(embed=join)

def setup(client):
client.add_cog(Greetings(client))```

proper thicket
proper thicket
buoyant crescent
#

and when i run it tell me that they havn't found

proper thicket
slate swan
vocal snow
# slate swan anyone mind explaining

discord.User represents a normal discord user, discord.Member represent a user inside a specific server (hence containing server-specific info and methods, like roles and nickname)

buoyant crescent
slate swan
proper thicket
vocal snow
slate swan
#

And stop naming your bot variable client

#

youtube tutorials moment CLi_NotLike

vocal snow
#

Users are a subset of Members

slate swan
vocal snow
#

there is no "better"

potent spear
#

"most appropriate"

vocal snow
#

it depends on what information you need to access or what endpoints you need to use

potent spear
#

a Member is used when you want also specific info about that User in a guild
if you don't care about that, you don't necessarily need a Member object

slate swan
#

so if i just want general info i dont need Member just User

vocal snow
#

yes

slate swan
#

but essentially it doesnt matter which one u use right? i mean if u use Member it doesnt make it slower or anything just provides u with more info?

swift trench
#

how do I invite my bot to my server?

potent spear
vocal snow
#

if you verify your bot in the future and cannot access member intents, core features of your bot may fail if they (unnecessarily) need Member

slate swan
swift trench
slate swan
#

Disable "Requires code grant" in the bot's settings in the developer portal

potent spear
#

this is more related to helper functions

swift trench
#

idk why its turned on

slate swan
potent spear
slate swan
#

okay so i need discord.Member for that right

potent spear
#

sure... because you actually want to make sure there's a member with that ID in the guild...
I feel like you're overthinking this a bit

slate swan
#

i am

#

im really confused as well

#

okay i think i got it, so if i need to access stuff from a user i use discord.Member, and if i just need to get their id or something, i use discord.User, am i getting this right @potent spear

potent spear
slate swan
#

so take a permission check command, i only need to access the user id of a user, so ill use discord.User or their actual id

potent spear
#

related to a guild => member
dm stuff, database stuff only => user

#

you're checking for their permissions in a guild...
just keep on using what you're using, in probably all your cases discord.Member is fine

#

you can always check what checks require what objects
but it doesn't make much difference if you were to typehint it to discord.User all of a sudden

slate swan
#

i meant like my own permissions from a db shouldve mentioned it

potent spear
#

yeah, but still, this is probably on a guild, so just keep using member objects

#

It's not like you'll be checking user permissions of other guilds in a command...

slate swan
#

but hows it related to a guild? If its just if its developer premium or normal user for commands?

potent spear
slate swan
#

yes, okay, thanks for helping

potent spear
#

gl hf

buoyant crescent
#

hi i still got an error

#
discord.ext.commands.errors.CommandNotFound: Command "aide" is not found
2023-06-27 22:54:06 ERROR    discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "music" is not found```