#Basic Pycord Help (Quick Questions Only)
1 messages · Page 76 of 1
guild_only
its that simple?
;3
lol ty
what will that return as a default message if the user tries executing the command nonetheless in dms?
because currently I get this (in dms)
refresh your client
guild_only will make it not show at all in DMs
If I make a change to the code and then run this command, the change is not reloaded so I still have to restart the bot completely. Why is this?
@bot.command()
@commands.is_owner()
async def reload(ctx, cog):
try:
bot.reload_extension(f'cogs.{cog}')
await ctx.send(f"Reloaded {cog}!")
except Exception as e:
await ctx.send(f"An error occurred while reloading {cog}: {e}")```
Hello, all the commands in my bot use @slash_command(), but I need them to also be usable with a prefix. Does anyone know how I can achieve this without having to create two separate commands?
Concept
Ah ok
Hi! Could you tell me, how to make a bot react to pressing any buttons?
how do you define the bot and the command?
ok i have a feeling this is related to the bad slash command sync implementation. what happens if you resync the commands after reloading
just as a test
react? as in add a reaction to the message?
or run some code?
subclass bridge.Bot
wait hold on
why do you have bot = bridge.Bot() but also have a subclass??
use only 1 bot instance
?tag client
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
bridge.Bot has all the features of the rest of the client classes
i tried with bot = Bot() but i get the same error, i don't understand very well
if you dont have any custom methods or stuff, avoid subclassing.
copy all the parameters from the super().__init__(...) into bridge.Bot(...), and delete the subclass
also, show the full error
did you import from discord.ext.bridge import bridge_command in the cog file?
Yes, I did it, I imported it like this, I received the same error. Maybe if I change the definition of bot, I can solve the problem.
not really. the problem seems to be in the cog, not the bot
can you show the full cog
What do you mean exactly?
reloading is perfectly functional above v2.2 or so
idk if you are aware, but if you unload the cog, the slash commands still work. that is until you call await bot.sync_commands()
this is because unloading the cog (somehow) doesnt remove the cmd from the internal bot cache
now i think reloading will be affected by this too. the old command wont be affected
sync isn't the issue here
...i think anyway; reloading doesn't need to resync or anything since it just needs to remap command objects to their IDs properly
Why does it not work if I add an await ctx.send("Test") to a command and then reload and execute the command again, the text does not appear?
is this for prefix commands?
I have an embed with a button and I change something in the button and it is not applied, even if I set the embed again, e.g.
prefix or slash command?
i don't think you can reload view callbacks(?)
prefix
||fk i was helping thinking it was about slash cmds đ||
nope. ive tested this. cant
well tbf they never specified
but yeah, cog management is limited to commands and listeners
Okay. I thought with this if I make a change or extension to a cog I can completely reload the cog so I don't have to completely restart the bot but apparently I was thinking a little too far đ
i think if you put the view in the same file as the cog, you might be able to do it. try this and see
because you can have commands in extensions without cogs, and still be able to reload them
so views should work like that too
probably not, the code itself never references ViewStore so the items are never updated
oh yeah, the existing view wont change, but futures ones should
oh yeah ofc
Is there a way to completely reload an existing cog when making an extension or adding a completely new cog to the bot without having to completely restart the bot ?
you can't
guild_only applies only to the root command, which subcommands inherit
(because discord doesn't actually treat subcommands as commands)
the same applies to stuff like nsfw and default_permissions
so if /logging setup is my (entire) command I needa do it for the logging part
yes
I no longer get any errors and the slash command works fine but I try to use the prefix command and nothing happens
ok first part is nice. can you show the parameters you pass to bridge.Bot() once again?
So i created a reload command that should reload an extension with bot.reload_extension(), and i tried to change the message the bot send as response to a command (this is located in a yml file) but it doesn't update. Any idea? Also it looks like it updates only if i change something in the cog.
There is like a way to force it?
I didn't change anything, I just changed the import, that was the error I had
do you load the yml file inside the bot file or the cog
for get the info of the yml file i use a function created in another file and import it into the cog
hmm can you show the cog file code?
whole?
well, omit any unrelated commands/functions i guess
also, do you cache the contents of the yml file, or do you re-read it in the function?
its painful my subcommand is pretty much a mess so uh this gonna take a while ig
it's get_commandsinfo?
yeah if i restart the bot it works
it updates the message in the yml file it updates it if i restart
but if i reload it doesnt
well i mean, it should work even with cog reloads
but the other function would also help
def get_commandsinfo(command, key):
if command and key == "prefix":
return commands["commands_prefix"]
elif command and key == "answer":
return commands["answer_command"]
else:
return commands[command][key]
what's commands?
with open("configuration/commands.yml", 'r', encoding="utf-8") as file:
commands = yaml.safe_load(file)
hmmmmmmmmmmmmmmm
that's probably the issue, reloading has some conflicts when it comes to imports
if you reload a cog, if you've updated a file that it imports the updated file doesn't actually apply
i read somewhere it was working perfectly so i thought about implementing it lol
iirc you can get around it through some hacks
where is this btw?
you could just load the yml in the cog init
in utils/config_parser.py
yeah that's the more reliable way
i decided to it this way for don't have duplicates over the files yk
hmm yea that file isnt being reloaded. so the yml isnt being read again
i have found 2 problems in pycord in a day lool
well the method i recall finding was
what i would do is, store commands as a botvar, and then add a utility function which reloads this var. personal choice however
- reload cog
- use
importlib.reloadto reload the imported function - reload cog again
sounds overkill? đ
it's not a particularly pretty method but it works, though i recommend just restructuring your code
so just import the yml file in the cog?
inside its __init__
that way, whenever you reload the cog it's guaranteed to load the new file
gotcha
if you want to restructure, instead of all these imports py from utils.config_parser import (get_commandsinfo, get_consolelogsinfo, get_optionsinfo, get_serverinfo, get_ticketpanelinfo)you should make that into a class that implements all those functions
then this class' init can take the yml file
and then the cog will load this single class instance which you can always reference py class TicketCommands(commands.Cog): def __init__(self, bot): self.bot = bot with open(...) as file: self.data = SomeClass(yaml.safe_load(file))
How in gods name was I supposed to get on this?
this is what made my subcommand part work (guild only, so it doesnt respond in dms)
But the documentation ab it is realllllllyy bad tbh.
class logging(discord.Cog, description='Logging commands.'):
logging = discord.SlashCommandGroup("logging", "Logging related commands", guild_only=True,
default_member_permissions=discord.Permissions(manage_guild=True))```
not really? the examples already show that
Here's the slash cog groups example.
i need to change how i get all the data, i want to cry xD
nah not particularly
if you go with a class structure, then after you've got the class you can just do some basic replaces
thanks
also as now i get the yaml file inside the cog i need to change the path i guess?
e.g. with my example above, get_commandsinfo becomes self.data.get_commandsinfo (though you may consider renaming the functions)
if you lead it with a / then the path will start from your main bot file
so it can remain relative
actually i think it always works from main file anyway?
@cyan quail a friend of mine (which helped me find out abt it; still doesn't particulary like it... cough
at least from what my own code is doing, idk just give both a try
idk seems pretty obvious to me
and all the attrs and methods are listed
unfortunately people are utterly incapable of reading docs, but that's their problem in the end
anyway @cyan quail maybe can you report the thing about the relaod?
hm?
reloading cogs or what?
you could make a github issue, but the problem with imports inside a cog is that they aren't particularly easy to handle
the importlib trick i mentioned probably works but it isn't really a good fix
hi, sorry to disturb, I dont understand how can I moove pepoles from a channel to another, could someone explain it to me please?
Objects: Attributes average_latency, channel, endpoint, guild, latency, loop, session_id, source, token, user. Methods async disconnect, def is_connected, def is_paused, def is_playing, async move_...
ty buddy
Hello again, i fixed the problem about @bridge_command(), but now there's a problem with the args.
@solemn idol here you can see it again with requests x3
pls dont use requests and use aiohttp instead
I know, I just fixed my own fun cog with basically /meme and /dog /everythingelse
and realized its much faster
like seriously usually it took like 2 seconds to load or smth idk now its just 250ms
ye because its also blocking the whole bot
ok, thank you, i'm just testing
If it takes like more than 1 minute to load the bot will not work at this time xd
try using @option decorators
wait no thats bridge
I am not sure if that works with bridge
yeahhhhh
async def create_embed(self, api_endpoint: str, footer_text: str):
async with aiohttp.ClientSession() as session:
async with session.get(api_endpoint) as response:
content = await response.text()
data = json.loads(content)
em = discord.Embed(
title=data['title'],
url=data['postLink'],
color=em_default
).set_image(url=data['url']).set_footer(text=footer_text)
return em
Which is why I am glad I did it like this
it does ^^
I literally didnt have to rewrite any of my other commands, just that function :P
@copper pine then I guess use @option decorators :P
How can I do that?
can you show the full error
you might need to use BridgeOption with bridge commands
uh thats not public iirc
oh it converts Option to BridgeOption automatically
yea
can you remove description= and see if that works
i think typehinting the Option doesnt work for bridge commands 
Because the error makes it look like the library is trying to convert the parameter to Option type, rather than str
if this doesn't work, try using @option
Correct, the command works, but it wouldn't have a description :/
hi, how do i set the correct error type?
async def on_application_command_error(ctx: discord.ApplicationContext, error: discord.DiscordException):
if isinstance(error, discord.ext.commands.has_role(110475336766700445)):
await ctx.respond("You are not allowed to use this command!")
else:
raise error # Here we raise other errors to ensure they aren't ignored```
no just remove exactly what i put
you can leave the actual description text as positional
you did Option(str, "description")?
what are you trying to do here?
if isinstance(error, discord.ext.commands.has_role(110475336766700445)):
commands.MissingRole
That works, thanks
Yes, if I do it that way the prefix command wouldn't work.
so only prefix breaks and not slash?
Yes.
The solution would be not to give a description to the argument :/
@client.bridge_command()
@discord.option("text", description="")
async def test(ctx, text: str):
that also should work with bride commands
Yes!!!! it works
Thank you so much
I'm a bit confused as to when to use guild.members vs guild.fetch_members()? I understand that the first is a cache, but if it is the first time it is access will it call back to the api?
what would be the best way to get all the members of a guild that do not have the @Guest role?
no. the first call to guild.members does not fetch them from the api. it is filled from the data received from the discord when the bot connects to the gateway
iirc, fetch_members does not have role data
ah...
and fetch_members is quite slow, especially with large guilds
yh i can bet (it being a direct api call for all members)
you could use a list comprehension
use guild.get_role(id) to get the role, and then do smth like [m for m in guild.members if role not in m.roles]
i was using a set comprehension but i didnt know the best actual method to call
{OptionChoice(name=f"@{member.name}", value=str(member.id)) async for member in guild.fetch_members() if not member.bot and guest_role not in member.roles}
if the guild is large definitely don't use fetch_members in autocomplete
will this still get all the members (still a bit confused about how the cache works)
by default more or less all your members will be cached
you can check this by printing len(guild.members)
if you wanna get a bit technical,
when chunk_guilds_at_startup is set True (True by default) in the Bot init, and members intent is enabled, then the library requests members data for each guild during startup. this data comes from the gateway, and not the api. this data is cached.
How can I create a new iterable when a slash command is used, to use in an autocomplete in that slash command? I want to get records from a database when the slash command is used, then present those records for the user to select one. Itâs an online database so currently itâs doing a records GET with each call of the autocomplete, hardly ideal
either way you should store the results in a variable outside of autocomplete, but two refresh methods:
- use
tasks.loopto refresh records periodically, so your autocomplete doesn't have to - let it refresh inside the autocomplete, but have a cooldown/check to see if it needs refreshing again
you could also use an LRU cache
hi yes im stupid, how do I get interaction.response.edit_message
to actually edit the message with new text?
content="xyz
thank you
Hi guys, I'm struggling right now with TortoiseORM running on my Bot in my cogs. The init in my main.py is working but the slash command gives me some ```tortoise.exceptions.ConfigurationError: default_connection for the model <class 'src.mako.db.models.DiscordGuild'> cannot be None
following up on the cooldown idea: it's pretty much impossible that the record set will change while the user is typing (it is selecting from a list of records they created themselves) - what kind of cooldown/check do you mean? perhaps I'm misunderstanding how autocomplete works, I sort of assumed it was called every time the user changes the input (adds or deletes a character?)
it's not every time, iirc discord will wait a second or two before calling it again
so if someone's typing out a full word it won't be spammed
but basically, lets say you have a var self.records = {}
in your autocomplete, you check if this has anything in it; if not, make the request and set self.records = ...
then you also record the current utcnow() in some other variable
with that current time, in your autocomplete you should also compare the current utcnow() with the previous utcnow() and see if a certain time has passed
e.g. via datetime.timedelta
and self in this case is... the class instance of the slash command?
well i was speaking in a cog context
if you aren't using cogs it'll still work without self
no cogs, am rank amateur
is there not even a single way to use the built in help command stuff to make a /help command...?
@commands.cooldown(1, 120, commands.BucketType.user)
@option("beg_method", description="Choose your beg method", choices=["Normal beg", "Super beg", "Advanced beg"])
@bot.slash_command(description="beg for money")
async def beg(ctx, beg_method: str):
why is it not letting me choice and wants the user to write it themselves does not display the options
Create a thread for this. Share the model and command where you use it. I'll check it out after waking up tomorrow
you could use bits and pieces, but it's built around prefix commands so no
I once thought of it, but it has heavily centred around prefix stuff lol
@errant crane has an interesting help command if you wanna poke at it https://github.com/Dorukyum/Toolkit
anyone
Option and cooldown decorators go below the command decorator
o
The command decorator is to be kept at the top
hmm
its a bit overcomplicated in my opinion but at the same time it does look nice... as in the code itself... my code on the other hand is an absolute mess rn.
You don't want to see my moderation cog đ
cough
It works but it is not done as well as it should've been done.
Just create one cog for every command xd
at that point you might yeah but my cogs are my categories in my current /help command soo uh
Do you use buttons?
How can i close for example session when my bot is stopped, so that i wouldn't get RuntimeError: Event loop is closed Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001B5A2E2CA60>
No- But I might for my next generation help command.
Hello! I've only recently gotten into âpycordâ. I'm frustrated with being asked by my supervisor to develop a Discord app using âpycordâ. This application requires the user to play an uploaded video or an RTSP video stream, and the video stream frame can be obtained on the server side for reprocessing. I want to know whether some components can meet such requirements and hope to get a simple guide.
what is an RTSP video stream?
#998272089343668364 message
can u pls answer
@dapper pasture let's make a new post. I have a feeling this will take some time.
k
@atomic slate If you mean a Discord "Stream" in a voice channel, that is currently not possible with bots.
similar to a live video
Also, Pycord is a Discord API Wrapper, meaning that it can help you view/interact with Discord. If you are looking ways to manipulate video data you might be looking for FFMPEG: https://ffmpeg.org/ or Pycord, an FFMPEG wrapper: https://pypi.org/project/pycord/.
You can get attachments on messages with message.attachments.
I'm not sure what you mean.
Thanks, I need to think carefully.
(if you somehow do mean over discord's voice channels, bots can't access the video API for those so you'd be out of luck anyway)
fabulous, that makes much more sense thank uuuuuđ
Is autocomplete just so confusing or am I pissing myself because it seemed confusing af when i first looked at it
If the checks of a MessageCommand fail, will it prevent it from even showing in the apps context menu list? or will it just prevent it from executing?
e.g. i am currently trying to get the "value" https://docs.pycord.dev/en/stable/api/application_commands.html#discord.AutocompleteContext.value
but i have no goddamn idea how since if i just do "value" it says its missing required positional arguments
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
nvm, i figured it out
The docs are REALLY bad at portraying that IMO
the value is an attribute of the interaction
What r u trying to do?
Question, tried some searches but couldn't find a similar issue. I've installed pycord, but PyCharm doesn't seem to be recognizing 'discord' as an alias for pycord.
So when I start with import discord, I get an error saying no module named discord despite pycord being installed. Any ideas?
Can you show us your pip list?
It might be that you had discord.py before and it interferes with pycord
Or that the version is just extremely buggy
So I'm not using a venv as im just testing this locally before I deploy, so please don't judge... but...
abstract_singleton==1.0.1
aiohttp==3.8.4
aiosignal==1.3.1
anyio==3.6.2
astroid==2.15.4
async-generator==1.10
async-timeout==4.0.2
asynctest==0.13.0
attrs==22.2.0
auto_gpt_plugin_template==0.0.3
autoflake==2.1.1
beautifulsoup4==4.12.2
black==23.3.0
bleach==6.0.0
blis==0.7.9
build==0.10.0
cachetools==5.3.0
catalogue==2.0.8
certifi==2022.12.7
cffi==1.15.1
cfgv==3.3.1
chardet==5.1.0
charset-normalizer==3.1.0
click==8.1.3
colorama==0.4.6
confection==0.0.4
coverage==7.2.3
cssselect==1.2.0
cymem==2.0.7
dill==0.3.6
distlib==0.3.6
distro==1.8.0
dnspython==2.3.0
docker==6.0.1
docutils==0.19
duckduckgo-search==2.8.6
en-core-web-sm @ https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.4.0/en_core_web_sm-3.4.0-py3-none-any.whl#sha256=35365d49d389ecb19ba33119dca9ab9ff80b36fbeb063fa5d44008197fead8fa
exceptiongroup==1.1.1
ffmpeg-python==0.2.0
filelock==3.12.0
flake8==6.0.0
frozenlist==1.3.3
future==0.18.3
gitdb==4.0.10
GitPython==3.1.31
google-api-core==2.11.0
google-api-python-client==2.86.0
google-auth==2.17.3
google-auth-httplib2==0.1.0
googleapis-common-protos==1.59.0
gTTS==2.3.1
h11==0.14.0
httpcore==0.17.0
httplib2==0.22.0
httpx==0.24.0
identify==2.5.22
idna==3.4
imageio-ffmpeg==0.4.8
importlib-metadata==6.6.0
iniconfig==2.0.0
isort==5.12.0
jaraco.classes==3.2.3
Jinja2==3.1.2
jsonschema==4.17.3
keyring==23.13.1
langcodes==3.3.0
lazy-object-proxy==1.9.0
loguru==0.7.0
lxml==4.9.2
markdown-it-py==2.2.0
MarkupSafe==2.1.2
mccabe==0.7.0
mdurl==0.1.2
more-itertools==9.1.0
multidict==6.0.4
murmurhash==1.0.9
mypy-extensions==1.0.0
newsapi-python==0.2.7
nodeenv==1.7.0
numpy==1.24.2
oauthlib==3.2.2
openai==0.27.2
openapi-python-client==0.14.0
orjson==3.8.10
outcome==1.2.0
packaging==23.1
pandas==2.0.1
pathspec==0.11.1
pathy==0.10.1
Pillow==9.5.0
pinecone-client==2.2.1
pkginfo==1.9.6
platformdirs==3.2.0
playsound==1.2.2
pluggy==1.0.0
pre-commit==3.2.2
preshed==3.0.8
protobuf==4.22.3
py-cord==2.4.1
py-cpuinfo==9.0.0
pyasn1==0.5.0
pyasn1-modules==0.3.0
pycodestyle==2.10.0
pycord==0.1.1
pycparser==2.21
pydantic==1.10.7
pyflakes==3.0.1
Pygments==2.15.1
pylint==2.17.3
PyNaCl==1.5.0
pyparsing==3.0.9
pyproject_hooks==1.0.0
pyrsistent==0.19.3
PySocks==1.7.1
pytest==7.3.1
pytest-asyncio==0.21.0
pytest-benchmark==4.0.0
pytest-cov==4.0.0
pytest-integration==0.2.3
pytest-mock==3.10.0
python-dateutil==2.8.2
python-dotenv==1.0.0
pytz==2023.3
pywin32==306
pywin32-ctypes==0.2.0
PyYAML==6.0
readability-lxml==0.8.1
readme-renderer==37.3
redis==4.5.4
regex==2023.3.23
requests==2.28.2
requests-oauthlib==1.3.1
requests-toolbelt==1.0.0
rfc3986==2.0.0
rich==13.3.5
rsa==4.9
scripts==2.0
selenium==4.9.0
shellingham==1.5.0.post1
six==1.16.0
smart-open==6.3.0
smmap==5.0.0
sniffio==1.3.0
sortedcontainers==2.4.0
soupsieve==2.4.1
spacy==3.4.4
spacy-legacy==3.0.12
spacy-loggers==1.0.4
srsly==2.4.6
stua==0.2
thinc==8.1.9
tiktoken==0.3.3
tomli==2.0.1
tomlkit==0.11.8
tqdm==4.65.0
trio==0.22.0
trio-websocket==0.10.2
tweepy==4.13.0
twine==4.0.2
typer==0.7.0
typing_extensions==4.5.0
tzdata==2023.3
uritemplate==4.1.1
urllib3==1.26.15
virtualenv==20.22.0
wasabi==0.10.1
webdriver-manager==3.8.6
webencodings==0.5.1
websocket-client==1.5.1
win32-setctime==1.1.0
wrapt==1.15.0
wsproto==1.2.0
yarl==1.8.2
youtube-dl==2021.12.17
zipp==3.15.0
This is from pip freeze, let me know if there's a better way to get this list đź
pip freeze?
Ya if you run pip freeze in cmd it will output a list of all your packages, is that not the way you'd like to see?
Idk I usually just get it using pip list
Okok it gave the same list just in a different format, would you like that?
Nah if it's the same it works fine ig
So basically you have py-cord... But discord isn't there anymore which should be installed with pycord (when you install py-cord) which is strange in your case
Okay, I've uninstalled pycord and pip installed py-cord per the documentation
Seeing py-cord2.4.1 but still no discord in the list, and getting the same error :/
click one of the triple dots and click on Python Packages. Then search for py-cord and install it.
I'm embarrassed, this was it, thanks. I was installing the package on my local PC, not the PyCharm auto venv
pycord is a FFMPEG wrapper
Right
Left
pipe install pie cord
No, because after Qc6+, thereâs Bb7+ blocking the check and forking your king and queen, so it is a draw by insufficient material.
Checkmate in 4
Checkmate sequence lost
Iâll just sacrifice my bishop for your passed pawn.
Are there events for timeouts and kicks?
wdym exactly?
For when someone gets kicked?
There's an event for on user leave
timeouts are called as a part of on_member_update. Although that also includes other events
can a message containing a view be updated/edited with a new view / embed?
yes
.rtfm message.edit
Please help, command pip uninstall discord.py doesnt work
Can a class take 2 classes at once? Example:
class Name1(discord.ui.View):
def __init__(self, ...)
super().__init__(timeout=180)
...
Name2()
class Name2(discord.ui.View, Name1):
def __init__(self, ...)
super().__init__(timeout=180, ...)
can you elaborate what you are trying to do?
When I click on a button instead of "view=Name1()" on "view=Name2()". Is it possible not to pass directly to "__init__" Name2 rather use "super().__init__()" to get the variables from Name1?
But a class originally have the discord.ui.View class, so is it possible to take the variables of two classes at once?
I searched the answer to this question but I didn't find it, so I decided to turn here
Please help. i installed pycord but i still get "no module named discord" error
Did you install pycord or py-cord
Both
Show your pip list
Requirememts.txt?
pip list
I said pip list
If you're using a host that installs the packages from requeriments.txt show it too ig
I cant show pip list because of hosting blocks such commands.
?
Got it thanks
Allowing files in interaction responses
Oh okay that makes sense, thank you 
Pycord already has this
Okey
I also have pycord installed from github, but what to do with the error there is "no module named discord"
I deleted folder site-packages and it work
But i get another error
Bad request. Invalid Form Body. In guild_id: Value "Ellipses" in not snowflake"
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/ephemeral.py at master · Pycord-Development/pycord
It takes an int
Not a string
all pycord examples are made with bot but i use client. Do I need to change this?
do you know basic python?
I'm beginner
Client is only events. I'm sure you're not looking for that.
?tag instances
No tag instances found.
?tag clients
No tag clients found.
Smh
?tag client
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
Tha ks lmao
Traceback (most recent call last):
File "/home/container/cogs/utils.py", line 60, in reload
self.bot.unload_extension(f'cogs.{extension_name}')
File "/home/container/.local/lib/python3.9/site-packages/discord/cog.py", line 1068, in unload_extension
self._remove_module_references(lib.__name__)
File "/home/container/.local/lib/python3.9/site-packages/discord/cog.py", line 722, in _remove_module_references
self.remove_cog(cog_name)
File "/home/container/.local/lib/python3.9/site-packages/discord/cog.py", line 706, in remove_cog
cog._eject(self)
File "/home/container/.local/lib/python3.9/site-packages/discord/cog.py", line 592, in _eject
bot.remove_command(command.name)
AttributeError: 'BridgeCommand' object has no attribute 'name'â
how to fix this? i want to reload a cogs using bridge_command
that is fixed on master branch
master branch has a few changes. make sure to read the change log
?tag install
- Uninstall discord.py or any other forks of discord.py you might have with the namespace
discord.
python -m pip uninstall discord.py discord -y
2a. Install py-cord
python -m pip install py-cord
2b. Update py-cord
python pip install -U py-cord
Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.
Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
update?
last line
ty
np! đ
AttributeError: 'NoneType' object has no attribute 'edit'
This error occurs when "on_timeout" fires after changing to the second class. on_timeout in second class doesn't see buttons, I don't understand why. If I use "on_timeout" in the first class then it fires in the second class changing to the buttons of the firts class
why doesn't guild.members or bot.get_all_members() output all users, just the bot itself?
you probably don't have the right intents
bot = commands.Bot(Intent=discord.Intents.all())```
I checked it on different versions of py-cord 2.x, the problem is the same, there is no such problem in other libraries
the kwarg is intents not intent
i think this is fixed on master branch. can you test it?
and i lowercase
@candid coral see last line to install master branch
on pycord there is no difference between Intent and Intents, if I am not mistaken
After "pip install ..." should I enter "import ..." at the beginning of the code?
no??
you code will remain the same as before
Cannot find command 'git' - do you have 'git' installed and in your PATH?
?tag git doesn't work
"?tag" is not an internal or external command, operable program, or batch file.
run the tag in #883236900171816970 lmao. not in the console
I installed it, thank you for the help. Now I won't have this error?
can you not use async def on_message function, and @commands.command stuff in the same file? 
you shouldn't. did you get the error or no
you can. events listeners and commands dont interfere
are you using @bot.event for the on message event?
yep
let me make an
example code that wasn't working for me
I've changed it up now but it's a bit dodgy the way I've done it, so please hol up 
@bot.event for the message event will stop prefix commands from running
change that to @bot.listen()
OHHHHHHHH
YOUR MY SAVIOUR T-T
Hello, pls help me someone:
how to use on_message event in cogs?
My code now:
class any(commands.Cog):
def __init__(self, bot):
self.bot = bot
@bot.event
async def on_message(self, message):
if message.content == "anything":
await message.delete()
await message.channel.send("Something")
def setup(bot):
bot.add_cog(any(bot))```
@commands.Cog.listener()
async def on_message()
Ok, thanks
the reload command for a cog should be in the main file or can it be in cog as well?
you can put it everywhere
ok thanks for the info
you can have it in a cog or main file
i don't know why i thought the command needed to be in another file and not in the cog
fun fact reload doesnt work because issues.
It does for me
well yes it works
slash commands dont really get reloaded do they?
the sync command is kinda broken xd
works on discord.py so it should work on pycord too :P
How should i handle NotOwner, i have tried this but it doesn't work.
try:
self.bot.reload_extension(f'tickets.ticket_commands')
await ctx.respond(f"{get_commandsinfo('reload_command', 'success_message')}")
except discord.ext.commands.errors.NotOwner as error:
await ctx.respond(f"{get_commandsinfo('reload_command', 'error_message')}")
are you using the is_owner check?
yup
?tag eh
Docs: https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html#error-handling
Example: https://gist.github.com/EvieePy/7822af90858ef65012ea500bcecf1612
Simple Error Handling for ext.commands - discord.py - error_handler.py
see that
ok thanks
How do I edit an embed in a newly created thread? I stored the message id of the newly created thread then tried to use .edit(), but that returned TypeError: Thread.edit() got an unexpected keyword argument 'embed'.
Code stub below:
forum_channel = bot.get_channel(CHANNEL_ID)
first_embed = discord.Embed(...)
msg = await forum_channel.create_thread(embed=first_embed)
new_embed = discord.Embed(...)
await msg.edit(embed=new_embed)
becuase create_thread returns the new thread, not the message
you want thread.starting_message
Thank you!
Is it normal for a command even with guild_ids to take time registering?
mmmm nope, either you need to refresh your client or it didn't sync at all
Yeah it didn't sync
have any commands synced?
One, but it was a while ago
using cogs?
well it's meant to auto sync so chances are you're doing something wrong
did you override on_connect?
oh shoot wait...
nice
What's the difference?
listen doesn't override
Thanks!
What's the best way to edit an old embed's field that is no longer in cache? It is a simple embed with only 2 fields (one inline) and a footer. I want to edit the inline field but keep the rest of the embed's content the same. I retrieved the message with the embed using .history()
edit: nvm. to_dict() and from_dict() make it easy.
fwiw you didn't need to/from_dict, if you have the embed object you can just edit embed.fields[x].inline
does before_invoke also count for message commands?
or what listener gets triggered on prefixed commands
Is it possible to get the duration a person is timed out for and the person who did it?
think so? give it a try i guess
you're looking for member.communication_disabled_until, which is a datetime for when their timeout is removed; you can subtract the current time from it to get the remaining duration
for who did it, you'd need to get it from audit log
Alright sounds good thanks for the help!
.rtfm on_command
discord.on_application_command
discord.ext.commands.Bot.add_application_command
discord.ext.commands.Bot.application_command
discord.ext.commands.Bot.application_commands
discord.ext.commands.Bot.get_application_command
discord.ext.commands.Bot.invoke_application_command
discord.ext.commands.Bot.on_application_command_auto_complete
discord.ext.commands.Bot.on_application_command_error
discord.ext.commands.Bot.on_command_error
discord.ext.commands.Bot.pending_application_commands
discord.ext.commands.Bot.process_application_commands
discord.ext.commands.Bot.remove_application_command
discord.ext.commands.Bot.walk_application_commands
discord.commands.application_command
discord.on_application_command_error
discord.on_unknown_application_command
discord.on_application_command_completion
discord.ext.commands.AutoShardedBot.add_application_command
discord.ext.commands.AutoShardedBot.application_command
discord.ext.commands.AutoShardedBot.application_commands
Huh why does that not show up
But anyways, the event on_command gets fired for each prefix command
because it is all hardcoded and I didnt put it in :(
im using a modal and it asks for inputs, takes them in fine using .wait() but after submitting (which uses the values to make a channel, which happens sucessfully), the modal doesn't auto close and instead says like "something went wrong, try again later.". any obvious reasons this could be happening?
đ
did you defer/respond to the modal interaction?
modal = Modal(
title = "Create a Ticket",
)
x = InputText(label="x", placeholder="X", custom_id="xxx")
y = InputText(label="y", placeholder="Y", custom_id="yyy")
z = InputText(label="z", placeholder="Z", custom_id="zzz")
modal.add_item(x)
modal.add_item(y)
modal.add_item(z)
await interaction.response.send_modal(modal)
await modal.wait()
x = x.value
y = y.value
z = z.value
thats basically what it looks like
not true exactly how to do that
Well,,, normally you'd assign a callback
Have you never used other items like buttons or selects?
i've used callbacks for those, but not for modals before
so this is basically like a ticket bot
Well it's the exact same structure
you click button, this is a callback of that button
Define the callback for the modal and respond to its interaction
kk
i think i broke something, my on_ready event is triggering properly but my bot isn't showing as online and none of its slash commands are showing up
even worse is that if i use pycharm instead of vscode and run the code it works
i think it's because of something on how the code is written because the code that's in vscode is very very different from the code in pycharm because i was doing a little temporary side project and just recycled the token
What versions of pycord are you running on each?
let me check rq
And does anything unexpected appear in console
2.4.1 for both
no there aren't any errors or anything just the ready from on_ready
You 100% sure? No difference in venvs or anything?
there's probably a lot of differences but im not entirely sure how to check
where my newbiness shows :(
Try printing discord.__version__ somewhere in your bot on both
they both show 2.4.1
Are you doing anything in particular in on_ready?
no just printing ready
Have you got anything else that runs on your bot outside of commands?
like prefix commands?
Well anything that doesn't require manual input
i don't think so, there's a couple functions that are called when a command is run though
well there's two different ones because i recycled the token for a different temp project
If they have different features then perhaps that's the issue...?
yeah that's what i was thinking but when i switched over from vscode it worked fine
all the previous commands disappeared and the new one appeared
but now it won't go back
i think resetting the token would be best here?
yeah i'm just gonna reset it and see if that fixes it
nope it is still very broken
I mean, personal opinion, just don't use vscode
would pycharm be better?
For python it's significantly better yeah
it was working fine with vscode until i decided to use the token in pycharm :/
You're not running both at the same time right
Please help, i cant use discord.Interaction.response. AttributeError 'CachedSlotProperty' has no atribute 'send_message'(and 'defer)
How to send message using webhook?
Can you check if you have accidentally specified an interaction url for the application on the discord developer portal
Show the code
async def Test(ctx: discord.ApplicationContext):
await discord.Interaction.response.send_message("Test", ephemeral=True);```
That's the class. You don't use that
Just use await ctx.respond(...)
Much simpler
Here's the slash basic example.
Ok.Thanks!
Quick question guys.
Is there any reason that the code below is not working?
I need to run a function daily at specific time and it's not executing when the time reaches.
Keep in mind that this is in a cog.
@tasks.loop(count=None, time=datetime.time(hour=17, minute=0, second=0))
async def hello_world(self):
print("Hello World")
Do you start it?
yes i did, i start it in the cogâs init. If I change to relative time, e.g. @tasks.loop(count=None, seconds=30) it works. Do I need to put in an array?
I mean do you have a line with "self.hello_world.start()"
yes I do.
My experience troubleshooting scheduled functions are telling me is timezone issue but i doubt it.
It uses whatever your machine's local time is
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
This error appears periodically. I don't know the reason
You're taking too long to respond
Nope, itâs empty
anybody have any tips on how to fix this or know what I am doing wrong? I am trying to make sure that discord.py is installed. Im on Windows.
maybe I should just install pycord
Do it xd
Despite the fact this is pycord support and not dpy
TRUE
Is there a good way to turn a dict into a list of discord.selectoptions for a dropdown menu?
yes
well there are built in from_dict and to_dict methods (albeit undocumented), as long as you have the correct format
discord/components.py lines 459 to 472
@classmethod
def from_dict(cls, data: SelectOptionPayload) -> SelectOption:
try:
emoji = PartialEmoji.from_dict(data["emoji"])
except KeyError:
emoji = None
return cls(
label=data["label"],
value=data["value"],
description=data.get("description"),
emoji=emoji,
default=data.get("default", False),
)```
basically this is best used if you've saved your SelectOption as a dict using to_dict
I have not
Basically just wanted to get all the keys from a dict and then turn them into dropdown list for the search
I'll send the first couple entries, it's just key then some matching aliases for that region
'Bachtalan': ['bachtalan', 'bach', 'talan'],
'Cortashar Dominion': ['cortashar dominion', 'cortashar', 'cd'],
'Dirk': ['dirk', 'drk'],
'Srath': ['divine empire of srath', 'srath', 'des', 'empire'],```
you can just iterate through easily py options = [discord.SelectOption(label="...", value="...") for x in dict]
Oh aye, that is pretty easy
x would just be the key; both label and value are required
so i'd recommend you do some transform on x to normalise it
though
perhaps it'd be better to leave the same so you can get the real value back through get
but thank you, this is a lot easier than manually editting it every time I gotta add a new entry to the dict
mhm, iteration is king
options = [discord.SelectOption(label=region, value=region, description=f"Select {region}?") for region in TravelTime.regions]```
Works well and without issue
figured it out, i need to use different pre-fixes. also installed py-cord
still waiting for docs
how do i make a task that repeats every X hours with cogs
In my code inside 4 different buttons there is the same part of the code, I want to put it into a function. The result of this function is to edit a message, which doesn't work:
class Name(discord.ui.View):
def __init__(self, argument1, argument2, ...)
super().__init__(timeout=...)
self.variable1 = argument1
self.variable2 = argument2
...
def function(argument1, argument2, ...):
...
await interaction.response.edit_message(...) # wrong
@discord.ui.button(...):
async def button(...):
...
function(self.variable1, self.variable2, ...)```
has to be async
Thank you
client.load_extensions("cogs.misc", recursive=True, store=False)
i keep getting errors trying to do this. so shouldn't this load every cog in the misc folder or have i not understood what load_extensions does?
what is the error?
not really an error but the commands just dont load. the bot goes online and has no errors.
my directory:
ââââbot
ââââcogs
â ââââmisc
â ââââmoderation
i've tried to wrap it in a try/except block still nothing.
are you sure if the cogs are loaded?
what was it?
it was me just not looking at my directory properly.
how do i properly create a slashcommandgroup using the decorator
there isn't a decorator
that's just the class... a decorator never existed
because unlike prefix groups, a slash group can't have a callback
so there's no purpose
||imagine docs being accurate||
true
yea i just realized, i did cogs.utilities now
it's weird that it imports based on the bot.py path
yea thats kinda intentional
That's always been like that :P
Do I need to worry about fixing this error?
The bot runs fine
Error was given when I debugged the file in Visual Studio Code
read the error
I did in fact read the error (???)
how do you define the token in the env?
TOKEN =
TOKEN or token?
the bot comes online and commands work
token = str(os.getenv("TOKEN"))
should I put this before the TOKEN line?
edit: It worked
Do you know basic python?
I am learning
Reading a guide on Python and trying to implement the topics taught as I go along
pls learn the basic's first
Alright...(?)
pycord is not a simple library
Well, i think it makes some sense the cog is loaded from the main file so anyway the imports have to be done as if you were doing them from it.
id say it is
haha
you've set the environment variable right
before you ran the bot
Why bot.close() throws an error, it works fine but still prints this.
https://paste.techscode.com/venumecuyebinaj.apache
if i understand correctly that is normal just like the connection being closed suddenly but it should be fine
No way to hide it?
idk i dont think so
just try-except it maybe?
why would this work? is bot.close() that throws it after it closes the bot
well you asked to hide it
i think they meant the functoin that closes the bot does not throw the error
some other thing does
but then again squid knows more about pycord than me
right
It's really weird about this. I'm using py-cord 2.4.1, and the documentation said it is new in 2.0 version. I've changed to use an array instead of single datetime and yet it's still not triggering when the clock hits 10:30 a.m. Should I use a different approach then?
class Birthday(Cog):
def __init__(self, bot: Bot):
self.bot = bot
print("Start Birthday Task")
self.wish_birthday.start()
@tasks.loop(time=[datetime.datetime.strptime('10:30AM', '%H:%M%p').time()])
async def wish_birthday(self):
print(datetime.datetime.now().strftime("%d/%m/%Y, %H:%M:%S"))
print("HAPPY BIRTHDAY")
def setup(bot: Bot):
bot.add_cog(Birthday(bot))
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/background_task.py at master · Pycord-Development/pycord
If this doesn't work, open an issue on github
Is the toolkit bot broken again?
I've been trying lots of things, I thought is data type issue or some sort, but i finally found the issue. The default timezone is set to UTC... I need to pass my own machine's timezone into the time object.
is it running on UTC? i assumed default was machine but i guess not
...though i can't remember if we fixed the timezone bug for that
I've only found that when I keep the bot running and it executes 8 hours earlier because my time is in UTC+8. So right now after setting to the correct UTC, it is working as expected. Thanks alot.
py-cord==2.4.1
attributeerror: 'bot' object has no attribute 'slash_command'. did you mean: 'add_command'?
Experiencing the above error on gated build for my python app.
Runs locally absolutely perfectly, fails GitHub gated build with the error above.
Requirements.txt file locally and in source control contain pycord lib.
Does anyone know how to fix this?
send full traceback and your list of requirements
pycord or py-cord?
yes
No stack trace. Just the error above and fails gated build.
Literally just the error above, not kidding. Well it says exit code 1 as well in GitHub.
Locally it works as intended. No errors.
List of requirements I will get.
Are you asking me?
Yes
These libraries conflict with py-cord:
discord==2.2.2
discord-ext-bot==1.0.1
discord-py-slash-command==4.2.1
discord.py==2.2.2
I see. What would the best approach be?
I don't think I do. I will give this a shot tomorrow.
Is it the case the py-cord contains these libraries?
no, these libraries simply conflict with Py-cord; they rewrite certain files that py-cord uses.
Ah. I see. Thank you for your help đ
yw
Hi, I'm completely new in creating discord bots. How can I use it with command for example !test?
import discord
from discord.ext.pages import Paginator, Page
my_pages = [
Page(
content="This is my first page. It has a list of embeds and message content.",
embeds=[
discord.Embed(title="My First Embed Title"),
discord.Embed(title="My Second Embed Title"),
],
),
Page(
content="This is my second page. It only has message content.",
),
Page(
embeds=[
discord.Embed(
title="This is my third page.",
description="It has no message content, and one embed.",
)
],
),
]
paginator = Paginator(pages=my_pages)```
Using the paginator with a prefix cmd?
Hi, in order to send a message on a voice channel (on it's textual place), can I just await channel.send() ir or is there a different syntax
.tias
How do I set any number of parameters for a slash command, 2 required and up to 8 optional?
When creating the option just pass required=True or required=False
You can find an example of slash commands here: https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_basic.py
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/slash_basic.py at master · Pycord-Development/pycord
ty
ok so if I get it, this work:
@bot.slash_command()
async def ping(ctx):
await ctx.send(f"Pong {ctx.author.mention}!")
but how do I add comments like this:
https://cdn.discordapp.com/attachments/1070805582447136819/1105826201102209064/image.png
use ctx.respond instead of ctx.send
that thing is the description btw
pass it to @bot.slash_command()
ok like this:
@bot.slash_command(description="this is a test")
async def ping(ctx):
await ctx.respond(f"Pong {ctx.author.mention}!")
?
yeah yeah I get it, it will work, but I want to know what else ccan I put as args into bot.slash_command() except name and description please?
- it's just doesn't work, like I can't use the command
reload your discord client
ty buddy, sorry for disturbing you
you can pass almost everything thats in the attribute list, but stick to only name, description, nsfw, guild_ids and guild_only
other stuff has better ways to do it. like decorators for default permissions, options, localisation, cooldown etc
discord.Option
unrelated, but cool minecraft font
File "/srv/barman/main.py", line 490, in <module>
type=discord.OptionType.STRING,
AttributeError: module 'discord' has no attribute 'OptionType'
aiohttp 3.8.4
aiosignal 1.3.1
async-class 0.5.0
async-timeout 4.0.2
asyncio 3.4.3
attrs 20.3.0
beautifulsoup4 4.12.2
blinker 1.4
certifi 2020.6.20
chardet 4.0.0
charset-normalizer 3.1.0
cloud-init 20.4.1
configobj 5.0.6
cryptography 3.3.2
dbus-python 1.2.16
distro-info 1.0
fail2ban 0.11.2
frozenlist 1.3.3
gyp 0.1
httplib2 0.18.1
idna 2.10
importlib-metadata 1.6.0
Jinja2 2.11.3
jsonpatch 1.25
jsonpointer 2.0
jsonschema 3.2.0
MarkupSafe 1.1.1
more-itertools 4.2.0
multidict 6.0.4
oauthlib 3.1.0
Pillow 9.5.0
pip 20.3.4
py-cord 2.4.1
pycurl 7.43.0.6
PyGObject 3.38.0
pyinotify 0.9.6
PyJWT 1.7.1
pyrsistent 0.15.5
PySimpleSOAP 1.16.2
python-apt 2.2.1
python-debian 0.1.39
python-debianbts 3.1.0
PyYAML 5.3.1
reportbug 7.10.3+deb11u1
requests 2.25.1
setuptools 52.0.0
six 1.16.0
soupsieve 2.4.1
systemd-python 234
tk 0.1.0
turtle 0.0.1
typing-extensions 4.5.0
unattended-upgrades 0.1
Unidecode 1.3.6
urllib3 1.26.5
watchdog 3.0.0
wheel 0.34.2
yarl 1.9.2
zipp 1.0.0
I dont have discord.py
from discord.commands import Option
other things to import from this or only Option?
still
Traceback (most recent call last):
File "/srv/barman/main.py", line 491, in <module>
type=discord.OptionType.STRING,
AttributeError: module 'discord' has no attribute 'OptionType'
for type, just type "str"
you can also just pass it as second positional argument
i always do Option("name", str, <kwargs>)
anyway,
@bot.slash_command(
name="meme",
description="Commande permettant d'envoyer un meme aléatoire dans le salon prévu à cet effet",
options=[
discord.Option(
name="type",
description="Type de meme",
type=str,
required=False,
choices=[
discord.OptionChoice(name="normal", value="normal"),
discord.OptionChoice(name="noir", value="noir"),
],
)
],
)
async def meme(ctx, type=None):
salon_meme = await bot.fetch_channel(923316086483587088)
salon_meme_noir = await bot.fetch_channel(923316086483587090)
salon_console = await bot.fetch_channel(1070805582447136819)
path_base = "/srv/barman/meme/"
path_normal = path_base + "normal"
path_noir = path_base + "dark"
if ctx.channel == salon_meme or ctx.channel == salon_console:
if type == "normal":
doss_name = os.listdir(path_normal)[
random.randint(0, len(os.listdir(path_normal)) - 1)
]
path_meme = path_normal + "/" + str(doss_name)
fin_meme = path_meme + "/" + str(random.choice(os.listdir(path_meme)))
await ctx.channel.send("Ce meme provient de **" + str(doss_name) + "**")
await ctx.channel.send(file=discord.File(fin_meme))
elif ctx.channel == salon_meme_noir and type == "noir":
doss_name = os.listdir(path_noir)[
random.randint(1, len(os.listdir(path_noir)) - 1)
]
path_meme = path_noir + "/" + str(doss_name)
fin_meme = path_meme + "/" + str(random.choice(os.listdir(path_meme)))
await salon_meme_noir.send("Ce meme provient de **" + str(doss_name) + "**")
await salon_meme_noir.send(file=discord.File(fin_meme))
else:
await ctx.send(
f"Cette commande est réservée aux channels <#{str(salon_meme.id)}> et <#{str(salon_meme_noir.id)}>",
ephemeral=True,
)
discord don't even show me the command when I use /
still thanks for the advice
then you're most likely doing something wrong lol
yeah, probably ahah
make sure to restart discord, sometimes it can be slow
you dont need to pass a name to the slash command decorator btw, it defaults to the function name anyway
does any other slash command you have show
could you give me one of your slash func syntax please bro?
yes
i mean i personally use the option decorator
try not passing the name argument in the slash command decorator
if that still doesnt work, just comment the whole thing out and see if it works with an empty decorator
TypeError: Command names and options must be of type str. Received "None"
show your code
@bot.slash_command(
name="meme",
description="Commande permettant d'envoyer un meme aléatoire dans le salon prévu à cet effet",
options=[
discord.Option(
description="Type de meme",
type=str,
required=False,
choices=[
discord.OptionChoice(name="normal", value="normal"),
discord.OptionChoice(name="noir", value="noir"),
],
)
],
)
and no, i mean THIS name
sorry
options always need a name
I tried like this:
doesnt work đŠ
are you actually saving and restarting your bot
I am
restarted discord, too?
ctrl r
hm
well sometimes it can take a minute or two for it to actually register but that should work how you have it there
you do double str? oof
well, I just don't get it
?
you can remove the str in the @option()
i would've removed it in the function declaration, no?
can you please show me your discord imports pls? I personally have those
do you guys know this error:
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In options.1: Required options must be placed before non-required options
i didnt put any opthion anywhere, thats the problem
screenshot the code that caused that :3
It dont give me the place
Ignoring exception in on_connect
Traceback (most recent call last):
File "/home/debian/.local/lib/python3.9/site-packages/discord/client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "/home/debian/.local/lib/python3.9/site-packages/discord/bot.py", line 1164, in on_connect
await self.sync_commands()
File "/home/debian/.local/lib/python3.9/site-packages/discord/bot.py", line 719, in sync_commands
registered_commands = await self.register_commands(
File "/home/debian/.local/lib/python3.9/site-packages/discord/bot.py", line 599, in register_commands
registered = await register("bulk", data, _log=False)
File "/home/debian/.local/lib/python3.9/site-packages/discord/http.py", line 371, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In options.1: Required options must be placed before non-required options```
well what code did you add before that happened
tbh I dont know
imma do ctrl z
wdym you dont know lol
you added some lines of code before that happened
which ones
lot of đŠ
yk what, just forget it, imma stay with normal commands, im too stupid for coding / commands

yeah sorry
slash commands are a lot easier than prefix commands imo
but I always do prefix, and never /
plus you do have a working one so you're doing something different with the one that doesnt work
just copy your working one, change the function name and see if it shows up
still
you always have to parse the string to get the arguments out of it properly if it gets more complex, not with slash commands
yes they are
I also like that you can add descriptions and other stuff
any idea of this?
from discord import option
ty
do you see an error there:
@slash_command(brief="Renvoie un meme")
@option("choix" bool, description="Renvoie un meme aléatoire", required=False, choices=["aléatoire","choisi"])
get it
forgot a ,
yea
unfortunately...
@slash_command(name="ratio", description="Commande permettant de 'ratio' un utilisateur")
@option("user", description="L'utilisateur Ă ratio", required=False, type=discord.Member)
@option("raison", description="La raison du ratio", required=False)
async def ratio(ctx, user: discord.Member = None, raison: str = ""):
"""
Commande permettant de "ratio" un user
discord.Member : user -> utilisateur Ă ratio
str : raison -> raison du ratio
"""
await ctx.defer()
if user is None:
mention = ctx.author.mention
else:
mention = user.mention
await ctx.send(f"EH {mention}! **RATIO**! {raison}")
or
@slash_command(brief="Renvoie un meme")
@option("choix", bool, description="Renvoie un meme aléatoire", required=False, choices=["aléatoire","choisi"])
async def meme(ctx, choix = "aléatoire"):
"""
Commande permettant d'envoyer un meme aléatoire dans le salon prévu à cet effet
str : arg -> optionnel, l'argument pour sélectionner le type de meme aléatoire
"""
salon_meme = await bot.fetch_channel(923316086483587088)
salon_meme_noir = await bot.fetch_channel(923316086483587090)
path_base = "/srv/barman/meme/"
path_normal = path_base + "normal"
path_noir = path_base + "dark"
if ctx.channel == salon_meme or ctx.channel == salon_meme_noir:
if choix == "aléatoire":
# Créez le menu déroulant pour choisir le type de meme
view = discord.ui.View()
if ctx.channel == salon_meme:
view.add_item(MemeTypeSelect("normal"))
else:
view.add_item(MemeTypeSelect("noir"))
await ctx.send("Choisis le type de meme :", view=view)
else:
if ctx.channel == salon_meme:
doss_name = os.listdir(path_normal)[random.randint(0,len(os.listdir(path_normal))-1)]
path_meme = path_normal + "/" +str(doss_name)
fin_meme = path_meme + "/" + str(random.choice( os.listdir(path_meme)))
await ctx.channel.send("Ce meme provient de **" + str(doss_name) + "**")
await ctx.channel.send(file=discord.File(fin_meme))
else:
doss_name = os.listdir(path_noir)[random.randint(1,len(os.listdir(path_noir))-1)]
path_meme = path_noir + "/" + str(doss_name)
fin_meme = path_meme + "/" + str(random.choice( os.listdir(path_meme)))
await salon_meme_noir.send("Ce meme provient de **" + str(doss_name) + "**")
await salon_meme_noir.send(file=discord.File(fin_meme))
else:
await ctx.respond(f"Cette commande est réservée aux channels <#{str(salon_meme.id)}> et <#{str(salon_meme_noir.id)}>")
all of theese doesnt work
even with /
do I need to aproove smth on the discord dev website orrr??
idk, sadge
Where to use persistent in Paginator code?
these should be @bot.slash_command, not just @slash_command
and they should be defined before doing bot.run
and i hope you didn't override on_connect
why does this not work?
previous_button is a button using discord.ui etc. the button itself works fine... but it doesnt directly get activated when executing this part.
*disabled doesn't work
I made it disabled = False
did you edit the message?
The same as views; Paginators are a sub-class of Views
yeah
wait how exactly do you mean, under self.previous_button.enabled = True I edit it again?
yes
how would I specify what message it edits tho
in the button itself I use
shi wrong clipboard
await interaction.response.edit_message(embed=definition, view=self) meant this
there's only a button.disabled, not a button.enabled
I know I changed that again, dont worry that part is undone lol, that was a wrong clipboard (I tried both enabled and disabled)
show full code maybe?
and also I don't think a button object is attached to the view
def update_buttons(self):
print(f'Current page {self.page}')
if self.page < 1:
print('Previous button disabled :', self.page)
self.previous_button.disabled = True
elif self.page >= 1:
print('Previous button enabled :', self.page)
self.previous_button.disabled = False
self.sort_button.label = 'Sort by Upvotes' if not self.sort_by_upvotes else 'Sort by Date'
print(len(self.data['list']))
if self.page < len(self.data['list']):
self.next_button.disabled = False
else:
self.next_button.disabled = True
It's not perfect yet, I need change some more values dont those but how exactly do I edit it?
you dont use async def?
it doesn't change anything
ok
but well how would I edit the specified message?
edit what specified message
the message with the buttons ofc.
I mean the button itself edits the message using await interaction.response.edit_message(embed=definition, view=self)
when pressed
but how would I edit the message in the update_buttons function?
pass interactions or the corotine into update_buttons?
just put self.update_buttons() above await interaction.response.edit_message in the button itself đ§
seems to work, but my bot stay in "is thinking" state
first command needs ctx.respond instead of ctx.send
same for the 2nd command, just replace send with respond
Yes
ty
can u help me with if_persistent() parametr with paginator
like where should i use it in example code
@commands.command()
async def pagetest_prefix(self, ctx: commands.Context):
"""Demonstrates using the paginator with a prefix-based command."""
paginator = pages.Paginator(pages=self.get_pages(), use_default_buttons=False)
paginator.add_button(
pages.PaginatorButton("prev", label="<", style=discord.ButtonStyle.green)
)
paginator.add_button(
pages.PaginatorButton(
"page_indicator", style=discord.ButtonStyle.gray, disabled=True
)
)
paginator.add_button(
pages.PaginatorButton("next", style=discord.ButtonStyle.green)
)
await paginator.send(ctx)```
or in this but i rather wanted to use prefix command
```py
@pagetest.command(name="custom_view")
async def pagetest_custom_view(self, ctx: discord.ApplicationContext):
"""Demonstrates passing a custom view to the paginator."""
view = discord.ui.View(
discord.ui.Button(label="Test Button, Does Nothing", row=1), )
view.add_item(
discord.ui.Select(
placeholder="Test Select Menu, Does Nothing",
options=[
discord.SelectOption(
label="Example Option",
value="Example Value",
description="This menu does nothing!",
)
],
))
paginator = pages.Paginator(pages=self.get_pages(), custom_view=view)
await paginator.respond(ctx.interaction, ephemeral=False)```
ngl i dont think it is possible to cleanly make the paginator persistent
unless you have static pages
yes content of embeds is static
oh then you might actually be able to do it
like i wanted to use command .roles which will show all the available roles on the server and have buttons to navigate between pages (a lot of roles)
you will need to make all the components have a custom id, i think you got that covered
you will then need to build the paginator on startup. probably on ready (on ready is not the best way)
since the paginator is actually a view subclass, you can just do bot.add_view(paginator)
hmm
thats not really static yk
cuz it needs the roles
what you can do is
only role names, not pings, and i wont add new roles or if so i will execute command once again
is this a private bot?
yeah
ah
can you hardcode the guild id?
then you can just get guild using bot.get_guild(d), get the roles and build the paginator on ready
can we go dm?
hmm. sure
Hi, @option doesn't work with cogs?
sup guys
maybe a stoopid question, but can i reference an looped function as a normal function?
it does
nvmd guys, i should start thinking before asking for help
What's the difference between Discord.py and Pycord?
biggest difference is the slash commands implementation
discord py don't have them?
both have them, but how you add them is different
in dpy you use a tree and stuff
in pycord, it is more like how prefix cmds are added
Ohh, thanks. Looks better the dpy's guide
Hey there. Just wondering how I can access the description of my application commands, given an ApplicationCommand object.
description=""
Not setting the description. Accessing it from an existing ApplicationCommand object.
I know its an attribute of SlashCommand, but that's not as accessible to me. Would it be in __original_kwargs__?
is it not directly available as an attribute on the object ? like cmd.description (if cmd is ApplicationCommand object)
I believe it's accessible via a SlashCommand object (which inherits from ApplicationCommand) and its handled by them, but the ApplicationCommand object doesn't have a description attribute.
I mean, if there's a way to get a list of the SlashCommand objects from the Bot class like there is for ApplicationCommand objects, that would make it a lot easier. Just haven't seen that.
pretty sure it would be a SlashCommand object
bot.application_commands claims to return a list of ApplicationCommand objects. Unless that is wrong and it instead also returns SlashCommand objects rather than objects of their super class (ApplicationCommand), then đ€·ââïž
Give me a sec to try something :)
well it contains return context menu commands too. what does bot.get_application_command say?
pretty sure that is just a typing thing
Yeah... I think I might be able to isolate out just the SlashCommand objects if it contains them. Working on something. Thanks btw đ â€ïž
Yep. Can just run an isinstance() check. It contains the SlashCommand objects đ
nice
how can I make it still defer at the beginning but then respond with an ephemeral if needed?
because defer basically always overrides the ephemeral of the ctx.respond for a slash command?
ping me if you respond :P
How do you add reactions to a response in a slash command?
https://docs.pycord.dev/en/master/api/models.html#discord.Interaction.original_response and add reactions to it
add ephemeral=True to your defer
the first followup has to be one or the other, i.e. what you're trying to do at the bottom there won't work
Hmm so to be able to use defer I must have it ephemeral or not at all?
This only replies to your first response
After that you can freely switch
yes but the below responses are basically both my first response
The only way around this would be to have another response beforehand
or typing instead of thinking?
You'd still have to have a first response though
I guess triggering typing after that if you want could work
I'll try it tomorrow and tell you if it worked, thanks for your help though:)
I need to draw messages from different data collections using the "slot_number" option. I tried a if statement but I didn't get a response from it. Does anyone have a suggestion on how I can do it?
we have no idea what your data looks like
I've encountered some rate limiting, after having made a /urban command using embeds and buttons, but I cannot find the cause, I start my bot and it gets rate limited but there's literally not a single timer in there so uh- ?
Ideas?
is it your host?
Wdym exactly? If I run my bot it gets rate limited. I have the logging feature on where it dumps info into s log file etc.
I'm just trying to pull the "ad" value
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.fields.0.value: Must be 1024 or fewer in length.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/vox/sparky/venv/lib/python3.10/site-packages/discord/client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "/home/vox/sparky/./main.py", line 227, in on_application_command_error
raise error
File "/home/vox/sparky/venv/lib/python3.10/site-packages/discord/bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/vox/sparky/venv/lib/python3.10/site-packages/discord/commands/core.py", line 375, in invoke
await injected(ctx)
File "/home/vox/sparky/venv/lib/python3.10/site-packages/discord/commands/core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.fields.0.value: Must be 1024 or fewer in length.```
do you host your bot locally or in the cloud?
Server
that's not a ratelimit
Linux server
Fk wrong clipboard
2023-05-10 21:40:55,968:WARNING:discord.client: PyNaCl is not installed, voice will NOT be supported
2023-05-10 21:40:56,714:INFO:discord.client: logging in using static token
2023-05-10 21:40:57,072:INFO:discord.gateway: Shard ID None has sent the IDENTIFY payload.
2023-05-10 21:40:57,324:INFO:discord.gateway: Shard ID None has connected to Gateway: ["gateway-prd-us-east1-c-4m58",{">2023-05-10 21:40:59,341:WARNING:discord.gateway: WebSocket in shard ID None is ratelimited, waiting 60.00 seconds
2023-05-10 21:41:59,348:WARNING:discord.gateway: WebSocket in shard ID None is ratelimited, waiting 60.00 seconds
2023-05-10 21:42:59,356:WARNING:discord.gateway: WebSocket in shard ID None is ratelimited, waiting 60.00 seconds
2023-05-10 21:43:59,364:WARNING:discord.gateway: WebSocket in shard ID None is ratelimited, waiting 60.00 seconds
2023-05-10 21:44:59,372:WARNING:discord.gateway: WebSocket in shard ID None is ratelimited, waiting 60.00 seconds
2023-05-10 21:45:59,380:WARNING:discord.gateway: WebSocket in shard ID None is ratelimited, waiting 60.00 seconds
2023-05-10 21:46:59,388:WARNING:discord.gateway: WebSocket in shard ID None is ratelimited, waiting 60.00 seconds
2023-05-10 21:47:59,396:WARNING:discord.gateway: WebSocket in shard ID None is ratelimited, waiting 60.00 seconds```
"check before you send" - probably some old white guy
are there any actual errors?
or does it just take a while
no except for that other Clipboard
I've had it running for like 3hrs and only found out ab it now... I hope discord not blacklisting my server 
but this only happened once on my command which I tried running
does it just take a while for on_ready to fire?
a little yes
The rstelimit was going for 3hrs tho so
so idk im quite clueless at this point
I shutdown my bot for now
But hm-
if you restart your bot does it work?
I restarted it and it got rate limited again
I am unable to access direct code right now maybe tomorrow but as of now it's just a huge pain in the ass
Log says : Error
Me : Can't find Error
đ„č
Do you have anything blocking?
Wdym blocking
?tag blocking
No tag blocking found.
?tags block
codeblock
anything that isn't async and takes a long time to execute (e.g. time.sleep)
I'm trying to put slash commands in cogs and its all working but when I try to add options they don't work, so any optional parameters dont appear as optional and stuff. Here is the code I'm trying, which is in my cog in an extension file:
@commands.slash_command(name="ntest", description="test command")
@option(name="testparam", description="test parameter")
async def ntest(self, ctx: discord.ApplicationContext, testparam: str):
await ctx.respond(testparam)
is there anything obvious that I'm missing? I've been looking for a while and havent found anything
options are not optional by default
You can add the required = False kwarg in the option decorator
even when I do that, it still claims its required
Try the following:
- Comment out the command, run the bot, uncomment, and rerun
- Restart your Discord app
Any idea on how to make a task execute at a certain time in local timezone? I've tried
pdt = pytz.timezone('America/Los_Angeles')
pdt_datetime_tz = datetime.timezone(pdt._utcoffset)
times = [
datetime.time(hour=16, tzinfo=pdt_datetime_tz),
datetime.time(hour=16, minute=57, tzinfo=pdt_datetime_tz),
datetime.time(hour=11, minute=23, second=30, tzinfo=pdt_datetime_tz)
]
@tasks.loop(time=times)
async def reminders(self):
print("working")
doesn't seem to execute unless the datetime.timezone is in UTC even though I converted it to pdt
cant u just calculate the difference between utc and your timezone and then just set the hours in utc?
ideally yes, but my timezone time changes based on daylight savings etc
if im not mistaken setting timezone for loops is currently broken
That would make sense lol, I've spent hours trying to find a solution and so far nothing
Thanks
yea
I just converted Pacific to UTC and just put the UTC time in the parameter for now
theoretically you'd only have to change for DST a single time and then never again if that bill fully passes
hopefully
How can I turn off adding a bot by a button in his profile? Help me, please
how do i create a guild specific command?
slash cmd?
pass guild_ids=[...] in the decorator
ok ty for helping
also why do i get this error in ctx.message.author.id?
NoneType has no attribute author
is this in an application command (slash command, user/message command) or a text-based command?
slash command
slash cmds do not have ctx.message. use ctx.author
@silver moat I fixed it... I found out that I had a task looping indefinite with a WhileTrue loop which constantly was trying to await something without making any change sooo.... ehheh.
is there a way to include view=MyView() inside paginator send?
When i want to do it like this
await paginator.send(ctx, view=MyView())```
error paginator.send got and unexpected keyword argument view
Use custom_view kwarg?
Or do you want to replace the default buttons?
Hi, does someone have an idea of why can't I use / commands with my bot? like even if my code is right, it doesn't show when I press /
.tag idw
Saying it doesn't work or asking what's wrong with this code is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
If I have a data stream, what would be the best way to dispatch a command/function to handle new data in that datastream? just a task that runs every second?
ooo maybe listen decorator
yeah sorry it was kinda dumb
you can just create your own event, as long as you have access to the bot object in that stream somehow
but now I have a problem where I show the code đ
@commands.is_owner()
@commands.slash_command(name="mute", description="Permet de mute un utilisateur")
@option("user", "L'utilisateur que l'on souhaite mute", required=True)
@option("reason", "La raison du mute", required=False)
async def mute(self,ctx, user, reason = 'L\'admin n\'a pas donné de raison'):
"""
Commande permettant de mute un user
discord.ApplicationContext : ctx -> Discord application command interaction
discord.Mention : user -> L'utilisateur que l'on souhaite mute
string : reason -> La raison du mute
"""
member_role = discord.utils.get(ctx.guild.roles, name='ă đžâMÎŁMBÎŁR ă') # Je rĂ©cupĂšre le role Member
mute_role = discord.utils.get(ctx.guild.roles, name='ă đâMuet ă') # Je rĂ©cupĂšre le role Member
mute_dico[user.id] = reason # J'ajoute la raison du mute dans un dico des personnnes mutes
if mute_role in user.roles:
# Si l'utilisateur est déjà mute
reason = mute_dico[user.id] # Je prend la raison dans liste des mutes
embed = discord.Embed(title='Membre déja mute',description='Ce membre est déja mute !')
embed.add_field(name='Reason :',value=reason)
await ctx.respond(embed=embed,delete_after=5.0)
else:
# Sion alors il faut mute l'utilisateur
mention=user.mention # Je crée une mention
mute_dico[user.id] = reason # J'ajoute la raison au dico des utilisateurs mute
await user.add_roles(mute_role) # J'ajoute Ă l'utilisateur le role muet
await user.remove_roles(member_role) # Je supprime Ă l'utilisateur le role member
embed = discord.Embed(title='Membre mute',description='Un membre a été mute sur le discord !')
embed.add_field(name='Il sagit de:',value=str(mention).format(mention=mention))
embed.add_field(name='Reason :',value=reason)
await ctx.respond(embed=embed)
Error:
Traceback (most recent call last):
File "/srv/barman/main.py", line 22, in <module>
import moderation
File "/srv/barman/moderation.py", line 22, in <module>
class moderation_class(commands.Cog):
File "/srv/barman/moderation.py", line 256, in moderation_class
async def mute(self,ctx, user, reason = 'L\'admin n\'a pas donné de raison'):
File "/home/debian/.local/lib/python3.9/site-packages/discord/commands/options.py", line 406, in decorator
func.__annotations__[name] = Option(type, **kwargs)
File "/home/debian/.local/lib/python3.9/site-packages/discord/commands/options.py", line 225, in __init__
self.input_type = SlashCommandOptionType.from_datatype(input_type)
File "/home/debian/.local/lib/python3.9/site-packages/discord/enums.py", line 786, in from_datatype
if datatype.__name__ in ["Member", "User"]:
AttributeError: 'str' object has no attribute '__name__'
Does someone could explain what am I doing wrong here please
ah that's even better thanks
basically if you define a listener such as py @Cog.listener() async def on_some_data(self, arg1, arg2)in any cog on your bot, and your stream has access to bot, you can call it via dispatch py bot.dispatch("some_data", arg1, arg2)
cool ty
try upgrading py-cord
seems that I have the lastest?
can you try typehinting your args then
e.g. user would change to user: str
same for reason
like this:
async def mute(self, ctx, user: discord.Member, reason:str ='L\'admin n\'a pas donné de raison'):?
yeah that works
ok imma try
ty
Traceback (most recent call last):
File "/srv/barman/main.py", line 22, in <module>
import moderation
File "/srv/barman/moderation.py", line 22, in <module>
class moderation_class(commands.Cog):
File "/srv/barman/moderation.py", line 256, in moderation_class
async def mute(self,ctx, user, reason = 'L\'admin n\'a pas donné de raison'):
File "/home/debian/.local/lib/python3.9/site-packages/discord/commands/options.py", line 406, in decorator
func.__annotations__[name] = Option(type, **kwargs)
File "/home/debian/.local/lib/python3.9/site-packages/discord/commands/options.py", line 225, in __init__
self.input_type = SlashCommandOptionType.from_datatype(input_type)
File "/home/debian/.local/lib/python3.9/site-packages/discord/enums.py", line 786, in from_datatype
if datatype.__name__ in ["Member", "User"]:
AttributeError: 'str' object has no attribute '__name__'
did you save
ofc I did
I sent the wrong one mb:
Traceback (most recent call last):
File "/srv/barman/main.py", line 22, in <module>
import moderation
File "/srv/barman/moderation.py", line 23, in <module>
class moderation_class(commands.Cog):
File "/srv/barman/moderation.py", line 257, in moderation_class
async def mute(self, ctx, user: discord.Member, reason:str ='L\'admin n\'a pas donné de raison'):
File "/home/debian/.local/lib/python3.9/site-packages/discord/commands/options.py", line 406, in decorator
func.__annotations__[name] = Option(type, **kwargs)
File "/home/debian/.local/lib/python3.9/site-packages/discord/commands/options.py", line 225, in __init__
self.input_type = SlashCommandOptionType.from_datatype(input_type)
File "/home/debian/.local/lib/python3.9/site-packages/discord/enums.py", line 786, in from_datatype
if datatype.__name__ in ["Member", "User"]:
AttributeError: 'str' object has no attribute '__name__'
maybe that it's coming from this:
@option("user", "L'utilisateur que l'on souhaite mute", required=True)
could it?
did you perhaps import annotations from future?
from what i can tell that's caused this error in the past
nop, but I added this:
@option("user", "L'utilisateur que l'on souhaite mute", required=True, type=discord.Member)
and now it say:
Traceback (most recent call last):
File "/srv/barman/main.py", line 22, in <module>
import moderation
File "/srv/barman/moderation.py", line 23, in <module>
class moderation_class(commands.Cog):
File "/srv/barman/moderation.py", line 255, in moderation_class
@option("user", "L'utilisateur que l'on souhaite mute", required=True, type=discord.Member)
TypeError: option() got multiple values for argument 'type'
seems easier
well... you're not meant to pass type manually
What should i use for fetch a message? As there is no bot.fetch_message()
it's under channel
ty
if the decorator isn't working then switch to Option typehinting. e.g. py @option("user", "description...", required=True)becomespy async def mute(self, ctx, user: Option(discord.Member, "description...", required=True), ...)
but like it works everywhere else, I dont get it
but imma try
the only thing i know that causes it is importing annotations


