#discord-bots
1 messages · Page 332 of 1
😅
my favorite feature is explain. you can hightlight code and it will explain it. very useful when debugging
Oh, nice.
Alr, nvm. I give up. 1k+ lines ain't that much.
haha you got this!!!
Why are you manually adding commands to the bot
what do you mean?
Why are you manually appending commands to the bots command list
i dont understand what your asking? haha if im doing it, its because thats what i found when i was trying to figure out to do something
ohhh what you tagged, thats just what it said from the discord link i shared
this
or i read it wrong
To load this extension we call await bot.load_extension('hello'). ahh i see now haha
why did he leave the server? lol he got it working
Yes, but a whole lot of what you told him is poor practice
You shouldn’t be manually adding commands, especially in the on_ready event
ok and i said i was newto coding mutliple times
You think the on_ready event is something it isn’t
Yeah, but you gave him advice and he took it
Now he’s going to have issues in the future
whoa now, i didnt give him advice. i clearly said i can tell him how i had to do it. which by the way, most of it i got from this discord
He’s using your code
my bad bro, ill shut up for now on
Even if you have no intention of giving him advice, he clearly took it
I’m not telling you to shut up, just in the future you need to ensure your code doesn’t have any major flaws before offering it as an example
!d discord.on_ready
discord.on_ready()```
Called when the client is done preparing the data received from Discord. Usually after login is successful and the [`Client.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.guilds) and co. are filled up.
Warning
This function is not guaranteed to be the first event called. Likewise, this function is **not** guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
Is this solved?
you tell me, i never had an issue
Read this
Intents.all() is generally discouraged as it causes a large amount of unnecessary caching
No, and it’s generally discouraged as well
Cogs are just classes, they have nothing to do with files/folders
so all these nots are doing it wrong using / as the command prefix?
I found a way to make it work yeah
i basically followed the code that someone had on their repo
sec i'll post here
from discord import Intents
from env import BOT_TOKEN
from discord.ext import commands
from pathlib import Path
import os
class MyBot(commands.Bot):
def __init__(self, command_prefix, description, intents):
super().__init__(
command_prefix=command_prefix,
description=description,
intents=intents
)
async def on_ready(self):
print(f"Logged in as {self.user}.")
async def load_cogs(self):
cogs_dir = f"{Path(__file__).parent}/cogs"
for file in os.listdir(cogs_dir):
if file.endswith(".py"):
extension_name = file[:-3]
try:
await self.load_extension(f"cogs.{extension_name}")
except Exception as e:
print(e)
else:
print(f"{extension_name} loaded")
async def setup_hook(self):
""" Runs when the bot first starts up """
await self.load_cogs()
def main():
bot = MyBot(
command_prefix="!",
description="Test Bot",
intents=Intents.all()
)
bot.run(BOT_TOKEN)
if __name__ == "__main__":
main()```
this worked for me
didn't realise setup_hook was a thing. but it seems to let you define an async function that can load cogs (and whatever else you want to load when you first start the bot)
Yeah it’s pretty useful
i still don't know why all the sample code on the internet doesn't work though
I presume load_extension has changed or something
because all the snippets I've seen treat it as a synchronous function
It used to be pre 2.0
hey
if interaction.channel.id != id:
embed_error = discord.Embed(title = "Wrong channel", description = "Please use the bot in channel", color = 0xFF0000)
embed_error.set_image(url = "")
await interaction.followup.send(embed = embed_error, ephemeral = True)```
I don't understand why with this the response is not ephemeral
was your defer ephemeral?
i don't think your followups can be ephemeral unless the original response is also
Nope
They cant be.
However! The initial response will always be ephemeral, and you can then set the ones afterwards to be non-ephemeral if you want.
At least, that's what I believe is happening when I run my code and make mistakes lol
I would test, but that requires setting up an entire bot just to test.
Hmm ok ty
I tested this as well
Only the initial followup follows the defers ephemeral settings
The more we know (:
@shrewd vapor Hope my tests have helped you
kk ty
!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
Indicates whether the deferred message will eventually be ephemeral.
Docs are your friend. Remember to check them out
when making discord modals, is it possible to allow mentions in the text box?
note: brackets are empty because there are no user or role mentions even though it contains the default text to mention. i have also tried <@userid> and that doesnt work either
no
Just use a user select
does that create a dropdown or something?
this is what you're referring to?
can it be epheremal?
i cannot do DMs for this, so i liked modals since they only appear to the user
Everything attached to an ephemeral message is also invisible
and i cant put a userselect in the modal instead of the TextInput?
no
damn, i just spent like 4 hours tryna get a modal to work and thats all useless now
the only reason i would need a team name is if im registering a team, in which they need to mention their team members so i can assign roles and put IDs in my db
so i cant use it
?
You’re given Member object with a user select
You can get the roles and IDs with that object
yes but i cant use userselect with a modal, so the time spent trying to get a modal to work is useless
I'm getting this when trying to install discord.py in my local machine
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for multidict
Failed to build multidict
ERROR: Could not build wheels for multidict, which is required to install pyproject.toml-based projects
any idea what it is?
at least someone is having a worse day than me😂
try uninstalling discord.py if it is installed
Are you not going to allow the user to choose their team name?
no, it's not install
new pc
Try this pip install -U --force-reinstall discord.py --extra-index-url https://abstractumbra.github.io/pip/
a userselect is in an embed right?
That isn’t in an embed
Holly cow! You're like a wizard to me xd
Not my wheels, im just a messenger
either way if the modal isnt a one-stop everything submitted window, i may as well have all the entry boxes in the same message instead of making them do a modal and then a dropdown
Embeds, views, drop downs etc are all attached to messages
thanks for your help, i didnt know what the dropdown thing was called ive seen it before
sad that it cant be in a modal
haha! thanks :D
iirc there was some glitch at the start where you could actually have a dropdown in one, but they patched it
They could be coming the future though
I believe that’s discords end goals with modals
it couldnt be that hard to implement right?
thanks for your help btw

Discord devs are very special
The amount of dumbass shit in their API would surprise you considering they're a multi billion dollar company
😂
yo currently working on a small bot that'll be used for a few servers but i came across a problem that i cant find a solution to online. right now, since im only working on the bot in a single server, i have each command use a constant guild id- however if im wanting the bot to be in multiple servers, how would i go about identifying the servers that the bot is in? its kinda hard to explain my problem here sorry yalls im relatively new to python, comin from lua
send_message doesnt return a message, hence it's None
!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) or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#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.
use that right after send_message to get the mesage
ok ill try that
thansk it worked
welcoem
if i open a file with with open will it interfere with the async function or do i have to use async with open to open files
well it will block but the "blocking" part is when you read the file, unless this is a large file with slow read, it wont really affect that much, but there is aiofiles if you still want async
what even is that
Say you delete a message
the bot will put it in a list, you run /snipe
it gives you the last deleted message
you can also store it in a db, but you really have no reason to do so.
it's a 50/50 with discord
because they're logging bots, even Dyno has it, but it's a grey area
well see
a friend said, most logs are in a staff area
but snipping can be ran by anyone
sniping*
I don't think it's against tos/enforced but it's still an invasion of privacy
when i open with async i have to await all the file.write and read?
Well there is a bot based on sniping, which is verified too
Im mainly needing to know if its against tos tbh
Dyno, Carl-Bot, both are verified, and have full logging.
why would you need that though
For fun lol
like say a friend send a stupid message then deleted it
you could snipe it then bully them :)
You think tos says everything 😭
What is deleted was meant to be deleted
i have never read it in my life
neither, n I never will
to much reading
It's against ToS, logging and message sniping.
my pc even agree with me i pulled up the tos and it just showign a black screen
Logging too?
yeah.
I thought logs like dyno n mee6 are fine?
loggings for staff perpose is legal
yeah thats what i meant
Okay, sniping is deleted then, imma add logs tho later, for staff, been needing to do all of that ngl lol
it's more accurate than Discords website itself.
this is part of a discord bot, not a self bot 
"certain types of automation" includes bots too.
you go with whatever floats your boat, but if you or your bot gets disabled for breaking ToS, I told you so.
@vapid parcel sniping without user's consent is prohibited
Report it for breaking developer policy (but actually check their privacy policy aforehead cause they might state that)
because that bot has it's use stated, and if it's added, people can leave the server, but if you're making one, with the idealogy to "bully" that's against ToS.
did you not remember me saying "friends"
dont twist it now 😭
So easily stating it in my ToS/Privacy Policy, makes it allowed?
Legal problems in discord bots are the hardest tbh 💀
wording here "bully"
If discord checks that and they approve yes
Nah when i mean bully, i mean like tease, not like actually bully bro
welcome to capatalism
i know i spelt that wrong
Okay so, you don't understand correct english grammar.
no way bro said that while having bad grammar 😭
whilst*
i think if you add a option to disable it and mention it on a server profile or smth if its turned on or not i thing it can work
So basically, if I ask discord, they approve, then im fine?
My bot has some grey area functionality, invite tracking to be precise, but I state that in privacy policy and also the ways to omit invite being saved to my db
That's like the only way to resolve legal issues
Nobody here really knows since we're programmers and not lawyers
cap
You are 100% a lawyer, you showed me your ID.. totally
Well technically
i already state that we store messages
So i should be fine honestly, discord has already verified me, not like they actually fucking read the bots, they are to lazy, but i mean, i do state what i do.
what can i do about this
its been a hour
its a command that is rate limiting you
what command is running a lot?
like example, role add, delete channels, add roles, mass delete roles..?
i ran it after 20 hours
heck if you delete to many messages
its testing bot i dont use it much
Private host is a w ngl
ive never been rate limited ngl
cuz of private vps!!
Well what command is running for a long time?
idk how else I could help without seeing some type of command or saying just add cool down
theres no such command i have basics only
name them.
wait
test:
test
No Category:
av Shows user avatar.
help Shows this message
slap .slap <user>
Type .help command for more info on a command.
You can also type .help category for more info on a category.
these are all
im using github codespace\
thats what i dont understand
of?
is your bot in?
Does that issue occur when using local machine
i didnt try i use only codespace
Fair point..
Do you have ability to test it locally
but i tried to change token and stilll same warning
Because it's IP based
i can try
God knows what runs on gh codespaces
gotcha ill change, thanks
Anyone have the issue of when hosting a bot locally, your ping is 100ms+?
File "/home/container/main.py", line 4, in <module>
import discord, aiohttp
ModuleNotFoundError: No module named 'discord'```
anyone know this ?
did you install discord.py?
how do in req.txt
Might be because you don't respond in 3 seconds
but it works fine for me
If error appears then how can it work fine 
when i run the command it works fine
when my friends runs it
it gives error
it only works for me and my alt
nothing else
Then this is weird since I'd say you don't respond in 3 seconds 
for sure sqlite3 is blocking so I'd consider using asqlite
but how is it working when i or my alt do it not when my friend do it
No idea
you can check the code
this is the code
I did and thats why I don't have idea
pip install discord.py run this in the terminal @slate swan
and what did it output after installing?
try
pip install discord.py --update
pip install -U discord.py
this
do you by any chance have few python versions installed?
what IDE u use?
in the botton there is a panel in there there should be one thing called python beside that should be a version tell that
!dashm
When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.
Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.
Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.
or be specific
yea i guess
python3.12 -m pip install discord.py
uninstall it first tho
this should work yeah
and does it still say ModuleNotFound?
how do you run python file
i mean how do you run it
Could you show the interpreter you’re using?
show the command it runs for you
judging from these screenshots, vscode is running your virtual environment but discord.py was installed to your microsoft store python instead
normally opening the terminal in vscode will automatically activate the virtual environment, but since you're using a separate terminal, you have to activate it yourself before you're able to install packages to the virtual environment: ps1 PS C:\> cd C:\path\to\my_project PS C:\path\to\my_project> Set-ExecutionPolicy Unrestricted PS C:\path\to\my_project> .\.venv\Scripts\activate (.venv) PS C:\path\to\my_project> pip install ...
(if you no longer see the PS prefix you've probably switched from the powershell terminal to command prompt, in which case you don't need Set-ExecutionPolicy)
was that directed for me? If so, It says unknown
Are you using prefixed commands?
im using @tree.command, which has a guild parameter. what i wanna know is how do i set that guild id for it to work with mulitple servers, opposed to just one.
Could you show an example of how you’re using the guild ID?
guild = 0 # The guild ID
@tree.command(name = "join", description = "Joins the selected Military.", guild=discord.Object(id=guild))
also during the on_ready, the tree.sync also syncs it with the guild id
Do you need the ID of every server the bot is in?
id assume so, if im wanting it to work for multiple servers
if you want it to work for every server you don't
have to specify the guild in commands and syncing
so this works, but now all the commands are doubled (the bot is now in two servers)
Quick question i am using buttons inside a cog. How do i run checks to only allow the button to work if the person who pressed it is the same as the person who used the command?
try
bot.tree.clear_commands(guild=None)
and sync after it
discord.ui.View has an interaction_check method
You can pass the author of the command to that view
and compare if user who used the command is the one
who tries to interact with it
in the on_ready?
Usually it's recommended to implement custom
command that sync but if you want to really do
that automatically then consider using setup_hook
Downsides can be ratelimits so if you want to
create a command then consider looking at this
Where can i find the documentation for this if i may ask as i am not to familiar with buttons
Thanks a bunch!

Oh with buttons, here you have some examples:
https://github.com/Rapptz/discord.py/tree/master/examples/views
For the UI docs take this
https://discordpy.readthedocs.io/en/stable/interactions/api.html#bot-ui-kit
Thanks Bud i got it all working now, One thing i couldnt find is there a way to add a custom server emoji to the button?
yeah just add it normally like !pithink
just like how u would add default emojis
I did try that but i got the actual string rather than the emoji
!d discord.ui.Button.emoji u set for this?
property emoji```
The emoji of the button, if available.
you’re going to need to give a lot more information than that if you want a partner
Does anyone know why when i click a button to edit my embed which has new buttons it auto interacts and fails before i can actually use the new buttons
Hi everyone ! I’m 25M, just started learning python last year, currently working on an IT automation course. I’ve been working alone and think I could benefit from some collaboration now. If anyone is willing to mentor me or work on projects together let me know. My goal is to treat this like I’m a junior engineer and do similar tasks/work flows
Show your code
Can i DM it to you if you don't mind?
Why
Am i allowed to send code outside of a help channel?
Yes…
Oh....
Lol alr one sec
Apologies took me awhile never used the pastebin for python lol
The issue i have is when it edits the embed to the 2nd one
it starts an interaction right away which fails
after that it works fine
any good libraries to use for components in my bot?
@trail maple how did u learn py?
Literally every fully fledged wrapper that's half popular supports components
'maximum number of slash commands exceeded 100 globally'?
You can only have 100 slash commands??
That's what it says...
But like, ive seen bots with way more?
You can have more subcommands
Im new to decorators and decided to become familiar with that. Im trying to code a discord bot with interactions.py.
def require_login(func):
async def wrapper(ctx: SlashContext, *args, **kwargs):
# print(args, kwargs)
user_account = await DatabaseWrapper.retrieve_account(ctx.author.id)
if user_account is None:
await ctx.send("You need to login first")
else:
await func(ctx, account, *args, **kwargs)
return wrapper
@slash_command(name="set_profile_picture", description="Set your profile picture")
@slash_option(name="picture", description="Picture you want to set as profile picture", required=True,
opt_type=OptionType.ATTACHMENT)
@require_login
async def my_command(ctx: SlashContext, account, picture: Attachment):
await ctx.defer()
picture_url = picture.url
await ctx.send(picture_url)
I get this error
TypeError: my_command() missing 1 required positional argument: 'picture'
when trying the command.
your decorator basically obliterates the annotations that discord.py relies upon
I've never used interactions.py but I bet it's similar to how you create slash commands in discord.py, read their docs. There must be a way to define checks for a command, rather than doing it through a normal decorator (well, it'd still be a decorator, but done in the discord.py way)
unfortunately, normal decorators and discord.py do not mix well
alternatively, you can use the @functools.wraps(func) function above wrapper to fix this (make it inherit the annotations)
but I do pass all args and kwargs i get from decorators over it
Ill check that out
Thing is, discord.py looks at ctx: SlashContext, account, picture: Attachment and uses it to define the command's parameters. If you give it *args, **kwargs it's just gonna say nah wtf is this? nothing useful here! and no parameters get defined
ohh makes sense
WHy wont it respond to my command
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.messages = True # Add more intents as needed
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'{bot.user.name} has connected to Discord!')
@bot.event
async def on_message(message):
if message.author.bot:
return # Ignore messages from other bots
if 'music' in message.content.lower():
channel = message.author.voice.channel
voice_channel = await channel.connect()
voice_channel.play(discord.FFmpegPCMAudio('https://commondatastorage.googleapis.com/codeskulptor-demos/DDR_assets/Kangaroo_MusiQue_-_The_Neverwritten_Role_Playing_Game.mp3'))
while voice_channel.is_playing():
await discord.ext.tasks.sleep(1)
await voice_channel.disconnect()
await bot.process_commands(message)
bot.run('')
You need the message_content intent
could you please tell me where to place it? 😭
!d discord.Intents.message_content
Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:
• The message was sent by the client
• The message was sent in direct messages
• The message mentions the client
This applies to the following events...
I keep getting error 429
@app_commands.choices() can I check which was chosen by using the value provided?
can someone tell me why my discord bot not registering commands and not showing debug errors aswell -_- im irritated bruh
Provide code
Slash command or prefix?
If slash command then make sure you have invited your bot with applications.command scope enabled and synced commands
If prefix command, make sure you dont have a on_message with @bot.event deco
Yes
Its Choice.value
prefix
import os
from discord.ext import commands
from discord import Activity, ActivityType
import traceback
import discord
# Define all intents
intents = discord.Intents.default()
intents.message_content = True
cogs_to_load = [
'cogs.general',
'cogs.antinuke',
'cogs.autoresponders',
'cogs.errorhandler',
'cogs.fun',
'cogs.moderation',
'cogs.owner',
'cogs.help.cog',
'cogs.music',
'cogs.pythonshell'
]
# Create an instance of the bot with intents
bot = commands.Bot(command_prefix=".", intents=intents)
bot.remove_command('help')
async def load_cogs():
for cog in cogs_to_load:
try:
bot.load_extension(cog)
print(f"Loaded extension: {cog}")
except Exception as e:
print(f"Failed to load extension {cog}: {e}")
@bot.event
async def on_ready():
print(f"Logged in as {bot.user.name} ({bot.user.id})")
print("Bot is ready!")
activity = Activity(type=ActivityType.listening, name=".help")
await bot.change_presence(activity=activity)
await load_cogs()
# CommandNotFound error handling
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
return # Ignore unknown command errors
traceback.print_exception(type(error), error, error.__traceback__)
raise error
# Run the bot with your bot token
bot.run("token")
pls tell me how to fix
-_-
in on_ready event ?
no
wait a sec
in setup_hook
async def setup_hook(self):
self.add_view(Invite())
print(f"Loaded Views For {self.user}")
await self.add_cog(setup.Setup(self))
await self.add_cog(admin_commands.AdminCommands(self))
await self.add_cog(tickets.Tickets(self))
await self.add_cog(ban.Ban(self))
await self.add_cog(warn.Warn(self))
await self.add_cog(usercommands.UserCommands(self))
await self.add_cog(embed.EmbedBuilder(self))
await self.add_cog(hangman.Hangman(self))
print(f"Loaded Cogs For {self.user}")
await self.tree.sync()
print(f"Synced slash commands for {self.user}.")
setup_hook ?
yes
should i add this in main file ?
yes
hm wait
and why the fk cogs a string
cogs need to be a Class
!d discord.ext.commands.Cog
class discord.ext.commands.Cog(*args, **kwargs)```
The base class that all cogs must inherit from.
A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html#ext-commands-cogs) page.
When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CogMeta) are equally valid here.
💀
and you dont even import your cogs so how r you gonna add them
bro i dont think tht's a cog issue i can see terminal output all cogs are getting loaded
And are loaded via load_extension
ik
i import all my cogs and have them import
Cogs are added in setup() function in extension
Yeah I'm explaining that to @fiery girder
Wrong way
@vale wingcan u fix my issue pls?
Yeah in a moment
from handlers import setup
from commands import admin_commands, tickets, ban, warn, usercommands, embed
from handlers.views import *
from games import hangman
``` bruh moment
np thnks buddy
u can use load_extention method to load cogs
"Registering commands", do you mean your cogs contain slash commands?
lol bro
nope its prefix commands
but didnt respondiong to any cmds
Cogs is a way to have bot command sections, on seperate files, and such, they need to be in a class, and loaded on the main bot.py file, and they are loaded on the bot setup hook.
@gray mantle first of all, do not ignore command not found errors
Either respond that such command doesn't exist or log
i am not getting any errors i am debugging my code but terminal not getting any errors
- Check your code, check for errors.
- Check your indentation.
- Is your cog loading?
Second, please show one of your extensions (a small one so I can see what I need)
kk let me show u my one extension
!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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
i need a setup function in my cog and then i just load all the cogs?
yeah
well
Use this, as an example.
https://gist.github.com/pinheaded/ac880263084a65b8d2f769c1fa46a3d7
a basic cog + extension example for discord.py v2. GitHub Gist: instantly share code, notes, and snippets.
Note: if you had all your commands in 1 file, all of your commands will need changing when using cogs, as you need to use self, as at the top of a cog, it needs to bring the bot class in, so the commands work, you will see what I mean in the example
In your extension
can i load a whole package of modules of cogs at once?
you need to define each cog file, in the load part.
Okay extension seems alright, lemme see
Not necessarily, can put them into a dir and just glob through it
Do it in the __init__.py file in your extension folder or something similar 🤷
i alr got the cogs setup but i was actually importing all the cogs and using self.add_cog
hm every time when i switches from nextcord to discord.py that fckin event happens -_-
wdym? my extensions are all loaded by using multiple load functions
self.load_extentsiom
Who would expect that you need to do things differently when changing to a different library
Average dpy experience
Do not, use replit.
@vale wingbro are u on replit ? i can share my whole srccode with u there
That comma
not am using vs rn
for p in Path("./cogs").glob("*.py"):
await self.load_extension(p.as_posix()[:-3].replace("/", ".")
caught me 😂
bruh, someone told me, in this server that you couldn't do that.
I also remember some libs had recursive load_extensions
it says that the load_extension is a corontine
Probably some "recommendation" because apparently "some modules might not need to be enabled" (trust me that never happens with good module management)
wdym
that you need to await it
Ok not in dpy
not the s
!d disnake.ext.commands.Bot.load_extensions
load_extensions(path)```
Loads all extensions in a directory.
New in version 2.4.
Disnake my beloved ☺️
well thank you, because that helps out a tonne.
Ok now to @gray mantle issue
what i do with that fcking dpy bro
!d discord.ext.commands.Bot.load_extension
await load_extension(name, *, package=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Loads an extension.
An extension is a python module that contains commands, cogs, or listeners.
An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.
Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine).
Comment out your error handler
this function is a corountine
that error handler extention ?
@fiery girder you're next on queue wait please ☺️
yes because it needs to awaited.
The event
Here
but he is not awaiting it
i'm not getting any errors
can u give me an edited code ? so i can inspect where i am doing wrong
he is loading them differently to you.
ok anyways
Damn typing code on phone with one eye closed is inconvenient af
I'm losing my brain cells
I coded my entire bot on mobile 
but why tf u are doing that 💀
💀 bro how
by typing on my phone keyboard, funnily enough.
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
cogs = [
'handlers.setup',
'commands.ban',
'commands.embed',
'commands.warn',
'commands.tickets',
'commands.admin_commands',
'commands.usercommands',
'games.hangman',
'games.tictactoe',
]
class Bot(Bot):
def __init__(self):
super().__init__(intents=Intents.all(), help_command=None, command_prefix="!")
self.testing_guild = discord.Object(id=1169236151467511822)
async def setup_hook(self):
self.add_view(Invite())
print(f"Loaded Views For {self.user}")
for cog in cogs:
await self.load_extension(cog)
print(f"Loaded Cogs For {self.user}")
await self.tree.sync()
print(f"Synced slash commands for {self.user}.")
async def on_ready(self):
activity = discord.Game(name="/help | Made By FedxD", type=3)
await self.change_presence(status=discord.Status.online, activity=activity)
print(f"Logged in as {self.user}.")
async def on_command_error(self, ctx, error):````
that code, For me is un readable
from pathlib import Path
class MyBot(commands.Bot):
async def setup_hook(self):
for p in Path("./ext").glob("*.py"):
await self.load_extension(p.as_posix()[:-3].replace("/", "."))
bot = MyBot(...)
@fiery girder @gray mantle solution to your both problems actually. Just make sure to put your extensions into ext directory 😀
And make sure your extensions have
async def setup(bot):
await bot.add_cog(Cog(bot))
At the end
def setup(bot: Bot): bot.add_cog(Setup(bot))
kk let me try
in handlers.setup
Nah it's async since some version
In dpy
hmm isee
You see I got a stupid eye inflammation called chalazion, this annoying mf been interfering with my well being for half a year now and the treatment is somewhat special
I started with mobile coding. This is masochistic compared to normal pc coding
I'm already used to it
👄👁️👄
I can't even wear lens 😭
@gray mantle was your problem solved
How to do double sub?
!d discord.app_commands.Group - the parent argument, set it to a another group
class discord.app_commands.Group(*, name=..., description=..., parent=None, guild_ids=None, guild_only=..., nsfw=..., auto_locale_strings=True, default_permissions=..., extras=...)```
A class that implements an application command group.
These are usually inherited rather than created manually.
Decorators such as [`guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only), [`guilds()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guilds), and [`default_permissions()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.default_permissions) will apply to the group if used on top of a subclass. For example:
```py
from discord import app_commands
@app_commands.guild_only()
class MyGroup(app_commands.Group):
pass
```...
@vale wingbro here it comes this error
you can also load cogs a different way if you wanted.
Reset your token btw
Some just are too afraid to
you kinda just showed your whole token.
Mm are you combining nextcord and discord.py 💀
ik i'll do it later thats a test bot
You're using both nextcord and discord.py?
oh fckin jesus 😂 i didnt noticed
Nextcord isnt good..
Uninstall it
best out of all wrappers is like pycord maybe

Rating of discord.py and forks
1: disnake
∞: nextcord
∞ + 1: pycord
∞^∞: discord.py
disnake is poop
is it good to sync all app command to a single guild first for development than syncing it globally?
I'd just make a completely different bot for testing
but doesnt it take time to sync app commands in discord i heard
That's exactly what we have in Bobux except we have like 10 different bots
It's pretty much instant now iirc 🤷
Any idea how I can fix this error? ```
Traceback (most recent call last):
File "D:\PROJECTS\james-util-bot\bot.py", line 2, in <module>
from discord import app_commands
File "C:\Users\rscdo\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands_init_.py", line 12, in <module>
from .commands import *
File "C:\Users\rscdo\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 51, in <module>
from ..enums import AppCommandOptionType, AppCommandType, ChannelType, Locale
ImportError: cannot import name 'AppCommandOptionType' from 'discord.enums' (C:\Users\rscdo\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\enums.py)```
I've reinstalled discord.py fully
Do you have multiple Discord wrappers installed?
Use pip freeze to see your installed packages and remove the unused Discord libs
oK
thanks alot bro u fixed my issue @vale wing
Try uninstalling discord
nvm I got pycord
Create a venv and install discord.py only

Ok
How to get sub commands in a help command?
From the HelpCommand.send_group_help method you will have access to group.commands
!d discord.ext.commands.HelpCommand.send_group_help
await send_group_help(group, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Handles the implementation of the group page in the help command. This function is called when the help command is called with a group as the argument.
It should be noted that this method does not return anything – rather the actual message sending should be done inside this method. Well behaved subclasses should use [`get_destination()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.HelpCommand.get_destination) to know where to send, as this is a customisation point for other users.
You can override this method to customise the behaviour.
Why is my Cog.listener not working
https://paste.pythondiscord.com/DKTQ
You're overriding your on_message listener by defining a new function with the same name as the function the listener is using
huh?
you can name the function anything as long as you provide the decorater with the function you want
so how is this making it not work
Maybe I wasn't clear, you overrode your on_message listener's function (method)
!e
class A:
def b(self):
print(1)
def b(self):
print(2)
A().b()
@naive briar :white_check_mark: Your 3.12 eval job has completed with return code 0.
2
i got it
Sign
thanks
how to make a command that would work like this:
if subject_code == "0417" and ranses == "w" and paper_number == "2" or "3" and ranyear == "2019":```
i want it to proceed only if all the conditions are accepted
!d discord.app_commands.check
@discord.app_commands.check(predicate)```
A decorator that adds a check to an application command.
These checks should be predicates that take in a single parameter taking a [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure) exception is raised and sent to the appropriate error handlers.
These checks can be either a coroutine or not.
Examples
Creating a basic check to see if the command invoker is you...
here
for appcommand
!d discord.ext.commands.check
@discord.ext.commands.check(predicate)```
A decorator that adds a check to the [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command) or its subclasses. These checks could be accessed via [`Command.checks`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command.checks).
These checks should be predicates that take in a single parameter taking a [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure) exception is raised and sent to the [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error) event.
If an exception should be thrown in the predicate then it should be a subclass of [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError). Any exception not subclassed from it will be propagated while those subclassed will be sent to [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error).
for prefix/hybrid command
you can use these or just make an if statement on the start of your code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
!paste
How suppose i fix this?
@client.hybrid_command(description="Check the status of Minecraft server")
async def minecraft_server(interaction : discord.Interaction, server_ip : str):
server = JavaServer.lookup(server_ip)
try:
status = server.status()
except:
status = "Not found"
try:
latency = server.ping()
except:
latency = "Not found"
try:
query = server.query()
query_name = query.players.names
except:
query_name = "Not found"
embed = discord.Embed(title=f"Server name : {server_ip}", description = f"Status : \n•Online players : {status.players.online}\nLatency : {status.latency}\nServer : \n•Latency : {latency}\nPlayers : \n{', '.join(query_name)}", color = 0xfc9803)
embed.set_thumbnail(url="https://cdn.icon-icons.com/icons2/2699/PNG/512/minecraft_logo_icon_168974.png")
await interaction.response.send_message(embed=embed)```
attributeerror: 'context' object has no attribute
hybrid gets a Context object, not interaction, just rename your interaction to ctx and use ctx.send instead to send messages
K
welcome
I edited to this
@client.hybrid_command(description="Check the status of Minecraft server")
async def minecraft_server(ctx, server_ip : str):
server = JavaServer.lookup(server_ip)
try:
status = server.status()
except:
status = "Not found"
try:
latency = server.ping()
except:
latency = "Not found"
try:
query = server.query()
query_name = query.players.names
except:
query_name = "Not found"
embed = discord.Embed(title=f"Server name : {server_ip}", description = f"Status : \n•Online players : {status.players.online}\nLatency : {status.latency}\nServer : \n•Latency : {latency}\nPlayers : \n{', '.join(query_name)}", color = 0xfc9803)
embed.set_thumbnail(url="https://cdn.icon-icons.com/icons2/2699/PNG/512/minecraft_logo_icon_168974.png")
await ctx.send(embed=embed)```
Unknown interaction error
(error code : 10062)
you should start sending the full error because it's quite vague
an interaction require you to respond within 3 seconds, more than that you get an unknown interaction if you try to send a message, its possible that your lookup/ping method there is more than 3 seconds, so you can use await ctx.defer() before you do the lookup so you have more time to respond
i see, yea i guessed it correctly, you would have to defer first so you can respond longer than 3 seconds
How suppose i use defer on ctx?
await ctx.defer()
And ctx.followup.send()?
no, just use ctx.send
K
im getting some import errors, how do i fix?
depends on the import error
this one
might be software related
it also shows me this when deleted so there could be more
and everyones favorite
undefined variables
ping with answers if anyones got em
ty
oh btw everything was coded in replit and it didn't work and nothing showed up as an error there so when i moved it to vsc to try and debug it more this started happening.
- u have discord.py and nextcord for some reason which is causing some name space conflicts
- as for undefined variables its as python says ctx dosent exist
wait i thought nextcord was compatible with py
no? they are different libraries
nuts
well how about the ctx?
Uninstall the forks and nextcord first
and then add a ctx param
gotcha
so im going to have to rewrite most of my code aint i?
so its not uninstalling
I keep getting 'WARNING: Skipping nextcord as it is not installed.'
even tho it keeps telling me to uninstall discord
Which are you trying to use, nextcord or discord.py
I was going for both, but i didn't know they were incompadible
now i think im too far in
whats the purpose?
why would you use 2 libraries designed to do the same thing
They both cover the entirety of the API. There’s no reason to use both
im an idiot for this but, i didn't know how to make a bot to do what i wanted. i looked up multiple yt tutorials, found some that used discord and others nextcord.
lesson learned
they get out of date quickly too
There's also disnake and pycord
And hikari but we don't talk about that here
Anyways here's the rating of discord.py and forks ☺️
Now i gotta reorg and recode several functions, break out the caffine this is gonna be a long one
I might do a pros/cons about forks
Their features and such
It’s mainly preference for the features
nextcord 
Nextcord and discord.py are pretty similar

Tutorials shouldn’t be a factor in your choice
alright
I’d probably be looking at:
Stability
Implementations of items like components and application commands
Documentation
Ease of use
Stability: Both Nextcord and discord.py are very stable and update quickly
Components/Application Commands: They both have all of discords available items, but have differing implementations
Documentation: Very similar documentation style
Ease of use: Very similar structure with a few large style differences
Could someone please lend a hand by testing the commands of my Discord bot in the server? Feel free to send me a direct message for the invitation. Thank you
Does anyone know any good APIs for gathering cryptocurrency data for usage within a discord bot?
What does “data” entail
Why can’t you just test them yourself
People aren’t really going to join your server and do allat. You’ll have better luck creating an alt and testing with it
like the current rates of cryptocurrency to usd
I want to be able to convert different crypto amounts to usd and different usd amounts to crypto
You can just make a Google search with requests and they have a widget for it
how would I go about doing that?
I have never made a google search using the APIs before
ok so, i am trying to use requests and get if the website exists or not... if the site doesn't exist.. it should send the message Paper not found with ephemeral=True but if the site exists, it should send a embed with ephemeral=False
what seems to be the issue? this seems relatively simple
it doesn't ephemeral
can you show us your code?
give me a sec
You just make a request with the search URL
There’s definitely some API you can find online though
Shouldn’t have to resort to using Google
@sick birch
https://paste.pythondiscord.com/CW2Q
line 96 onwards
oh, this is nextcord. I can't help with that, sorry
isn't it similar?
Not sure. Never used it so I can't tell
What's a good or recommended way to sanitize a users input or message?
Sanitizing for what? Is it going into an SQL query?
No.
it's for the on_message function.
I want to ensure nobody is sending anything that can mess with my bot
how, exactly?
So when someone sends a message in chat.. the bot reads it and sends a message back
if you're asking for "How exactly they can fuck with the bot" - NFI that's why im here.
if there was some string input that could lead to remote code execution just by itself (as in assuming your code isn't bugged), that would be a pretty serious, undiscovered security flaw in the library
I don't think so?
The user messages the bot, and the bot then takes that message and sends it to a channel.
and do you think your code does something poorly while manipulating the user's string?
I just take it and stick it into an embed and yeet it.
Can you repaste it
Safari says it can’t connect
!d nextcord.InteractionResponse.defer
await defer(*, ephemeral=False, with_message=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
_ DEFERENCE _
I love a good deferral
well ig make sure you don't have infinite loops, excessive string multiplication, or whatever, but afaik there isn't a standard procedure to prevent security bugs in any program
huh
So when the embed sends it’s not ephemeral when it should be?
well I guess I'll address any issues when they pop up ¯_(ツ)_/¯
well. anywhere he replies he either has ephemeral set to false or not at all (by default it's false).
Except for line 112
nono.. so i defered the message cuz i was using requests and i wanted it to ephemeral the message "We are sorry, but the paper you are looking for is not available. Perhaps you can try a new search." becuz the page doesn't exist and it returned 404. if it returns 200, then it should send the embed without ephemeral
im having alot of issues importing discord.
I’m aware
And what issue are you having?
im having issues INSTALLING discord
No suitable Python runtime found
Pass --list (-0) to see all detected environments on your machine
or set environment variable PYLAUNCHER_ALLOW_INSTALL to use winget
or open the Microsoft Store to the requested version.
What do i do
It seems the only difference between each of those pdf urls is _qp_ and _ms_ and _in_
Couldn't you just chuck all of them into a dictionary or function somewhere? or something to minimize the need for re-writing the text multiple times?
What command did you run
import discord
class MyClient(discord.Client):
async def on_ready(self):
print("Logged on as {0}!".format(self.user))
async def on_message(self, message):
print("Message from {0.author}: {0.content}".format(message))
client = MyClient()
client.run('my bot token')
File "c:\Users\Usuário\Documents\discord.py\meu_bot.py", line 10, in <module>
client = MyClient()
^^^^^^^^^^
TypeError: Client.__init__() missing 1 required keyword-only argument: 'intents'
why its happening this
im beginner
!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.
py -3.6 -m pip install -U discord.py
discord.py doesn’t support 3.6, but this is a separate issue
First install a supported version, 3.9-3.12
Then we’ll work from there
always the latest version.
i did it says i have 3.12 version when i enter py --list
it is not sending both in the format ephemeral or its sending both
-V:3.12 * Python 3.12 (64-bit)
Okay, but you’re specifying 3.6
So it’s installing into your 3.6 environment, which it says doesn’t exist
imo i suggest using Python 3.11.7 for discord.py, it's the newest version that doesn't have the same package compilation "issues" that 3.12 currently has (although workarounds do exist if you really want 3.12)
i got another problem aa
py -3.12 pip install -U discord.py
C:\Users\Naseer\AppData\Local\Programs\Python\Python312\python.exe: can't open file 'C:\\Users\\Naseer\\pip': [Errno 2] No such file or directory
You missed the -m flag
You need to specify pip as a module or python thinks it’s a file
ngl i want
yh ik
thanks m8
still installing
It’ll error
check.warn(importable)
copying multidict\__init__.pyi -> build\lib.win-amd64-cpython-312\multidict
copying multidict\py.typed -> build\lib.win-amd64-cpython-312\multidict
running build_ext
building 'multidict._multidict' extension
error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for multidict
Failed to build multidict
ERROR: Could not build wheels for multidict, which is required to install pyproject.toml-based projects
you can tack on --extra-index-url https://abstractumbra.github.io/pip/ with the install command, it provides prebuilt wheels just for discord.py's dependencies
Multidict is missing wheels for 3.12, so you can fix it two ways:
Install using umbras wheels: pip install -U --force-reinstall discord.py --extra-index-url https://abstractumbra.github.io/pip/
Downgrade to Python 3.11.7
Two options
or if you don't trust their index but still want 3.12, you can follow the link in that error message to install the C++ build tools yourself
Keep in mind Umbra is a moderator in the discord.py server and a heavy contributor to discord.py
Danny has also recommended using the wheels as a fix, so he trusts them
C:\Users\Naseer>pip install -U --force-reinstall discord.py --extra-index-url https://abstractumbra.github.io/pip/
'pip' is not recognized as an internal or external command,
operable program or batch file.```
Prefix it with what you used to install discord.py before
You’ll receive help if you share the issue
That did install discord
sqlite3 is installed by default, but you’ll want to use an asynchronous version
asqlite can be installed from GitHub
from discord import Color, Embed, Message
from discord.ext import commands
import config
class Context(commands.Context):
async def neutral(
self, content: str, color: int = config.Color.neutral, emoji: str = "", **kwargs
) -> Message:
return await self.send(
embed=Embed(
color=color,
description=f"{emoji} {self.author.mention}: {content}",
),
**kwargs,
)
from discord import Embed, Color
from discord.ext.commands import Cog, Command, Group, command
from time import time
from helpers.rogue import Rogue
from helpers.utilities.human_timedelta import human_timedelta
from helpers.variables import colors
from helpers.managers.context import Context
import config
class Information(Cog):
def __init__(self, bot : Rogue):
self.bot: Rogue = bot
@command(
name="uptime"
)
async def uptime(self, ctx: Context):
"""
View the bot's uptime
"""
return await ctx.neutral(
f"**{self.bot.user.display_name}** has been up for: **{human_timedelta(self.bot.uptime, suffix=True)}**",
emoji=":alarm_clock:"
)
class Color:
neutral = 0x5f9ea0 # cadetblue
approve = 0x9acd32 # yellowgreen
deny = 0xdc4747 # failurered
warn = 0xffa500 # orange
class Emoji:
approve = "✅"
deny = "❌"
warn = "⚠"
when i run my bot, and run the uptime command, why do i get this error?:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'neutral'
my file tree (rogue.py stores my bot class, main.py runs it):
simple thing is the discord donot returns that Context it returns the normal commands.Context
did u override get_context?
class MyBot(commands.Bot):
async def get_context(self, message: discord.Message, *, cls=CustomContextHere):
return await super().get_context(message, cls=cls)
I organize my commands in cogs inside of a "cogs" folder and then loading them automatically using the code bellow but, if I wanted to separate my cogs in folders inside of the cogs folder. Would this way I'm using go through each folder inside of the cogs folder and load each .py file inside correctly?
@bot.event
async def on_ready():
for cog_file in settings.COGS_DIR.glob("*.py"):
if cog_file.name != "__init__.py":
await bot.load_extension(f"cogs.{cog_file.name[:-3]}")
tysm
yes given ur path and loops are set correctly ultimately ur just required to pass in the path to the cog file relative the root directory where the bot is in
You haven't separated the values in the list with a comma
app_commands.Choice(name="⭐️", value="one")
Is one element and app_commands.Choice(name="⭐️⭐️", value="two") is another element. Since they're in an array each element here needs to be separated by a comma
thanks
Hi, it's been a few days since python reads me anymore the fivem library, can anyone tell me how to do it? I redid the "pip install FiveM" but it doesn't work anymore
!pypi fivem
what exactly dosent work and how?
in terminal run
py -0
PS C:\Users\stefa\Desktop\BotPython\Bot\botiii> pip install fivem
Requirement already satisfied: fivem in c:\users\stefa\appdata\local\programs\python\python311\lib\site-packages (1.1)
Requirement already satisfied: requests in c:\users\stefa\appdata\local\programs\python\python311\lib\site-packages (from fivem) (2.31.0)
Requirement already satisfied: charset-normalizer<4,>=2 in c:\users\stefa\appdata\local\programs\python\python311\lib\site-packages (from requests->fivem) (3.2.0)
Requirement already satisfied: idna<4,>=2.5 in c:\users\stefa\appdata\local\programs\python\python311\lib\site-packages (from requests->fivem) (3.4)
Requirement already satisfied: urllib3<3,>=1.21.1 in c:\users\stefa\appdata\local\programs\python\python311\lib\site-packages (from requests->fivem) (2.0.4)
Requirement already satisfied: certifi>=2017.4.17 in c:\users\stefa\appdata\local\programs\python\python311\lib\site-packages (from requests->fivem) (2023.7.22)
hey guys, is there any way to make error handler for all commands in Group?
this is a error @shrewd apex
are you able to run the bot?
no
whats the traceback u get when running it
It won't let me start, and that's the error that comes out
PS C:\Users\stefa\Desktop\BotPython\Bot\botiii> & C:/Users/stefa/AppData/Local/Programs/Python/Python311/python.exe c:/Users/stefa/Desktop/BotPython/Bot/botiii/HADES[RP].py
Traceback (most recent call last):
File "c:\Users\stefa\Desktop\BotPython\Bot\botiii\HADES[RP].py", line 26, in <module>
from fivem import FiveM
ModuleNotFoundError: No module named 'fivem'
PS C:\Users\stefa\Desktop\BotPython\Bot\botiii>
Have you installed it?
What do I need to install?
Whatever you’re trying to import
Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.
To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)
Then, to activate the new virtual environment:
Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate
Packages can then be installed to the virtual environment using pip, as normal.
For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.
Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.
Note: When using PowerShell in Windows, you may need to change the execution policy first. This is only required once per user:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
Although the path of packages and py executable seems the same it's likely cause of path issues
this question is better suited for #1035199133436354600, but i dont think you have the right project because that package doesn't declare any FiveM class, as per their source code
the hours= parameter in your loop is set to 23, did you mean to write 24?
Is there someone that is good with / command and using discord.py that could guide me on how to make my bot and help me if I struggle on things here pls ?
well if they trigger at the same time asyncio event loop will simply run both tasks concurrently
also if you happen to be using discord.py>=2.0, there's a time= parameter which lets you specify one or more datetime.time()s to run the loop on
discord.py is well known in this community so there's likely someone that can answer when you ask here
Okay, why the documentation is bad ?
And do you know how I could make simply a leaderboard command for my EXP system (it's made) but with buttons to change the pages of the leaderboard
I struggle with the buttons
if by bad you mean why aren't there official guides on slash commands, iunno, their dpy guide has been in development for a while now (see Rapptz/discord.py#7654 )
regardless there are official examples on the dpy repository, and third party guides to them:
https://github.com/Rapptz/discord.py/tree/v2.3.2/examples/app_commands
https://fallendeity.github.io/discord.py-masterclass/slash-commands/
Ty
well, if you start at 12AM and then sleep 23 hours, the next iteration is going to be at 11PM
I will read that when i'll be rested a bit
good afternoon everybody
When you DM a bot, it will contact the server moderation team, in that server.
via, a private channel, Or something similar
oh i gotcha, so if im createing a bot for my server thats a probably a good feature to install eh? sounds easy
yeah, it's a good thing to make, as long as it's hosted all the time, for your server members.
it can be a good project to work on too
it is. yea thats what im thinking. dont sound too difficult. i dont know anything about bots recieving dms but probably just sent it up so if anyone sends a dm to that bot it posts a message in the mod channel?
A good modmail feature is slightly harder than you think
bro hello world was hard for me hahah, but it doesnt sound out of my league is what i meant. not like some of the stuff that gets talked about in here. completely over my head
Steps:
Once the user DMS a bot, enter a confirmation code, and then once confirmed to contact the mods, send a message as To who you would like to report, reason, user ID, etc, and send that message, to a channel, and lay it out nicely with an embed.
and make the bot return a confirmation message, with a report ID, that can be used to refer To, as the reporter, Or admin etc
i dig it, thanks bro. i screenshotted and will use that as my blueprint
print("hello world")```

hahaha i overexaggerated slightly but you got my point haha
It doesn't resolve
If you need anymore help, I would gladly assist with any questions you have.
I mean, this is just opinions. I prefer a simple forum channel lol
He wanted a mod mail, discord bot.
like:
thanks bro. i have some other things i want to do first but i added it to my list. i just finished some giveaway commands and going to work on history comamnds.
seems like more work
yes, but it's more organized
true
whatchat mean forum channel? i saw the mailbot and was curioous what it does. but definitely need some sort way to message the mods i assume, for my server
there's also the git repo you can check out, but at a glance their source code is quite complex
https://github.com/python-discord/modmail
their readme has a summary of what it does:
When a member sends a direct message to the bot, Modmail will create a channel or "thread" into a designated category. All further DM messages will automatically relay to that channel; any available staff can respond within the channel.
that's a valid point
my modmail needs database stuff and everything (source code for context)
That's why I said modmail is slightly less easy than it may seem haha
git repos confuse me haha
i tried look at sir lancelot code and cant even figure that out hahah
any codebase is hard to tackle all at once, but you can try focusing on one feature at a time when you're exploring their source
regardless you have a lot of ways to implement a modmail, so have fun with it
thanks!
What doesn't resolve? You made the venv?
I can't install Venv
Why
We agree that to make a discord bot I dont need anything else than VS code, I don't need something like django or else ?
@vale wing is this tutorial a bit too old
https://www.youtube.com/watch?v=4EIy0bw7s-s
Welcome to the updated discord.py series - the series where I teach you how to build a discord.py bot for your server! Below are some links to get you started.
Series requirements can be found here:
https://files.carberra.xyz/requirements/discord-bot-2020
You'll also need an IDE; I use Sublime Text in this series:
https://www.sublimetext.com/
...
Django is web framework, completely unrelated
that's what i thought I don't know the frameworks tho
To develop a discord bot in python you need python interpreter >=3.9 or smth I forgor what libs support
Vscode is merely a code editor
If you are skilled enough you can use notepad
And actually if you're skilled enough
Nvm I thought of something so epic matrix servers exploded
(discord.py, disnake, nextcord, and pycord still support 3.8 too, though it'll be EOL in 10 months)
Anyone know a good spot to just see a lot of idea commands based on Presence Intent?
Is it possible to edit things on my own account with a bot?
Is it possible in general?
I forgot how much you can fit into a single embed description lol.
quite a lot it turns out.
can you do that so the bot also posts a picture? without a url tho, like the user just drops and drags?
There's 2 ways I know of to do that. Grabbing the image URL and sending it as an embed image
Or doing that discord file download thingy.
discord file download? is that how we just click and drag for images to create forum posts? not having to upload and get a url first would be preferred
Using a discordbot, the only 2 ways I know of how to send an image a user has sent is to either temporarily download it and send it, or to grab the image URL and send it as part of an embed
there may be other better more ideal ways
ok let me clarify tho, my original question was about bot the modmail bot and the one guy let me know they can also create forum posts. well i want to adapt that for commands to create forum posts which wold be added to a database for some other reasons. so it wouldnt be through dm if that makes a difference, it would be though commands. can i add an image that way, the same way if i was just doing it?
I've never worked with forum posts, most servers I operate within refuse to update to include forums, mostly coz their communities cannot be trusted..
So I dont know specifically how forums work, I would assume they work the same as any channel and you just need a channel ID and you can send to that specific channel.
As for the rest of what you said, it confused me so I didnt comment on it lol
lol..... i dont want to have to upload an image before posting, but i think you already answered my question. i just need to research the discord download thingy and see if that is what im talking about
thank you so much for you help!!
you know when you doing commands and if an option is channel, it shows up with all the channels, how do you that with custom options? like if the option was sport, how do i get the pop window to show the different sport names instead of having to write it in?
Annotate the argument with GuildChannel
If you want a text channel specifically you just annotate it with TextChannel
hi there i want to use choices in slash commands but the choises are in database how to make the bot get the choices and add them to the command
use autocomplete
thx for helping
how to define?
define what?
satureafkon
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'satureafk' is not defined
make command with that name then
no
@bot.command()
async def satureafkon(ctx):
...
u should probably do through the documentation
mm
@discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.
The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) you receive and the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button) being pressed.
Note
Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button) manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
Nextcord good
eh nextcord is a copy paste of discord.py when it comes for button/view implementation, without the newer discord.py's features within view and probably still have the view memory leak problem
Is there any thing that nextcord does better than discord.py? 
In my humble opinion no, they're mostly the same lol
Only pet peeve for me is that a Cog.cog_(un)load method(s) can't be async in nextcord
Plus (afaik) nextcord doesn't have the new discord.ui.DynamicItem class (unsure)
while being rate limited. we get token ratelimit or ip ratelimit?
or its the same thing
token its bot based
@t.command(name="balance", description="Check your current balance.")
async def balance(interaction, member: discord.Member = ):
how do i make the member argument optional?
discord.py 2.3.2
set default value to None
it says
Expression of type "None" cannot be assigned to parameter of type "Member"
Type "None" cannot be assigned to type "Member"
this is only a typing error but if you wanna fix it you can annotate it as union of Member and None
Assalamun Alaykum Warahmatullahi Wa Barakatuhu
I know that it probably is some stupid issue from my side but when i run my discord bot it just simply says that there is no module called discord.
This is what i have imported so far: discord.py, discord.ext and requests
Thanks in advance for any help 😀
what is the coding to avoid chat spam?
Sorry i didnt understand what you meant?
import discord.py
from discord.ext import commands
import requests
Is this what you mean?
Anti spam code
Ohh nvm i thought you meant something else
!custom-cooldown
Cooldowns can be used in discord.py to rate-limit. In this example, we're using it in an on_message.
from discord.ext import commands
message_cooldown = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user)
@bot.event
async def on_message(message):
bucket = message_cooldown.get_bucket(message)
retry_after = bucket.update_rate_limit()
if retry_after:
await message.channel.send(f"Slow down! Try again in {retry_after} seconds.")
else:
await message.channel.send("Not ratelimited!")
from_cooldown takes the amount of update_rate_limit()s needed to trigger the cooldown, the time in which the cooldown is triggered, and a BucketType.
That’s really not enough information to understand what you want
Run py -0 and show the output
Alr one moment please
It says the command py does not exist
if i defer and interaction the time i answer the interaction do i do interaction.response.send_message or interaction.followup.send
You can only respond to an interaction once
Which OS are you using
so i followup to it ?
Yes
ok thanks
Windows 11
Can you show the entire error
is it worth switching to python 3.12 for discord bot coding?
It would be better if i showed you the "error" that shows up when trying to install the discord module: https://paste.pythondiscord.com/BBHQ
everytime I try pip install discord.py it gives this error:
ERROR: Failed building wheel for multidict
Failed to build multidict
ERROR: Could not build wheels for multidict, which is required to install pyproject.toml-based projects``` any fixes?
pip install -U --force-reinstall discord.py --extra-index-url https://abstractumbra.github.io/pip/
@livid roost @stray cliff
thanks! worked
Thank you it worked
that depends on how badly you want the new features
depends on the features lol
I'd read up on the 3.12 changes then if I were you
nah i prefer watching a vid on a features
any of you fimilar with Merriam-Webster dictionary api
i want to make a defind function but i dont know which list have the synonyms and its a huge json mess
Then find it yourself
yea i will
whenever i run the avatar command,
async def avatar(self, ctx: Context, *, member: Member | User = None):
member = member or ctx.author
gif = member.avatar.with_format("gif") if member.avatar.is_animated() else ""
jpg = member.avatar.with_format("jpg")
png = member.avatar.with_format("png")
webp = member.avatar.with_format("webp")
return await ctx.send(
embed = Embed(
title=f"{member.name}'s avatar",
url=((gif if member.avatar.is_animated() else png) or member.default_avatar),
description=f"[[jpg]]({jpg}) [[png]]({png}) [[webp]]({webp})" + ((f" [[gif]]({gif})") if member.avatar.is_animated() else "")
).set_image(url=(member.avatar or member.default_avatar))
)```
and i dont supply a valid member from the server, it gives this error:
```discord.ext.commands.errors.BadUnionArgument: Could not convert "member" into Member or User.```
how can i handle this and return an error message with ctx.send()? i've tried some stuff but it always returns the same error
Do you know how to create command specific error handlers?
no i don't
i thought for this one it would be better to make a specific error? since i want to make it say something like "could not find user or id" and not something general just for that error
!d discord.ext.commands.Command.error
@error```
A decorator that registers a coroutine as a local error handler.
A local error handler is an [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error) event limited to a single command. However, the [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error) is still invoked afterwards as the catch-all.
Changed in version 2.0: `coro` parameter is now positional-only.
ahh thanks
What you usually do is to have 2 views

