#Basic Pycord Help
1 messages · Page 47 of 1
guh
uninstall that and py-cord yes, uninstall both and then only reinstall py-cord (make sure to include the dash)
if not you might have leftover discord.py files in the directory
show your pip list again
also sidenote but idk why you have a DateTime package, python has a built in datetime package, might mess things up
i actually have no idea i dont recall installing anything like that
everything runs fine
ok so now onto this
@bot.bridge_command()
async def fight(ctx, user):
member = ctx.author
gifs = ['https://tenor.com/view/murro-punch-punching-mad-madness-gif-24184117', 'https://tenor.com/view/meme-memes-memes2022funny-meme-face-punch-gif-25436787', 'https://tenor.com/view/mochi-cat-vans-gif-21776348', 'https://tenor.com/view/hasbulla-hasbik-funny-trending-meme-gif-21766562']
randomgif = ''.join(choices(gifs))
print(randomgif)
embed = discord.Embed(title=f"{member} has {''.join(choices(['punched', 'hit', 'knocked', 'slammed']))} {user}")
embed.set_image(url=randomgif)
await ctx.send(embed=embed)
yea, those are not proper gif links
you need to copy the acutal gif link from the site, e.g. https://media1.tenor.com/m/x39il9SwZK0AAAAC/murro-punch.gif for the first one
oh ill try
just right click the gif and click copy image link
not sure what this is for though..
gets a random gif from the list
but why ''.join lol
just do choices(gifs)
never heard of that either lol, i just use random.choice()
wont it do like the dumb []
from random import choices
ah
yea but choice is different from choices
peak coding
choice selects a single item from the given iterable
choices returns multiple, as a list

my lord this code is like
absolutely cooked
yippee!
ok so now i actually have to make it work when someone pings the user
so its
.superkomfort has knocked @usernamehere
and not
.superkomfort has knocked @spiral wharf
should be easy actually
bingo it was easy!
now i actually see how much better pycord is
yea you just put discord.Member as typehint
Is it possible to hide specific args from showing in the slash command to discord user?
why hide?
I want to use the same function that can be invoked by slash in discord by another command in the program but don’t want use to be able to give a value for it
wdym another command
Function *
can you show what you mean
I have 2 commands on my bot optimize() and backtest(). Backtest takes a bunch of args provided by user. Optimize() is a function that runs on a schedule (not slash command) but it calls backtest().
When backtest is called, there is a “system” flag so it modifies logic if user is using it with slash or if optimize() is calling it.
I don’t want user to see “system” as an arg
honestly I'd just make the actual code of the backtest command a separate function which you call directly from the slash command, and then you just pass idk system=False in your code
that way you can just remove the arg from the command
Hmm okay may have to do a bunch of refactoring then 😅
not really lol
make a new function, paste the entire code there, then just call that function from the command and from your optimize function
that's it really
just wondering how it even works rn like, without a command invocation you don't have stuff like ctx or anything lol
Gotta run will explain later tough
is it possible to get user activity status
i got a wierd idea of using it in getting information of current song playing in spotify
why do you need example code for this
idk i am confussed, but let me try
i will figure it out
"the activities that the user [...] is doing" sounds so weird
i got it thanks
working
yay
but here's the thing, it works only if you have the bot in the server somehow i doesn't for the user installed app
it does, but only for the invoking member
the problem is that other members are only passed as their user equivalent for user apps
and I'm p sure user objects don't have the activities
that or they blocked it anyway (discord)
privacy. You wouldn't want anyone able to just fetch with your ID and get your status/activity would you?
yea
yes it doesn't 🥲
true it's okkay :D
user apps are unfortunately a little too limited imo
how to disable all logger.info to work from py-cord but not from my code (if possible ofc)
like i can do logger.info it will work but all the logger.info from discord will not appear
create a new logger instance which isnt named "discord"
no my goal is to keep discord logger to have the warning etc
logging.getLogger('discord').setLevel(logging.WARNING)
how to remove field from embed?
May be a stupid question but just dont add it in the first place (?)
Some classes are just there to be data containers, this lists them. Unlike models you are allowed to create most of these yourself, even if they can also be used to hold attributes. Nearly all clas...
oh ok thanks
You didn’t understand, I want to be able to reveice the discord logging of warning but to use the same logger to do logger.info for my code and it only show the one from mycode
Ig it’s too specific
how do i make user app commands?
(or something along these lines)
i wanna be able to use russian roulette everywhere
did you already enable user install in the developer website?
yup!
and you already installed it on yourself?
Here's the slash users example.
i think so
But... why...
no offense but probably another one of Lumas crazily overcomplicated ideas that achieve the same thing as something much easier
its the thought that counts
according to my copy and paste it should work
Do you remember actually using the oauth url to install it to your user
If your bot has the "add app" button on its profile you can use that too
LO AND BEHOLD IT DOES!
what is that cat emoji in the bottom right
vencord plugin
i have a little kitty following my cursor at all times
its on top of your pfp now!
oh lol

Logger.info from discord send way to much message ; ) and i like to type logger.info instead of logger.log
That’s how I progress ; )
anyways now ill implement this on every (possible) command now
So set log level on startup and then just use getLogger like everyone else suggested
so i can stop RELYING ON OTHER BOTS!
be careful and test every command
user apps are quite limited
Yeah but so if I do
logger.info it will not appear right ?
you only receive User objects for any User apart from the command invoker for example
so it can quickly break if you use e.g. member.roles
surely if it can send embeds it can send the avatar of the specified user
only the global avatar though, but yes
But ig I will just overwrite the .info func to then if a special key is there is work and else it does not emit
exactly what im lookin for
it cant access the guild-specific one except for the one of the person that used the command
eh i dont mind that
assign getLogger to a variable, then setLevel on it and use that
you mean like so :
logger = colorlog.getLogger("discord")
logger.setLevel(colorlog.INFO)
if yes this will also add the log from py-cord
No, because you're intruding on the discord logger again
Why do you have to use the discord name?
Luma with all your requirements just fork pycord and change everything
literally you want to rewrite like half the library
to get access to the logging like rate limit etc
This isn't even pycord related, theyre trying to tackle a core package now
ah
by rewrite i learn how do that work, its more to progress than else
What
and i didnt change a lot of thing only the class of the bot to create hybrid command
by using that logging when my bot is rate limit or anything else its log it inside the terminale right ?
I guess? But you have to receive all the logs :)
(See docs for how to filter logs, I'm not bothering to explain that here)
if i set it to warning i get everything else than warning, but its okay i will continue to use logger.log. It seems not really logic
also i got another issue, im trying if the logger is more than a certain level to send it via a webhook to discord
so i will first focus on that
thanks for the help tho
is there a way to close out a ctx.defer() without sending a response back (i.e ctx.response())
ok thansk
defer -> ctx.delete?
yes you can according to nelo
You could try defer -> ctx.delete?
no idea, but i see zero use cases where you would just.. not respond at all
if the command timesout
like you should give the user something
it still just says thinking..
then make sure that cant happen
the user has 60 seconds to review the arguments they provide otherwise i want it to delete
I am
like button that edit a message for example -> to not rate limit
async def _confirm_action(ctx, embed):
class ConfirmView(View):
def __init__(self, timeout=60):
super().__init__(timeout=timeout)
self.value = None
@discord.ui.button(label="Confirm", style=discord.ButtonStyle.green)
async def confirm(self, button: discord.ui.Button, interaction: discord.Interaction):
self.value = True
await interaction.message.delete()
self.stop()
@discord.ui.button(label="Cancel", style=discord.ButtonStyle.red)
async def cancel(self, button: discord.ui.Button, interaction: discord.Interaction):
self.value = False
await interaction.message.delete()
self.stop()
async def on_timeout(self):
# Check if the message still exists before attempting to delete
if self.message:
try:
await self.message.delete()
except discord.NotFound:
pass # The message was already deleted
view = ConfirmView()
await ctx.send(embed=embed, view=view)
await view.wait()
return view.value
just use ctx.respond..
so they can cancel and re send command if they provide bad arg
just getting rid of the defer as this is instant and going to put it after
but it peaked the curiosity if it were possible
why do you defer at all then..
just respond and delete the message if the user doesnt do anything
Can you help me with this problem? The command returns an error that it needs permissions but the Bot is admin on the server. It also has intents enabled.
This is the first time I try to modify the nick of a member, is something wrong?
Error:
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
are you the server owner?
yes
and trying to use the command?
yes
bots cant edit server owners
ooohh
also, use ctx.respond(), its shorter and does the same thing
Ah yes, you're right I tried it with my other account and it worked, and thanks for the tip!
i noticed one more thing, the subcommands of a group does not work in user installable apps
like if i have a group called emotes a
and i have a emote named smile so it won't show up in user installable apps
but only works in server that has teh bot
You have to set the install context on the group, not the subcommands
k
let me try
it worked thanks
can someone give me a doc on selects and modals please
thanks
is there any cog.listener for users as in user installable apps
Here's the slash cog example.
like i want to make a afk that works anywhere ( i don't think that will work )
but is there possibilisty it would ?
what are the exact limits of user apps
i noticed my spotify command doesnt work in servers that the bot is not in
they're quite limited
you of course can't join vcs since you're not actually in the server
you only ever get user objects instead of member objects except for the person calling the command
you can't take any actions on the guild, in fact you barely get a guild object to begin with
make sure to limit commands that don't work on user install to only being used if your bot is installed on a guild to not confuse your users
no
according to discord, soon
sad :F
ahh that should do
yeah i do that
but i also noticed that fmbot's /spotify command also doesnt work in other servers
I mean yea, as I said, it's not possible to join VCs with a user app lol
no its not that
its supposed to show currently listening
ah
If you access to the channel to check that it might be the issue since the bot can’t access to that channel
yea you cant get activities of anyone other than the command invoker
because for anyone but the person using the command, you only get the User object, which doesnt have activities
in my case i cant even get activities of the command invoker
or maybe my code is absolutely ass
print(member.activities) ig
what do i do with that
check if there are any? lol
yea i mean then the spotify activity will be there too if you open spotify
oh wait no its right there lol
yea because DMs dont have a member object to pass
as you can see it tells you "User" object
oh
commands that need activities can only work in guilds, and if you have a user app, only on the person calling the command
so i can try and fix it but itll only work on the person using the command?

same
i actually have no idea how to do this
i also had a ton of ideas for user apps but they were all ruined
i REALLY want to do this but i have no idea how
well i told you the limits
i'd probably just limit it to guild installs
ah
https://docs.pycord.dev/en/stable/api/models.html#discord.Member.activities well according to this you should be able to iterate through the activities until isinstance(activity, discord.Spotify)
if i'm reading that right
i did steal some code
and added my own embed
and other stuff
and got this
i mean..
for activity in member.activities:
if not isinstance(activity, discord.Spotify):
continue
# your code here
ah
yea
why is this greyed out lol
do i do that instead of if isinstance
it says its unreachable for some reason lol
but it clearly reaches people
i mean yours is the same thing lol
oh
okay so i put that instead
yea
still greyed out but should work technically
weird
well try to get into that if clause and print something ig
if it works then ignore what your IDE says, but weird
but doesnt it make it optional
Also, i do it like this because there's a concept called something like "exit as early as possible"
It can make your code cleaner, because I have one less indentation than you now for the actual spotify-handling code for example
and that can quickly stack up
No, in the if clause, not in the function header
@bot.slash_command ()
async def spotify(ctx, user: discord.Member = None):
if not user:
user = ctx.author
for activity in user.activities:
if not isinstance(activity, Spotify):
continue
embed = discord.Embed(title=f"{activity.title}",
url=activity.track_url,
description=f"**{activity.artist}** · *{activity.album}*"
colour=0x27b300)
embed.set_author(name=f"Now playing - {user.name}",
icon_url=user.avatar)
embed.set_thumbnail(url=activity.album_cover_url)
return await ctx.respond(embed=embed)
await ctx.respond("User isn't listening to Spotify", ephemeral=True)
thats how i'd do it
also yeah the greyed out part actually works
yea weird, then its just VSC being dumb
peak ide
pycharm >>>>>>>>>>>>
i did use pycharm
but it broke someday and i just switched to vsc
honestly i dont even remember
and remember to do some failsafe if there is no spotify activity, like i did here
i would
also i'd recommend using the @discord.option decorator to handle options with defaults etc
that way you can set descriptions, make it not-required without needing = None in the function header, pass a default etc
ok yeah i really want the descriptions
HOLD ON THERES A FEATURE SO PEOPLE CAN CODE WITH YOU???
hop on
what pycharm plugins are recommended
is there an event that triggers when a user installs the app for himself ( discord.IntegrationType.user_install )
how can I get a roles ID just from its name?
i think like this
role = discord.utils.get(guild.roles, name='Foo')
if role:
role_id = role.id
aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host discord.com:443 ssl:default [Temporary failure in name resolution]
How to solve?
just wait, ur host seems to have some issue
Thx
i think for the moment there is still not even for user_install
how to i make my select menu work for a longer period of time where it doesnt time out and cam be reused
Here's the persistent example.
as in something like this zervy?
self.add_item(discord.ui.InputText(
label="User ID:",
placeholder="",
custom_id="persistent_view:id",
))
.tag persistent
The Issue
When you send a message with a view, button for example
if your bot restarts, you will lose the ability to use this button.
How To Fix This
- Set your view timeout to
None
- By default, the view timeout value is set to 300 seconds
- Pass a
custom_idvalue to the view
- Custom ids must be unique
- Chose a custom id that has a meaning in relation to your view
- Add the view to the bot
- You can use the method
Bot.add_view(YourViewClass()) - Make sure to add the view when the bot begin ready
thanks bro
How do I fix this?
Is Pycord supposed to work with mypy? It doesn't seem to be detecting types from it when I run mypy on my project 🤔
yea but I think in ultimate only
what even is that
are you sure
you don't have to typehint that..
I think
ok
It's the type checker for Python, iirc it's the one most people use: https://github.com/python/mypy
never heard of that, and frankly, I think typehints as they are in python are enough
wanna try
so if it doesn't work it probably isn't supported by pycord
no
aw alright
Well no, I'm not even getting any type hints in VS Code returned from a call to discord.Bot(). That's not correct, right?
but why can i avatar.url but i cant banner.url
what
if you create an object of a class that can only return... an object of that class
there's no way discord.Bot returns anything but a discord.Bot
Yeah, VS Code seems to not even know that discord.Bot is a class... I'm thinking it can't find the types for Pycord, but I'm not sure why
well im using vsc i have no issue at all about that
You're getting types to pop up just fine?
if you ctrl+click discord.Bot it should bring you to the appropriate file in Pycord tho
if it doesn't chances are you didn't install it properly
yea that's one thing vsc does do properly at least
does anyone know
if it doesn't do that something is wrong
I thought so, maybe there's something wrong. I have it installed with Poetry, how did y'all install it?
check the docs
pip lol
pip install py-cord
yes, the dash matters
venv -> requierment.txt
and venv, yes
why does the search work so slowly in pycord doc 😭
Yeah I've been using that, I'm just trying it in a fresh venv to see if it makes a difference. Just one sec lol
it's not slow, the results are just genuinely ass
e.g. if I look for Member, discord.Member is like the tenth result
why.
that too
but it has no delay for me
i do have a couple
bro looked up team fortress 2 in the Pycord search
I DIDNT I SWEAR
ITS PROBABLY FROM ANOTHER WEBSITE
what browser even is that
please do
yknow what sure
hands down ogx is the worst big browser if I had to pick
can i transfer data
p sure there's an import process yea
from the bottom to the top of my heart thank you for encouraging me to switch
just did
also #general lol
I did some testing @sage tendon @fresh sierra, and it looks like my typing tools freak out when mypy is set to use strict typing (types won't even appear in VS Code if I have the setting set up in mypy's config file). Is this expected?
for what do you really need mypy?
To make sure I'm using everything correctly in my project, afaik it's used pretty widely
Just seemed like best practice to make sure I'm coding good
I can just talk for myself but I have never seen anyone use that
you cannot really use anything wrong if you know what you are doing
and seems unnecessary
you don't need typehints all that often anyway
just for function parameters and if you feel fancy, function return values
Both of which are hard to get wrong
I mean Pycord uses them: https://github.com/Pycord-Development/pycord/blob/master/.github/workflows/lint.yml#L31-L53. I've seen it used on a lot of other project, but that's besides the point. I was mostly just wondering if y'all know anything about Pycord getting janky with strict mode on
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - Pycord-Development/pycord
yea but Pycord is a whole big library
To be fair I haven't used mypy a ton in my Python programs yet, but it seemed like best practice from all the projects I've seen using it. Would you guys know if strict mode is just not supposed to be used or something?
your bot is like 1% of the code probably
my genuine advice is, don't use it
if it just causes issues it's not worth it
Well yeah ofc, but it doesn't change the fact that I want to make sure I write good code. Typing just helps ensure that
Alright, sounds good
there's not really much you can do wrong
if you typehint at all you're already better than many
I'm coming from type-forced languages like Rust, I just like ensuring bugs don't get introduced where they could be avoided. Better to catch them now before they pop up later on lol
But is Pycord itself not meant to work with strict typing? That's moreso a question outside of the scope of my project, is that some faulty behavior with Pycord or is that intentional?
I mean as I said there's not much to get wrong
If you typehint a command parameter incorrectly you will inherently notice because it doesn't work, and for anything else like return types of your own functions, I don't think you can get that wrong either unless you're very confused lol
like yknow what I mean
I can open an issue for that on GitHub if it'd be better too
no idea
Yeah, but I'd still like to type everything if I can, it's not really much more work from my perspective.
I'll go ahead and just make an issue then, I should be good outside of that. Unless you got any other thoughts haha
I mean you can type everything :> it's just not strictly enforced
and tbh ive never typehinted up until a year ago or so and never had issues really
Yeah of course, I guess Rust just got me into a certain pattern of programming. I'm not positive if strict typing is the norm in Python, but I guess I'll find out more on that once the issue's up :/
type hint is always a good thing to do
Rust enforces it, it's all I know anyway 😭
Should be good once I get this issue posted though, thanks for the help up to this point 🙏🙏🙏
strict typing is also often a hindrance and annoying, in my limited experience with python
I do it in python to for more autocomplete at the IDE
in python I have functions that can return like 3 different types
pain to do in java
well, impossible in java unless you duplicate the code
in python you can easily typehint it
;3
yes
| None is python's any lol
not really but close enough I know
and correct me if I'm wrong but I think if you typehinted something like
number: int = string_function()
it would show a warning in your IDE
as long as the string function has a return type hinted
ay @sage tendon i took your advice to do some doc surfing and now my banner command works woohoo!
I have yet to find an actual error in the docs
And everything is there
well some very obscure classes are missing but if you need those the question is rather "what are you doing"
can someone help me with this please: TypeError: LeakCodeModal.__init__() missing 1 required keyword-only argument: 'title'
cogs/panels.py:
class LeakCodeModal(discord.ui.Modal):
def __init__(self, *, title: str) -> None:
super().__init__(title="Leak Code")
async def on_ready(self):
if not self.persistent_views_added:
from cogs.panels import LeakCodeModal, StartMessageModal, FinalModal
self.add_view(LeakCodeModal())
self.add_view(StartMessageModal())
self.add_view(FinalModal())
self.persistent_views_added = True
your __init__ requires title but you don't use it
def __init__(self, *, title="xyz") -> None:
?
You don't need the title in the __init__ method because you already use the title in super().__init__()
If you don't need additional parameters you should just use __init__(self)
Thanks for that just a quick one should i not have my modals in my on_ready just the view?
@errant trout here's the whole method
from discord import Poll, PollMedia, PollAnswer
@commands.slash_command(guild_ids=[717808299675877406], name="poll")
async def poll(self, ctx, question: Option(str), option1: Option(str), option2: Option(str)):
"""Start a poll"""
try:
await ctx.response.defer()
except:
pass
poll = Poll(question=PollMedia(question), answers=[PollAnswer(option1), PollAnswer(option2)], duration=1, allow_multiselect=False)
print(poll.to_dict())
await ctx.respond(poll=poll)```
I just checked and discord.__version__ prints 2.6.0
File "/usr/local/lib/python3.11/site-packages/discord/commands/core.py", line 138, in wrapped
ret = await coro(arg)
^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/discord/commands/core.py", line 1078, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "/crewbot/cogs/misc.py", line 106, in poll
await ctx.respond(poll=poll)
File "/usr/local/lib/python3.11/site-packages/discord/interactions.py", line 618, in respond
return await self.followup.send(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/discord/webhook/async_.py", line 1790, in send
data = await adapter.execute_webhook(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/discord/webhook/async_.py", line 224, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message```
hm, using the same code it worked on my end...
long shot, rename the command function?
trying py-cord==2.6.0 real quick
still broken
rename doesn't work either
pycord supports python 3.12 right?
I just realized my dev container was still using 3.11
same error with 3.12
yes
idk i literally can't repro
what if you change the token
if you wanna dig through source, it's all handled here (just ctrl+f for poll)
maybe try sending it with content?
weird
I'm having some issue with having selecting a news channel with a discord.TextChannel type in a command, I have it as
async def setchannel(ctx: discord.ApplicationContext, channel: discord.TextChannel):
bot can list other channels fine, but it seems that news channel are not accepted as a valid option there, is there another selector I have to use for that?
the type of option is handed to discord which then chooses what to display to you
i suppose they made it so you cant put news channels there
hm, that's certainly interesting
I have the same behaviour for my bot though, never noticed that
i never noticed my announce command which is supposed to announce stuff in announcement channels doesnt work in announcement channels
can I delete the bot's own messages simply by passing the message id?
await bot.get_message(<id>).delete()
wont work if its not cached, keep that in mind
so any messages sent before the bot started wont work using that
if you want to delete uncached messages its a bit more of a pain, since you need to store the channel ID too
yea then you can do
message = await bot.get_channel(<channel_id>).fetch_message(<message_id>)
await message.delete()
thanks, so what is delete_messages() used for then?
well, if you wanna delete more than one message in the same channel
but it needs a list of messages
you could make use of https://docs.pycord.dev/en/stable/api/models.html#discord.TextChannel.purge too
but id still end up needing the whole
bot.get_channel(<channel_id>).fetch_message(<message_id>)
right?
well, since you need to pass the messages as proper object, yes
if you need to delete multiple messages just use purge IMO
i know zervy
not you
:>
but as long as the channel exists, get_channel shouldn't be None
nah only a single one for now. Might need that in the future tho, so good to know
what if I use
fetch_channel()
in stead of
get_channel()
Only if its in the cache
yea you can pass a check function to purge where you can just do return message.author.id = <bot_id>
both
which itll always be unless they meddled with the case
use both and check if its in the cache
avoid fetch whenever possible, btw
always try get first
I personally have never had get_channel fail as long as said channel exists
I'm not sure if pycord limits cache itself when the bot is in too many servers, but i doubt you'll ever have problems with it
why is that? I somewhere read that if get_channelreturns none then you should go for fetch_channel, but at this point if fetch_channel is safer, Ill just go with fetch_channel
Because you wanna send as few API requests as possible
API requests take time, and they also count towards the, well, API ratelimit
oh so get simply checks in the cache
yes
.get_x
Any function that starts with get_ in Py-cord is retrieving the related object from your bots cache. If the object is not in the bots cache the get_ method will return None. Because of this behavior you should check if the get_x method is None and if it is use the fetch_x method.
Why Is Using fetch_ Without Using get_ First Bad?
The fetch_ method makes a call to the discord API. This API call is unneeded if you already have the information. It will also make your command take longer because it will have to send and than wait for a response from the discord API. It will also contribute to the discord APIs global rate limit of 50 requests per second.
What Is Cache?
The cache is a temporary storage inside your bot. It holds many objects from members to messages. When you restart your bot the cache will be empty. When the cache is full it will delete older objects to make space for the new objects.
get is instant, fetch needs an API call which can take ~300ms or so to come back
can add up a lot, plus ratelimit issues if you do it a lot
there's also discord.utils.get_or_fetch but i find it a bit weird personally
for completeness sake
good thanks, I just learnt something new. Whats the discord rate limit?
well, pycord handles that itself
and fetching stuff like channels should have quite a high one
dont worry about it
I do it like this
but still, use get whenever possible
Absolutely, I will
example:
channel = await discord.utils.get_or_fetch(self.bot, "channel", channel_id)
I try to get more and more into OOP
thanks, I think Ill stick to the original
try get
except fetch
no nvm im dumb I meant
if get is none ill go for fetch
yes
no, because it only works on the cache which is in memory
its so fast that async is unnecessary
use discord.abc.GuildChannel
Discord does not agree
We don't have a NewsChannel class because it serves little purpose, but it's its own type
plus it contains any channel, right?
ahh, ok
GuildChannel is any channel in the guild yes
so even categories?
Probably
let us see
Otherwise you can refine it with the channel_types param
Also lol #1226541894113431663 message
with discord.TextChannel as the main type too?
Yeah
Main type can be any channel class if you use channel_types, it gets overridden anyway
does contain categories
interesting
never seen that before
but you cant make it list only announcement channels right?
You can if you set channel_types
when I send with content, it sends just the content and not the poll
...what if you don't defer?
if i had to guess (uneducated guess!) you can't send a poll after deferring for some reason
that, or pycord bug with deferring and polls
works without defer
yes?
send us your code please i wanna test too
the poll gets sent without defer
like the minimal breaking code
lets see
idk looking through the source there's zero reason for it to not work
😄
option typehint spotted i hope you stub your toe
Yoooo he's real for that
I'm not rewriting a 2000 line bot just because you have an opinion
why not
shorter
same thing
a defer can fail?
yes
If you've already responded/deferred
but as the first line?
if you do a defer at the slash command and add a defer to a sended button
How can I type hint a drop-down / drop-down values to say it is a str drop-down?
That's not what I meant
can you repro @sage tendon
Then what
i can reproduce
Wtf
3 different results
but yes infinite defer
amazing
If I access dropdown.values I want to type hint something in a way that it know it is a list of str | None
if i pass any content, it works
then list[str | None]
you get the poll and the content?
yes
I just get the content
does your bot not log errors?
The type checker is going to yell
uhh
Why
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
""" Send help message when a mis-entered command is received. """
print('Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr)
traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)```
command errors but what is for events?
i have an error handler that eats the error i think
its a listener, but it doesnt handle that type of error i think
I want to type hint m drop-down so that it's values are typed as list[str]
Hey I'm doing some type checking on my project and getting weird type errors.
Code like guild = await bot.fetch_guild(GUILD_ID) is returning types.guild.Guild instead of discord.guild.Guild according to the pyre type checker. This is causing all sorts of weird type issues downstream. Seems to happen for other core classes like Messages, Interaction, etc. Any thoughts as to why?
stay in one channel pls
Deleted in #general, sorry
yea okay if i force the error to be printed, i get it too
404 @fickle salmon
you already created a thread
you mean 400?
yea 400 mb
why can't nelo repro
nelo
@discord.slash_command()
async def poll(self, ctx: discord.ApplicationContext):
"""Start a poll"""
await ctx.defer()
poll = discord.Poll(question=discord.PollMedia("question"),
answers=[discord.PollAnswer("option1"), discord.PollAnswer("option2")], duration=1,
allow_multiselect=False)
print(poll.to_dict())
try:
await ctx.respond(poll=poll)
except Exception as e:
print(e)
This is my minimal code that throws the error
can you try exactly this code
ok, can repro, but fully convinced this is a discord error
defer -> respond results in Interaction.followup.send - this is equivalent to Webhook.send
the weird thing is, regular webhooks can send polls
they use the exact same method for sending, yet only followup webhooks fail
I'll see if I can raise it with them, somehow...?
Kek?
is it possibile to create a command that only a user can see? like a guild command but just for a user
change the command permissions (settings > integrations), or look into user-installable commands
Here's the slash users example.
is therea bug within the pycord library? When I try to replace an image by using
message_to_edit.edit(content=post_caption, file=discord.File(post_bytes))
it just adds the new image without replacing the old one
try files=[discord.File...]
attachments = []
to remove the current attachments
does this work too?
files only adds new files
i see
ok, i need to update pycord for slash commands users?
2.6 yes
bruh
need to change something between the 2.4.1 to 2.6?
It had a few changed and breaking stuff ;3
this works, thanks!!
Am I dumb or is this not using semantic versioning then since breaking changes are being released in a minor version when it should be marked as a major release?
they aren't mutually exclusive, but yes, we did technically break semantic versioning, but it wasn't part of the core library
Oh. I was told by someone in here that it used semantic versioning when v2.5 was released lol. I asked if there were breaking changes and they told me it was a minor release and I should learn semantic versioning. What's funny is I had a breaking change when moving to 2.5 lmao
we try to avoid breaking changes but if discord changes something, then it's out of our control
Anyway, I came to say when I searched "textchannel" in docs.pycord.dev it gave me a cloudflare error but not anymore so nvm guess it was a glitch
unironically might have been me
3.x :>
wouldn't that make it ironic?
discord bot cached_message attribute takes up memory right
yes
well for the options in a slash command how to not make it compulsory, like let's say i have a emote cmd to wish good morning, how do i make it such that it can do it without adding a user as a parameter, it works with user apps but not in server where the bot is
async def goodmorning(self, ctx: discord.ApplicationContext, user: discord.User = None):
gif = await get_gif("anime_goodmorning")
if user == None:
embed = discord.Embed(
title=f"{ctx.author.display_name} Wishes Goodmorning",
color=0x2F3136,
)
embed.set_image(url=gif)
await ctx.respond(embed=embed)
if user != None:
embed = discord.Embed(
title=f"{ctx.author.display_name} Wished {user.display_name} A Goodmorning",
color=0x2F3136,
)
embed.set_image(url=gif)
await ctx.respond(embed=embed)
i want to take a mp3 file as input from the user , how can I do that?
Here's the slash options example.
See the last command of the example above, lmk if you have any questions about that
will we have attachment (for my case a audio file) as file = await attachment.to_file()? Can I save it locally?
.rtfm discord.File
https://github.com/Pycord-Development/pycord/blob/master/examples/audio_recording.py
in this example , how should I save the audio file locally , I tried with File.fp , but it's output is only noise
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - Pycord-Development/pycord
whenver I'm attaching a audio file it doesn't response
working fine with images
show your code
exactly what's given in the github example
.
any error?
Traceback (most recent call last):
File "C:\Users\praff\PycharmProjects\AutomatedScreening\.venv\lib\site-packages\discord\commands\core.py", line 138, in wrapped
ret = await coro(arg)
File "C:\Users\praff\PycharmProjects\AutomatedScreening\.venv\lib\site-packages\discord\commands\core.py", line 1082, in _invoke
await self.callback(ctx, **kwargs)
File "C:\Users\praff\PycharmProjects\AutomatedScreening\core\platforms\discord\client.py", line 127, in say
await ctx.respond("Here's your file!")
File "C:\Users\praff\PycharmProjects\AutomatedScreening\.venv\lib\site-packages\discord\interactions.py", line 616, in respond
return await self.response.send_message(*args, **kwargs)
File "C:\Users\praff\PycharmProjects\AutomatedScreening\.venv\lib\site-packages\discord\interactions.py", line 957, in send_message
await self._locked_response(
File "C:\Users\praff\PycharmProjects\AutomatedScreening\.venv\lib\site-packages\discord\interactions.py", line 1288, in _locked_response
await coro
File "C:\Users\praff\PycharmProjects\AutomatedScreening\.venv\lib\site-packages\discord\webhook\async_.py", line 222, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```
add await ctx.defer() as first line of the command
your internet is too slow to upload the file in time i guess
@self.slash_command(name="attach_file")
@option(
"attachment",
Attachment,
description="A file to attach to the message",
required=True, # The default value will be None if the user doesn't provide a file.
)
async def say(
ctx: ApplicationContext,
attachment: Attachment,
):
"""This demonstrates how to attach a file with a slash command."""
await ctx.defer()
if attachment:
file = await attachment.to_file()
self.process_audio(file.fp)
await ctx.respond("You will recieve the response in your dm. Please keep the permission to get Dm open")
else:
await ctx.respond("You didn't give me a file to reply with! :sob:")
this is the code and I've a pretty decent internet
self.slash_command
what
lol
self is reference to bot
I'm inheritingg it to create a client
You shouldn't get a 404 with that code
class DiscordClient(Bot):
it reponse 404 in 15 secs 😅
yep ik , update required to True, so yeah
required is true by default, you dont have to specify that btw
first I want to make it work , optimisation can be done later
oh, i see now
i think
File "C:\Users\praff\PycharmProjects\AutomatedScreening\core\platforms\discord\client.py", line 127, in say
await ctx.respond("Here's your file!")
this is the issue, however that gets called when you run that command
unless im missing smth
what even is that file path
also, why?
wanted to add few methods
is it possible to map every command name and description?
Wdym
Like, load them from a file or something?
no
for example:
for command in bot.all_commands:
print(command.name, command.description)
i am asking because when i printed bot.all_commands i didnt see description
Uhh it'll still be on the command object
cant you use the walk_commands thing
@commands.slash_command(name = "test")
async def test(self, ctx):
for command in self.bot.walk_commands():
print(command)
output:
help
walk_application_commands
since ur using slash
got it
What is the rate limit for channel creation in a guild? And what channel types are affected by this?
i only know channel renames, which is 1 rename per 10 minutes per channel
i think channel creation will have a relatively low ratelimit as well
id honestly just try to run into it deliberately but thats up to you lol
honestly no clue, it just let me create 100 channels in 13 seconds
o.o
(50 each on 2 bots)
@bot.slash_command( contexts={discord.InteractionContextType.private_channel}, integration_types={discord.IntegrationType.user_install}, )
what if i want that command in a DM with a bot?
i mean what's the context name
private_channel is correct
not
?
eh, bot_dm?
private_channel is correct
restart discord after changing anything like that about a command
Just realised it's kinda difficult to even get into a user app's DMs, like you have to use a command to do so
Hey there, what's the limit of options in slash commands?
25
But why do you ask?
I have a command that should rotate images by a specified number of degrees, so i want to know what's the limit of images i can pass in a slash command
wouldnt a single option that can handle a zip file be preferable
Yeah, definitely i just wanted to avoid that the user has to create a zip file. But having 25 options is probably worst than the zip file
why do you want to rotate so many images
Im working for someone else idk why the want something like that 🤷♂️
I just created a channel using an http api request and it gave me back the rate limit headers saying like 2000 left and reset in 3.5 hours. So I guess it's 2000 per few hours...
But maybe it's different for public bots. That was a bot that's just on my server.
yeah, I guess bots that are in multiple guilds have lower limits...
no lol
what
screenshot
yea but nothing there says this lol
yea
that's exactly what I was saying lol
you said bots in more guilds have smaller ratelimits
oh that was just an assumption...
oh I read your message wrong... thought you responded to the other.
Hello. How can I create a private text channel, which only 1 role, and 2 members can view the channel? I think you use the overwrites argument in Guild.create_text_channel, but my question is how to get the @everyone role so i can set the view channel permission to null
does index 0 of guild.roles return this?
nvm found Guild.default_role
just a bot
application
:9
I have a string I am using in an embed
self.buyer is interaction.user.id
but the output returns this instead of pinging someone with the @ like @sacred gale
how to make it ping someone
Are you adding backticks
it works, thanks guys
As a side note since it’s an an embed they won’t be notified
man
I don’t think he recognized me
No I’ve been here for ages I like looking at the questions for fun
someone give this man helper role
lol
Hello everyone!
What options do I have to embed a video on Discord so that another user cannot download it?
If I send the video directly to the channel, I can't disable the download of the video, can I?
Don't think so unfortunately
how can I send an album of images (or a mix of images and videos) in a single message?
You could create a list and then send the list using ctx.send?
is that something that works for sure or is that something youre suggesting to try
async def send_album(ctx)
file_list = [
discord.File("path/to/...")
discord.File("path/to/...")
]
await ctx.send(content="message", files=file_list)```
I've not tested it personally, no, but i see nothing wrong with it?
did i type it incorrectly or?
is your respond now yellow too? ;3
nice
should be good now
Huh I mean yeah but interesting that it's blue 😂
Okay that's really one thing that's missing from Discord...
For application its in blue and bridge etc in yellow
I use application myself and it's yellow 💀
it depends on your theme...
White during the day and dark during the night...
I was drung probably
drunl
drunk
also idk about yall but i hate this style of
functioncall(
args, kwargs, owo
)
it just looks weird imo
like at least for shorter calls
idk my formatter does it for me so I don't have to think
because thinking uses your brain
and using your brain makes your brain age
and so you die faster
black?
depends but most of the time it's black
depends?
also yea idk i just use the default whatever thingy, "reformat file" on save and thats it
Well some projects aren't mine
I cant always decide
and I try to use new things too so I change sometimes
not only, function are usually yellow and using application context its blue, its like a property
yeah
Why does the whole thing not work although the file parameter is specified in the docs under create_thread?
video_file = await video.to_file()
thread = await channel.create_thread(name=title, content=message, file=video_file)
Error:
400 Bad Request (error code: 50008): Cannot send messages in a non-text channel```
your channel is not a text channel
I try to create the whole thing in a forum, a new thread with the Video in the first message
print the channel name first to ensure its correct
It is a discord.ForumChannel
well, then i dont know
One question, does the bot attribute of the User object also work for other Bots? I want to check if a message is sent by a Bot
yes
ok ty
@commands.slash_command(
name="create_video_thread",
description="create_video_thread",
)
@option(
"channel",
description="Forum Channell",
type=discord.ForumChannel,
)
@option("title", description="Titel ")
@option("message", description="Message")
@option(
"video",
description="Video",
type=discord.Attachment,
)
async def create_video_thread(
self,
ctx: discord.ApplicationContext,
channel: discord.ForumChannel,
title: str,
message: str,
video: discord.Attachment,
):
try:
await ctx.defer(ephemeral=True)
if not isinstance(channel, discord.ForumChannel):
await ctx.respond(
"No forum Channel", ephemeral=True
)
return
video_file = await video.to_file()
channel_type = channel.type
print(channel_type) # Gives me forum
thread = await channel.create_thread(
name=title, content=message, file=video_file )```
Ignoring exception in on_connect
Traceback (most recent call last):
File "C:\Users\luca\PycharmProjects\***\.venv\lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\luca\PycharmProjects\***\heart\bot.py", line 63, in on_connect
await self.sync_commands(delete_existing=False)
File "C:\Users\luca\PycharmProjects\***\.venv\lib\site-packages\discord\bot.py", line 742, in sync_commands
registered_commands = await self.register_commands(
File "C:\Users\luca\PycharmProjects\***\.venv\lib\site-packages\discord\bot.py", line 595, in register_commands
data = [cmd["command"].to_dict() for cmd in filtered_deleted]
File "C:\Users\luca\PycharmProjects\***\.venv\lib\site-packages\discord\bot.py", line 595, in <listcomp>
data = [cmd["command"].to_dict() for cmd in filtered_deleted]
AttributeError: 'Command' object has no attribute 'to_dict'```
i cant figure out why this error occurs, any ideas?
Well in THE SAME theme, sometime the respond is yellow or blue according to the class :)
for me its always the same color
what did you do since it last worked
so it doesnt create the thread at all? or does it throw the error below that
can you show the pip list ?
I am trying to read the docs and I am confused, how do you actually create application commands?
# in a cog
@discord.slash_command()
async def name(...)
# without cogs
@bot.slash_command()
async def name(...)
AttributeError: 'Bot' object has no attribute 'slash_command'. Did you mean: 'add_command'?
show your code
too big for discord message so I am sending the file
show your pip list
i think you have discord.py installed
also whats that class from lol, and why
aiocache==0.12.2
aiohttp==3.9.5
aiosignal==1.3.1
async-timeout==4.0.3
attrs==23.2.0
brawlstats==4.1.1
cachetools==5.3.3
certifi==2024.2.2
charset-normalizer==3.3.2
dnspython==2.6.1
frozenlist==1.4.1
geographiclib==2.0
geopy==2.4.1
idna==3.7
motor==3.5.1
multidict==6.0.5
pillow==10.3.0
py-cord @ git+https://github.com/Pycord-Development/pycord@5ad95dc1dd8db8bd1b674c184cd032c5d1bbbb07
pymongo==4.7.1
python-box==7.1.1
python-dotenv==1.0.1
requests==2.31.0
typing_extensions==4.11.0
urllib3==2.2.1
yarl==1.9.4
ive tried 2.6.0 too
^
why are you using a git version and not 2.6
cus i was testing out user apps
and forgot to change it back
but yeah i will use 2.6
i still have the problem tho
def load_module(module_name):
module = __import__(module_name, fromlist=[''])
loaded_modules.append({'name': module_name.split('.')[-1], 'help_text': module.help_text})
module.setup(bot)
# Load all modules
module_dir = 'modules'
for filename in os.listdir(module_dir):
if filename.endswith('.py'):
module_name = filename[:-3]
load_module(f'{module_dir}.{module_name}')
```are these meant to be cogs?
you didnt just reinstall py-cord @ 2.6 in about .5 seconds
i said i already tested it before
i'm pretty sure it's discord.py code / discord.py install
test it again
if it's magically solved now we'd be poking at nothing
the version is completely unrelated
they have some weird module loading that isn't relevant to this library
I get no errors, the cog loads but unlike the help command from the main file this command doesn't register
import discord
from discord.ext import commands
import aiohttp
import os
help_text = """
`/image [image]` - Sends an image if you don't have image perms
"""
class ImageEverywhere(commands.Cog):
def __init__(self, bot):
self.bot = bot
@discord.slash_command(name="image", description="Send an image if you don't have image perms")
async def image(self, ctx: discord.ApplicationContext, image: discord.Attachment):
temp_file_path = "temp_image.png" # Temporary file path to save the image
async with aiohttp.ClientSession() as session:
async with session.get(image.url) as response:
if response.status == 200:
with open(temp_file_path, 'wb') as f:
f.write(await response.read())
else:
await ctx.respond(f"Failed to download image: {response.status}")
return
try:
await ctx.respond(file=discord.File(temp_file_path, spoiler=image.is_spoiler()))
except OSError as e:
await ctx.respond(f"Failed to send image: {e}")
raise
finally:
os.remove(temp_file_path) # Clean up the temporary file
def setup(bot):
bot.add_cog(ImageEverywhere(bot))
nelo i think you're mixing the 2 people up rn
what could be the issue here
oh that's whack
restart discord
also... you dont have to download the entire file just to upload it again lol
that code was originally supposed to work with disnake so I had to work around an error it spat, but it doesn't have application commands
also whats the point of not giving people image perms if you're gonna give them a bot to send images
also still can't use it everywhere, did I miss something crucial?
okay first of all, what do you mean "everywhere"
...disnake does have application commands
like an app
all bots are apps
when you add it you can use the commands everywhere exernal apps are allowed
user apps? you never set a context
Here's the slash users example.
thats a user app
and you need to make your bot user installable and install it on your account
its on by default for new bots though
Also I'm not quite sure right now but if you lack permission to send images, can you actually bypass that like that?
like what
no clue, but typically Attachment option doesn't work without channel permissions
My guess is it'd be forced to be ephemeral
To send message without perm with a bot u can pass them inside an embed if it’s picture
cannot really remember, do you maybe know what could cause this? i could also revert files 1 by 1 and then check whats causing this but it would be some afford..
do you still run into the same issue on 2.6?
The thread is not even created and I get the error message
ah
yea then i truly dont know
does anyone have a link to an exemple/in the doc of how I could make a slash command that will display a color picker so my user can choose a color ?
doesnt exist
you'll have to make that some other way, usually you just give them color choices that have the actual hex codes as values
you're right but the most important thing for me is that my user can input precise colors
yea i'm not sure right now but i think if you put discord.Color as input type it should convert the hex color to a discord.Color
but i dont do stuff with color often, could be wrong
thank you I'll see
you can make pylance ignore those warnings with some setting thing
convert one command to use decorators
trust me
idk how
also do you not put descriptions or anything lol
never used the decorator side of things besides making commands and checks
its the exact same args
i do its just cropped
with this in particular, you could literally leave discord.Option away entirely and have the same result
here, an example command of mine with quite a few options
but yea the reason you get that warning is that i think it's not really intended to use function calls in place of typehints
i mean it works yes but its kinda hacky i think
also reading this text... choices can be attachments?
gotta test that tomorrow
news to me
Well yes but there's default settings 
How can I set the thumbnail of an embed to a local file? Btw, this is in a cog. This is my project structure:
.
├── LICENSE.txt
├── README.md
├── __init__.py
├── __pycache__
│ ├── drawer.cpython-311.pyc
│ ├── firebase_helper.cpython-311.pyc
│ └── helper.cpython-311.pyc
├── assets
│ ├── JosefinSans.ttf
│ ├── __pycache__
│ │ └── drawer.cpython-311.pyc
│ ├── axe_icon.png
│ ├── crystal_icon.png
│ ├── dia_pot_icon.png
│ ├── drawer.py
│ ├── leaderboard.png
│ ├── neth_pot_icon.png
│ ├── smp_icon.png
│ ├── sword_icon.png
│ └── uhc_icon.png
├── cogs
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-311.pyc
│ │ ├── config_cog.cpython-311.pyc
│ │ ├── info_cog.cpython-311.pyc
│ │ ├── ranks_cog.cpython-311.pyc
│ │ ├── stats_cog.cpython-311.pyc
│ │ └── ticketing_cog.cpython-311.pyc
│ ├── config_cog.py
│ ├── info_cog.py
│ ├── ranks_cog.py
│ ├── stats_cog.py
│ └── ticketing_cog.py
├── config.json
├── database.db
├── helpers
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-311.pyc
│ │ ├── config_helper.cpython-311.pyc
│ │ └── firebase_helper.cpython-311.pyc
│ ├── config_helper.py
│ └── firebase_helper.py
├── main.py
├── requirements.txt
└── service_account.json
8 directories, 40 files
mmm minecraft
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)```
where (what file/cog) are you trying to add the file to the embed
the ticketing_cog.py I'm tryna call, and one of those .png files I'm tryna attach
|| Sorry, I got timed out, I didn't know subtexts weren't allowed, my bad, sorry ||
as long as you don't start the path with a /, it'll act relative to your bot's main file
so e.g. use assets/crystal_icon.png with the example the bot shows above
alright, so i do that, and use embed.set_thumbnail?
mhm
alright, lemme give that a shot, thanks
wait can you do chaining with embed stuff? like .set_image().set...
yeah
embeds and polls, someone also requested it for views so maybe it can slip into 2.7
it works with brackets
like I saw in some java code
this.that()
.andthat()
.andthose()
not as neat as other languages, but it's possible


