#Basic Pycord Help
1 messages · Page 23 of 1
this should be good right? im doing that for every view
is the view timeout the same one than the tokens ?
because here it says the default timeout is 180 so its not 15 minutes, maybe its not the same thing we re talking about
sorry to bother lol, its just that i keep getting this error for a long time
remove default=True
the default timeout we personally set is 3 minutes on views, meaning it will stop functioning after 3 minutes. The "15 minute" timeout is referring to interactions - if you defer an interaction response, you have to followup/respond within 15 minutes or it errors. Further followups will not be possible after that time is up.
Thank you this stops it from defaulting back to general but do you know of anyway that I can have it so that if I select one of the options then it'll keep that as selected item until i choose another and then it'll change what was happening with the default thing to that selected option?
that is the default behavior already
what is it doing currently?
i get it, thanks for clarifying
is it maybe possible to update it manually?
update what manually
im having a panel where users can do things on it, so if an user doesnt do anything for 15 minutes then the buttons are not working since it timeouts right
my problem was sending ephemeral messages
if i select one then it'll do the callback just fine but it'll reset all selected items and only have the placeholder there
the buttons work i mean, its the ephemeral messages that crash, basically sending a followup
iirc every message edit resets it, you could set default=True on the current option (select.options[(get_index_somehow)].default = True), do the response edit, and then unset default
you can set timeout=None to ensure the view keeps working
Here's the persistent example.
and you use the persistent method to keep it working through restarts
yes, but im talking about the interaction
le "c:\Users\billy\Desktop\disco\cogs\projects\audio.py", line 151, in generate_audio
await pnl.ephemeral(f"Audio block **{pnl.audio_selected[0]}** generated successfully!", file=discord.File(pnl.proj.path + f"/audio/{pnl.audio_selected[0]}.wav", filename=f"{pnl.audio_selected[0]}.wav"), expire=300)
File "c:\Users\billy\Desktop\disco\cogs\__init__.py", line 93, in ephemeral
return await self.panel.send_followup(content=text, file=file, ephemeral=True, delete_after=expire)
File "C:\Users\billy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 1776, in send
data = await adapter.execute_webhook(
File "C:\Users\billy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 222, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 50027): Invalid Webhook Token
i am trying to send a followup as an ephemeral
panel is the interaction
thats an old traceback haha, renamed it to interaction now
but i keep getting this error when trying to send followups
you're always using a single interaction object? or does this refresh
maybe its the 15 minutes timeout
it refreshes each time the users clicks a button on the panel
would be easier to figure out with the full code
if a user presses a button and you respond to the interaction in under 15 minutes then that wouldn't happen, unless you're actually taking that long?
in fact it does not take that long
its very very big, i have a panel class where the interaction keeps getting updated
also this is the reason i cant save persistent views from what i saw, because each view is particular to an user so i would have to save them in a database or something to then rebuild the panel instance
but thanks for your help, now i get it so i will re look at my whole code, i did something wrong then
can you just send the ephemeral function?
yes
async def ephemeral(self, text: str = "", embed=None, file=None, expire: int = 10):
if embed and file:
return await self.inter.respond(content=text, embed=embed, file=file, ephemeral=True, delete_after=expire)
elif embed:
return await self.inter.respond(content=text, embed=embed, ephemeral=True, delete_after=expire)
elif file:
return await self.inter.respond(content=text, file=file, ephemeral=True, delete_after=expire)
else:
await self.inter.respond(content=text, ephemeral=True, delete_after=expire)
(not sure i could have these parameters as None)
self.inter is the interaction that is always updated on a button press
oh you're using the new respond function ic
hmmm
what about the generate_audio function?
if it's too big it'll convert to a text file anyway, which is fine
i will shorten it to essential
fair enough
the audio is first resetting self.inter to the actual Interaction
then it generates audio with elevenlabs api, and sends the generated file as an ephemeral message
once it sends the generated file, it updates the view to show that audio is generated
and the code
async def callback(self, interaction: Interaction, cog: Type[Any], run_func = None, end_func = None, cog_is_func = False):
self.inter = interaction
if cog_is_func:
return await cog(self)
if (not run_func is None) and run_func != 0:
tcb = await run_func(self)
if tcb: # not used yet
return
if isinstance(cog, UI.Modal): # is a modal
return await self.send_modal(cog)
cmptype = interaction.data.get("component_type")
if run_func is None and cmptype == SelectCmp:
await self.execute_cog(cog)
await self.init_cog(cog)
await self.edit()
if not end_func is None:
await end_func(self)
it runs this function with the interaction, my custom cog (self.edit() is a function that edits the interaction with the data from my cog)
run_func is generating the audio and sending the ephemeral message, so nothing too much
i got a pretty complicated system, do you need anything more?
hm, so how long does this normally take (without errors)?
did you ever defer?
no i did not, can that be the reason?
try await interaction.defer(ephemeral=True) before your heavier functions
okay okay thanks, btw i will be able to edit it after right ? wont cause any issues
im running some tests but i need to wait 15 minutes each time 😭
should be fine
interaction.respond and interaction.edit in 2.5 already account for defers
(i hope anyway, i implemented it like last june and haven't used it since)
oh gosh, so it should work anyways
anyways i understand why it does that, most likely a bug from my code because it should not happen otherwise
is there anywhere i can donate you?
pls don't im fine LOL
i would have realised it was defer earlier but the error confused me
in general, if your function takes more than 3 seconds you have to defer interaction
okay 😅
yeah but it should do it automatically
because it works for anything else
i just think i messed up somewhere so im checking again, thank you for your help!
defer automatically?
if you're unsure on how long it takes, then always defer
okay will do !
I actually started to defer every Interaction because you never know if your internet will be slow at some point or discord
If your internet is slow / inconsistent then deferring won't save you from anything
that's not really good practice
There is nothing called Type
It is select_type=
I got it already thy
if interaction.user.voice.channel:
AttributeError: 'NoneType' object has no attribute 'channel'```
How can i grap this?
If i do:
```py
if not interaction.user.voice.channel:
The same error comes
Check first for user.voice?...
is there a shortcut to return a list of only TextChannels from a guild
instead of return a full list and having to remove every channel that isn't a TextChannel
Also, how do I detect the class type of a channel
I don't think so
hey guys how can i delete the last response of an interaction? and will it work if i want to delete it like 30 minutes later?
You can detect the type with
isinstance(channel, discord.TextChannel) you could pair that with a list comprehension
.rtfm Interaction.delete_
Interaction tokens expire after 15 min so 30 min will not work
so the solution would be to defer it right?
Defer still only gives up to 15 minutes
damn
but ii only want to delete the message, like a normal message, why wouldnt that be possible?
i mean manually i can delete it even after a few hours, maybe i can stack the id of the interaction message or something and after fetch the message and delete it?
You would have to have the message ID, you can get that via interaction.message it it was the first one I think
okay thanks!
How do I get the channel which system messages are posted (i.e. new member/nitro boost)
this thing
Ohhh im sooo dumb thanks
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
thank you!
self.inter is an Interaction that has timeouted, when i try this code it says
msg = await self.inter.original_response()
await msg.delete()
401 Unauthorized (error code: 50027): Invalid Webhook Token
But on discord i can simply right click and delete the message, I don't get it why it's not possible in my code
Why the self?
its in a class
i have a panel basically
this is a function that is supposed to delete the panel if the user opens a new one
but im having an issue where if the user doesnt touch the panel for more than 15 minutes, then reopens a new one, the old one is not deleted and i get this error
What objects does discord.TextChannel.can_send accept
I'm trying to check if the bot can send messages on a channel
You have to store the original_response before the timeout
Okay thanks
Nothing. It's a method that returns True or False
.rtfm TextChannel.can_send
Or it does. Probably the same stuff as a normal channel.send
thats mediocre documentation tho
i am storing it directly after editing it
then 30minutes later i am trying to delete it, and i still get the error
any idea guys?
delete it with it's ID
discord.Bot.get_partial_messageable
discord.Client.get_partial_messageable
discord.Thread.get_partial_message
discord.DMChannel.get_partial_message
discord.TextChannel.get_partial_message
discord.ForumChannel.get_partial_message
discord.VoiceChannel.get_partial_message
discord.ext.commands.Bot.get_partial_messageable
discord.PartialMessageable.get_partial_message
discord.StageChannel.get_partial_message
something like that?
if thats the way to do it, it would be nice to maybe have a direct function attribute to do it directly
can't you just call delete on the original response?
hm
Use get_partial_message like squid said to avoid an API call
okay thx
How can i create modals like this
the same pretty much
replace view with modal and assign callback, then add_item takes inputtext instead
Thx
how to follow a channel in pycord?
Copy pasted code from a past project which has been working fine
titlePerm = {guild.default_role: discord.PermissionOverwrite(read_messages=False, send_messages=False, view_channel=True),
guild.me: discord.PermissionOverwrite(read_messages=True, send_messages=True, view_channel=True)}
NewsCategory: discord.CategoryChannel = await guild.create_text_channel(name="📰┊BitThreadz", overwrites=titlePerm, position=0)
and I'm getting this error:
titlePerm = {guild.default_role: discord.PermissionOverwrite(read_messages=False, send_messages=False, view_channel=True),
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: PermissionOverwrite() takes no arguments
what am I missing
we haven't made any changes related to this, did you install py-cord properly?
show your package list
how do I make a long running command async? defer() doesn't work by itself, when the one command is running other commands time out
that will need some context
isn't there a way to wrap a line in a new thread or whatever
like you have a slash command that needs time to execute?
code
async def generate(self, ctx, prompt: Option(str, "Prompt")):
"""generate an image from a text prompt"""
try:
await ctx.response.defer()
except:
pass
response = await ctx.respond("generating ...")
try:
result = await self.sd_generate(prompt) # slow line
except ConnectionRefusedError as e:
await response.edit(content="server is down, try again later")
return
except Exception as e:
import traceback
traceback.print_stack()
await response.edit(content="server is down, try again later")
return
image = result.get("name")
await response.edit(content=prompt, file=discord.File(image))```
thats a lot of try excepts
ok
you can use ctx.defer btw
well if the sd_generate is actually async, it shouldn't block your other code
but as you described it it sounds like it isnt
I just want to wrap that line in a new thread or whatever
no need
yes need, it's blocking
are you making an API request?
you're not answering my question

Bot.loop.create_task(code) might work
self.bot?
👍
why not just make the API request async
ok, tell me how to make websocket-client async
I'm using this code https://github.com/comfyanonymous/ComfyUI/blob/master/script_examples/websockets_api_example.py
yes
there's also await bot.loop.run_in_executor https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_in_executor
None uses the default, should be fine
hm I still get The application did not respond on the 2nd invocation
idk that's meant to do exactly what you're looking for, runs a func in another instance/thread
idk
try to use ctx.defer and not ctx.response.defer
might just be a shortcut but idk
they're the same
true
but their problem is the bot gets blocked regardless
(i hope you're not calling () it in run_in_executor)
I was, and it errors, but the 2nd run still times out
so run_in_executor(None, self.sd_generate, prompt) still breaks it?
ctx.defer is a shortcut
yes
they're the same
hm now I'm getting Application Command raised an exception: AttributeError: 'coroutine' object has no attribute 'get'
what do I do with an awaitable
...await it?
I did
do it again
isn't it because you made sd_generate async too
this is correct
ah so no parens 🤔
like
thats how everything in the lib works, ctx.send() and await are separate
should I try making a ThreadPoolExecutor or will that cause problems
go for it
i think you need to dive into sd_generate , since that isn't the blocking function itself; it happens to run other blocking functions
same issue 🙃
hm maybe
even if I move it further down it still errors
there's a while True loop that calls ws.recv(), that's where most of the time is spent
ah... while true....
can I use asyncio.ensure_future?
ig just keep trying and see what sticks, not much experience here from me
yeah not much here either 🙃
maybe loop.run_forever() and then loop.stop()?
no, nevermind
so I just added await asyncio.sleep(0.1) in the loop and I think that worked
well, it worked once. running a 3rd time still times out
hey, quick dumb question
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'respond'
i checked and Context has this attribute, what should I do instead?
await self.ctx.respond(embed=embed, view=self.view)
send
Context doesn’t have this attibute
ctx gets passed into your function, drop the self
i am in a class
respond is only for slash commands, otherwise use send
that too
okay thank you i get it now
(they've passed ctx somewhere else)
i need to change the docstring
but its in a class so dw, works now
another thing guys,
i am having this command
bot = Bot(command_prefix=commands.when_mentioned, intents=discord.Intents.all())
@bot.command()
async def menu(ctx: Context, custom_id: str = None):
is there a way to have this command work when i only mention the bot?
Now it only works when i do @mybot menu
ehhh use on_message event then run the function there instead?
yeah thought about this, was wondering if there was a more intentional way of doing that 🤔
they mean to bypass the command name and have it run directly on mention instead
yeah
but at that point, why have it as a command
i would just like to have it run when the bot is mentionned, wasnt sure if there was a way of doing that without going through on_message
well... on_message is how mentions are detected in the first place
yeah, i think i'll go directly with that, thx for clarifying
also refer to this section in the FAQ to make sure your commands don't break
added a longer sleep and it's totally working
nice
okay nice
Running this gives me the error discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
you don’t have the permissions to send a message in that channel
somehow the bot can still send messages
Made sure that the guild system channel is set to the correct channel?
Ye it seems my bot cannot view the channels mb
I’ve experienced this too cause weird glitches in my bot lmao
I believe that discord allows the bot to send interaction responses in channels that it cannot send messages in or see. The bot will just not be able to send unprompted messages.
you're correct. had the same thing a while back. this also causes paginator errors, when it sends embeds. somehow it is allowed to respond to a given command but not allowed to edit its own message (e.g. deactivate buttons on timeout) when channel permissions arent granted.
Only responses bypass perms; timeout edits generally won't work because chances are it's out of the response window, something like edit_original_response would still work but gotta be <15min
(If not that then presumably response.edit_message, but that's obviously a first response rather than something on timeout)
😅 I just catched and passed the error for that
Do i need a session to edit a WebhookMessage?
I always get a Session closed error when trying to edit one.
is there a way we can fetch a message through an attachment, i tried using the ids in the url, the first one corresponds to the channel id but the second one doesn't with the message apparently is there any way to get the message
Through an attachment URL?
The message ID where said attachment is on is the second ID in the url https://media.discordapp.net/attachments/1132206148309749830/1214371968128778271/image.png …
It’s better off to get the message ID from something else tho
i only need sevrer members intent, how do i define it here?
intents = discord.Intents.none()
intents.members = True```
okay thanks a lot
yes, I only have pycord installed
aiohttp 3.9.3
aiosignal 1.3.1
attrs 23.2.0
certifi 2024.2.2
charset-normalizer 3.3.2
frozenlist 1.4.1
idna 3.6
multidict 6.0.5
mysql-connector-python 8.3.0
pip 22.3.1
py-cord 2.5.0
requests 2.31.0
setuptools 65.5.1
tabulate 0.9.0
urllib3 2.2.1
wheel 0.38.4
yarl 1.9.4
(Resending problem for context) 👇
Copy pasted code from a past project which has been working fine
titlePerm = {guild.default_role: discord.PermissionOverwrite(read_messages=False, send_messages=False, view_channel=True),
guild.me: discord.PermissionOverwrite(read_messages=True, send_messages=True, view_channel=True)}
NewsCategory: discord.CategoryChannel = await guild.create_text_channel(name="📰┊BitThreadz", overwrites=titlePerm, position=0)
and I'm getting this error:
titlePerm = {guild.default_role: discord.PermissionOverwrite(read_messages=False, send_messages=False, view_channel=True),
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: PermissionOverwrite() takes no arguments
full traceback?
Ignoring exception in command setup:
Traceback (most recent call last):
File "\Lib\site-packages\discord\commands\core.py", line 131, in wrapped
ret = await coro(arg)
^^^^^^^^^^^^^^^
File "\Lib\site-packages\discord\commands\core.py", line 1013, in _invoke
await self.callback(ctx, **kwargs)
File "\Lib\site-packages\discord\commands\core.py", line 49, in setup
titlePerm = {guild.default_role: discord.PermissionOverwrite(read_messages=False, send_messages=False, view_channel=True),
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: PermissionOverwrite() takes no arguments
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "\Lib\site-packages\discord\commands\core.py", line 1130, in invoke_application_command
await ctx.command.invoke(ctx)
File "\Lib\site-packages\discord\commands\core.py", line 376, in invoke
await injected(ctx)
File "\Lib\site-packages\discord\commands\core.py", line 139, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: PermissionOverwrite() takes no arguments
there you go
traceback 👆
try reinstalling py-cord
show your package list
Scroll up a bit
ah mb
That fixed it, thank you.
i have a view which edits the message to something else upon timeout
how am i supposed to override this when finishing a command
self.message.edit?
depends what do youmean by override
oh ok
How do I change another button's appearance upon clicking a button
I know each button has custom ids but have no idea how to use them
# e.g.
self.children[0].disabled = True
await self.message.edit(view=self)
thanks, I guess I didn't need the custom_id after all
what can i do here guys?
custom_id is needed for e.g. persistent views
i guess use interaction.client
as far as i see from error you probably using self.client
Show your code
remove the self also?
^
but yeah without self as you should use callback interaction arg
uid is a collum in my table and stands for "userid"
this is a new error btw the old one is fixed
show your get method
sure
here
static methods do not take self
ahh
so your method actually takes 4 args
yes, and instead of self i may use interaction right? to like connect to the db with "async with interaction.client...."
that works too
@staticmethod
async def get(interaction, mid: int, gid: int, uid: int):# -> list or None:
async with interaction.client.pool.acquire() as conn:
async with conn.cursor(aiomysql.DictCursor) as cursor:
try:
data = await cursor.execute(
("SELECT * FROM surveys_votes WHERE gid = %s AND mid = %s AND uid = %s", (gid, mid, uid)))
data = data[0]
except (IndexError, TypeError):
return None
return UserVote(data['mid'], data['uid'], data['gid'], data['vote'])
Do you think that is okay?
ahh and the vote arg, how could i add that in the function?
yea i somehow have the same error still 
wdym vote arg
i mean uid sorry, i dont understand how i can fix that error
its saying somethign with uid but idk what
show the error?
that one
youre not passing interaction
you mean UserVote.get(interaction)?
and now youre missing the other arguments...
yes yes wait is it UserVote.get(interaction.message.id, interaction.guild.id, interaction.user.id)?
UserVote.get(interaction, interaction.message.id, interaction.guild.id, interaction.user.id)
ahhh
okay, sorry i came back to coding after a long time, sorry!
yes you are right
ah yes, so much for descriptive variable names
ah damn it, never seen an error like this one
async def save(self, interaction) -> None:
async with interaction.client.pool.acquire() as conn:
async with conn.cursor(aiomysql.DictCursor) as cursor:
return await cursor.execute(("INSERT INTO surveys_votes (gid, mid, uid, vote) VALUES (%s, %s, %s, %s)",
(self.gid, self.mid, self.uid, self.vote)))
its in this part
that doesn't look like the part that's causing it
somewhere something expects an object to get an id of but gets nothing
Is there a way to get emojis from servers in which the bot isnt in for stealing etc
ahh maybe when i click the button of the survey, one second
looks like it
before i got an error saying that there is missing an "Interaction" in the brackets which i added then and got the current error
i got a way but i have a error in reading it
It's not possible for all I know
It is
well then
Gut it with
emoji = discord.PartialEmoji.from_str(emoji)```
any ideas how to fix that?
that's not the issue since there'll obviously be an interaction to pass
Isn't the first parameter supposed to be the sql query? You've added extra parentheses
You've made the entire sql query + the variables to a tuple and passed it as the first parameter
i use mysql if you mean that
ruh
huh
Can you fix your parentheses and see if it works
sure!
i dont know where i have placed brackets wrong hm
in the execute
you mean the 2 start brackets?
yes
ahhh
it worked halfly, the button response works now, it says which button i voted for, but the percent should change, which it doesnt
then make it change lol
sure!
somewhere you aren't editing that value 
man i have never used any non discord decorator idfk
what?
Is there a way to get messages which got hold back from automod?
They are normal messages in the automod channel
what what?
was that message related to me?
yes
but what do you mean with that message, im not really good at english sorry 
i dont know
okay 👍
so you can get them from the automod channel
that for sure, yes
the author of that message will also be the person who wrote the initial message
if you can catch them otherwise, idk
Okay
staticmethods are underrated
You're passing interaction.mesage.id to the method and the method is trying to extract the bot attribute from the id
Which doesn't exist
Actually you're getting 2 different errors from 2 different areas
damn it
Seems like you're trying to fix some pre existing code or smth
@staticmethod
async def getAll(pool, mid: int, gid: int, vote: str = None): # -> list or None:
async with pool.acquire() as conn:
async with conn.cursor(aiomysql.DictCursor) as cursor:
if vote:
data = await cursor.execute(
("SELECT * FROM surveys_votes WHERE gid = %s AND mid = %s and vote = %s", (gid, mid, vote)))
else:
data = await cursor.execute(("SELECT * FROM surveys_votes WHERE gid = %s AND mid = %s", (gid, mid)))
if data is None:
return None
return [UserVote(data['mid'], data['uid'], data['gid'], data['vote']) for data in data]
do you think this will work hm 
you generally should be knowing what methods you've defined and their parameters
yes you're right
either that or chatgpt
because for the code you send you seem to have surprisingly little clue about python
You again messed up the parentheses
damnnnnn haha
no no i did it with the debugging tool or idk what its name was, but i didnt tried the code yet
no, i mean your code doesnt seem like it was written by you entirely
its old, i was better before i stopped for a while
i feel dumb as hell asking here and dont knowing what you are talking about haha
but its getting better
i think
You can start of by something more simpler than a discord bot and work your way through
Facts, i onced hate the urge to start coding a discord bot, and damn it, it was so hard starting, i was completely lost, but i think i developed myself better by the time, but the decision to stop again was a big mistake
But I just kept working on it for like 2-3 years now and I've gotten most of pythons core concepts well
i see, you are very good 💪
okay so ive been trying the past 5 minutes, as it says the error is from the other function, and i think i found a way to fix that:
votes = {}
for i in range(Anzahl_der_Votes):
votes[i] = await UserVote.getAll(pool, interaction.message.id, interaction.guild_id, i)
this is the part btw
If you read further the error tells you there is something wrong with UserVote.getAll method
Because the methods first parameter accepts a pool object but instead you passed in an integer as the argument
Which is interaction.message.id
In your line 260
I'll give you a better way to fix all your errors: scrap whatever you wrote before and rewrite it again from scratch.
man you are using ChatGPT or you're just copying someone's discord.py repo, you cant tell me otherwise
Scratch??🫣
Oh
Personally, yes
i agree
again, i highly believe that you didnt write that code
so, yea
its ok i wouldnt believe myself too 
Example method to follow a channel via bot?
hmmm, i do not have to put a guild id? 'cauze it's another server
you can use bot.get_channel(id) to jump past guild entirely
do you think i can just add interaction, same as before?
like (interaction, .....)
If you just look at how getAll is defined you should be able to figure out the error immediately
they seem to have just as little clue about their own code as everyone else does
its ok bro, no need to hit one on it 👍
Is it possible to use a different proxy for each request? Instead of only establishing one proxy at the very start?
no, why?
i just cant fix that error 
read the stacktrace
what is the default timeout limit for buttons if a timeout is not set
and what is the maximum timeout we can set, for buttons
15m for both i believe
Aight, thanks! 🙌🏻
@bot.slash_command(description="Set Announcements channel")
async def setannouncements(ctx, channel: discord.TextChannel):
canale_annunci = bot.get_channel(1214305562112565349)
await channel.follow(canale_annunci)```
> Application Command raised an exception: TypeError: follow() takes 1 positional argument but 2 were given
its not a positional argument, its a kwarg
hm
Why do you use follow?
how to reload slash commands list without reloading my client?
wow, dark, hi!
is there any way to get the bot user itself as guild member, without member intent or fetching it every time from the api?
I want to check, if the bot has a specific permission on a guild, and need the bot as member to do this.
but without member intent, the "guild.me" is None
sure, the bot can not get all members as normal without the intent, but it would be useful, if the bot knows itself....
without member intent, the bot member should still be present
thats, what I thought, but it is not
hmmm just checked and it's worked fine on my end
do you stlll have the guilds intent?
I have no intents at all
you need some at least
ok, nice to know, will try it, give me a second
i'd go through https://docs.pycord.dev/en/stable/api/data_classes.html#discord.Intents and see if you need anything else
intents=discord.Intents.default() should be enough, right?
intents.default gives you every intent apart from presences, message_content and members
if not (destination_guild := await get_or_fetch_guild(self.bot, ctx, destination_guild_id)):
return
print(f"Me: {destination_guild.me}, guild name: {destination_guild.name}")
still yields
Me: None, guild name: BTS2
so the bot does find the guild, but the bot member does not exist
you 100% sure you passed intents? i just checked, and disabling guilds intent dropped my bot member
thats, what I thought, yes
class Bot(discord.Bot):
async def on_ready(self):
print(f"{self.user.name} is ready and online!")
def __init__(self):
super().__init__(intents=discord.Intents.default())
print("Connecting to database...", end=" ")
# rest ignored
print("Starting bot...")
bot = Bot()
as far as i know, this should be enough, or am I missing something?
hm, looks fine to me...
what happens when you print(len(list(self.get_all_members()))) (where self is the bot)
(i changed the class name before sending the message and removed the database stuff, because this is just al lot of code, which is not important here)
it gives me 3
and im guessing your bot is in 3 guilds?
nope
then how many
it prints twice itself (in two guilds) and one time myself (also in both guilds; bot only one time in the output)
so it's in 2 guilds, and it sounds like you are getting the bot member in both guilds?
the reason you only show once is because it only recieved you in one guild through other means (e.g. interaction)
bot and me are in guild a and guild b
it prints
itself in a, itself in b, myself in a
no other users are shown
nope
None
show the exact output of guild.members
sec
[<Member id=1087478322834980934 name='bottest' discriminator='8370' bot=True nick='ChannelMirrorTNT2k' guild=<Guild id=1087478373346983988 name='Bot Test Server' shard_id=0 chunked=False member_count=36>>, <Member id=759537934873133076 name='tnt2k' global_name='TNT2k' bot=False nick=None guild=<Guild id=1087478373346983988 name='Bot Test Server' shard_id=0 chunked=False member_count=36>>]
the bot and myself
then i have no clue why those other methods are failing
this is literally how guild.me is defined py @property def me(self) -> Member: self_id = self._state.user.id return self.get_member(self_id) # type: ignore
i found a clue
if I try to get the bot user in the guild, I run the command, it works.
if I want to get the bot user of the other guild, it does not work.
can you show the code you're using
sure, give me a second to clean it up a little
@group.command(name="create", description="")
async def create(self, ctx,
source_channel: Option(TextChannel, ""),
destination_guild_id: Option(str, "")
):
if not (destination_guild := await get_or_fetch_guild(self.bot, ctx, destination_guild_id)):
return
print(destination_guild.members)
print(ctx.guild.members)
print(ctx.guild.me)
so this yields
[]
list with two members (there are more on the guild)
the bot user
is get_or_fetch_guild your own function
can you show that too
async def get_or_fetch_guild(bot, ctx, guild_id) -> Guild | None:
try:
return bot.get_guild(guild_id) or await bot.fetch_guild(guild_id)
except Forbidden:
if ctx:
await ctx.respond("Not a member of destination guild", ephemeral=True)
return
except NotFound:
if ctx:
await ctx.respond("Destination guild doesn't exist", ephemeral=True)
return
except:
if ctx:
await ctx.respond("An error occurred", ephemeral=True)
return
can you convert guild_id to int
so can slash commands not get the bot user of this instance in the other guild?
I could, yes, but this does not change anything, the destination guild is not None
if it was, the command would exit right away
get_guild returns None because it's a string
it does not?
nope
oh, thats indeed a problem
https://docs.pycord.dev/en/stable/api/clients.html#discord.Bot.fetch_guild
Using this, you will not receive Guild.channels, Guild.members, Member.activity and Member.voice per Member.
so how do I fix that? I can convert it to int, but if the bot does not have this guild in its cache, the "guild.me" would be empty nevertheless
converting it to int fixes everything because the bot must have the guild in its cache
you can't fetch a guild you aren't in
nice to know. ideally, i would require an int as argument, but ids are too large
just convert it in the command
so the fetching can be removed completely? nice, thanks
yes
thats nice to know, thaks a lot for the help
allgood
Are u a bug hunter or smth
not particularly
Somewhat of a security question - are bots (like spammer bots) able to read button values? Like if I wanted to do a math problem, should I make the IDs randomized instead of the actual label? Trying to reduce as much automation possibility as I can.
is there any way to let a bot trigger a slash command? wanna test something with slash commands, and it would be way easier to do it that way, than disassembling the api.... i need to test something permission related, and users do not really care, if the should do something or not...
as spammer bots are not bots but automated users, yes, they should be able to do that
Yeah, so the question is whether I should obfuscate the values or whether the label is going to make that useless
well, you can do something different and more complex like "tell me were the cross in this coordinate system is" and you just make an 8x8 grid and put the red cross somewhere in it
I do not know, if the id will help them, but the label certainly will, because the users must be able to read it
im fairly sure it'd be possible, yes
just map your randomized IDs internally
Yeah. The (theoretical) question is whether all of that effort would be effective
I wonder if I can send unicode for the numbers so it's not just straight characters. \x0030 or however you'd do it. Make the client render
it's not really that much effort, but also it depends on if you think people would actually bother
if they are specifically targeting automation of your bot they will be able to do all the simple captchas. If you just want to protect against normal math bots you can change it up
Yeah, I know it's not going to be easy 😦 I am thinking of presenting a simple-ish math problem with a grid of numbers. When you click the first number, the grid shuffles.
All I know is that I'm currently using captcha.bot and everyone unilaterally hates it. It takes you out of Discord to link your account to a centralized entity's website that is probably a pretty big target for compromise.
Haven't seen any good existing solutions to draw inspiration from.
Was going to try to do a 'one of these things is not like the other' with Pillow, but ChatGPT solves them effortlessly, even with backgrounds that try to break computer vision.
you can
but depends on need
i mean you can e.g. unload/load cogs and then call sync_commands(cmds)
and use delete_existing if needed
but it makes the most sense only for bots that have a time-consuming startup
Hey all, I'm trying to add logic to my slash command so a certain autocomplete value adds another option/argument to the command. For example:
@option(
"update",
description="Fields to update",
autocomplete=discord.utils.basic_autocomplete(
["Character Info", "Add Image"]
),
So if option == "Add Image" :
/add ["Add Image"] [New Option appears here that is not there when "Character Info" is selected as first argument]
I don't need help with the whole command, just curious about how to dynamically add @options in a slash command.
I think I remember seeing a post about it a while back (either here or on stack) but can't find it for the life of me.
No essentially I want to give users the option to upload an image when "add image" is selected. But not give them that option when "Character info" is selected.
you can add 2 options with default None and check if e.g. option1 == X and option2 is not None
so like:
opt[update]
opt[text] = None
opt[image] = None
if opt[update] == "Character Info" and not opt[text]:
// text not provided
if opt[update] == "Add Image" and not opt[image]:
// image not provided
but the better way wold be just make your command run like
opt[text] = None
opt[image] = None
so you'll just select what do you want to update
and if none then return original or an error
description="Fields to update"
let options be your fields
and update them if they are not None / default (unless None is possible)
Thank you for the help so far! I've been trying this to no avail.
@option(
"image",
discord.Attachment,
description="Image files must be .png or .jpg",
required=False,
)
In the above declaration, it seems you can't set the option = none.
I also tried here:
async def autocomplete(
ctx: discord.ApplicationContext,
name: str,
update: str,
image = None
#image: None
):
That at least compiles and runs, but the option for the image is always there.
I like this idea and it would work elsewhere, but here each of the autocomplete values opens a separate modal with lots of fields to update.
ah okay, so I think best way to deal with it would be leaving both args if you don't want separate command and just check like I mentioned before
So kinda like that but simpler with only second check
Or both if needed
or you can use different logic of args like update_info: bool+avatar:...
if not avatar and not update_info:
error
if avatar:
update avatar
if update_info:
return send modal
respond
Again I don't see how this works when you can't set option = None
After more digging it seems conditional fields in a slash command aren't possible. Or at least weren't in 2022. https://discord.com/channels/881207955029110855/1010143589633896448
why is this?
how to realese event on_message in cog?
type, description
thanks
import discord
@discord.option(...)
ok thx a lot
is there even a difference between option and Option
option = decorator
def option(name, type=None, **kwargs):
"""A decorator that can be used instead of typehinting :class:`.Option`.
No
@discord.option
or
(
option: discord.Option(...)
)
Do you guys keep your embeds and views in a separate file?
I do
Eh, not really? Up to you
I use a core folder where you can see all the views utils etc
util file ftw
Util file?
I tend to put boilerplate embeds generators in my View file. Like myview = MyView(…); myview.get_embed()
That way I can better track aspects of the embed if I need to modify it in response to interactions with the View
For EmbedFields do you have to insert the keywords or just do (arg1, arg2, arg3)
What @sage tendon means is that there is an option decorator like this;
import discord
from discord import option
@discord.slash_command(name='your_command')
@option('user', discord.Member, description='Choose a member.', required=False)
async def your_command(ctx: discord.ApplicationContext, user: discord.Member=None):
...
I put it so that you can choose to select a discord user in this example
which eventually looks like this
Hey quick question:
[<Reaction emoji='👍' me=True count=2>, <Reaction emoji='👎' me=True count=2>]
This is message.reactions
How do I make this readable
As in, fetch the count for reactions
As you said, fetch it first, and then just go trough the reactions like in a list or dict and then finally .count I suppose
Tried .count(), didn't work as expected
but I got it working using a for loop and .emoji
Thanks!
without the ()
just
oh
okay
welp ig
Would've just said
message = await message.channel.fetch_message(message-ID)
upvote = message.reactions[0].count
downvote = message.reactions[1].count
print(f"Upvotes: {upvote}, Downvotes: {downvote}")
This is much simpler. Thanks, I'll go with this!
np
The Voxy the helper soon?
Why tho... I didnt contribute to the library so I really dont deserve it
Time to change that
Wait, all helpers have contributed to the development? W team
idk but if I recall correclty, anyone on the staff has contributed.
I do not know why, but I have several instances of bots. As a result, when using the command, I get an error message: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction At the same time, I get a response from an old instance of the bot. The picture shows that when I enter the same command, I get different answers.
Just reset your token
What should I do to prevent this from happening in the future?
don't run your bot twice
why is there this error: ValueError: View is not persistent. Items need to have a custom_id set and View must have no timeout?
what line does that error come from?
you cant add that view to the bot because its not persistent ig
The hell is that second button
wip i guess
And why are syncing commands on on_ready?
i didnt even know that was a thing
arent slash commands synced automatically?
ah are you sure? i want to know why
read the persistent view guide i guess
if i remove second button its work
i read it 3 times bro
oh, i guess because you assigned an id to the buttons but not the view?
Because that's not how you define link buttons.
You can't define link buttons through a decorator.
You add it manually
self.add_item(discord.ui.Button(label="My Link", link="https://google.com", style=discord.ButtonStyle.url))
oh its pizdec
why do you define the bot again in a cog?
wait what?
oh 4 line
idk this is not my code
bruh
....
breh
nice, thx bro
love u
its saying that pycord isnt installed, but it is
i tried uninstalling and reinstalling it
can you show your packages?
ok
you sure it's running in the pycharm venv itself
good question
still doesnt work
which venv do you use?
What was it?
it was the wrong interpreter
pycharm will complain about importing discord because it doesnt match py-cord
that was an actual import error, not pycharm
i know
I dont think I did before I was helper.
Not sure this is worth an entire post because it's probably me just being blind, but details are below:
I am trying to crate a bot that catched invites and refuses them unless they are created by specific people. I have done this using the following code:py @bot.event async def on_invite_create(invite): if invite.inviter.id not in [user_ids.get('tobezdev'), user_ids.get('vimto'), user_ids.get('self')]: await bot.delete_invite(invite) e = discord.Embed( title="Invite Creation", description=f"Invite creation is disabled on the `{invite.guild.name}` server. To invite a user, please use the `/invite` command.", color=embed_colors.get('200_warn') ) e.add_field(name="Prefilled Invite Command", value="Click here to invite a user: </invite:1213823153835352174>") await invite.inviter.send(embed=e) e = discord.Embed( title="Invite Blocked", description="An invite was blocked from being generated.", color=embed_colors.get('200_warn') ) e.add_field(name="User Info", value=f""" User ID: {invite.user.id} Username: {invite.user.name} Display Name: {invite.user.display_name} """)
The event catches it fine, however the bit gets a discord.errors.HTTPException: 400 Bad Request (error code: 50007): Cannot send messages to this user from attempting to DM itself.
My question is: Why does the bot attempt to run the invite.inviter.send even when its ID is in the list of allowed IDs?
I have checked both the invite and the ID in the user_ids dictionary, and they all match up.
Thanks in advance.
Still why me tho and not Toothy or Zervy 🥹
Are you sure your user ids.get returns an int and not a string or anything else
Which may cause the not in to not get accessed.
-> int | None -- I have a filter that catches None if it is returned built-in to the get function.
Ah
The only way it gets to the error line is if the ID is type int.
IDs must be an int
ID is an int.
Thats why I'm so confused
I mapped everything to PyCord docs and it all checks out
Also the error you're getting is just the bot failing to dm the user because they may have disabled their dms
It's the bot trying to DM itself, because it created an invite.
The bot's ID is in the allow list.
🤷
if invite.inviter.id not in [user_ids.get('tobezdev'), user_ids.get('vimto'), user_ids.get('self')]:
@bot.event
async def on_invite_create(invite):
if invite.inviter.id not in [user_ids.get('tobezdev'), user_ids.get('vimto'), user_ids.get('self')]:
await bot.delete_invite(invite)
e = discord.Embed(
title="Invite Creation",
description=f"Invite creation is disabled on the `{invite.guild.name}` server. To invite a user, please use the `/invite` command.",
color=embed_colors.get('200_warn')
)
e.add_field(name="Prefilled Invite Command", value="Click here to invite a user: </invite:1213823153835352174>")
await invite.inviter.send(embed=e)
e = discord.Embed(
title="Invite Blocked",
description="An invite was blocked from being generated.",
color=embed_colors.get('200_warn')
)
e.add_field(name="User Info", value=f"""
User ID: {invite.user.id}
Username: {invite.user.name}
Display Name: {invite.user.display_name}
""")```
Thats the whole event ^
global user_ids
user_ids = {
"vimto": 381938080690733056,
"tobezdev": 969254887621820526,
("self", "bot"): 1212532236583440434
}```
Does it work if its you the one creating the invite?
To be honest, I haven't tried, give me a moment.
:o
Also maybe for the future consider using try except blocks >~< they're much more useful in the handling of these types of errors.
Yep, works flawlessly. Also got my friend to try, the other one in the list, same result as me.
Uh
Wait what
Now I'm really confused
There's a filter on it that prevents None from even being returned
Yes, {} represents a Dictionary
Just double it.
Double it?
global user_ids
user_ids = {
"vimto": 381938080690733056,
"tobezdev": 969254887621820526,
"bot": 1212532236583440434,
"self": 1212532236583440434
}```
I think there's a misconception how indexing dicts work
I'm sure python sees the tuple, as literally a tuple with "self" and "bot" inside and that's the index in the dict
In fact, indexing it as a tuple returns the int
In Python, when you use parentheses around multiple values, it creates a tuple.
So, ("self", "bot") is actually a tuple containing two strings: "self" and "bot".
Fuck I messed up
The 2nd part was my own messsge
First was google
Ugh
Even if its obvious but yah
I think it's setting the value of ("self", "bot") to the ID, and then seeing that 'self' != ("self", "bot")?
No again, its not a key anymore its an entire string
In my head, it's treating ("self", "bot") as the store of data, not self and bot induvidually.
Welp, anyways. Its sorted now so no point arguing over it. Thanks so much guys <3
It's indeed what happens
The tuple is the key.
Not each value inside of it.

(in python, any object can be a dict key which leads to some fun interactions)
If my Select is in a class do I need to pass (self, select, interaction) or just (self, interaction) in the callback
The first
Wait
Oh I see, no it's the latter
oh thanks!
The first is if you're using the @select decorator inside views
ah I see, thanks a lot
Is it possible to determine whether an ephemeral is still active? Like will get_message fail if it's been Dismissed (or work if it hasn't been?)
no
Damn, why doesn't Discord want us to make state-aware apps
because thats not how ephemeral messages work
But ... hear me out -- it could. Click a button, get a response that shouldn't be public, but only one copy of the response, unless it was deleted.
in its current state, the "copy" of the response is sent to all clients currently logged into that account
you never initiated the parent class
so I should use super().init().add.item()?
you need a super().__init__() somewhere in your __init__ (preferably first line)
ah ok
When I copy message id via this:
message = await ctx.respond("smth")
message_id = message.id
And then I compare it with the ID that I get when I click the “copy ID” button on the message, I get different results. Why?
respond usually returns an interaction, not a message. The interaction ID is different from the message ID
so how can i get message id?
As far as I understand, the Interaction object must have an attribute "message", but when I try to receive a message using interaction.message I get NoneType object
no, it’s optional. That attribute only exists for components (buttons and select menus).
okay, but how then to get the message object?
the first one
Thanks you, that works
my interaction failed and there is no error message in my terminal
I can't even find any errors
How do I get the value the user selected in this case?
with self.values[0]
how do I define a callback for a button i addee via self.add_item()?
I'm not using a separate class for that button
you made a view class, no? so the function for the button should already be there
If you're subclassing view you can use the button decorator https://docs.pycord.dev/en/stable/api/ui_kit.html#discord.ui.button
The library has helpers to help create component-based UIs. Shortcut decorators: Objects: Attributes children, disable_on_timeout, message, parent, timeout. Methods cls View.from_message, def add_i...
You needn't manually add the button to the view
yeah but I need to set a button's properties based on a conditio?
then you can use self.add_item() and use this instead https://docs.pycord.dev/en/stable/api/ui_kit.html#discord.ui.Button
And for it's callback you can set it through discord.ui.Button.callback
The library has helpers to help create component-based UIs. Shortcut decorators: Objects: Attributes children, disable_on_timeout, message, parent, timeout. Methods cls View.from_message, def add_i...
@subtle moth So I have to define a function then set the callback as that function?
Yes
Alright thank you very much
Subclass the button instead.
apparently there is no callback argument for discord.ui.Button
I should just subclass it
what's this error
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.1.components.0.label: This field is required
You didn't pass a label
I set a label but the issue still persists
Show your code
slash command
@bot.slash_command(description='View information on a specific Pokémon.')
@discord.option('name', description='The name of the outfit or Pokémon', autocomplete=discord.utils.basic_autocomplete(filter_names))
async def pokemon(ctx, name):
try:
pokemon = pkmn.get_by(name=name)
await ctx.respond(embed=models.Main(pokemon=pokemon), view=models.MainNav(pokemon=pokemon))
except Exception as error:
print(f'An error occured: {error}')
await ctx.respond(embed=discord.Embed(description='This Pokémon or outfit does not exist. Did you misspell it?'))
view object
class MainNav(discord.ui.View):
def __init__(self, pokemon: pkmn.Pokemon, level: int=25, ol: int=4):
super().__init__()
self.pokemon = pokemon
self.level = level
self.ol = ol
self.add_item(OutfitSelect(pokemon=pokemon, level=level, ol=ol))
self.add_item(ShinyButton(pokemon=pokemon, level=level, ol=ol))
async def on_timeout(self):
self.disable_all_items()
class ShinyButton(discord.ui.Button):
def __init__(self, pokemon: pkmn.Pokemon, level: int=25, ol: int=4):
self.level = level
self.ol = ol
if pokemon.get_counterpart() is None:
self.has_shiny = False
else:
self.has_shiny = True
self.counterpart = pokemon.get_counterpart()
super().__init__(label='', style=discord.ButtonStyle.success, disabled=(not self.has_shiny))
async def callback(self, interaction):
await interaction.response.edit_message(embed=Main(pokemon=self.counterpart, level=self.level, ol=self.ol),
view=MainNav(pokemon=self.counterpart, level=self.level, ol=self.ol))
I'm sure the label can't be " "
import discord
from discord.ext import commands
from discord.ui import Button, View, Modal
class Review(Modal):
def __init__(self, title="Отзыв"):
super().__init__(timeout=15, title=title)
first = discord.ui.InputText(
style=discord.InputTextStyle.short,
label="Оценка",
required=True,
placeholder="Введите вашу оценку(10/10)"
)
second = discord.ui.InputText(
style=discord.InputTextStyle.long,
label="Отзыв",
required=True,
placeholder="Напишите отзыв о игре"
)
async def on_submit(self, interaction: discord.Interaction):
user_id = 906115102888046623
user = await bot.fetch_user(user_id)
embed = discord.Embed(title="Новая Заявка!", description=f"{self.user.name} написал отзыв!", color=discord.Colour.blurple(), timestamp=interaction.message.created_at)
embed.add_field(name="Оценка:", value=f"{self.first.value}:starr:/10:starr:", inline=True)
embed.add_field(name="Отзыв:", value=f"Отзыв: {self.second.value}:kodart:", inline=True)
embed.set_footer(text="Kodart :heartt:")
embed.set_author(name=self.user)
await user.send(embed=embed)
await interaction.response.send_message("Ваш отзыв был отправлен!", ephemeral=True)
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
@bot.slash_command()
async def hello(interaction):
button = Button(label="Оставить отзыв..", style=discord.ButtonStyle.grey, emoji=":00settings:")
async def button_callback(interaction):
modal = Review()
await interaction.response.send_modal(modal)
button.callback = button_callback
view = View()
view.add_item(button)
await interaction.response.send_message("Привет!", view=view)
bot.run(TOKEN)
Ignoring exception in view <View timeout=180.0 children=1> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='Оставить отзыв..' emoji=<PartialEmoji animated=False name='00settings' id=1215000851597238342> row=None>:
Traceback (most recent call last):
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ui\view.py", line 426, in _scheduled_task
await item.callback(interaction)
File "C:\Users\Lenovo\Downloads\KodArt\main.py", line 47, in button_callback
await interaction.response.send_modal(modal)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\interactions.py", line 1178, in send_modal
await self._locked_response(
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\interactions.py", line 1243, in locked_response
await coro
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\webhook\async.py", line 222, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components: Must be between 1 and 5 in length.
oh yeah I mean to put an emoji there but I forgot
You didn't add the inputs to the modal
And on_submit doesn't exist in pycord
It's callback
how do i add inputs?
Next time say something like "hey, I've been trying to debug this but I can't find a solution. Could you help?"
We aren't AI
self.add_item
Here's the modal dialogs example.
but why if i can use inputText?
sorry
What
Type that again in understandable English
what is self.add_item?
Read the example
You are supposed to add the inputs to the modal
Just defining them on the init doesn't magically add them
why doesn't it work after rebooting the bot?
UPD: non-relevant problem
.idw
Saying it doesn't work or asking what's wrong with this code is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
idi nahui
horosh
ah ok, what can i say about it? it doesn't work after rebooting. no errors and works when i run the command set_channel:
@commands.command()
async def set_channel(self, ctx, channel: discord.TextChannel = None):
# Проверка наличия роли "Верефицированный"
verified_role = discord.utils.get(ctx.guild.roles, name="Верефицированный")
if not verified_role:
embed = discord.Embed(title=":error: | Ошибка", description="**Роль** `Верефицированный` **не найдена. Пожалуйста, создайте эту роль перед использованием команды** `set_channel.`", color=0xff0000)
await ctx.send(embed=embed)
return
# Установка канала для верификации
if channel is None:
embed = discord.Embed(title=":error: | Ошибка", description="**Пожалуйста, укажите канал для верификации.**", color=0xff0000)
await ctx.send(embed=embed)
return
global verification_channel_id
verification_channel_id = channel.id
curs.execute("INSERT INTO verify_settings VALUES(?, ?)", (ctx.guild.id, verification_channel_id))
conn.commit()
embed = discord.Embed(title=":success: | Канал верификации установлен", description=f"**Я отправил сообщение на канал** {channel.mention}", color=0xff100)
await ctx.send(embed=embed)
# Отправляем сообщение в установленный канал
embed = discord.Embed(title=":verify: Верификация", description="**Добро пожаловать!\n\nДля того чтобы продолжить участие на сервере, необходимо пройти процедуру верификации. Просто нажмите на реакцию ниже (:verify:), чтобы подтвердить свою личность. После успешной верификации у вас откроется доступ ко всем каналам и возможностям сервера.\n\nБлагодарим вас за понимание и сотрудничество!**", color=0x009bff)
message = await channel.send(embed=embed)
await message.add_reaction(':verify:')```
My bot is administrator, but he still can`t mention everyone. My respond:
interaction = await ctx.respond(ctx.guild.default_role.mention, embed=embed, view=GiveawayView(code, giveaway_id))
But i get this:
just send a raw @ everyone
no need to use ctx.guild.default_role.mention
it doesnt work too
interaction = await ctx.respond("@everyone", embed=embed, view=GiveawayView(code, giveaway_id))
bot has one role that has permission "Administrator"
pass allowed_mentions=discord.AllowedMentions.all()
But if im not wrong its true by default?
i`ll try
spoiler: im wrong
interaction webhooks work in a weird way
It can
No. It can't.
Maybe it worked for me because of the emoji
guys blyat
what can i do?

yea make it work
I ain't no github copilot
and what i need to say?
And I quote this message
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
Did you even try to debug it by yourself using prints?
yeah
no results
bruh
that's literally the purpose of a debugger, but ok
people can't use debuggers
^
Then see where it stops printing. And check the line
anyways, is the command even being triggered?
Noooo! They want you to use breakpoints.. ...BREAKpoint sounds dangerous! 😟

how is your bot or client defined?
i mean, the way it was worded is ambiguous
commands.Bot(prefix)
alright I might be a bit dumb but don't reactions require intents?
is that actually what it says or is that what you think it says
yes, but it should be included in default
which is ... the default if no intents are passed
haha
the specific code for it would be helpful
it actually says that
and your commands work just fine?
yes
what discord.py or py-cord version are you using
py-cord 2.5
do you have discord.py installed at all?
i don't see how your code is functioning at all rn

can you send the output of pip list
you'd think if someone wants help they'd answer properly
i cant do it
you can
nah
lowkey think theyre trolling atp
man just do it in a console
wouldn't work if the env isn't right
my hosting doesnt have console
bruh
yeah
can you send that
And don't use requests
^ use aiohttp instead
You can run blocking code (such as PIL/Pillow) in an executor to run it in a separate thread: ```py
def my_blocking_func(*args):
...
@bot.command()
async def test_command(ctx):
ret = await bot.loop.run_in_executor(my_blocking_func, 'put', 'args', 'here')``` See the python documentation for more info.
File "/home/container/bot.py", line 14, in <module>
import discord
ModuleNotFoundError: No module named 'discord'```
🙂
reinstall pycord
+, but on_reaction_add method doesn't work
any error?
Don't you need intents for that
use the raw instead and what are your intents?
default
so you dont have the reaction intents?
it's part of default intents
but in first it works
guys were spinning in circles
is it?
Doesn't look like you're passing intents.
no one
according to squid
squid said if it's not passed it's default
the only ones that aren't are members, presence, and message_content
oh ok
yeah but their bot still works somehow without message_content so I have no idea
my main question is where is the event listener even defined
and how do you know it doesn't work
they said the commands work
man I'm getting lost here
cog
what? ah, if he doesn't dm anything and doesn't give a role - does it work?
if you put a print into the event listener does it print at all?
like at the very start
they said nothing happens
yeah, but i can try do it again
nah, it doesn't print anything
hah, if i add reaction to new message i can see this:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 400, in _run_event
await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
TypeError: Verify.on_reaction_add() takes 2 positional arguments but 3 were given```
well then
How can I perform dynamic checks on slash commands in a cog?
Like checking for a role that may be changed.


