#Basic Pycord Help
1 messages · Page 26 of 1
discord.Bot(...status=discord.Status.dnd, activity=discord.Activity(...))
Nope doesnt go in dnd
show what you have now
Okay partially there... how can I do autocomplete for a slash command?
Nowww
@target.autocomplete("team") async def target_team_autocompletion(interaction: discord.Interaction, current: str) -> typing.List[app_commands.Choice[str]]: data = [] for choice in TEAM_NAMES: if current.lower() in choice.lower(): data.append(commands.Choice(name=choice, value=choice)) return data
make a function that takes a single argument as its input, and returns a list of strings
then pass its name via the autocomple parameter WITHOUT ()
Take a look at the documentation and our guide
Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!
that link will show you how to use autocomplete
ty
also, since i see "choices" there
dont use autocorrect if theres a set amount of valid choices
if you need that, use the choices= parameter
Found a bug
just because you can't figure it out doesn't mean its a bug
that being said
it also very well could be
what you got
lol
Since when u cant set the bot status in change_presemce
.
that's what you have right now? exactly?
yes
try turning off your code, waiting until your bot goes online, then running it again
@frail ocean is there any other code in your program that manages status? If not, can you send us the context or surrounding code of where it changes?
Des
Yes*
There is no other code. In on ready is this line
this is wrong, status is separate from activity
So how can I change status to dnd
(that being said, i can't get custom status working; i'm debugging it now, but you can alternatively use discord.Game or similar)
in change_presence, status should be outside of your discord.Activity
So I can set a custom status with dnd status?
from docs https://docs.pycord.dev/en/master/api/clients.html#discord.Bot.change_presence ```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
you should be able to, but im not sure if "custom" status is working at the moment
(it may also be that bots can't set that type)
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.custom, state=":poop: ") status=discord.Status.do_not_disturb)```
you're missing a comma but yeah
Like that
Yes wrote fast on phone
already told them that lol
U said to me, that I should set status where I define bot
i told you how to do it, i sent you a line of code
.
well doing it in Bot is only for startup, change_presence is still its own thing
yea but same syntax
oh wait
you need to be on 2.5 for custom status
I know that
Yes
async for chunk in response:
text += chunk.text
if edited:
await ctx.edit(content=text)
else:
await ctx.respond(text)
edited = True
or you can use a conditional expression
async for chunk in response:
text += chunk.text
await (ctx.edit(content=text) if edited else ctx.respond(text))
edited = True
Other question:
How can I get if a server has premium from a bot
Buyed like upgraded
they mean bot subscriptions
you asked this [2 weeks ago](#1132206148309749830 message), i don't really have much else to add on that
He actually asked like 3 times
I also answered that question.
Bruh
Has anyone seen this?
what pycord version are you using?
2.5
This only happens when i deployed it to a new bot, Using my test bot token no issues
weird
lovely
go to discord/interactions.py and move line 72 to line 30
so is there a workaround?
you can probably downgrade to 2.4.1
you want to PR that?
probably
nelo, you mentioned something about already forked master. Was that resolved?
oh right that merged
this worked
just fyi
tyank u
alright ty for finding a fix for it
as in?
that's just the bot's role permission
now they dont appear on the members list
did you invite with bot scope?
did you install it as a user bot?
I dont believe so
how do i do this
well, you can add permissions to that
did not know that how so
in the discord dev portal, click on your bot, OAuth2, URL generator.
Check bot
then check the permissions you want
then copy the link
heyo, in the process of migrating from disnake. Does pycord have a guild-only specific ApplicationContext typehint?
uhhh there isn't a separate one no
Disnake has GuildCommandInteraction which typehints .guild as Guild rather than Guild | None

Like all interactions are under the Interaction class
i mean, you can make your own contexts
if you really want
i'm afraid to ask, but how good is the typehinting on the overall lib?
Here's the custom context example.
internally it's fully typehinted
for the user we don't have anything special aside from some method of using Options
ic ic
maybe AsyncIterators?
interesting...
yo- how do i make guild-only sub command groups in cogs?
guild_only=True in the command decorator
tyvm :3
how would i localise a scg in a cog using #1220155366743212114
i can't exactly type-hint a variable
actually scratch that, is there a way to make slash command groups like this instead;
class Cog:
@slash_command(...)
async def command(...):
...
@command.sub_command(...)
async def sub(...):
...
@command.sub_command_group(...)
async def sub_group(...):
...
@sub_group.sub_command(...)
async def sub_group_cmd(...):
...
hmm no
rather than the whole py class Cog: cmd = SlashCommandGroup(...) @cmd.slash_command(...) async def sub_command(...): ...

given that new (unfortunate) knowledge, how would I go about this?
you can probably manually do it
wdym
i had an idea and i realized it doesn't work
this migration is causing me physical pain
you can definitely localize it
yeah that's currently what i'm trying to avoid using haha
i don't use localization
i sadly have to
there could very well be a simple solution that i don't know
ill keep poking around
mmmm this was possible with "prefix" commands, but it was decided against for slash commands because groups and subgroups cannot be run on their own
what's your issue with the i18n method?
i wanna be able to localise via a json file -- that way i can send off my file to translators and just drop in what they send back
right, which that does
huh
yes, my issue is localising slash command groups
which it seem to not be able to do, no?
it should work fine
they're treated the same as commands
...i guess it's not as obvious as im thinking, but for example
if you have a group /settings, subgroup user and subcommand name all these are valid keys for localization: settings, settings user and settings user name
all good
(admittedly that is entirely theoretical, but i assume it works because that impl. uses command.qualified_name; if it doesn't work, i could try patch it myself to support groups)
Hello, is there a difference between SlashCommandGroup.create_subgroup and SlashCommandGroup.subgroup ?
yes but is there a way to check it on a cmd run
i think you can like store this in a database
or use this
await fetch_entitlements()
@bot.event
async def on_raw_reaction_add(payload: RawReactionActionEvent):
if payload.emoji not in emojis:
return
if payload.channel_id not in channels:
return
SocialCreditTable[payload.user_id] += 5
emoji = f"<:{payload.emoji.name}:{payload.emoji.id}>" if len(payload.emoji.name) != 1 else payload.emoji.name
await payload.member.send(f"You reacted with {emoji}, good job! Plus `5` centimeters of social credits")
print(f"Channel id: {payload.channel_id}, Emoji: {payload.emoji.name}")
@bot.event
async def on_raw_reaction_remove(payload: RawReactionActionEvent):
if payload.emoji not in emojis:
return
if payload.channel_id not in channels:
return
SocialCreditTable[payload.user_id] -= 5
emoji = f"<:{payload.emoji.name}:{payload.emoji.id}>" if len(payload.emoji.name) != 1 else payload.emoji.name
await bot.get_user(payload.user_id).send(f"You un-reacted {emoji}. Bad job. Removed `5` centimeters of social credit")
print(f"Channel id: {payload.channel_id}, Emoji: {payload.emoji.name}")
It just stopped working
What do you mean it just stopped working?
Reacting and un-reacting messages are not doing anything anymore
I don't know why
Did you change any permissions?
lol
Someone removed it, idk who
is this possible to create a custom check asynchrony’s ?
@commands.command()
@customcheck
async def
Checks can be async yes https://docs.pycord.dev/en/stable/ext/commands/commands.html#checks
@errant trout
Bots: Attributes activity, allowed_mentions, application_flags, application_id, auto_sync_commands, cached_messages, cogs, debug_guilds, description, emojis, extensions, get_command, guilds, intent...
took me about 2 seconds on the docs
no need to ping people when you can find all the info in the docs
guys, how do i generate timestamp codes with the bot
i want it to generate codes from the moment i run the command
datetime.datetime.now().timestamp()
hello, is there a way to use a coroutine in the command_prefix ?
async def get_custom_prefix(bot: discord.Client, message: discord.Message):
pass
bot = commands.Bot(command_prefix=asyncio.run(get_custom_prefix()), intents=intents, owner_id=owner_bot)
ty
Shouldn't this make a /help command automatically?
(no, that is not my name in there)
w...why are you running it with asyncio? why are you not just putting your prefix in there?
Because it need to be a coroutine
command_prefix='!'
done
That not What I asked ; )
Yea, but its also not what I asked you
Its for custom prefix so
why do you need to run a function to get the prefix
then you cant do that like that
its the bot's global prefix
I know
you need to handle custom prefixes per-server differently
Because u dont know how it works ; )
Yes it works…
what is not clear in i how can i use an async fonction in the command_prefix ?
are u stupid ?
i explain you
that i need custom prefiux
and since i just swtich to an async database
yea, good luck fixing it yourself
i need this fonction to be async too
again, you do not need to put a function there
I know you want custom prefixes per-server
This is not how you can do that, at all
but since you just insult me, i think you can also fix that yourself
because you just didnt read
and say no it does not work like that
when it work like that
you can use command_prefix to define per guild prefix, i used that for month and it has always work
you need to handle guild-specific prefixes within your on_message
stop insulting me
if you want help, dont be a dick

and again my quesiton is not about this function cos it work
my question is how can i use an async function here
you do not use a function there because for nothing, ever, do you need to do that
i know you love your way, but that is not how its done
so a custom prefix is nothing ?
that prefix field is meant for the global default prefix of your bot
It should just be a string
yea, no, good luck doing it on your own
ok
on my own (just without u)
first u didnt answer about what i ask and u just say it doesnt work when it work and say custom prefix is useless when its not so i think that not a big deal
i said thats not how you handle it. stop twisting my words.
u said use an on_message...
that like 10 times worst than my function
so anways
hi how can i send an ephemeral response
in your message sending function, add ephemeral=True
with an interaction
is doing ctx.response("", ephemeral=True) enough?
yes
hello, is there a way to use a coroutine in the command_prefix ?
i was using a def fonction but since i switch to an async library, i now need to use a async def.
I was thinking about something like that :
async def get_custom_prefix(bot: discord.Client, message: discord.Message):
pass
bot = commands.Bot(command_prefix=asyncio.run(get_custom_prefix()), intents=intents, owner_id=owner_bot)
i was before using this
def get_custom_prefix(bot: discord.Client, message: discord.Message):
pass
bot = commands.Bot(command_prefix=get_custom_prefix, intents=intents, owner_id=owner_bot)
does not seem to be working
show your code
it is a slash command interaction, does that change anything?
it has to be
ctx.respond is right
if is_plan_generated:
embed = await generate_war_plan_embed(embed=discord.Embed(), plan=plan_response)
await ctx.respond('', embed=embed)
else:
await ctx.respond(f"Please add {', '.join(plan_response)} to the sheet", ephemeral=True)```
this is from withing the slash command function
well, show the result in the chat
i only want it to be ephemeral in the else part
.
do you mean the result of the response?
yes
restart your bot :>
it should have the dismiss thing right?
await ctx.defer()
is_plan_generated, plan_response = await war_plan()
if is_plan_generated:
embed = await generate_war_plan_embed(embed=discord.Embed(), plan=plan_response)
await ctx.respond('', embed=embed)
else:
await ctx.respond(f"Please add {', '.join(plan_response)} to the sheet", ephemeral=True)```
here is two more lines before
i am also using defer, does that change anything?
yea
i think you can make the defer ephemeral too
and it has to be for any response to be ephemeral
like await ctx.defer(ephemeral=True)?
yes
you have to ephermeral the defer if you send a message with it
also lil questio nof my own since i read this, how does "invisible" differ from the normal defer? doesnt it always say "x is thinking"?
okay, so if i ephemeral the defer, will it still be a normal message when the if is true? i just want it to be ephemeral in the else part
okay
ah, might not actually
try it and see but i dont think it can override that
rip
yea actually it makes sense that the defer dictates the state
you can work around this though
you can save the defer as a variable, and then respond to that with an ephemeral reply
okay do you see any way out of this? the part that is generating the plan just takes a while
first thing i'd try rn
so
defer_obj = await ctx.defer() ?
lol i literally cannot see a difference whether this is true or false
yea
okay and how do we respond to that?
invisible removes the thinking text/loading animation on components
alright let me try that i really apprecite your help
okay it says defer object has no respond attribute
i just need it to be emphemeral if the plan isnt generated
no
else has to be public
i mean ideally you'd find some logic that runs checks on whatever inputs the user gives so you can defer 2 ways, once ephemeral and once without
thatd be my second idea lol
actually the slash command is without any inputs
on the backed the bot checks if any entries are missing from the google sheet, and if they are i need it to softly tell the moderator whats missing
ah
else the plan can be posted for everyone to see
my third (and a lil clunky) idea would be to respond immediately with a custom waiting text, and then if it didnt work, you reply to that ephemerally then delete the initial waiting message, and if it did work, you just edit that mesage
How long even is the non-deferable response time
not sure ;-;
hits me often too tho
needing to call APIs or smth that take 5s or so so i always need to defer, and it does take away flexibility
id love if defer literally just extended the timeout and didnt generate a message in chat like it does
yeah this is connecting to two diff apis and then doing a fair bit of sorting and all to create the plan
@sage tendon is it possible to change the ephemerality after the initial ctx.defer() is invoked?
proc = self._process
AttributeError: 'FFmpegPCMAudio' object has no attribute '_process'```
How can i fix this
no
did you install ffmpeg
yes
pip and local?
or what is the other module?
meme
Restarting the program xD
What does that mean
User
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: OpusNotLoaded: ```
well it seems like Opus ain't loaded

As this is a fork of discord.py perhaps this might be interesting to you; https://github.com/Rapptz/discord.py/issues/783
As it's a discussion related to this issue
Bruh
Yes
discord.ShardInfo
discord.ShardInfo.connect
discord.ShardInfo.disconnect
discord.ShardInfo.id
discord.ShardInfo.is_closed
discord.ShardInfo.is_ws_ratelimited
discord.ShardInfo.latency
discord.ShardInfo.reconnect
discord.ShardInfo.shard_count
discord.shard.AutoShardedClient
discord.shard.ShardInfo
discord.on_shard_connect
discord.on_shard_disconnect
discord.on_shard_ready
discord.on_shard_resumed
discord.GroupChannel.owner_id
discord.Thread.auto_archive_duration
discord.WidgetChannel.created_at
discord.ConnectionClosed.shard_id
discord.TextChannel.get_thread
discord.ext.commands.AutoShardedBot
discord.CategoryChannel.created_at
discord.ChannelType.news_thread
discord.ForumChannel.get_thread
discord.MessageFlags.has_thread
discord.SlashCommandGroup.guild_ids
discord.SlashCommandGroup.guild_only
discord.TextChannel.category_id
discord.ForumChannel.category_id
discord.StageChannel.category_id
You want to get the guilds which are on shard 1?
As example
like i have a loop with a for guild in guilds, and since i dont want it to be done 10times for each guild, i need it to be done only in the guilds shard
@bot.event
async def on_raw_reaction_add(payload: RawReactionActionEvent):
print("Detected Add")
if payload.emoji not in emojis:
return
if payload.channel_id not in channels:
return
SocialCreditTable[payload.user_id] += 5
emoji = f"<:{payload.emoji.name}:{payload.emoji.id}>" if len(payload.emoji.name) != 1 else payload.emoji.name
await payload.member.send(f"You reacted with {emoji}, good job! Plus `5` centimeters of social credits")
print(f"Channel id: {payload.channel_id}, Emoji: {payload.emoji.name}")
The bot has correct permissions, the reacting still is not getting called
are you sure that the bot still has role in the server ?
yes
The bot literally has admin
Last time u say it was working again after giving him rôle, What did u change in the script since
Nothing
Does the print statement occur ?
Lemme see
So ?
The top is before. After reacting, I ran the command again, and it's not getting called. (The other person that works on the bot sees the console)
Okay, so
u lost me to be honest
Most likely the interaction timed out and the error handler couldn't send a message
Raise the error instead of trying to send a message with it
Wait, it already does that
The thing looks for reacting in emojis in certain channels
The on_raw_reaction_add and on_raw_reaction_remove
yet that's not what's wrong
A slash command they're using to send it (I assume) is taking more than 3 seconds
Huh
Slash commands
I have one command that has buttons
But that command was not ran
All other commands are responding in time
The error is not coming from your event. Its coming from an interaction
You'll have to find it
About your event, do you have intents? I think you need intents for reactions
Ohh yeah, intents... I don't have any
what intents do I need
The default ones
Just added intents = discord.Intents.default()
that should be enough I think
Would it be
intents = discord.Intents.default()
bot = discord.Bot(intents=discord.Intents.all())
or
intents = discord.Intents.default()
bot = discord.Bot(intents=intents)
.
2nd one
alrighty
trying that now
It worked once...
So now i have bot = discord.Bot(intents=discord.Intents.default()).
The bot noticed me react once, and that was it??
No errors
whyyyyyyyyyyyyyyyyyyyyyy

how would the top one even work lol
do you python
What the Toothy means is;
Why would you define the top intents variable if you're not even going to pass it into your bot class.
intents=intents
could be any
intents=variable_name
because the intents you still see in this example is just how the Bot class allows you to pass in intents, so your intents actually get set as intents and not as bot name or something.
yes
guys pls help me: i want to log in a discord channel when the bot starts and when it stops, i already did the part where it logs when the bot is online using on_ready and now i need the other part, here is my code for now:
async def on_ready(self):
await bot.change_presence(status=discord.Status.dnd, activity=discord.Game(name=f"Pycord 2.5"))
print(f"Logged in as {self.user} (ID: {self.user.id})")
print("------")
try:
global lastMessageId
timestamp = datetime.datetime.now().timestamp()
canal = bot.get_channel(1220424323400208524)
lat = round(bot.latency * 1000)
embed = discord.Embed(title="Bot online!", description=f"Started: <t:{int(timestamp)}:R>", color=discord.Color.green())
if lat <= 50:
button = Button(label=f"{lat} ms", emoji=":goodping:",style=discord.ButtonStyle.grey, disabled=True)
elif lat <= 200:
button = Button(label=f"{lat} ms", emoji=":midping:",style=discord.ButtonStyle.grey, disabled=True)
elif lat > 200:
button = Button(label=f"{lat} ms", emoji=":badping:",style=discord.ButtonStyle.grey, disabled=True)
view = View(timeout=None)
view.add_item(button)
message = await canal.send(embed=embed, view=view)
lastMessageId = message.id
except discord.NotFound:
print("Uptime channel not found")
perhaps you'd like to take a look at tasks
.rtfm task
discord.ext.tasks.Loop
discord.ext.tasks.Loop.add_exception_type
discord.ext.tasks.Loop.after_loop
discord.ext.tasks.Loop.before_loop
discord.ext.tasks.Loop.cancel
discord.ext.tasks.Loop.change_interval
discord.ext.tasks.Loop.clear_exception_types
discord.ext.tasks.Loop.current_loop
discord.ext.tasks.Loop.error
discord.ext.tasks.Loop.failed
discord.ext.tasks.Loop.get_task
discord.ext.tasks.Loop.hours
discord.ext.tasks.Loop.is_being_cancelled
discord.ext.tasks.Loop.is_running
discord.ext.tasks.Loop.minutes
discord.ext.tasks.Loop.next_iteration
discord.ext.tasks.Loop.remove_exception_type
discord.ext.tasks.Loop.restart
discord.ext.tasks.Loop.seconds
discord.ext.tasks.Loop.start
witch one should i use?
Click the first link and scroll up for examples
Hello, since im using an async database with my bot in python, i have a lot of those error :
ERROR:asyncio:Task was destroyed but it is pending!
task: <Task pending name='pycord: on_message' coro=<Client._run_event() done, defined at /home/container/.local/lib/python3.11/site-packages/discord/client.py:392> wait_for=<Future pending cb=[Task.task_wakeup()]>>
does someone has an idea about what should i look for ?
any examples of this form?
that's called a modal
Can someone tell me why Music bots in py are so buggy? I kick him out of the voice and then when you make a query whether player is playing.
Player is still playing
Do I have to code a event or smth to clear the player?
if you mean your own bot, yes
Which event and what have to be in the event
vc disconnect ig
And what I have to write in it
find out
😳
hey is this wiki page still updated https://guide.pycord.dev/voice/playing ?
Pycord and Wavelink try to keep the playing of audio as simple and easy as possible, to keep making Discord
there's little investment in them because discord doesn't like music bots
Wdym
well not discord but the big ones got c&d'd by yt and other platforms ages ago
that aside, in general the regular maintainers don't do much with voice
So how can I fix the problem
anyone more interested in those systems is free to contribute to the relevant libraries themselves
fabio its not so hard from the context you gave
if vc disconnect event, stop the player associated with that channel
watch him ask for an example
Is someone creating a help thread and deleting it again?
I saw 6 times a new one and it was gone
I just closed a bunch, discord might have been glitching
Okay thanks bro
cAn yOu sEnD me a eXaMpLe
xDDD 
How do I add a description for the argument?
@bot.slash_command(name="choose")
async def choose(ctx:discord.ApplicationContext, *, choices:str):
"""The bot chooses an item from a comma separated list."""
...
this is what I have right now
@bot.slash_command(name="choose")
async def choose(ctx:discord.ApplicationContext, *, choices: discord.Option(str, description="My Choice", choices=["choice1", "choice2",...]):
"""The bot chooses an item from a comma separated list."""
...```
Np 😄
And in the command u can check that:
if choices == "choice1":
await ctx.respond("Lala")
@bronze mist
do you use if else or match case?
@bot.slash_command(name="choose")
@option(name="choices", type=str, description="item1, item2, item3, ...", required=True)
async def choose(ctx:discord.ApplicationContext, *, choices:str):
"""The bot chooses an item from a comma separated list."""
...
This is my final implementation. Works great now
you can use @discord.option() or discord.Option
you dont need the * at the slash commands
yup, i just did from discord import option
also little tip you don't need the name argument in the slash command decorator
it automatically takes the function name
Wdym
x = 10
if x == 10:
print("Its 10!")
match x:
case 10:
print("Its 10!")
if
thats just a wrong statement
depends on the context
exactly why its wrong
It is possible to do a add_role or remove_role to a member and get the received response form discord?
member.add_role just returns the updated member
Or do you mean you want the raw response...?
Yes I mean the raw response
With the rate limit information
Hmm we generally don't keep it
Rate limits are automatically handled so you generally don't need to worry about them
If you really want you could probably edit role.py to keep the raw response data
But rate limit info would be in the headers which further complicates things
I see, I would need to change how the http.request function work in that case ?
yes ! I currently have recurrent timed role in my bot. With these you can add/remove a role for all members of your server each x time interval(minimum 1 minutes). I just realized that could be problematic for big servers or if some server have a lot of these timed role at the same time.
To solve the issue, I want to implement a system where I do 1 request per server (and skip the guild that are currently rate limited for that route). I am only interested for the member.add_roles and member.remove_roles for that processing. Not all request
exemple: I have guild A, B, C
I process A, B(skip B because rate limited), C, A,B ...
Oh dear
yeah ahaha 😄
yes it is already in 2600 servers
Hmmmmmmmmmm
The thing is, role ratelimits are pretty short
Like, a couple seconds
In practice it's something like 5/5sec? But like all ratelimits are per-route and dynamic, then the client has auto retry so you don't notice anything apart from the short delay and info log
But then the issue comes with this being used at scale, there's a chance the higher level ratelimits are enforced or the bot gets temp banned
yeah per route and per top level parameters. So in my case the add/remove roles from member have different rate limit for each guild
what do you mean ? if I dont go over the rate limit how would I get banned
Well, in this lib it won't let you go over the limit anyway
But if you push them too much (e.g. hitting the hardcap limit) then it's possible there's some automatic pushback against your bot
Again, this is very hard, but not unheard of (and something like editing the roles of every member every minute might attract attention in itself)
Then if that case, I could stop before hitting that hardcap limit no ? in the response discord tell you how manym ore you can to with the time
yeah that it why I am gonna maybe put a minimum
of the interval
now it is 1 minutes, but will probably put something like 1 hour at least
If it's one hour you shouldn't have to worry at all
Maybe have some queue system that spaces out every X edits for larger servers
that would be a good idea !
Do you think it is a good idea to process 1 event per Guild in alternance ? To make it more fair if one Guild take like all the rate limit at a certain time
Well the thing is you can do multiple guilds at the same time
As they have their own ratelimits
But bear in mind the global ratelimit is 50 reqs per second so you don't wanna do too many
I see, I could put them in some queue and process them at like 40 req per second (just to be safe with other events of the bot)!
so it does not the limit to often
also bear in mind that, at a minimum, the amount of seconds it will take to complete is equal to the amount of members
yeah I know ! it cannot run very fast, but as long as it ocmplete it should be fine 😄
Well, for example
3600 members and 1 hour interval would be rather disasterous
Hm lemme just test first
I see ! I can maybe put the minimum interval based on the Guild size 😄
Ok yeah, small test on 34 members took 32 seconds
So you really gotta consider how this scales
I see that is pretty slow 😵💫
this is not the main feature of the bot, so maybe I can say that it might take some time and they got to deal with it 😄
Fair enough
If you do wanna do a dynamic minimum interval, id recommend 2*membercount
that would probably be good yes !
Thank you for your help !
All good
if i create and send a button then how long the button should work?
because I saw in the ticket tool bot when I use a command where the user can press the delete button then that button will work for a long like
bot send the button then if the user presses it after a week it works
by default it is 5 min
then how other bot's extend it to days
and hours
i don’t know what libraries other bots use so I don’t know for sure
in pycord, you use persistent views
js and py
for long period?
yes
ok
just a btw, those aren’t libraries
there are like a total of like 10+ different js and python discord libraries
if i remember correctly you could adjust how long those buttons are active
fr how?
show me what you're using to send it and i'll help looking. only did this with paginator buttons myself
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - Pycord-Development/pycord
is this what you were looking for?
ive been getting many many (10+ in the last 24h) random bot shutdowns due to the connection being severed from my bot on discord's end. i haven't heard of anything breaking API stuff from here or discord, so was curious if anyone knew what was up? last time i updated that bot was about 2 months ago.. been smooth sailing since up until yesterday
Which py-cord version do you use?
could you send the exact error message
also that ^
2.4.1
have to keep clearing output just to restart all the systems and the bot itself. im mostly getting WinError 10054 but also have gotten others similar. for example "cannot write to a closing transport". none of the files in either traceback lead to files written by me. they originate within pycord files, then to aiohttp/requests
I have not seen that before. If it happens again please send the full error here but that might just be a discord issue
then to aiohttp/requests
you probably should not be using requests in your bot. (aiohttp is fine)
all the errors originate from the py-cord files. i cant remember the root of the WinError, but i know the root for writing to a closed transport was aio
funny how it just happened again
incoming AIO error
future: <Task finished name='Task-275' coro=<ConnectionState._delay_ready() done, defined at C:\...\Python\Python311\Lib\site-packages\discord\state.py:567> exception=ConnectionResetError('Cannot write to closing transport')>
Traceback (most recent call last):
File "C:\...\Python\Python311\Lib\site-packages\discord\state.py", line 581, in _delay_ready
future = await self.chunk_guild(guild, wait=False)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\...\Python\Python311\Lib\site-packages\discord\state.py", line 1259, in chunk_guild
await self.chunker(guild.id, nonce=request.nonce)
File "C:\...\Python311\Lib\site-packages\discord\state.py", line 523, in chunker
await ws.request_chunks(
File "C:\...\Python\Python311\Lib\site-packages\discord\gateway.py", line 701, in request_chunks
await self.send_as_json(payload)
File "C:\...\Python\Python311\Lib\site-packages\discord\gateway.py", line 646, in send_as_json
await self.send(utils._to_json(data))
File "C:\...\Python\Python311\Lib\site-packages\discord\gateway.py", line 642, in send
await self.socket.send_str(data)
File "C:\...\Python\Python311\Lib\site-packages\aiohttp\client_ws.py", line 153, in send_str
await self._writer.send(data, binary=False, compress=compress)
File "C:\...\Python\Python311\Lib\site-packages\aiohttp\http_websocket.py", line 690, in send
await self._send_frame(message, WSMsgType.TEXT, compress)
File "C:\...\Python\Python311\Lib\site-packages\aiohttp\http_websocket.py", line 646, in _send_frame
self._write(header + mask + message)
File "C:\...\Python\Python311\Lib\site-packages\aiohttp\http_websocket.py", line 663, in _write
raise ConnectionResetError("Cannot write to closing transport")
ConnectionResetError: Cannot write to closing transport```
im pretty sure that the connection is being closed by discord. it might sometimes cause the winerr, and sometimes cause this
im going to upgrade to 2.5 and restart again to check if fixed
I was looking through the pas t instances of this and the only somewhat solution I wound was that your internet is not good. I dont think this is something that is controllable.
You could run a ping command and see if you are geting higher than nromal numbers
after upgrading i ran into some problems and now my cog loader is not recognizing imports
ModuleNotFoundError: No module named 'typing_extensions'
typing_extentions is built in so im confused whats going on here
Can you show the pip list pls
(run pip list in a cmd prompt)
fixed
well, what was it
broke my app
going 2.4>2.5 should not break anything lol
remembered thing about non-included dependancies in python
what?
i have ~ 25 commands that use discord.Option for arguments, all of them are now erroring and the cogs are not loading
trying to replace options with typing_extention.Annotations as i saw that looked like a fix in the update note
still, not related to upgrading from 2.4 to 2.5
It's a minor update aka it shouldn't (and didn't) include breaking changes
you really shouldnt
just use the @option decorator, my personal suggestion
cleanest and easiest
id believe you if it didnt just break my app man
i mean, i had the same setup as you
nothing changed
what is even the exact error or whatever you get
discord.errors.ExtensionFailed: Extension 'cb_command_edit_raw' raised an error: TypeError: Invalid class <class 'discord.ext.commands.context.Context'> used as an input type for an Option
but really, dont do this
yea i mean you got something messed up in your code lol
its trying to read the context as the input type
what could've happened is that a fix fixed unintended behaviour which you used lol
show your code for your options
@commands.slash_command(guild_ids = DEVELOPER_SERVERS, name = _edit_raw.name, description = _edit_raw.description)
@cooldown(1, _edit_raw.cooldown, BucketType.user)
async def edit_raw(self, ctx : commands.Context,
key : discord.Option(str, "Data Key", name = "data", choices = ["yellow","banned", "blue","currentrank","ranklevel","highrank", "skins"], required = True),
data_ : discord.Option(str, "Data Entry", required = True),
user : discord.Option(discord.User, "User To Edit", required = False)
):
i used the docs to make this header
i mean judging by this error, some option of yours has commands.Context as its input type, somewhere
and if you wanna typehint options, just use the @option decorator
Then you can just typehint the option as the type it is in the actual function header
why do you have commands.Context at a slash command?
oh, yea
has to be discord.ApplicationContext
thats weird, youre right
2 commands had it
weird that it functioned with commands.Context for v2.4
now it at least starts
ill do this eventually, had no idea it was a decorator option. thanks!
finally back to my original issue.. :/
example
thanks lol, i have like ~75 commands and most use my style, but that looks so clean like you mentioned. unfortunately, im having issues with my prod bot, but ill fix options for the next update. i appreciate your feedback
send the line of code that causes this error
bot just fell offline, no console output
i have logging mode on and nothing was printed from pycord nor my logs
on_ready had/has not been called
had to flush output, let me chack quick
what line do you mean?
oh it's during startup?
im almost certain its occuring during the startup/ready process
keep in mind, if you restart your bot with 75 slash commands that you get a ratelimit really fast and your commands are not gonna show up
But if you don't change the commands it doesn't matter no?
i know, im trying to solve the issue asap while staying out of range of the limiter
i dont think it matters, server and client gotta contest potential changes
a restart is a closed connection and the bot has to sync the commands again
like I have 40 commands or something and sometimes my test bot restarts like 10 times a minute and nothing changes
so I am highly sure unchanged commands don't count
Limit is 200 command every day
you have to sync them yes, but not register new ones
yea, register.
40 times the same command with no option changes is still the same command
just got the error again (cannot write to closing transport) and the bot is now up and running seemingly fine
but if you change an option its a different command and needs to be registered
try with another token to see if it's s ratelimit
i would agree this is potentially a wifi/internet connection, however my bot is hosted on my webserver in AWS, so unless theres a big problem with internet down there, its not that
but don't you get the error on your pc (too)?
i have other bots running on my in-house webserver, just checked and none of them have had any disturbances in the past 52 hours. its just this big one with the v2.5 impl
do you use ext.bridge
when it started, its uptime was around 1mo, 16 days so i dont think its that
you mean because of the breaking changes?
taking a jab
no
i fixed it, i had used commands.Context instead of discord.ApplicationContext
why not? 
maybe 1 or 2 (sarcasm)
...seeing that your error is in chunk_guild, that's the relevant question
around 2.1k - 2.5k, honestly i dont keep up with it as i never expected it to be so popular
i have no shards though if thats what youre asking
"im not sharded" if thats the proper way to say it
You don't use autoshardedbot?
no, wha ¯_(ツ)_/¯
...please do
shouldn't you shard at the latest at 2k servers?
It's forced at 2.5k, you're recommended to start earlier
just got the ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host error
wow Minecraft ass error lmao
If you're actually in 2.5k servers then discord is literally rejecting your bot
yikes okay
looks like the next update just got moved up
All about Sharding Discord Bots.
doesn't require any changes apart from bot definition right?
yeah it's not particularly hard
just curious, if its so simple why isnt it just automatically done to every bot? (from the client side)
because it's not intended for smaller bots
is there any downsides to using it anyways, other than a larger amount of resources?
(strictly speaking, every bot is "sharded", just at 1 shard)
enabling multiple shards when you don't have many servers supposedly degrades performance, or something, idk there's just no reason to
in the page you sent, it states that discord will contact me when its time, and they havent yet. should I anyways?
also im really confused about the concept of sharding, i remember reading about it maybe 2 years ago but i still have no idea what it realy does and why its neccesary
LMAO
if you want you can read the full documentation on it here
it's basically splitting the bot across several processes, which each recieve their own events
many large libs make this easier for the user by handling that under-the-hood and routing everything for you
for pycord, you can read about sharding-specific parameters and attributes here
so what im hearing is basically "your bot has so many guilds! this wil make your computer cry because its so hard to process all of that. but now, you can split up the connection so it somehow is.. reads paper less efficient?"
it's not for your computer, it's for discord
when the client is in so many guilds, sending all requests and all events down a single line is inefficient
okay i think i understand now
why do they blow it out of proportions by giving it a big scary name and a whole api page.. thats all i needed to know to understand what/why/how
because that's how documentation works...
thats not what i meant
also lets say i had another bot that im migrating to my web server soon, this second bot is coming up on 900 guilds (as of about a month and a half ago). should I shard it yet? i dont know when to shard essentially
you wouldn't need to, no
You can at 1000, you dont have to until 2500
discord gives such a large window because every bot has different needs
Because under the hood, its a lot more than just changing discord.Bot to discord.AutoShardedBot
some bots will start struggling earlier than others, so they'll start sharding at a lower guild count
a very lightweight bot could make it to 2500 guilds without issue and then be forced to shard anyway (in theory)
my 900-guild bot had a lot more daily interactions than my 2.2-2.5k one (like 4- 6 times as many), should I shard at 1000?
i'd say, give it a go and see if there's any significant changes
Also dumb question about sharding; does every shard run on its own CPU thread? or how is it realised
would the changes be noticable? (response time)
from what i understand no
but im no expert
from what ive seen from other systems, if sharding is similar, no
but im guessing that would be the way to go eventually
(on your end)
well i asked nelo :)
damn i see
anyways thanks for the help, if the issue persists ill come back again. will shard within a day or so
just glancing through the file shards are done with create_task, asyncio accomplishes most stuff concurrently without multithreading
asyncio does have some threadsafe functions, but most of it is singlethreaded
(hence threading is its own library)
ahh
Is there a way in pycord to make your shards run in different server ?
I would literally just try to run the bot on multiple servers with the same code
idk if thats how it works but thats how it should work imo
I see I will try ! Thank you
uhhh in theory, as long as you manually specify the shard_ids
yeah, but there need to have some kind of node that will dsitribute those shard_ids
....congratulations, you discovered the purpose of autoshardedbot
I though it only does it for the same machine, not multiple one
well yeah AutoShardedBot is designed to run in a single process for the user, and it'll determine the recommended shard count from discord and set it
if you want something more hacky then just throw shard ids in and hope it works
and at higher shard counts, you have to start shards concurrently in order to avoid ratelimits
I see thank you !
i think Vincent was working on clustering for v3 (but not anymore) which would be the term for "sharding on multiple machines"
definitely doable
just specify shard_ids & number of shards
only thing is cache won't be shared
@tasks.loop(minutes=1)
async def check_birthday(self):
await self._check_birthday()
print(1)
async def _check_birthday(self):
now = datetime.datetime.now()
for guild in self.bot.guilds:
today_birthdays = await db.get_birthday_date(now.day, now.month)
embed = discord.Embed(
title="🎉 Happy Birthday! 🥳",
description="Let's celebrate with them:",
color=discord.Color.gold()
)
file_path = os.path.join(os.getcwd(), "img", "birthday.jpeg")
embed.set_thumbnail(url="attachment://birthday.jpeg")
birthday_info = ""
for user_id in today_birthdays:
member = guild.get_member(user_id)
if member:
birthday_info += f"🎈 {member.mention}\n"
next_birthday = datetime.datetime(now.year, now.month, now.day)
if next_birthday < now:
next_birthday = next_birthday.replace(year=now.year + 1)
else:
print("Next birthday is today.")
days_until_birthday = (next_birthday - now).days
birthday_info += f"Next birthday in {days_until_birthday} days\n\n"
channel_id, role_id = await db.get_birthday_channel(guild.id)
birthday_role = discord.utils.get(guild.roles, id=role_id)
if birthday_role:
await member.add_roles(birthday_role)
await asyncio.sleep(86400)
await member.remove_roles(birthday_role)
else:
print(f"Member with ID {user_id} not found on server {guild.name}.")
embed.add_field(name="Birthday Members", value=birthday_info)
channel_id = await db.get_birthday_channel(guild.id)
channel = guild.get_channel(channel_id)
if channel:
await channel.send(embed=embed, file=discord.File(file_path, "birthday.jpeg"))
else:
print(f"No channel found on the server {guild.name} for the sender of the birthday message.")``` no embed is sent XD idk why
does the task run at all
yes, everything works, I also get the role and so on, but no embed is sent and there is no error message or anything like that
could you add a print inside if channel and after that if-else?
did you forget to expand the variables? py channel_id, role_id = await db.get_birthday_channel(guild.id) ... channel_id = await db.get_birthday_channel(guild.id)
really you should run this once at the top of your guild loop
because right now you're running it twice for every member your bot is checking
class Birthday(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.check_birthday.start()
@tasks.loop(minutes=1)
async def check_birthday(self):
now = datetime.datetime.now()
for guild in self.bot.guilds:
today_birthdays = await db.get_birthday_date(now.day, now.month)
embed = discord.Embed(
title="🎉 Happy Birthday! 🥳",
description="Let's celebrate with them:",
color=discord.Color.gold()
)
file_path = os.path.join(os.getcwd(), "img", "birthday.jpeg")
embed.set_thumbnail(url="attachment://birthday.jpeg")
birthday_info = ""
for user_id in today_birthdays:
member = guild.get_member(user_id)
if member:
birthday_info += f"🎈 {member.mention}\n"
next_birthday = datetime.datetime(now.year, now.month, now.day)
if next_birthday < now:
next_birthday = next_birthday.replace(year=now.year + 1)
else:
print("Next birthday is today.")
days_until_birthday = (next_birthday - now).days
birthday_info += f"Next birthday in {days_until_birthday} days\n\n"
role_id = await db.get_birthday_channel(guild.id)
birthday_role = discord.utils.get(guild.roles, id=role_id)
if birthday_role:
await member.add_roles(birthday_role)
await asyncio.sleep(86400)
await member.remove_roles(birthday_role)
else:
print(f"Member with ID {user_id} not found on server {guild.name}.")
embed.add_field(name="Birthday Members", value=birthday_info)
channel_id = await db.get_birthday_channel(guild.id)
channel = guild.get_channel(channel_id)
if channel:
print("Sending birthday message to channel:", channel.name)
await channel.send(embed=embed, file=discord.File(file_path, "birthday.jpeg"))
else:
print(f"No channel found on the server {guild.name} for the sender of the birthday message.")
print("Birthday message not sent due to missing channel.")```
uh....
what does db.get_birthday_channel actually do
because you seem to misunderstand your own code
does it return a channel id, role id, both in a tuple, something else?
You get the role and so on, but the channel is also there but it doesn't send everything in, everything is also in the database!
right....
so at the moment, you're doing this py role_id = await db.get_birthday_channel(guild.id) birthday_role = discord.utils.get(guild.roles, id=role_id) ... channel_id = await db.get_birthday_channel(guild.id) channel = guild.get_channel(channel_id)do you not see a problem here?
@tasks.loop(minutes=1)
async def check_birthday(self):
now = datetime.datetime.now()
for guild in self.bot.guilds:
today_birthdays = await db.get_birthday_date(now.day, now.month)
channel_id = await db.get_birthday_channel(guild.id) # Fetching channel ID once per guild
embed = discord.Embed(
title="🎉 Happy Birthday! 🥳",
description="Let's celebrate with them:",
color=discord.Color.gold()
)
file_path = os.path.join(os.getcwd(), "img", "birthday.jpeg")
embed.set_thumbnail(url="attachment://birthday.jpeg")
birthday_info = ""
for user_id in today_birthdays:
member = guild.get_member(user_id)
if member:
birthday_info += f"🎈 {member.mention}\n"
next_birthday = datetime.datetime(now.year, now.month, now.day)
if next_birthday < now:
next_birthday = next_birthday.replace(year=now.year + 1)
else:
print("Next birthday is today.")
days_until_birthday = (next_birthday - now).days
birthday_info += f"Next birthday in {days_until_birthday} days\n\n"
channel = guild.get_channel(channel_id)
if channel:
print("Sending birthday message to channel:", channel.name) # New print statement
await channel.send(embed=embed, file=discord.File(file_path, "birthday.jpeg"))
else:
print(f"No channel found on the server {guild.name} for the sender of the birthday message.")
# Additional print statement after the if-else statement
print("Birthday message not sent due to missing channel.")
else:
print(f"Member with ID {user_id} not found on server {guild.name}.")``` her is mein new code
No channel found on the server test server for the sender of the birthday message.
Birthday message not sent due to missing channel.
Member with ID None not found on server test server.
Member with ID 0 not found on server test server.
Member with ID 0 not found on server test server.
Member with ID 24 not found on server test server.
Member with ID 3 not found on server test server.```
are your IDs saved as strings
(also are those meant to be real users or did you create fake data)
real users
yes
ok so 1) convert all IDs to int when you use get_channel, get_member etc.
and 2) if they're real users why are those IDs so short
because those are obviously not discord user IDs
pretty sure None is not an ID
probably some weird data in their db
json superiority frfr
how can I create command groups while inside cogs
#969574202413838426
i thought i could ask here it's just a quick question 😭
lmao
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - Pycord-Development/pycord
tanks
I justed changed a normal reply into a Paginator using paginator.edit(message=msg) where paginator is just a paginator object and msg is a pervious ctx.respond() message
Now my Paginator doesn't respond to any user interactions? What fixes that?
use paginator.respond
Unfortunately that would ruin the way the bot looks and I really would like to edit the prior message to become a paginator?
No other options?
ah wait are you saying you switched to paginator.edit?
you can fix it by either setting author_check=False or upgrading to master
sorry to sound stupid, but where exactly can I do that lol?
author_check is inside Paginator
alright, thank you, I'll see if it works
just note that disabling it will mean that any user can use the buttons
Yeah thought that would happen, but it isn't a problem as my message is sent as an ephemeral
fair enough
...im not sure if paginator.edit works with ephemerals
but if it does then sure go for it
Yeah it did work, thanks for your help
allgood
@signal trench To get a command by name, you want bot.get_application_command
okkay thankss
Is it possible to add and remove a complete cog while a bot is running?
So that you can expand the bot without having to restart the entire bot?
Yes you can
How can I do it?
When I try it this way, the slash command is still displayed although I get the message that the cog has been unloaded.
And when I try to load it again, I always get an error:
Application command names must be unique
@bot.command(name="unload", hidden=True)
@commands.is_owner()
async def unload(ctx, *, module: str):
try:
bot.unload_extension(module)
await ctx.send(f"`{module}` unloaded.")
except Exception as e:
error_msg = traceback.format_exc()
await ctx.send(f"Error unloading `{module}`: {error_msg}")```
I wonder if sync the command is still working x3
If I use bot.sync_commands(), this unfortunately does not change anything either
In Cog with a prefix command it works without problems but with the slash command it causes problems.
I have also tested whether it makes a difference if the slash command is declared globally or only for a guild, but that doesn't make any difference either.
Add the command to the sync
What do you mean exactly?
Get the command from the cog, unload the cog and sync the command
How can I get the command from the cog?
I have no success with this either 😄
@bot.command(name="unload", hidden=True)
@commands.is_owner()
async def unload(ctx, module: str, command_name):
try:
command = bot.get_command(command_name)
bot.unload_extension(module)
await bot.sync_commands(commands=command)
await ctx.send(f"`{module}` unloaded.")
except Exception as e:
error_msg = traceback.format_exc()
await ctx.send(f"Error unloading `{module}`: {error_msg}")```
I can help you later
i might not understand the doc i guess,
xp_group = discord.SlashCommandGroup(name=xp_.name, description=xp_.description, guild_only=True)
@xp_group.command(name=xp_.setup.name, description=xp_.setup.description)
@is_owner_or_has_perm("administrator")
async def setup(self, ctx: discord.ApplicationContext):
and i have an Extension 'Slashs.XP.setup sub' raised an error: AttributeError: 'function' object has no attribute 'command'
bot is now sharded, still receiving this error occasionally. bot will shut down for a few minutes then come back online (unsure if on_ready is ever called)
Okay thanks 🙂
Cannot write to closing transport usually appears when your bot was shut down incorrectly and tries to come back online too shortly afterwards.
Alternatively it can be caused when something in your bot is blocking async operations for too long and discord therefore assums it was offline. eg; time.sleep, super complex loops, this sort of thing.
might be worth opening a topic for it, sharing error and code
How to do Error handling for specific checks? I created some checks and I'm aware that it raises CheckFailure when a check fails, but how to respond with a message on a failure of a specific check?
I don't want to do this in the "predicate" code for the check itself because then the response message will also be sent on the Help command (with verify_checks enabled)
cant you pass a message to checkfailure?
Not that I know of? Wdym
show your code
This is my allowed_in_channel check, it checks in the database whether commands in ctx.channel are allowed
def allowed_in_channel():
def predicate(ctx):
if ctx.guild is None:
return True
guild_config = GuildConfig(ctx.guild.id)
command_channel_id = guild_config.command_channel_id
if command_channel_id:
return ctx.channel.id == command_channel_id
else:
return True
return commands.check(predicate)
Now when this check fails I want to respond with a specific message, but only when this check fails and not others
okay first of all why do you have a function in a function lol
The Pycord v2.5 docs (https://docs.pycord.dev/en/stable/ext/commands/api.html#discord.ext.commands.check):
and as for your question, I dont really think you can and checks aren't really made for that
Handle it within your command code
Raise an error
With else: raise or ctx.respond
He can and why check are not supposed to do that lmao
Like this check if its’good channel
The error handling of this error raised won't be used on verify_checks in HelpCommand?
It will be check by the help command
So if he is not in the good Channel, ir will be tell
I just don't want the help command's output to send all responses on CheckFailure. I only want to reply with an error message on the command itself
e.g.
!ping -> "You can't do this command in this channel."
!help -> Only show Help response but not that error message
but I do want the Help command to have verify_checks. So the user doesn't see commands he can't use.
ticket closing button doesnt work, if i restart the bot it works once but on the next ticket i get that error
I will not send thé ouput
Just not appear
Alright thanks
Commands have an @error decorator https://docs.pycord.dev/en/stable/ext/commands/commands.html#checks
That page includes an example for CheckFailure if you scroll down
But this is on any check failure right? Is there a way to respond differently depending on which specific check failed?
Create a subclass of checkfailure
(Also on that page)
help?
Are you using add_view
this?
Ah, subclass of commands.CheckFailure instead of what I've been trying with Exception. I missed that. Thanks!
Are you meant to be passing the bot in instead of self?
Your error is with your own code
do you mean instead of the self i should use bot?
Idk man it's your code
i mean i can try, one sec
I'm making a guess based on your error
Right... so what arg do you think should be passed
bot ✅
Congrats
🥳
oh god, i remember using that color scheme
btw, you dont have to typehint an argument you're never gonna use anyway lol
okay haha
and i highly recommend you make a db handler class
because look at how nested your stuff is getting
7 deep
I’ve you really wanna get fancy, use an ORM like SQLAlchemy
also, you don't need an "else" if you return in the initial if clause anyway
iam still getting the same error, after bot restart the button really closes the ticket but then i get the error again
bot.add_view(ticketsystem.MyView(bot))
bot.add_view(ticketsystem.MyClass(bot))
The same error or a new one
Traceback (most recent call last):
File "C:\Users\lenov\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "c:\Users\lenov\Desktop\cogs\cogs\ticketsystem.py", line 307, in callback
async with self.bot.pool.acquire() as conn:
AttributeError: 'MyClass' object has no attribute 'pool'
I feel like you're making the exact same mistake
please dont call it myview and myclass lol
thats like the least descriptive names possible
😂
Why not just do interaction.client like above
this just started happening, the uptime before errors was over 15days with 0 issues. this just started maybe 2 - 4 days ago and is now nonstop
what code? the error root is from the py-cord library. the error is in the message i responded to tho
bangs head on the table
ofc there is an error from the py-cord module when you get a closing transport message.
Also:
When you look through a clean window you can, most of the times, see the world outside. More news at 10.
There still has to be something causing it and the most common source is how and what you do in your code.
Furthermore, it is totally possible that operations work for a long time and some blocking part in your code doesnt have a harmful effect normally, then when a guild with a butload of members runs the same command, you loop through all of them and do sh -> BAM.
This however can only be seen when looking at your code. so make a topic and provide more information or live with it.
also, you are quite literally the only one here with that issue
naah had that too, was able to solve it though
and the flaw was on my end, not with pycord
pycord only provided the error
Thanks for the backup though @sage tendon
wdym?
look at the first line of your callback
again, the uptime was over 15 days before anything happened. ive got 20k-40k interactions on an average day and this just started happening not too long ago. also again, what code. im not sharing the source for my project. im also unsure how any of my code could be forcing or.. really have any effect on the py-cord module at me, if you do know how or why or have an example that would be great.
@lapis dock not cool
Sorry, found the answer although this is a lot easier than self.bot._connection._messages XD
Question for those who want it: How to access cached messages
:p
which permissions do i have to give my bot to get rid of this error
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: PermissionError: [WinError 5] Access is denied
that's your windows, not discord
running as administrator should grant it higher permissions
i suppose that could work
running as administrator does not seem to work
I think it is something in your code, can you send the command you are runing
is it possible to create an attachment option in a slash command and make it optional? i tried using
attachment = discord.Option(discord.Attachment, description="")
but it's still marked as required
this is the code for the command i used when the error occured: ```py
@bot.slash_command(description = "Summons a goose on Villeravn's computer!")
async def goose(ctx):
global goose_count
if goose_count < goose_limit:
goosecmd = subprocess.Popen(['"C:\Users\ville\Documents\programing\python\discord\bots\goosebot\DesktopGoose v0.31\GooseDesktop.exe"'])
goose_count += 1
await ctx.respond(f"Summoned new goose on villeravn's computer, total number {goose_count}")
await asyncio.sleep(90)
subprocess.Popen.kill(goosecmd)
goose_count -= 1
await ctx.respond(f"Goose despawned :slight_frown:, total number {goose_count}")
elif goose_count >= goose_limit:
await ctx.respond(f'Already at max count, total number {goose_count}')
You need to add the required=False to discord.Option
even when its a slash command?
normally i just make it = instead of : and it becomes optional
either windows doesn't have access to open or kill the process (what I think at least)
ive already tried running it as administrator and checking the permissions of my users
Yes, the prefix command way might still work but it is better to explicitly define it.
This might be the issue
https://stackoverflow.com/questions/5573257/windowserror-error-5-access-is-denied-when-trying-to-kill-a-subprocess-pytho
worked, thank you very much
im struggling to see how i can apply this to my code
Is it possible that your exe completes before 90 seconds?
the file im running should stay open indefinately
If you look higher in the error you should see either your open line or kill line. Can you confirm what one it is
File "C:\Users\ville\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\bot.py", line 1130, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\ville\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\commands\core.py", line 376, in invoke
await injected(ctx)
File "C:\Users\ville\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\commands\core.py", line 139, in wrapped
raise ApplicationCommandInvokeError(exc) from exc```
this + the previously sendt error is all the errors i was provided
I'm not entirely sure. You might have some luck in the python discord .gg/python but this is not Pycord related.
alright, ig ill head over there
Sorry I could not help more
cant expect 1 person to know absolutely everything
Traceback (most recent call last):
File "D:\Night Club\.venv\Lib\site-packages\discord\ext\commands\core.py", line 180, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "d:\Night Club\command\clean.py", line 28, in clean
await embed_message.send_embed("Cleared all messages.")
File "D:\Night Club\.venv\Lib\site-packages\discord\ext\bridge\context.py", line 99, in reply
return await self.respond(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Night Club\.venv\Lib\site-packages\discord\ext\bridge\context.py", line 92, in respond
return await self._respond(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Night Club\.venv\Lib\site-packages\discord\ext\bridge\context.py", line 168, in _respond
message = await self._get_super("reply")(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Night Club\.venv\Lib\site-packages\discord\ext\commands\context.py", line 405, in reply
return await self.message.reply(content, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Night Club\.venv\Lib\site-packages\discord\message.py", line 1826, in reply
return await self.channel.send(content, reference=self, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Night Club\.venv\Lib\site-packages\discord\abc.py", line 1651, in send
data = await state.http.send_message(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Night Club\.venv\Lib\site-packages\discord\http.py", line 373, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In message_reference: Unknown message```
?
bot sending this error
Hey, how can I send an audio file (mp3) as a voice message, like the one sent from mobile?
Using py cord
async def join(ctx: commands.Context):
^^^^^^^^
NameError: name 'commands' is not defined
what does this mean
💀
Do you import commands?
i cant
like
it wouldnt let me
from discord.ext import commands
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)
Can you show pip list
aiohttp 3.9.3
aiosignal 1.3.1
attrs 23.2.0
DateTime 5.5
frozenlist 1.4.1
idna 3.6
multidict 6.0.5
pip 24.0
py-cord 2.5.0
pytz 2024.1
setuptools 69.2.0
yarl 1.9.4
youtube-dl 2021.12.17
zope.interface 6.2
If you recently updated Pycord can you restart your ide
hm
now it gives me
raise ClientConnectorCertificateError(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000)')]
You need to update your certificate some how. I could not find anything quickly. You could ask in .gg/python where they might have more experienced people
How to handle a concept of local variables, I mean the ones that are custom to a specific user.
Let's say I have a slash command, and I don't want the user to execute the same command once again if he didn't click the button in the previous one. So yeah, I can create a variable with conditional just for that, but it's "global" it isn't specific to a user, in case where someone else will execute the command it could be blocked because someone else could've typed command already
do you know what dictionaries are?
in python
yes, but I've never seen someone using them in the context of a slash command, I mean veryfing if the same comand was typed out just a second before
and was wondering if pycord has something built-in to make it all easier (with freeing-up the data after it's no longer in use)
that does seem like something that you would be able to handle. If the data is supposed to be somewhat permanent, you can use a database to keep track of it. If the data is relatively ephemeral, then you can use a dictionary.
you can add a cooldown that's tied to the specific user, runing the command to make commands not spamable. is this what you are searching for?
If yes, would you like an example for a simple main file or cogs?
Edit:
a user
the specific user, runing the command
please ping on response, may take me a while to get back here though.
Traceback (most recent call last):
File "C:\Users\fagol\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 131, in wrapped
ret = await coro(arg)
File "C:\Users\fagol\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 1013, in _invoke
await self.callback(ctx, **kwargs)
File "C:\Users\fagol\Downloads\BBA\main.py", line 189, in gengemini
await ctx.edit(embed=embed, view=RegenerateGemini(message, ctx))
File "C:\Users\fagol\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 464, in edit_original_response
params = handle_message_parameters(
File "C:\Users\fagol\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 648, in handle_message_parameters
payload["components"] = view.to_components() if view is not None else []
File "C:\Users\fagol\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 219, in to_components
children = sorted(self.children, key=key)
AttributeError: 'RegenerateGemini' object has no attribute 'children'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\fagol\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1130, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\fagol\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 376, in invoke
await injected(ctx)
File "C:\Users\fagol\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 131, in wrapped
ret = await coro(arg)
File "C:\Users\fagol\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 1370, in _invoke
await command.invoke(ctx)
File "C:\Users\fagol\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 376, in invoke
await injected(ctx)
File "C:\Users\fagol\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 139, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'RegenerateGemini' object has no attribute 'children'```
you view should look something like this
class myView(discord.ui.View):
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
@discord.ui.button(...)
async def callback(self, button, interaction):
interaction.respond(self.arg1)
Is that what you mean
yeah
that
class RegenerateGemini(discord.ui.View):
def __init__(self, prompt, ctx):
self.prompt = prompt
self.context = ctx
@discord.ui.button(label="Regenerate", style=discord.ButtonStyle.primary, emoji='🔃')
async def button_callback(self, button, interaction):
button.disabled = True
button.label = "Regenerating..."
embed = discord.Embed(title="Text Generation (AI Chatbot)",
description=" Regenerating Response...",
color=0x3498db)
...
yes ik im using ctx
...why?
my generate needs the ctx from the command calling itself
you get all the context you need from the button interaction
OOP really isn't hard
you just need to know how it works
and why are you not sending the entire view
I pass in self to my views, but not ctx 🙃
do you ever call
super().__init__(...)?
super what now
i have not made interaction classes bro
i am stupid as fuck
oh
you are sublcassing a view to make your own view
so you need to let the view class run its stuff, which is what you do with that
so put super thingy inside subclass?
make it the first statement in the constructor
im so used to doing this without classes so excuse my stupidness
class RegenerateGemini(discord.ui.View):
def __init__(self, prompt):
super().__init__()
self.prompt = prompt```
?
yea
ok that worked
ty
ily
please kiss me
whats the docs link for the fucking button interaction context
.rtfm discord.Interaction
discord.Interaction
discord.Interaction.app_permissions
discord.Interaction.application_id
discord.Interaction.channel
discord.Interaction.channel_id
discord.Interaction.client
discord.Interaction.custom_id
discord.Interaction.data
discord.Interaction.delete_original_message
discord.Interaction.delete_original_response
discord.Interaction.edit_original_message
discord.Interaction.edit_original_response
discord.Interaction.followup
discord.Interaction.guild
discord.Interaction.guild_id
discord.Interaction.guild_locale
discord.Interaction.id
discord.Interaction.is_command
discord.Interaction.is_component
discord.Interaction.locale
how to solve unknown interaction error ?
send full traceback
I don't have rightnow this error but sometimes it gets this error
there could be many sources that cause this error so it is hard to say
Oh okey thx
Unfortunately, I still haven't found a solution.
Target not found, try again and make sure to check your spelling.
Item not found.
chill lol
does pycord have ability to control webhook?

