#discord-bots
1 messages ยท Page 258 of 1
Because "identifier" doesnt need choices.. I was using it to just update a global variable lol.
You'd only be able to do it once the command is sent
So then if I cant dynamically change the choices for a param I might as well as take a different route.
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
i think you're focusing on the wrong paramater..
which paramater do you think I am having an issue with?
Identifier?
No
Then that's because you didn't specify it, how do you think I'd know
I've been specifying it..
Where
๐ฅณ
COOKIE
๐ช
thanks
Dont worry. I'll just retype everything.
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.
I just told you to combine the two autocomplete decorators
!d discord.app_commands.autocomplete
@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...
why do you even need to autocomplete the first parameter
and how does steam token relates to unmuting a person on the server
ERROR : 103 no route to host
How to fix this
Pls tell best python book
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
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.
No matching recourse found
Pls U tell that
the link has multiple?
I do believe aiohttp (the http library discord.py uses under the hood) has basic web server capabilities
It should be enough for the redirect page (since all you need to do is grab the code)
No
Online shopping apps
Oh, I think that could help. Do you happen to have an example or the documentation for that?
shopping apps? wdym?
the provided link has loads of python books
The book that also have the create database topic
that's not really python related, more like SQL
not all of them are paid
But they are coming in dollers am๐ฎ๐ณ
some are free...
Awesome, thanks!
Can I use json rather than create database
depends on what you're trying
in case you're writing a discord bot, please don't use json, json is not a database
Why not json
Ah so much English
you can use a local DB file with aiosqlite or get a free MongoDB plan
But I understand
none of which cost money
Oo
scary
I message here daily I ask questions daily but I can't create bot From 2 month ๐ฅ
I need a patner for creating the bot where can I find?
learn python basics first I'd say, because coding a bot is more something for intermediate programmers
you can always ask around
Hm
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
Where to learn basics
change to what exactly?
when you do !changeblocked <1,3,4,5,6> or whatever it changes blocked = ["1", "2", "-3", "4", "5"] the thing in bold
do you want this to persist when the bot restarts?
if yes is your answer, you should consider using a database instead of just a variable to store this info
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)
Couldnt i have a json file as a DB

I don't know how to use MongoDB is there a video on how to ?
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
don't use video's, they are mostly outdated regarding dpy
ask a good question in #โ๏ฝhow-to-get-help and people will surely help you out
pymongo/motor docs
how would u add permissions for app commands for server owners, or certain permissions for admins, mods?
@app_commands.default_permissions()
ty!
and for hybrid commands it would just be the
@commands.guild_only()
@commands.is_owner()
@commands.has_permissions(administrator=True)
yes
gotcha. tyvm
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'
I got an error when using this
guys I wanna learn abt discord moderation methods but idk where it is in the docs. Can anyone lend me a helping hand
!d discord.Interaction.original_response
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.
You have to call it
thank you

Mostly methods of discord.Member
okay thanks and what abt voice channels
what about them?
i mean they are methods of which class
music bots and all
average 572287th multipurpose discord bot
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)```
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.
is scraping not allowed?
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)
you can claim a help channel; #โ๏ฝhow-to-get-help
Why would it
rule 5 was referred so idk
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 
@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
did you check if the error handler fires?
wdym
i mean if it is called
yes
did you try printing anything
for example printing error to see what error actually happens
in console?
yeah
hmm just tried, it didnt print anything
idk why it is not being called
so its not being called
other errors works just fine
what should I do?
show your command definition
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) ```
no other decorators?
well then no way the MissingPermissions wont throw since you dont check if user has this permissions
!d discord.ext.commands.has_permissions
@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").
what about bot
i dont think .purge itself throws it
!d discord.TextChannel.purge
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...
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
@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").
alright thanks
and also what do u prefer? making on_command_error or making seperate handlers for each cmd
next time try to debug it a little
see if its being called
if it does what param values are etc
i always used global error handler
i belive there are cases to use per command but i never needed that
depends on case
hm
alr
Hello.
Can anyone help me?
are you sure this is a regular bot?
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").
!intents
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.
this code looks like some self bot stuff
I am watching courde on youtube.
He said and i did.
it is literally the most basic bot
message.client ?
Just make sure you know python basics before you watch any discord bot tutorial or you'll end up copying more than learning
Yes
you sure this exists
That explains why the code looks like that
where did you get this odd attribute
old discordpy code
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...
Is the message.client even ever existed
2 years ago
Host free, huh
maybe
just stick to the docs it is well documented
That's already suspicious from the title
You can send me ciurse
doing a discord bot from youtube 
Can anyone help me?
this wont solve your problem tho
you cant even rewrite from youtube video 
learn python first man
did you learn python already?
you've been told to do so countless times
Yes
(and not from YouTube)
doesnt look like
Send me video Course discord.py
i dont use youtube for coding i dont know any
You can use YouTube for coding!?!?
you can code in comments
Hey guys! Today we go over how to create a start a Discord bot project using Discord.py in Python. In this video we go over setting up a bot, and coding it to go online. (and running a command even though I never planned on it)
Thank you so much for watching! pssst.. subscribe
https://discord.com/developers/applications
BOT INVITE LINK TEMPL...
I can watch this?
well you can do anything but you wont learn python from it
nor how to make a discord bot
intents = discord.Intents.default()
intents.messages = True```
try adding this to your code
messages is already included in default()
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").
also change the client part
That's very vague
client = discord.Client(intents = intents,help_command=None)```
commands.Client
commands.Client?
odd
client = discord.Client()
Did you get this from YouTube, also?
me when style guides
change this @tidal folio
PEP 8 cried
with this
There's no help_command kwarg in that class
yeah help_command is only for Bot since it supports prefixed commands
this removes the default help command ig
so there are any you can list on help page
i aint a professional but im pretty sure this exists
it does in commands.Bot yeah
Not for the discord.Client
not in Client

how would u get a channels lowest role?
the ones with the least permissions?
right.
Why would you want this?
hey,
how to check if discord id is member in the guild or not
also how to send private message to discord id member
if you have a member object you know it's in a guilg
!d discord.User.send
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**.
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.
lowest permissions would be a mess to check
im guessing get a list, then check the hoist positions
based on the list of role id's
you could loop through roles and check for discord.Role.position
and check the higher role position
right cause the highest role has the least permissions
not necessarily, the lowest role could have admin and the first one couldnt
but that's for lowest... not highest... right?
can someone please help me with this error i am getting i added a setup function and it still gives me problems
ur setup function is indented.
setup function is supposed to be in global scope not in the Cog
global scope?
how are you going to create a cog in a method that needs a cog to be created
i already have cogs in all my other files
and it works perfectly
show other files code then
the other files are not the problem
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?
the indenting?
and
yeah
wdym and its a difference if the functon is in the global scope and if its not
i typed and on accident
Also i'd suggest to use the same indenting everywhere
Having 8 spaces in one place and 1 space in another hurts my eyes
!e ```py
def setup():
print("Setup working")
setup()
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
Setup working
!e ```py
class A:
def setup():
print("Setup working")
setup()
@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
indentation matters
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
Oh okay i understand now thank you and keira btw how can i do the thing you just did the '''py
!code
Alrighty thanks.
Yea i use to use them.
What
Also dont think its only the indenting
still responding in a error
Can you help me if down is gone?
me?
0 can be anything you want. roles are not ordered by their permissions
ye
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))```
wdym
unindent it all the way
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
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
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
!d max - or literally just this
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.
to generate a temp channel that holds the permissions so when it's made it's not made for everyone and anyone, but only those with the lowest roles.
so if the channel makes a temp room for a valorant group, mods also have that permission to view the channel also.
o.o i've never heard of this.
!d min - or this if you want the lowest one
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.
so i'd pass in the role positions to find the min/max?
If you want to compare them by positions. As we said, role permissions don't depend on their position
oh it compares obj not just ints
!d discord.Role
class discord.Role```
Represents a Discord role in a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild")...
whats the best choice for hosting a bot online?
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.
@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 ;-;
how can i check if a user is timed out in the on_message event?
because in free hosting you are provided with a shared ip which means if the ip gets blocked then there goes your bot
wdym with shared ip
multiple users are using the same ip address
tho if u still want a free hosting u can check discloud.com i believe it has a free tier
ofc
but i can restart it right?
u can but then u will need a new vps
so yeah you might either buy a vps or can check out the www.discloud.com
is 100 enough ? ๐
depends on what you are doing with your bot
if its a small bot then this should be enough
then it should be ok
but what if used some apis or databases
again it depends on what the bot is doing
so u should try and see if it works or not
how can i check if a user is timed out in the on_message event?
!d discord.Member.is_timed_out
is_timed_out()```
Returns whether this member is timed out.
New in version 2.0.
!d discord.Member.is_timed_out just read the docs for once
I didnt even know is there a util function but took me 20s to check
Docs are for a reason there
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
I am assuming that adding code to a discord bot to kick members based on when they last posted is against discords ToS?
What 
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.
can I make a message be sent once
cause its sending it twice
Probably not, I don't think
Uhhh, don't know whether to risk or not :>
Why would it be
Could be seen as a form of nuking?
Since Discord already has a kind of a similar thing (prune, like you said) built-in
can I make a message be sent once
cause its sending it twice
Stop repeating your question
sorry
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.
save the details in database and check from it if the message sent before or not
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
How to solve a bot sending twice a same message:
Check why your bot sends messages twice, e.g. your bot is running twice by mistake
Store all the messages the bot sends in a database and double check every time before sending a new message
Better:
use channel history before sending each message
The send method shouldn't be raising that kind of error
Is it inside an app command and you didn't respond to its interaction?
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
the users dms is off
got it to work. ty :3
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)}")
i heard that pycord is better for ui thank discord.py
isnt it forked from discord.py? how it could be better
I wouldn't recommend py-cord.
I'd recommend discord.py or Hikari for more advanced Python programmers.
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?
You're not the only one using your replit
Replit isn't meant as a hosting platform so many many users can "share" the same machine
Could be because Repl.it shares ip adresses so someone else could be doing it.
but it's a private replit
Using replit as a host is not recommend BTW
Doesn't affect the way how they virtualize their systems.
That only controls the "visibility"
Someone else is still sharing the same machine as you
so does that mean my tokens are compromised, like those people can see my secret data?
No your token shouldn't be compromised that way
But it can get your bot banned off Discord if it keeps happening
ok, so if replit is not recommended, where else could I host my bot?
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
Everywhere that offers a dedicated IP to a VPS or container host like Azure.
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 ๐
Basically, yeah.
@cloud dawn a quick search found me Heroku, is that one fine?
no
#965291480992321536 message see here for a list of options
Thanks a bunch, will look into it
It's more advanced but yeah it's good.
what IDE would you recommend for coding?
IDE is preference but the majority including myself uses vscode.
spotted that raspberry pi immediately, have u ever tried running snekbox on it?
have not - but that would be an interesting proposition 
Just a docker container, after all
Why do you ask? Using Snekbox for one of your own projects by chance?
yes, correct
Can't you just run snexbox inside a container?
Cool! We're selfhosting Snekbox for another project I'm involved in as well, it's pretty neat
selfhosting, where?
what do u mean, i tried running a docker container yeah
Azure app service I believe
and how much does it cost
Azure is expensive.
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
But reliable
Actually I'm not entirely sure it's on App Service
@feral timber can you confirm?
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
Ah yeah you need to authorize that in linux.
One sec playing overwatch otherwise my team will kill me
no worries
@slate swan Meaning you need to give write permission to that process.
right, and how would that work? how do i give it write permissions
yeah but how, thats logs from the docker container
im not able to connect my discord bot to mongodb and im getting this error
https://paste.pythondiscord.com/tidasojexu
You'd need to edit the dockerfile
which part to be more specific
You'd need to change the permission before the process starts.
i really dont know what i need to edit, i havent got much experience with docker
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
I send an article.
okay so somewhere in the dockerfile i need to do chmod 600 on that file
wym output?
ain't it showing when you run in google collab
Preferably everything inside the project just to make sure.
so chmod 600 /?
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
Go to that path and check if that file exists.
It's also a bit weird that there isn't a default amount of percentage it can use.
where do u configure that then? in the snekbox.cfg?
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.
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
Porb gets created when the procerss is ran.
ur right, im in /sys/fs/cgroup/NSJAIL.22 now
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```
Any issue on the github?
Are these default settings?
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
Not too sure then.
It is showing, I just want to make it run by discord bot
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)```
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
Most likely that it's the key that you got.
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
^
Oh
If i remove result = cursor.fetchone() its good no ?
wym
run by discord bot
Like its when you run your code in replit [discord bot] and there's going to be things getting displayed and it will work perfectly fine It don't mater on which IDE you on
Like it just runs
send a pic of the what's so called run by discord bot or mb your output in google collab
FYI ||{Don't use online IDEs when making discord bots, can be harmful sometimes}||
actually I am PMing you
Idk what PMing meand did you mean DM me?
Yes
disabled Dms and Friend requests
sorry had to add you
total soldier boy
And the definition of the guide id
???
???
What ?
The definition of your guide id?
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)
```
i don't understand
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
first of all that's now how you send an embed I think so
you do
await ctx.send(embed=help)```
!e what does get_role_id returns? It's at least a tuple, not just integer. Or sqlite3.Row in your case it seems
import sqlite3
connection = sqlite3.connect('test')
cursor = connection.cursor()
cursor.execute("SELECT 1")
print(cursor.fetchone())
Actually it was already answered
@buoyant quail :white_check_mark: Your 3.11 eval job has completed with return code 0.
(1,)
Files with no extension can't be uploaded.
and also change the command name to something that's not help like
async def helper(ctx)```
๐คทโโ๏ธ
it still give me the error
^
@buoyant crescent
ty it worked
ok i'm going to check that ty
Did you complete the definition of your bot
To remove use help_command=None when creating your bot variable, and not remove_command()
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
Umm. What will be the difference?
why create a command and remove it if you can just not create it
You won't die from it
!d discord.app_commands.Command.autocomplete
@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.
docs are for a reason
yeah you also wont die for creating 100 instances of empty classes but why
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
about what action are you talking
- moving member between channels
- moving channel between (or outside) category
- none of above
@stuck cosmos ^
moving a channel to a different catergory
and how can it fail
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
there is such limit?
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:
well you wont know until you try
thats what ive got rn, but i wont know until the category hits 50 ig ๐ญ
it doesnt specifically say on the docs
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
yh ive had it hit 50 before so i was just tryna make sure it would move to the second category if the first one is full
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
!paste
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.
not discord bot related #โ๏ฝhow-to-get-help
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))```
does any other testcommand in the cog work? (create one if necessary)
everything els works
being what exactly?
is that in the same cog?
yes same cogs folder
yes
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?
why am i getting this
Can you paste the entire file?
Can you also paste the mod cog?
alr
@sick birch main error is AttributeError: module 'discord.ext.commands.bot' has no attribute 'has_permissions'
how do i import it
Delete that line
You don't need it since you already have it in the line above
The @commands.bot.has_permissions one
oh yea it should be bot_has_permssions
nvm thx, im dumb
well everything is fine now, its just the cog is not being loaded ๐
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
Add a print in the init to see if it prints or not
It'll print in some and not others
Sorry robin, didn't mean to interrupt ๐ญ
yes
Nah you're fine, carry on
That means either you don't have manage messages or the bot doesn't
Both have to be true
well the purge cmd is not being shown in help cnd either
and i have exceptions for missing perms so its not the case
Is it a custom help command?
yea
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:
Async.sleep?
No, asyncio.sleep as the documentation says
Oh nvm sorry my WiFi took too long to send that
@sick birch so is there anything I can do to fix it?
No, like
x = await ctx.send(...)
await asyncio.sleep(...)
await x.edit(...)
Sometimes it's worth reading the documentation that was linked you know?
Okay it takes delay time in seconds as a int
See, reading documentation isn't rocket science
can sm1 help me
What's the issue?
cog is loaded still cmds not showing in default help cmd and not working as well
code: https://paste.pythondiscord.com/azohonocet
and cog code: https://paste.pythondiscord.com/ayojayirir
1st is for?
!d discord.ext.commands.Context.invoke # though it's probably better to have a common function you call in both commands
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...
main code
Okay gotcha thanks for help
I would say for loop for cogs is worse practice
hm
Here's my setup
But it would be better for you if you just use cog's name instead of using loop
alright
Also cog should be loaded before bot logs in with token
Not at all

Loading cogs like you did is very fine
so whats the problems?
What if instead of
asyncio.run(main())
you just do
asyncio.run(load())
same issue
shows this tho when i execute purge
await is not used while sending message
await context.send
yea but why also the help cmd is empty as i said earlier
It's not same code you have given us before
i just changed load function to main in main file
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")
Go ahead and await both the send, just like in your cog
await it and try
help cmd empty still
nvm
ty all
hello help me pls #1123151889350008962
original message is msg and you pass it into the view
@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!")````
can you print error.argument in your error handler
ah its MissingRequiredArgument
then its error.param
also error comes from this that you are expecting a reason but you do not provide it
tried by providing as well
why do you get random errors like BadArgument now
did you change command you run
no
it was MissingRequiredArgument before
nvm worked
just the mistake was i wrote reason: None
instead of =
yeah i told you you are expecting reason but you do not provide it
yup
im doing dumb mistakes a lot today lol
Hello how should I learn to make a bot?i kinda know some things but wanna start from start
if you know a little python you can make a discord bot, it's not that complicated
you can check the https://discord.com/developers and stuff
or you can just watch some youtube vids
Usually not recommended since a lot of them are outdated and provide bad code imo
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
I think transparency is essential for moderation, so I wouldn't make them ephemeral
okay thank you
I passed it as argument because i wanted to try msg.delete but that wasn't the solution i was looking for
well i mean i know to make a bot but Like how to code it and kinda understand function and things to add features
Learn Python or look at the examples
https://github.com/Rapptz/discord.py/tree/master/examples
It's kind of like refresh function for beginning message
I have an issue where only my old commands are showing but i have completely removed the file?
you need to sync after you remove them
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)```
Should be working fine
Its avatar.url
Don't use url params if you want to leave it blank
ok
Or else use None
yes thank you it worked
ok ty
๐
Is it possible for a discord bot to edit the servers integrations channel? such as the slash commands etc?
How do I register Slash commands
can anyone help me with interactions.py
i want to learn basics of python from where to learn?
YouTube, or some teaching websites all depends on your preference
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
What help do you need
Sync them
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
check my thread
embed.set_image(url=)
ty
what's the *
You don't need to put that in code
ok
This is enough
embed = discord.Embed()
embed.set_image(url='link')
@buoyant crescent this way
yes thank you it worked
how can i put an image that is in my folder ?
https://peps.python.org/pep-3102/ arguments that can only be supplied by keyword
Python Enhancement Proposals (PEPs)
can i learn python by w3school website
thank you for your help !
You can put it on discord and copy attachment url ๐ (cheap tricks)
Yep you can
But practice is more important than just learning
yes i think i will do that because when the gif is in my folder it work fine the first time but after i got an error
What error
Show error
i make but how to run in write print("Hello, World!") but where to run
IDE? Complier?
Visual studio codes?
Sublime?
Pycharm?
Vim?
first one
Do it
how?
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```
Go to YouTube and learn bro this channel is for discord bots
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)```
!d discord.File
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.
It's not meant to be used more than once
oh that's why ;-;
can someone tell me where is django discussion channel?
!e
print("Never, ever, watch YouTube tutorials")
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
Never, ever, watch YouTube tutorials
ty
print("Youtube is god for all ")
how you do this
!e
code
!e
print(" don't play with it")
@hasty pike :white_check_mark: Your 3.11 eval job has completed with return code 0.
don't play with it
no second line
thrre?
Yes
lol
@sonic vapor
thanks bro
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)```
!d discord.Embed.set_footer
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.
The method is keyword-only
what it mean ?
oh i forgot the text=
sorry if I ask stupid ;-;
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
its bot.user.name
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='')
member.avatar.url
join.set_image(url=member.avatar.url)
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
Just trying to figure out how do i get back original message ๐
How would i pass that variable into button class?
You mean like this
msg = await ctx.send(embed=vam, view=antinuke(author, guild))
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?
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
Because you named it clear?
Use description
Anyone?
Ping?
Pong
Hi Krypton

Colors are integers, not sure why you use to_dict and from_dict as well - why not just edit the attribute directly?
You can use an integer or disscord.Color object, also why are you converting it to dict
bruh slow internet moment

Nah haven't got a reason tbf
I was talking about myself
anyway, ```embed.title = ...
embed.color = ...
color could be 16711680, 0xff0000, discord.Color.red()(this also returns the same thing)
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
Eh, could u help me?
Cog named 'Moderation' already loaded
says it all
wat
idk what to do
what are you doing?
so what am i post to put it as
But its a moderation command
the color variable is a string, it cant be used for embed color
wym same cog
You load twice the same cog, don't do it
how did i load it twice?
So what should i put instead? discord.Color?
You coded it, you tell me
Check your code
what is the user inputting?
$editembed channel msgid updatedmsg color
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))```
Unrelated to loading cogs
like what exactly is the user inputting as the color?
This doesn't explain the problem
And for your eye's sake, remove those unnecessary empty lines in your code
ohh, hex
so something like #123456
correct
Check if you have 2 moderation classes
i do one for purge
Welp that's the problum
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
got it thanks.
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```
Or just
embed.color = int(color[1:7], base=16)
not always sure that the input contains a #
embed.color=int(color.replace('#',''),16)```
Thanks, think that fixed it but now my title is getting an error
what error
AttributeError: 'dict' object has no attribute 'title'
where would i put ?
await msg.edit(embed=embed)
@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))```
Question what is another way to define Moderation?
but in another way discord.py?
!paste
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.
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
is this from chatgpt?
nvm
no
can u help me with my error please?
what is your error
Question what is another way to define Moderation?
but in another way discord.py?
cause i am using cogs and its not allowing me to use Moderation 2 times
Moderation?
Yes
pyawait client.add_cog(Moderation(client))
oh i see
not that
i am just asking for another way to define Moderation
i dont think so
so what am i post to do?
no its returning with mutople errors
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
its already loaded
alright
what about this
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".
count messages that has been purged
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))```
hm idk
your code is right
for me
this is crazy
what is this lol
how can I make a bot not send a message because of a message
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"```
what
Maybe you have ApplicationCommandInvokeError and it is not Forbidden
how can i make a message be sent once only once like can I set that?
I don't understand you
like a message is being sent 3 times how can I stop that
Don't send it 3 times ยฏ_(ใ)_/ยฏ
but its anti spam
So you want to punish user that sent 3 messages very fast?
no when they spam its times out them but my bot is sending 3 messages
here
oh no
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: ValueError: invalid literal for int() with base 10: 'adngoandog'
``` i get this error, maybe i need another else statement to add the description if that fails.
You didn't finish previous runs for some reason maybe.
Check for unfinished processes and kill them (or just restart the pc)
ok
indeed i was right
guys i am making a project computer in discord i want developers to help
Its discord bot
What part do you need help with? This isn't really a recruitment forum
also when do u use discord.User and when discord.Member
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
this
Just add parameters to the command function
oh thanks
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 )
@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
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)```
The ID of the object.
id=int(userId) my god

Mb just asking
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))```
also its showing discord.ext.commands.errors.CommandNotFound: Command "unban" is not found
idk why u sending bigbrain for but aii
and when i run it tell me that they havn't found
async def load():
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
cog_name = filename[:-3]
await bot.load_extension(f"cogs.{cog_name}")
print(f'Extension: {cog_name} succesfully loaded')```
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)
it says me python c:/Users/MYOUSSEF/Desktop/bot/main.py:30: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited client.load_extension(extension)
which means, i should use discord.Member for slash commands that have something to do with the members? or should i use discord.Member more or something
what is BotBase.load_Extension?
you need to await it like the error tells you
You need to await client.load_extension(extension) as the error says
And stop naming your bot variable client
youtube tutorials moment 
outdated
you need discord.Member if you need access to a server member and server specific data like roles, permissions, nickname, etc.
If you need generic user information (username, avatar, etc) need you can use a discord.User object
Users are a subset of Members
but its still better to use discord.Member right?
there is no "better"
"most appropriate"
it depends on what information you need to access or what endpoints you need to use
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
so if i just want general info i dont need Member just User
yes
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?
how do I invite my bot to my server?
mhm, it's from cache anyways
but be as minimal as possible I'd say
don't get a member when you just need a user
or don't pass the whole ctx in a function when you only need the author for example
it's main implications are with intents
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
wdym by that? can i see an example of the ctx?
ah okay
anyone know why I cant invite my bot
Disable "Requires code grant" in the bot's settings in the developer portal
I just mean that if you only need a certain attribute of an object in a function, don't pass the whole object as an argument, just only pass the needed attribute
this is more related to helper functions
idk why its turned on
right so then for moderation stuff yk kicking time out and such i just need user no?
no, moderation is member related
okay so i need discord.Member for that right
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
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
sure, but in most cases, you'll be using the member object as you're trying to add roles or what not
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
nope
permissions are member related...
I mean, it makes sense doesn't it?
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
i meant like my own permissions from a db shouldve mentioned it
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...
but hows it related to a guild? If its just if its developer premium or normal user for commands?
sure, if it's for all commands of a bot in any guild, then you can use the discord.User object
yes, okay, thanks for helping
gl hf