#Basic Pycord Help (Quick Questions Only)
1 messages · Page 46 of 1
You need 3.8+
Eh
You can try it and see
How do i time out a command
await asyncio.sleep(5) os.unlink(f'{ctx.author.name}.png')
Would this time out rest of the code it gives 5 seconds for the rest of the code to rin
asyncio.sleep will pause that command's function for x seconds; if that's what you want, then go for it
It dosnt work
what are you trying to do?
So it sends a capctha then u answer in a certain time if you dont it deletes the captcha files and ends the command
oh i see
assuming you have the message_content intent, you want to use bot.wait_for
see https://docs.pycord.dev/en/master/api/clients.html#discord.Bot.wait_for for usage and examples
Ive got that
I need the command to end in a certain amount of time
how can i get the og message object of a fourm thread
yes, so you use timeout=5 in wait_for
meaning if the 5 seconds have passed, it will raise asyncio.TimeoutError which you can catch
this is demonstrated in the second example py try: reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check) except asyncio.TimeoutError: await channel.send('👎') else: await channel.send('👍')
you can use the check function to verify that they did the captcha correctly, as seen in the first example ```py
def check(m):
return m.content == 'hello' and m.channel == channel
msg = await client.wait_for('message', check=check)
await channel.send(f'Hello {msg.author}!')```
use thread.starting_message https://docs.pycord.dev/en/master/api/models.html#discord.Thread.starting_message
note there's a chance that this isn't always cached; if this is the case, you can try await thread.fetch_message using thread.id as starting message id is the thread ID
ok thank you so much! I had tried thread.starting_message before but I was getting a NoneType error whenever I tried to use it. must have been cause it wasn't cached
yeah caching with threads is pretty weird
and if that doesn't work either, one final method could be using thread.history with limit=1 and oldest_first=True
Ok thank you!
hey guys is there any function that can be executed before a slash command function gets called?
is it also possible to cancel the function then
put code before ctx.respond?
I mean I have then thousands of commands
if how can I make some function that checks everytime when a slash command gets executed
wait
I can use commands.check() right?
rip wil still take some time to modify each command
thats if you process it through an on_message first
but its different for slash
is there any function like that but for slash commands?
@marble obsidian
but do I have to process the slash command ?
what do you mean
this should work
like
yes
nevermind
how can I cancel then a slash command
like that it doesn't execute ping
respond with a message saying 'not allowed'
but it will still execute the command ping
You have to include the process line
?
use return
You override the on_application_command event, so you have to include process_application_commands
Otherwise none of your commands will work
oh
but it will give me an error
dont proccess the command if its not allowed
Oh wait my bad
?
on_application_command can be overridden without process since that's handled somewhere else
Are you trying to add permissions to your commands?
kind of like:
if the user is in a database then:
the user is allowed to run the commmand
else:
alert
Just an update on my errors I was trying to get help for - having Sparked wipe my server for me to start over worked. No issues lol
but what if I have like alot of commands
No, there's a way to add a check to all your commands which you can catch in your error handler
Just docs won't load for me...
so that's the only thing what works?
This section outlines the different types of events listened by Client. There are two ways to register an event, the first way is through the use of Client.event(). The second way is through subcla...
There are several methods but a bot check is easiest
You can also have checks for each cog
so there's no way to automate it
It's a single function
ok I will do that then thanks
Bot check = global check for all commands
bot check?
how do I do that
just @commands.check(check)?
or how do I make a global check
oh wait @cyan quail
okay that's much better
btw how do I create an error handler for application commands?
on_application_command_error
can you give me an example?
And checks will raise discord.CheckFailure
Have you made a regular error handler before?
oh not commands.ChecksFailure?
I think it was moved to discord
oh I don't wanna update since I have to rename discord -> pycord
AttributeError: 'Bot' object has no attribute 'add_roles'
Whats wrong with that
Should be member.add_roles, bot.add_roles is from years ago
👍
I just don't wanna rename import discord to import pycord
You don't need to
same for remove roles?
v3 isn't for months
Yep
Yeah
I'm not sure but:
@bot.on_error
async def on_err(ctx: commands.Context, error) -> None:
if isinstance(error, commands.ChecksFailure):
await ctx.send("oh no")
else:
raise error
I THINK that's only for prefix commands but I'm not sure
oh
Rather, you should use @bot.event with on_application_command_error and add your exceptions there
bridge commands
it takes the same parameters?
Well if it works then go for it
Yeah
Though it'd be discord.ApplicationContext instead
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'User' object has no attribute 'add_roles'
welp should it be add_role?
No add_roles is correct, but you got a user instead of a member
now how do i fetch a member 
Can you show the command code?
nope
user_added = self.bot.get_user(result["discord_id"])
Which is why I suggested discord.CheckFailure
Is this in a guild context, or do you need to get the guild separately?
oh does that also work
i do need to get it seperately as it is a task
Then use bot.get_guild
now it works
alright thanks
whats the difference between user and member is what i dont get
ah so user.mention should work right
That's fine
or this better
discord.utils.get is certainly useful, but guild.get_role does the same and is shorter
It looks like you're transferring from 0.16.2 or something
Yes that works
Member inherits all the attributes of user
I'd recommend checking out the models section for other attributes and methods https://docs.pycord.dev/en/stable/api/models.html
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 ...
Yep thanks so much
Allgood
last thing, can someone tell me how i add multiple views to a message (multiple buttons to be precise)
Technically speaking, you can't have multiple "Views"
A view has multiple buttons
hm how would I do that?
Here's the confirm example.
👍
Hey, how would I add a a channel select option to my slash command?
slash command:
@bot.slash_command(name = "announce", description = "Allows anyone with the administrator permission to send announcements")
@default_permissions(administrator=True)
also is there anyway to have it check if a user has a role or not compared to whether a user has a permission like above?
can I record and play audio at the same time?
This may help you with the channel select - https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_options.py
You can create an option and either populate it manually with a list of names, or use autocomplete - https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_autocomplete.py
what's the pycord equivalent of discord.py's timed_out_until ? Looking at the docs and am unsure
communication_disabled_until?
yes
sweeet
?
oh good to know
but it is not working for me I get an error
how are you doing it
code? error?
yea w8 a sec I will send
👍
Right now I’m trying to come up with an idea of a reaction roles system using buttons with each button giving a customizable role from the database. I was thinking of using on_interaction for this since I can handle all callbacks for a reaction role message (from a check) in one. Is there another way of doing this that’s more efficient? Since I don’t want to have to create persistent views over and over again every time the bot starts up.
I would rather do this with custom ids. Persistent views only rely on custom id. Not the label emoji or anything. Pass the role id to the button's custom id.
You wont even need a db tbh if this is a cmd based function, you may need db ig. not sure
Then what would I handle the callbacks with?
on_interaction?
a single button?
No
There are multiple buttons
That are able to be added by command
It’s a public bot so it has to be customizable
oh then the number of buttons wont be fixed too right
So I have to use on_interaction
so the view is dynamic
But I’ve had trouble with on_interaction in the past if the button was sent before the bot restarts, probably wasn’t in the cache I think.
yeah seems so. but i still recommend directly passing role id to the custom id, and getting the role object from that. this avoids a db
what wasnt in the cache? button?
you wont have a button object in cache if you plan on doing it with on_interaction
K
How can i ask user that component life time expired
is there an ability to let users create custom commands?
Creating non-slash commands shouldn't be a problem since you can just store the command name, the expected result and the guildID in for example a database.
Then you'd just have to check if the command with name x exists for guild y.
However, if you're talking about slash commands or a more complex form of the result than just text, I'm not certain how to do that.
somebody already helped me, but thanks. I'll look into it
Any ideas?
component life time expired
wdym by that?
After 10 min button doesn't work
And i want to send user message that this button doesn't work
You can't make a button do something after it has timed out. In that case just disable the button or edit the message in on_timeout
slash commands doens't show for me but for my friend it does
check if use the legacy chat input is off
yep works now
404 Not Found (error code: 10062): Unknown interaction
when is this error triggered
When you usually take too long to respond
is it normal that load/reload/unload_extension() doesn't affect commands ?
i have only one debug guild so when i restart my bot all changes are instantaneous, but when i use these methods new/removed commands aren't usable on discord
More than 3 seconds.
Indeed
How can I set cooldown for bridge commands?
The same for a prefix or slash_command
but if i use await interaction.response.defer()
i cant use response again
You must use a followup
How can I do CommandOnCooldown error for bridge command? If I use prefix, it send message in a chat. If I use slash_command, it send message in console
ctx.respond
Not send
Restart the bot
I'm trying to make my bot log avatar changes. This is what I've got but nothing happens. I've added loggers for nicknames using the same concept and it worked. How could I get this to work?
@bot.event
async def on_member_update(before, after):
channel = bot.get_channel(channelid)
if before.avatar != after.avatar and after.avatar is not None:
embed = discord.Embed(description=f"**{after.mention} changed avatar **\n\n([before])[{before.avatar.url}] **->** ([after])[{after.avatar.url}]\n\nUser Id: {after.id}", color=0xe67e22)
try:
embed.set_author(name=after, icon_url=after.avatar.url)
except:
embed.set_author(name=after)
await channel.send(embed=embed)
Wait
I know
I saw what the problem is now
You use on_command_error
But that is only for prefix commands
What do I need to change it to?
Can you try .reply?
Same problem
you'd need on_application_command_error for the slash side
How can i edit a voice channels name?
Is there a command check to see if a member is the guild owner?
Couldn’t find anything in the docs
you could always make your own
True
Thanks.
Anyone know how i could fix this error and what does it mean
That's a pretty basic error. It means you're trying to access an index/key of a list or dict that doesn't exist.
Can a bot edit its own about me or can that only be done in the dev portal?
In content: Must be 2000 or fewer in length.```
I got a function that works fine, but it gives this odd error when run
The line that it flags is
await ctx.channel.send(video)```
But the text isn't 2000 character long
Wait should I move this question to a thread
What is video?
the latter
wdym
the last choice
Oh
why doesn't on_disconnect call if you close the bot by pressing stop in ide
Hi guys I have a question,
Currently I have a command that blocks a list of words that the user selects,
but my bot is not able to read the messages sent by weebhooks and other bots, Is it possible to achieve this?
intents
What kind of intents?
message intents
message content intents
I have message intents
did you enable on dev portal?
you also need messages intents
i just use discord.Intents.all()
yes
because you killed the process.
uninstall discord.py
?tag install
- Uninstall discord.py or any other forks of discord.py you might have with the namespace
discord.
python -m pip uninstall discord.py discord -y
2a. Install py-cord
python -m pip install py-cord
2b. Update py-cord
python pip install -U py-cord
Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.
Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
?tag git
No tag git found.
A link to a bob ross video
In this call back to Season 10 of The Joy of Painting, learn how to create an almighty mountain, distant hills and trees, and a happy little path.
Follow along as certified instructor Nic Hankins guides us through the iconic Bob Ross wet-on-wet painting technique. From happy clouds to almighty mountains, these delicate instructions preserve ha...
Could you show the code for the entire function?
Ok sorry
i got this code
vote_board = await ctx.response.send_message ( embed = vote_embed )
emojis = ['1️⃣','2️⃣','3️⃣','4️⃣']
await vote_board.message.add_reaction(emoji = emojis[0].encode("ascii", "namereplace"))
it says as a error discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'add_reaction'
which is weird bc vote_board.message exists
read the error
yes it says nonetype
but how is it nonetype when i sent it like some seconds ago
is there some gotcha to using @tasks in a cog in a separate file that's loaded when the bot loads?
im not working with cogs
why?
well i don't want to
I'm having an issue lmao, sorry wasn't responding
here is my code tho for more detail
oh
@bot.command(name="voting_board", description="Pocket Calculator Here For Anything!")
async def _voting_board(ctx: discord.ApplicationContext,
title: str,
description: str,
timeout: str,
options: discord.Option(int, name = "options", description="The Amount Of Options", min_value = 2, max_value = 4)):
server = bot.get_guild(665249741289947157)
mod = server.get_role(953715870591496202)
if ctx.author.top_role.position < mod.position:
error_embed = discord.Embed ( title = "Uh Oh A Error!", description = f"It Seems That You Cannot Use The Command As You Need To Have A Moderator Role Or Higher, Please Use The Command Again When You Have The Moderator Role Or Higher", color = discord.Color.red ( ) )
error_embed.set_thumbnail ( url = Logo )
error_embed.set_footer ( text = "Below Moderator Role Power" )
await ctx.response.send_message(embed = error_embed)
return
number = re.findall("\d+", timeout)
time = timeout[len(number[0]):]
seconds = float(number[0])
if time == "m":
seconds = float(number[0]) * 60
elif time == "h":
seconds = float(number[0]) * 3600
elif time == "d":
seconds = float(number[0]) * 86400
vote_embed = discord.Embed ( title = title, description = description, color = discord.Color.dark_gray() )
vote_embed.set_thumbnail ( url = Logo )
vote_embed.set_footer ( text = "Voting Time, Cast Your Vote Now!" )
vote_board = await ctx.response.send_message ( embed = vote_embed )
emojis = ['1️⃣','2️⃣','3️⃣','4️⃣']
await vote_board.message.add_reaction(emoji = emojis[0].encode("ascii", "namereplace"))
wdym
Do you know basic python?
Aha, for the benefit of whoever is CTRL + F -ing in the future. Keywords: cog task has no attribute: when you're loading a cog with a task decorator you should do it in on_ready() not wherever you're doing it now
ctx.respond is not returning a message
oh
but then how imma gonna respond to the interaction
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 ...
is there a way to get all those arguments in commands.check ??
like i made a custom check and i want to check if the role which user pass in argument is above or not
how do i get a discord file input from a member
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Invalid class <class 'discord.file.File'> used as an input type for an Option
i tried and got this
discord.Attachment
@client.slash_command(name="ask", description="ask lol")
async def ask(ctx, gm:Option(str, "game master", required=False), gm_file:Option(discord.Attachment, "uplaod it in file format", required=False)):
await ctx.defer()
if gm_file:
print("got here")
with open(gm_file, "a+") as f: # stops here idk why
print("gptt shere")
gm = f.readlines() ```
i tried this and it didnt work and gave no error.
can you upload a file?
yes i am able to
with open(gm_file, "a+") as f: it doesnt work like that
then?
.rtfm discord.Attachmet
Target not found, try again and make sure to check your spelling.
.rtfm discord.Attachment
discord.Attachment
discord.Attachment.content_type
discord.Attachment.description
discord.Attachment.ephemeral
discord.Attachment.filename
discord.Attachment.height
discord.Attachment.id
discord.Attachment.is_spoiler
discord.Attachment.proxy_url
discord.Attachment.read
discord.Attachment.save
discord.Attachment.size
discord.Attachment.to_dict
discord.Attachment.to_file
discord.Attachment.url
discord.Attachment.width
discord.Message.attachments
discord.InteractionMessage.attachments
discord.WebhookMessage.attachments
discord.SlashCommandOptionType.attachment
oh okay
In a custom cooldown function, how would I check if the command is currently on cooldown? I want to interact with my db if the command is on cooldown when the command is sent. I tried using is_on_cooldown() but I got a maximum recursion depth error.
if you are implementing the cooldown with the decorator, CommandOnCooldown Exception would be raised in on_command_error https://docs.pycord.dev/en/stable/ext/commands/api.html#discord.ext.commands.CommandOnCooldown
The following section outlines the API of Pycord’s prefixed command extension module. Bots: Bot: Attributes activity, allowed_mentions, application_flags, application_id, cached_messages, case_inse...
what is your custom cooldown function?
def my_cooldown(message):
bot = message.bot
record = bot.syncMongoDB[str(message.guild.id)].find_one({"user": message.author.id})
if record:
if bot.itemCheck(record["inventory"],"ancient scroll") and message.command.is_on_cooldown(message):
bot.syncremoveItem(message.author.id, "ancient scroll")
return None
else:
return commands.Cooldown(1, 7200)
else:
return commands.Cooldown(0, 7200)
@proud mason
oh i am stupid
i cant use is_on_cooldown within the cooldown function
ffs thats funny
A helper function would probably solve my problem here
Yeah i'm still struggling on how to implement this. I want it to reduce the cooldown if a database record has a certain value, but only if the command is currently on cooldown. So it is an 'item' a user can have to use a command again once instantly without a cooldown.
i think you would need to maintain the cooldown checking yourselves. but im not sure
Code is in the error 💀
By fetching a message, it returns discord.Message, how can I tell if this message is a discord.WebhookMessage object?
Messages sent by a webhook have a User object as their author, while a message sent by a "regular" user has a Member object (in guilds). Therefore, you have to ensure that the Message has a guild or the channel is not a DMChannel.
oh alr, i didn't know that. thanks 
Had to test that first as well.
ah
Hello! So i was trying to make a bot display a streaming status like when someone do a twitch stream (picture) however even tho i filled with name, game and all that stuff i can't manage to make it look like that, just the watch button appears.
Is it that a discord bot can only show that or maybe i coded it wrong?
bots are kinda restricted when it comes to stuff like that, so it could be just lack of permission
How can i add a persistant view in cog?
yes that is what i thought, however as the streaming function has the values of game and all that stuff I was confused, ty!
The same way you do it normally
Found a forum post about it here and that seems to work
Is there a never ending loop
cogs are weird i hate cogs
Where
Wym where
Wym Is there a never ending loop
Like is there a loop tht mever stops
No?
I can't get the cooldown in the Command class to work
Are you perhaps looking for this?
https://docs.pycord.dev/en/stable/api/events.html
This section outlines the different types of events listened by Client. There are two ways to register an event, the first way is through the use of Client.event(). The second way is through subcla...
thanks
oh damn thats interesting
i dont think thats in the docs
a while True loop never stops unless you break. but dont use that in a discord bot. rather use the tasks ext
tasks?
Can i use em inside a async def
I'd be surprised if that's even intended
ig
yeah that doesnt seem intended
.rtfm discord.Message
discord.Message
discord.Message.activity
discord.Message.add_reaction
discord.Message.application
discord.Message.attachments
discord.Message.author
discord.Message.channel
discord.Message.channel_mentions
discord.Message.clean_content
discord.Message.clear_reaction
discord.Message.clear_reactions
discord.Message.components
discord.Message.content
discord.Message.create_thread
discord.Message.created_at
discord.Message.delete
discord.Message.edit
discord.Message.edited_at
discord.Message.embeds
discord.Message.flags
Like here
there should be smth that is intended and tells you if msg is a wehook
found it- https://docs.pycord.dev/en/stable/api/models.html#discord.Message.webhook_id
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 ...
oh yeah you can definitely use tasks.loop for this.. but i dont recommend editing a msg that often
@ruby palm hey this looks intended
It isnt a message its a channel
How the fuck did I oversee that
And example or explanation on how i could do it
oh then you should definitely slow that down
How am I supposed to use the Cooldown class to set a cooldown for command usage? I don’t understand the docs
@dim cape check this for example
async def wtv():
@cedar depotsks.loop(seconds)
cod
no
i could have helped but some mf took away slash perms from this channel
it was working in the morning...
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/cooldown.py at master · Pycord-Development/pycord
you use the decorator
and not the cooldown class
RecursionError: maximum recursion depth exceeded in comparison what in the world is this error
recursion
python has a limit
you can change it ofc
i hope you know what recursion is
(its a func calling itself)
if you dont return out of it based on conditions, you will run into this ^
or if you intensionally want it, handle it with try except
I think you can increase the limit if needed
google
async def btc_check():
if a == await bitcoin():
print("same")
else:
await a.edit(name = "BitCoin:" + str(await bitcoin()))```
traceback?
Could this work @proud mason
sys.SetRecursionLimit(0) put this in your main script
its not really a good idea to do that
Yeah no, don't do that
If you're reaching the limit you probably have an issue somewhere in your code
i fixed it
_raise_connection_failure(error)
without having to do that
smth with that?
oh how?
i had a variable trying to do something with the variable that has the same name
duplicate names
whhere you you get a from?
aah
@rare ice btw check what i found
rather than this
@proud mason dms?
i dont use tasks.loop a lot. wait for someone else
i think that looks good
How do i continue a task.loop
continue?
It creates channel then edits then stops
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Anyone
you might want to take the loop outside the command and then start it
Thanks
Then it isnt defined
you can pass arguments to loop.start
loop.start(btc_check)
no
you would need to pass a
im sensing you arent quite familiar with python?
is that so?
then discord bot is not a good project for starters
Ik some from w3school
Read rule 1 in #help-rules please
ik most things but tasks.loop
If all you've learned is from w3schools, you are most definitely not ready for a Discord bot
Hi, I was trying to work with set_permissions method (to create a lock command that removes send_messages permission from a selected channel), but I can't figure out how to pass a desired role to as target. I went through the docs but couldn't exactly find an answer.
target=some_role ?
Do I just pass a role like that?
I checked it out already, but I can't figure out how to pass a role exactly there, lol.

just pass the role object
to target
oh actually it might be a positional argument
lmk if this doesnt work
Ok so I just tried something, and yeah passing the role object worked. I had to create an additional option that takes role input from the user inside a container (which is the parameter of the command func). I then passed that container/parameter as a target and it worked.
I was wondering if there was another way for it though. I wanted a role (say @everyone) to be the default value of that parameter or container.
Can I use a method to extract that desired role from the guild? Any idea if such a method exists?
.rtfm guild.get_role
are you referring to this?
Is it possible to make the bot not say interaction failed without sending a response?
Yes, I think this is exactly what I was looking for. Let me try.
not really. is it a slash cmd or a button
you can defer and forget a component, but not an app cmd
for app cmds, the best you can do is send an ephemeral response (only visible to the author), and if you want, delete it
@proud mason Alright, it'll work (I haven't tested it yet since it's kinda late for me). Thank you for the help.
i'm atm operationally blind 😅
How in the world do i use a local image in a embed for the image field?
You’re welcome 🙃
send the image as a discord.File along with the embed
and set the image url to attachment://file_name.ext (eg attachment://sexyman.png
keep in mind that the filename and extension set to the File must be the same as the one you use in the url
oh wow i found a tag for this
?tag localimage
No tag localimage found.
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)```
yeah
Thanks mate ^^
No worries 🙃
Button
Can you drop an example please
Yo how do i make space in between slash commands ive seen it somewhere
Yi
Hey, how can I send an error in Discord via embed, the error should look exactly like in the console, how do I do that? Because with on_error I find nothing suitable
Hi, I do coding on my windows 7 laptop normally, But i have got a new host for my bot, How can i make the bot with the latest version of pycord and python online? Ive restarted so i dont have a current file.
depends on your host.
Hm?
also, Python dropped support for Windows 7, the latest version you can use is 3.8.16
you can install pycord with pip install py-cord
Alright, cool, Ill try that now and just transfer the files over, Thanks!
how many inputs can a modal have?
5
Accident
haha can happen
traceback.format_execption
You need that
It returns a sting
ah thanks
5 and only string input
okay thanks
?tag aiohttp
Use aiohttp.
requests and urllib are blocking. Do not use these libraries within your asynchronous code as they're not asynchronous.
(http://discordpy.readthedocs.io/en/latest/faq.html#what-does-blocking-mean)
discord.py uses aiohttp, so it should already be installed. An example of code using aiohttp and discord.py:
async with aiohttp.ClientSession() as cs:
async with cs.get('https://httpbin.org/json%27') as r:
res = await r.json() # returns dict
await ctx.send(res['slideshow']['author'])
For more help, see aiohttp's documentation: <http://aiohttp.readthedocs.io/en/stable/>
is 1k the limit of a discord bot?
message.guild.members.find(lambda m: m.name == 'as'), whats the error?
ok?
ok what
?tag idw
Saying it doesn't work or asking what's wrong with this code? is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
#help-rules
well, the code is just that, and i hope to find a member by his username
.rtfm utils.find
@warm kindle
Hi, For some reason when i do a slash command whilst using my laptop as a host, It works but when i put the exact same code into the host i use this error shows, Does anyone know why?
File "/home/container/main.py", line 14, in <module>
@bot.slash_command(description="testing")
AttributeError: 'Bot' object has no attribute 'slash_command'
What host are you using?
Cybrancee bot hosting
And are you sure you have pycord installed, and not discord.py?
why?
oh wait
how do I put my errors in a cog and reference them when I make my commands?
my checks I mean
I could not figure out how to put pycord in, so i thought pycord was already inside of the main.py built in
that is not how python works
How can i add pycord too the requirements
just add py-cord to the requirements file?
oh wait, its just py-cord?
yes? what else would it be?
LOL
i spent 3 hours trying to get my bot to turn on as i was using the pip command to install it
then i found discord.py works
thanks so much!
ah, it works now
How would i make my bot dm a user before kicking them?
.rtfm discord.User.send
Alright
How would i use this? Ive tried
await discord.User.send(f"u have been kicked for {reason}")
and that didnt dm
discord.User represents a user object
you can call .send on a user object to send them DMs
Ive just noticed that that discord.user.send was a link, I think i may have it now. Just gonna test
Ah ok. so i will need the full discord.User.send then? Then i would do this:
await discord.User.send(content=f"You have been kicked for {reason}")
remove debug_guilds to register globally
do you know what a user object is?
No.
?tag oop
https://www.digitalocean.com/community/tutorials/understanding-class-and-instance-variables-in-python-3
https://docs.python.org/3/tutorial/classes.html
There's a difference between a class and an instance. Think of it like this:
- A class is like a blueprint, or a concept. It defines what something should have, but it's not the same as actually having it.
- An instance is the 'realized' version of the class, it contains everything that the class defines should be on it, but you can actually access and interact with these features.
Let's consider the Cat. We know a Cat has a name and an age, but Cat.age won't work, because Cat isn't an actual cat, it just represents the concept of a cat. It's like asking "What is the age of a cat?" - it doesn't make sense, because we need to have an actual cat.
mimi on the other hand is an instance of a Cat - it has everything a Cat should have. Maybe mimi was constructed, like mimi = Cat("Mimi", age=4), or maybe mimi was retrieved from somewhere else, like house.cats[0], but in any case, it has everything we need, and mimi.age will rightfully give us 4.
There are many situations in Object Oriented Programming where you will need an instance instead of a class to perform an operation properly (in fact, you almost always need an instance instead of a class), and these cases will usually be documented.
You should learn a good amount about Object Oriented Programming before working extensively with Pycord.
@thorny kindle ^
Alright.
ty
Ah
i think i understand
so im only putting in half of what i need to do, i need to mention a user
but how do i put the user in?
youre in a kick command right?
Yea
how are you kicking the user?
with await member.kick()
.rtfm discord.Member.kick
so member is your instance of discord.Member
Ok
you can use discord.Member.send to send them a dm, but remember to use your instance
Alright
Ahhh i think i see what i did then
So i used member as a placeholder for the user, But then i used a different placeholder for the dm so it could kick but not find who to dm.
oh. I changed it too:
await discord.Member.send(f"You have been kicked for {reason}")
And
await discord.Member.send(content=f"You have been kicked for {reason}")
but none worked
you’re calling .kick on a member object, with the same member object, you can call .send to send a DM
Im confused, Isnt that what i did in what i just sent with discord.Member.send?
discord.Member is a class, did you read the message this one replies too?
Yea.
Wait, so it needs a instance and a class
but isnt the message the instance?
forget what i said. 2am reading dont work. Ill read it again and try and make more sence of it
So im missing something to make discord.Member a instance then
right.. to kick a user in a guild, you need to have a discord.Member object which you clearly have, then you would call the following in your code:
await <discord.Member object>.kick()
if you compare the difference between the above code and your code, you should know what your member object is defined as (it replaces <discord.Member object>)
to send a DM to a user, you are able to call discord.Member.send as shown below:
await <discord.Member object>.send("Hey! This is a DM.")
as discord.Member is a class rather than an instance, you are required to replace it with the member object which you have
I can’t really put this any other way without spoon feeding (kinda already am)
So does <discord.Member object> just mean the user i mention then. But the object has to be there otherwise its incomplete?
define "the user i mention then"
the object which you call .kick one is the same object you call .send on
So if i did /kick @thorny kindle, @thorny kindle would be discord.Member
But thats only a class. So the object completes it
a user mention & user object are 2 completely different things
oh
Im gonna go watch some videos on this before i go to bed, Hopefully by the morning ill understand what it all is, Sorry for any problems ive caused. Just gotta hope by morning i know what im doing.
Thank you so much for your help!
Read rule 1 in #help-rules
Oops, sorry
was anything changed to commands.FlagConverter ?
mine doesnt work anymore
and im also getting TypeError: Flag.__init__() got an unexpected keyword argument 'name'
class StatsFlags(commands.FlagConverter, delimiter=" ", prefix="-"):
d: Optional[str] # Detailed
``` this is my code that's been working well for over a year, not sure what could have went on...
There's nothing about it in the changelogs
maybe someone changed it without documenting

I read through both dpy and pycord changelongs just incase
But you didn't update? Or does it work with older versions?
and saw nothing
im on 2.3.2
Hm, no clue tbh
full error trace?
Traceback (most recent call last):
File "C:\Users\Ghoul\Documents\TeamMai\Mai\mai.py", line 254, in cog_watcher_task
self.load_extension(extension_name)
File "C:\Users\Ghoul\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\cog.py", line 910, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\Ghoul\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\cog.py", line 777, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.Osu.Osu' raised an error: TypeError: Flag.__init__() got an unexpected keyword argument 'name'
Traceback (most recent call last):
File "C:\Users\Ghoul\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\cog.py", line 774, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib._bootstrap_external>", line 940, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "C:\Users\Ghoul\Documents\TeamMai\Mai\cogs\Osu\Osu.py", line 50, in <module>
class StatsFlags(commands.FlagConverter, delimiter=" ", prefix="-"):
File "C:\Users\Ghoul\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\flags.py", line 335, in __new__
for flag_name, flag in get_flags(attrs, global_ns, local_ns).items():
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Ghoul\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\flags.py", line 168, in get_flags
flag = Flag(name=name, annotation=annotation, default=flag)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Flag.__init__() got an unexpected keyword argument 'name'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Ghoul\Documents\TeamMai\Mai\mai.py", line 254, in cog_watcher_task
self.load_extension(extension_name)
File "C:\Users\Ghoul\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\cog.py", line 910, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\Ghoul\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\cog.py", line 777, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.Osu.Osu' raised an error: TypeError: Flag.__init__() got an unexpected keyword argument 'name'

Clients are limited to 1000 IDENTIFY calls to the websocket in a 24-hour period. This limit is global and across all shards, but does not include RESUME calls. Upon hitting this limit, all active sessions for the app will be terminated, the bot token will be reset, and the owner will receive an email notification.
Might be this
could try doing a git bisect if you really wanna find out
lol
that's probably not needed
but from what im seeing
I think this was updated
but not documented
i think you're supposed to actually use discord.ext.commads.flag
but im not sure how...i dont see any args for delimiters or prefixes
so probably not that actually
.rtfm slashcommand.mention
.rtfm applicationcontext.command
Target not found, try again and make sure to check your spelling.
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
.rtfm status
discord.Status
discord.Status.online
discord.Status.offline
discord.Status.idle
discord.Status.dnd
discord.Status.do_not_disturb
discord.Status.invisible
discord.ScheduledEventStatus
discord.ScheduledEventStatus.scheduled
discord.ScheduledEventStatus.active
discord.ScheduledEventStatus.completed
discord.ScheduledEventStatus.canceled
discord.ScheduledEventStatus.cancelled
discord.AutoShardedBot.status
discord.ext.commands.Bot.status
discord.AutoShardedClient.status
discord.Bot.status
discord.ext.bridge.Bot.status
discord.ext.bridge.AutoShardedBot.status
discord.Client.status
"not working" doesn't say anything. Explain what is wrong
Yeah, it's not a coroutine
You have already been told how to
Because your code is wrong
get_application_command is not a coroutine
interaction.response.send_message() returns nothing. Is there a way to get the interaction message?
interaction.response.send_message returns the interaction
To get the actual message, call interaction.original_response
.rtfm interaction.original_response
Hi, I'm trying to create a Slash Command that allows users to set a role icon by uploading an image attachment in the command
The issue is that the icon appears to be low resolution, and also lacks a transparent background
@discord.slash_command(description="Create and adjust a custom role")
async def custom_role(self, ctx, icon: Option(discord.Attachment, required=False)):
role = await guild.create_role(name="Test")
await role.edit(icon=await icon.read())
I tried to write the bytes object to file by using the following code
with open("icon.png", "wb") as binary_file:
binary_file.write(icon_byte)
and got the following result
You should probably use an image processing library for that, like PIL.
Between await icon.read() and role.edit()?
I mean to create the file that gets uploaded, instead of just writing raw binary
I thought that the role icon needs to be a bytes object
Never mind, it might be an issue with the image
Do you need presence intent to get a user object from id?
await bot.get_user(id)
returns None when I disable it
get_user is not a coroutine, and it only gets from the bots cache
.rtfm discord.Bot.get_or_fetch_user
i dont want to get stuff from database
i want to create a database
use pycord
"make an api" doesn't say a lot. Explain your use case more specifically
You can set up an asynchronous web server using aiohttp as well. And run it alongside your bot on the same asyncio loop
https://docs.aiohttp.org/en/stable/web_quickstart.html#run-a-simple-web-server
in the same file?
make a loop?
Ext.loop
I don't see a reason to, but sure
That entirely depends on how you set up the API
You can get the bot's event loop through discord.Bot.loop
And then just do something like
my_web_server = MyWebServer()
bot.loop.create_task(my_web_server.start())
👍 ❤️
Hi, can someone tell me how I can start a task after the bot comes online?
i have a expire_invite.start() over here
Await task.start()
Cant you just pass args?
its a task how do I make it fetch a guild before the bot starts up
I would need to wait for the bot to start up
self.expire_invite.start()
self.check_invite.start()
# Does for manual invites too, so not removing it
@tasks.loop(hours=12)
async def expire_invite(self):
guild = self.bot.get_guild(self.bot.config["guild_id"])
member_alerts_channel = discord.utils.get(guild.channels, id=self.bot.config["member_alerts"])```
this is a snippet of what im tryna do
.rtfm discord.Bot.wait_until_ready
Maybe this is useful?
@west quest
yep thanks!
how to make a sub command inside a command with same arguments
slash groups
example?
ty
Examples for both, cogs and normal ^
np
Anybody know how to make an emoji message jump link?
There's one in #server-announcements message
holy shit thats a novel idea
but im not sure
it might be this [emoji](link)
but i thought that only works inside embeds
src/main/java/com/jagrosh/giveawaybot/commands/RerollMessageCmd.java line 102
+ " [\u2197](" + String.format(JUMP_LINK, interaction.getGuildId(), interaction.getChannelId(), msg.getIdLong()) + ")") // ↗```
yeah but that only works in embeds
but i recently came to know messages sent via webhooks or interactions allow it too
cool
how do i get the try_after in HTTPException ?
show your code
and bot.add_application_command(blacklist) at the bottom
You're using the create_group method completely wrong
.rtfm discord.Bot.create_group
Heyyy, how can I make a select menu so that when you select an option it automatically becomes unselected?
how can i add subcommands?
Look at the examples and read the docs
?
Yeah? That is not how you used the method
oh
Read the docs
ty i just know how to do now
help pls
what should i set the guild value to be such that by default given a guild id it will be automaticaly only showing that and if the user does not have access thay should not be able to add the bot
The way i'd do it is whenever the select is interacted with, in the callback, edit the message with the same view added again
Anyone got a scalable file structure template?
edit the message with the same view
Ok
you want to use guild=... (takes Guild object) and disable_guild_select=True. Note that users can edit the URL to disable these options, so it shouldn't be relied on for security.
how can i make the guild object?
also im by default the bot is not part of the server
you can use bot.get_guild(id)
though note that you technically don't need a guild object; you can create an arbitrary discord.Object with id=... and pass it in
how can i do that?
discord.Object(id) was the sexiest thing man had seen
thx Om & Nelo it works
hello, how to use pycord with aiomultiprocess to like avoid API limitation
import aiomultiprocess as amp, os
@client.event
async def on_ready():
guild = client.get_guild(guild_id)
legend_role = guild.get_role(role_id)
async with amp.Pool(os.cpu_count()) as pool:
async for color in asyncgen_color_seq
await pool.apply(legend_role.edit, kwds={"colour": color})
# this code should call cores asynchonly i.e. when first core is processing the request you call second one
oops
Why would you want to avoid api ratelimits
I need to do one command really fast
Ratelimits exist for a reason
but when I do it in common way feels like 10fps
You're not meant to avoid them
no, it's not like ratelimits I guess
pycord made that way to interact with discord with async/await
but you know when I send request (to change the role for instance) not the bot, but my PC proceeds it and takes some runtime so using threading makes no sense
multiprocessing should help me to short the latency
(aiomultiprocess, not the synchronous one)
:(
Hello, I'm getting this error;
AttributeError: 'Bot' object has no attribute '_CogMixin__extensions'
I'm trying to use load_extension method of bot
Can't help with no code.
mine pls?
import os
from dotenv import load_dotenv
load_dotenv()
from src import Bot
bot = Bot()
cogs_list = [
'greetings',
'owner',
'errors'
]
for cog in cogs_list:
bot.load_extension(f'src.cogs.{cog}')
bot.run(os.environ('TOKEN'), reconnect=True)
and my Bot class;
import discord
class Bot(discord.Bot):
def __init__(self):
self.Version = "0.1.0"
async def on_ready(self):
await print(f"{self.user} is online.")
You didn't super().init
for cog in cogs_list:
bot.load_extension(f'.src.cogs.{cog}')
#place the dot
you forgot the dot
.src.cogs
That's not even the issue lol
But that's not the issue as I said
try to reinstall pycord from github
@polar plume
maybe something went wrong or I don't have any ideas
sooooooooooooooooo, who can help me pls?
question is above
As im learning python, i have some issues. How can i fix this issue
dude a new error spawned after i added the super part
discord.errors.ExtensionFailed: Extension 'src.cogs.greetings' raised an error: AttributeError: 'Bot' object has no attribute 'add_command'
Show your code dude
crap lmao, but its a test bot anyway
reset what?
Your token
import discord
class Bot(discord.Bot):
def __init__(self):
self.Version = "0.1.0"
super().__init__()
async def on_ready(self):
await print(f"{self.user} is online.")
.
What's your pycord version and show the greetings cog
Show your pip list
latest prob, installed it today
wtf is that, im new to visual studio. and python, i only know lua as of know. Little of C#
"Prob" unspecific answers are not helpful
import discord
from discord.ext import commands
class Greetings(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command() # creates a prefixed command
async def hello(self, ctx): # all methods now must have both self and ctx parameters
await ctx.send('Hello!')
@discord.slash_command() # we can also add application commands
async def goodbye(self, ctx):
await ctx.respond('Goodbye!')
@discord.user_command()
async def greet(self, ctx, member: discord.Member):
await ctx.respond(f'{ctx.author.mention} says hello to {member.mention}!')
@commands.Cog.listener() # we can add event listeners to our cog
async def on_member_join(self, member): # this is called when a member joins the server
# you must enable the proper intents
# to access this event.
# See the Popular-Topics/Intents page for more info
await member.send('Welcome to the server!')
def setup(bot): # this is called by Pycord to setup the cog
bot.add_cog(Greetings(bot)) # add the cog to the bot
Then learn python before coding a bot
#help-rules 1
Thats what im doing
i mean i iinstalled it today, so it should be latest right?
yeah
No, you're a trying to code a bot before learning pyrhon
im learning along the way,
Remove @commands.command. that's a prefixed command and you're using a Discord.Bot instance which only supports slash commands
You don't even know the basics. Py-cord is not a simple library. #help-rules
i mean, i legit started yesterday 
Indeed, don't expect help.
what if i want to use prefixed commands too?
Then you use a commands.Bot instance
okay Sir, thanks for your help < 3
Excuse me,
How do I invoke such commands that are not slash commands
@discord.user_command()
async def greet(self, ctx, member: discord.Member):
pass
@bot.event
user commands are the one you get when you right click on a user
Learn all about Context Menus (User Commands & Message Commands) and how to implement them into your Discord Bot with Pycord!
try:
await ctx.respond(f'{ctx.author.mention} {response}')
except:
with open("tempfile.txt", "r+") as tf:
tf.write(response)
await ctx.respond("here is your answer: ", file=discord.File(tf))
os.remove("tempfile.txt")```
anyone know what's wrong here, i am trying to create a temp text file if the discord bot is unable to send it, so it can send the text in the file
hi so I was wondering how to make a slash command without the sub command
Like I want to have a command /parent and command /parent command1 but I don't see how I am able to make these
In the example they used discord.SlashCommandGroup("math","Commands related to math.")
and makes a command /math add
but how would I make a command /math along with it (to maybe give like an info about the command)
How can i figure out what the "object" should be on this:
await <discord.Member object>.send(f"You have been kicked for {reason}")
learn python
#help-rules
To my knowledge that is not possible with command groups.
My guess would be to create a "regular" slash command and add a not required option with the choices being the names of the sub commands.
why use an actual file for temp storage? use io.BytesIO
It is exactly a "temp" file
try making a separate command (outside the group) called math
if that doesnt work, then you best bet is doing math help or smth
nop doesn't work
shows error
guess it's not possible
What error do you get?
Because when I use this:
@bot.command(name="math", guild_ids=[...])
@option(
name="operation",
choices=[
"add",
"subtract"
],
required=False
)
async def math(ctx: discord.ApplicationContext, operation):
if not operation:
await ctx.respond("This explains the command")
else:
await ctx.respond(f"You chose: {operation}")
It works perfectly fine.
It removes the file instantly after creation
Hi, I wanted to know if there's a method to check a role's permission for a specific text channel. In other words, if there's a method to know whether a particular role has a certain permission in a specific text channel.
check channel.Permissions_for something like that
.rtfm get_role
Hm. But doesn't that method return every permission the passed role/user has? Or is there a way to check if the passed role/user has a specific permission as well?
@commands.slash_command(guild_ids=[guild_id])
@commands.guild_only()
@commands.has_permissions(ban_members=True)
async def poll(self, ctx, intrebare, optiune1, optiune2):
await ctx.respond("✅", ephemral = True)
Isn't this how you give hidden replies back ?
TypeError: InteractionResponse.send_message() got an unexpected keyword argument 'ephemral'
ephemeral
fu** i'm stupid. 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 ...
yes literally what i have pointed out
use if statements to get the perms u r finding
Ah right. Was a bit confused. Thanks.
I was thinking if there was a way to do it without an if statement (if I could pass the perm I'm looking for as a parameter maybe?), lol.
When editing ClientUser using bot.user.edit, avatar requires a bytes-like object. I have a slash command with a discord.Attachment option, how would I make that discord.Attachment a bytes-like object?
.rtfm attachment.read

o
how can i find a user that is not cached by id or username?
what do you know about the user
.rtfm fetch_user
discord.ext.commands.Bot.fetch_user
discord.ext.commands.Bot.get_or_fetch_user
discord.ext.commands.AutoShardedBot.fetch_user
discord.ext.commands.AutoShardedBot.get_or_fetch_user
discord.ext.bridge.Bot.fetch_user
discord.ext.bridge.Bot.get_or_fetch_user
discord.ext.bridge.AutoShardedBot.fetch_user
discord.ext.bridge.AutoShardedBot.get_or_fetch_user
discord.Client.fetch_user
discord.Client.get_or_fetch_user
discord.AutoShardedBot.fetch_user
discord.AutoShardedBot.get_or_fetch_user
discord.AutoShardedClient.fetch_user
discord.AutoShardedClient.get_or_fetch_user
discord.Bot.fetch_user
discord.Bot.get_or_fetch_user
what
if you are trying to find the user, what do you know about the user?
anything
They mean to ask that if you don't know the user's ID or username, is there anything else at all that you know about the user?
no i am trying to make a simple avatar command. i want to show avatar by user id, name or nickname
Does your command take any parameters?
wdym
Do you know which user's attributes you want to access?
just .avatar
Are you looking for the command's author or is that provided by the author?
i am looking for the given user
Oh mb I meant to reply to the other person
simply, user.avatar.url
I meant this doesn't work and shows error
no i really think you misunderstood my question
i want to return the avatar of a user that may not be in the cache
use bot.fetch_user, you can only do it by ID
is it not possible?
i think no
i mean it is... only with ID though
i want it to be possible by username too
aren't they always cached?
you can't request any user just from username alone
yeah but like users in servers the bot doesn't share etc.
I think that was your only chance 
You can't fetch those users
Iirc
so is it not possible to find a user that is not cached by username?
I ended up making a different command instead 
bad
Ohh
this is explicitly not possible https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups
Using subcommands or subcommand groups will make your base command unusable. You can't send the base
/permissionscommand as a valid command if you also have/permissions add | removeas subcommands or subcommand groups
Is it possible to mention slash commands with pre-filled arguments?
negative
thanks
how do I convert a datetime object into something like this <t:1672350806:D>
Parse the datetime object to an int and add it between <t: and :D>
Don't you have to .timestamp() it
how can i return bot invite url?
i thought it wouldn't be the same format as it returns a float but it turns out that simply converting it to int works, thanks a lot
.rtfm utils.oauth
^
thx little squid
np
how can i do allowed mentions (user)
Have you tried reading the docs
There's usually plenty of info about the library there
Yes, I already tried to look for it, and I didn't find it
.rtfm AllowedMentions
You sure bout that?
yes
how should i deal with this
because if i set everything on a new line
it will not end up good
thanks
welp
some things u cant have in life ig
oof
Its not the same in discord
ik
in terminal it looks how its supposed to
Use a pic of it lmao
.rtfm permissions
discord.Permissions
discord.Permissions.DEFAULT_VALUE
discord.Permissions.VALID_FLAGS
discord.Permissions.add_reactions
discord.Permissions.administrator
discord.Permissions.advanced
discord.Permissions.all
discord.Permissions.all_channel
discord.Permissions.attach_files
discord.Permissions.ban_members
discord.Permissions.change_nickname
discord.Permissions.connect
discord.Permissions.create_instant_invite
discord.Permissions.create_private_threads
discord.Permissions.create_public_threads
discord.Permissions.deafen_members
discord.Permissions.embed_links
discord.Permissions.external_emojis
discord.Permissions.external_stickers
discord.Permissions.general
never thought of that
How can I return a list of user permissions? (I tried discord.abc.GuildChannel.permissions_for(message.author.id)) and it wasn't
.tag oop
https://www.digitalocean.com/community/tutorials/understanding-class-and-instance-variables-in-python-3
https://docs.python.org/3/tutorial/classes.html
There's a difference between a class and an instance. Think of it like this:
- A class is like a blueprint, or a concept. It defines what something should have, but it's not the same as actually having it.
- An instance is the 'realized' version of the class, it contains everything that the class defines should be on it, but you can actually access and interact with these features.
Let's consider the Cat. We know a Cat has a name and an age, but Cat.age won't work, because Cat isn't an actual cat, it just represents the concept of a cat. It's like asking "What is the age of a cat?" - it doesn't make sense, because we need to have an actual cat.
mimi on the other hand is an instance of a Cat - it has everything a Cat should have. Maybe mimi was constructed, like mimi = Cat("Mimi", age=4), or maybe mimi was retrieved from somewhere else, like house.cats[0], but in any case, it has everything we need, and mimi.age will rightfully give us 4.
There are many situations in Object Oriented Programming where you will need an instance instead of a class to perform an operation properly (in fact, you almost always need an instance instead of a class), and these cases will usually be documented.
You should learn a good amount about Object Oriented Programming before working extensively with Pycord.
Object-oriented programming allows for variables to be used at the class or instance level. This tutorial will demonstrate the use of both class and instance…
could someone pls explain how i can make a bot to use oath2 code grant?
For what purpose?
i want to make a bot only enterable to a guild if a user has set that as their guild
??
how would i make a basic word blacklist? I tried using on_message but that doesn't detect the word
How can i send a modal in a normal select view
def __init__(self, *args, **kwargs) -> None:
super().__init__(
discord.ui.InputText(
label=config.QUESTION_ONE,
placeholder="Please put your discord ID",
),
discord.ui.InputText(
label=config.QUESTION_TWO,
placeholder="Please put your age!",
),
discord.ui.InputText(
label=config.QUESTION_THREE,
placeholder="Please put your Country & Time Zone",
),
discord.ui.InputText(
label=config.QUESTION_FOUR,
placeholder="Please put your job or education",
),
discord.ui.InputText(
label=config.QUESTION_FIVE,
placeholder="Please fill this out fully!",
style=discord.InputTextStyle.long,
),
*args,
**kwargs,
)
async def callback(self, interaction: discord.Interaction):
channel = bot.get_channel(STAFF_APP_LOGS)
embed2 = discord.Embed(
title=f"Your Staff Application --> {ticket.mention}",
fields=[
discord.EmbedField(
name=config.EMBED_ONE, value=self.children[0].value, inline=False
),
discord.EmbedField(
name=config.EMBED_TWO, value=self.children[1].value, inline=False
),
discord.EmbedField(
name=config.EMBED_THREE, value=self.children[2].value, inline=False
),
discord.EmbedField(
name=config.EMBED_FOUR, value=self.children[3].value, inline=False
),
discord.EmbedField(
name=config.EMBED_FIVE, value=self.children[4].value, inline=False
),
],
color=discord.Color.random(),
)
await channel.send(embed=embed2)
embed = discord.Embed(description=f'📬 Ticket was Created!', color=0xe800ff)
await interaction.response.send_message(embed=embed, ephemeral=True)```**MODAL**
async def fifth_button_callback(self, button: discord.ui.Button, interaction: discord.Interaction):
if "support5" in interaction.data['custom_id']:
if interaction.channel.id == TICKET_CHANNEL:
guild = bot.get_guild(GUILD_ID)
ticket_owner = interaction.user
for ticket in guild.channels:
if str(interaction.user.id) in ticket.name:
embed = discord.Embed(title=f"You can only open one Ticket", description=f"Here is your opened Ticket --> {ticket.mention}", color=0xff0000)
await interaction.response.send_message(embed=embed, ephemeral=True)
return
modal = MyStaff(title="Staff Application")
await interaction.response.send_modal(modal)
open_ticket = bot.get_channel(LOG_CHANNEL)
category = bot.get_channel(CATEGORY_ID4)
ticket_channel = await guild.create_text_channel(f"ticket-staff-application-{ticket_owner}", category=category,
topic=f"Ticket from {interaction.user} \nUser-ID: {interaction.user.id}")
await ticket_channel.set_permissions(guild.get_role(STAFF_APP_TEAM), send_messages=True, read_messages=True, add_reactions=False,
embed_links=True, attach_files=True, read_message_history=True,
external_emojis=True)
await ticket_channel.set_permissions(interaction.user, send_messages=True, read_messages=True, add_reactions=False,
embed_links=True, attach_files=True, read_message_history=True,
external_emojis=True)
await ticket_channel.set_permissions(guild.default_role, send_messages=False, read_messages=False, view_channel=False)
embed = discord.Embed(description=f'Welcome {interaction.user.mention}!\n'
'Please wait while we review your answers!',
color=config.EMBED_COLOR)
embed2 = discord.Embed(description=f'We have received your staff application answers.\n'
'Please wait, we will get back to you shortly',
color=config.EMBED_COLOR)
await ticket_channel.send(embed=embed2)
await ticket_channel.send(embed=embed, view=TicketClose())
embed3 = discord.Embed(title='**Ticket Opened**', description=f"{ticket.mention} Was created!", color=config.EMBED_COLOR)
await open_ticket.send(embed=embed3)
return``` **TICKET**
interaction.response.send_modal?
.tag idw
Saying it doesn't work or asking what's wrong with this code is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
turn message into list of words (search for .split() )
Loop through list if words and check if each word is in blacklist
If so ban or something
Why spilt? You can do if word in msg.content
You can do if any((word in msg.content for word in ban_words_list))
Else you can straight up use regex and it will be the fastest and most efficient
Typically speaking, regex will be slower. But it requires a lot less code, and the speed difference usually isn't that vital unless you're checking thousands of messages every second.
I thought regex will be faster if you have a compiled search pattern, considering that you are checking a whole list of words
Yeah, it of course depends on what you're checking. But from what I've seen regex is usually slower, but more suited for complex pattern checks that would be too tedious to code with regular checks. And it's a matter of milliseconds anyways, so you should just use whatever suits the situation better.
Hmm true 
Do discord model buttons follow different parameters than normal buttons?
I'm trying to disable one on button click using
button.disabled = True
await interaction.followup.edit_original_message(view = self)
but I'm getting AttributeError: 'Webhook' object has no attribute 'edit_original_message'
simply interaction.edit_original_message
ohh boi, I see!
It's the little things lol
Thanks!!
Hello, How do i set activity of my bot?
.rtfm bot.activity
thanks !
I need an implementation example.
bot = discord.Bot(activity = discord.Game(name = "a game"))
I did try something like that but doesn't show any activity to my bot
activity = Activity(name='Anime', type=ActivityType.watching)
bot = Bot(activity= activity)
Bot Class
class Bot(discord.Bot):
def __init__(self, *args, **kwargs):
self.Version = "0.1.0"
super().__init__(args=args, kwargs=kwargs)
super().__init__ should be the first line under __init__

