#Basic Pycord Help
1 messages Β· Page 2 of 1
antispam: bool
yup
What you can do imo:
Detect if user not in "exceptions list"
Get ~5 first and ~5 last letters
Store them in dict and store amount of spam messages
If new message contains exact first and last letters -> add more to spam amount if spam amount is big enough -> punish
Yes.
Nothing will change lol
str[-5:] will just return 1 letter if message is 1 letter long (like just f)
i dont understand
"The silly fox really loves programming"
"The silly fox really loves programming"[-5:] -> "mming"
"The silly fox really loves programming"[:5] -> "The s"
"f"
"f"[-5:] -> "f"
"f"[:5] -> "f"
its basically taking some of the contents of the 1st message then checking to see if the other messages have the same contents?
Yes
if the user's message has the same contents as his previous message
how can i put this into code for my bot event?
make bot.event to bot.listen
add bots check
wym bot checks
or if message.author == client.user: return x3
like this?
one great oneliner xd
@bot.listen
async def on_message(message):
if user is bot -> skip
if message.author.bot:
pass
if antispam == "Enabled":
π
make if message authot return, not bot pls
Only self messages, and also not bot check
Now I want to ask for basic Python ;3
im sorry, but im so confused on what you mean
if message.author.bot:
return
Delete
if message.author.bot:
pass
depends whats basic
Have you already written discord bots?
yesa
Tell me that's a joke
dang im getting clowned π
its not tho, why?
Because that code doesn't make any sense
im just taking his advice
they gave you pseudocode and you just slapped it in
i didnt know it wasnt pycord after all this is a pycord server
THE OM KILLER? π
new programming language just dropped
you should have enough experience with python to know that was pseudocode and not real python
?tag lp
Official Beginner's Guide: https://wiki.python.org/moin/BeginnersGuide
Official Tutorial: https://docs.python.org/3/tutorial/
Shortcuts:
https://wiki.python.org/moin/BeginnersGuide/NonProgrammers
https://wiki.python.org/moin/BeginnersGuide/Programmers
Learn Python:
https://automatetheboringstuff.com/ (for complete beginners to programming)
https://learnxinyminutes.com/docs/python3/ (for people who know programming already)
https://docs.python.org/3/tutorial/ (official tutorial)
http://python.swaroopch.com/ (useful book)
http://www.codeabbey.com/ (exercises for beginners)
i dont know what pseudocode is
How to make buttons work in the dms ?
the same like at the server?
Yup
than why do you ask?
Because when i click it shows interaction failed
after a restart of the bot?
Yup
Here's the persistent example.
check this out @glossy latch ^
did you respond?
Yup
Send your code please
hey im building a slash command with options. When i use it, it doesnt show the options that the user inputted in the original message. It just shows the slash command used. Any way to display the options inputted?
when you click the command itself, it will show the options used
Is there a way to get how many / commands the bot have?
Is it still true that you cannot combine a discord.Member Option type with an autocomplete, or otherwise filter the users that show in that control?
yes
only string autocomplete if thatβs what you mean
but you can always code your own
Thanks!
Maybe one day Discord will be more flexible
I was using a member auto complete to act on a member in that channel, and the initial list was filtered to members in that channel. So I wonder if discord is doing that by default, or learning the use case of each command or something, or even something as simple as showing recently active users
Can you use buttons, context menu's etc. within DM's to people? Via a bot obviously.
Yes you can
It works the exact same way as normal.
Discord always sorts mentions off of who sent the most recent message to the channel and so on. Not sure how many users it saves before just doing off name tho.
Is it possible to use multiple selection with a slash command in autocomplete?
No, but you can do it manually in autocomplete. So after they select an option the next suggestion is a , then it will suggest things again
As an example here:
Can I select both German and English here?
@option(
"language",
description="Choose your Language.",
choices=["English", "Deutsch"],
required=True,
)```
Yes I know.
So is it not somehow possible to select multiple options?
Here is what I have in mind:
Choices: ["apple", "banana", "tomato", "potato"].
shopping_list: Apple:2 Tomato:1 Banana:3
And then in the callback I want to extract the values accordingly using the : so I know how much of each I need.
You would have to use autocomplete to do it manually. Or use a select menu.
How can I do it with autocomplete?
Somehow I can not manage that I can select a second thing π€
async def test_autocomplete(self, ctx: discord.AutocompleteContext):
buffs = ["Buff1", "Buff2", "Buff3", "Buff4"]
return [buff for buff in buffs if buff.startswith(ctx.value.lower())]
@slash_command(
name="test",
description="test",
)
@option(
"test",
description="test",
autocomplete=test_autocomplete,
required=True,
)
@commands.has_permissions(administrator=True)
async def create_template(
self,
ctx: discord.ApplicationContext,
test: str,
):
await ctx.respond("Successfully.")
Can anyone help? π
Hello. Is it possible to restrict a slash command to be visible only to some users or only in one server?
Only for permissions
Okay. Thank you
You would need to add more then just a simple auto complete. I've never done it but I would do something like.
buffs = ...
Choices = []
if ctx.value.lower() in buffs:
Choices.append(ctx.value)
return [ctx.value + ", "+ buff for buff in buffs if buff.startswith(ctx.value.lower().split(", ")[-1])]
Just add guild_ids to the command (as of right now this will on update on a bot restart.) Otherwise you can use default permissions. But to restrict users that will have to be done per server by server admins. Or you could use a check but that would still show the slash command to all just not let the command return anything.
Yeah that works but I wanted it to be clean and not show all the administrative commands to everyone. The permission restriction is good enough.
I don't quite know how this is supposed to work.
I would like to have several entries in the field of the autocomplete, but they are all in the given list.
list = ["apple", "banana"]
var: Apple:2,Banana:3
Tomato should not be possible then e.g.
I can't make the whole function for you but the basic idea would be.
- Get the current input
- Split the input into options EX split(", ")
- Do simple auto complete on the last element of step 2.
- Reconstruct the return list with previous selections and the new suggested option at the end.
- Repeat above steps until command is submitted
- In the command split the string into individual options again (same as step 2)
- If there is an invalid option return an error.
List> banana, apple, watermelon, pear, grape, orange, blueberry,
User> wa
Suggested> watermelon,
User> watermelon, b
Suggested> watermelon, banana,
watermelon, blueberry,
User> watermelon, blueberry, app
Suggested> watermelon, blueberry, apple,
Okay I will give it a try.
Or do you have another idea how I can maybe make it better?
I have a list with 19 entries. From this I want to select the entries I need and additionally to each entry I want to specify how much of it I need. The number can be different for each item.
To make 19 options with choices from 0 - 10 would not be very useful and very confusing, so I am looking for another good solution π€
I think that this is the best way to start. The numbers will make it more difficult but you should be able to use some python knowledge to figure out the algorithm.
||ChatGPT might be able to help with the algorithm part||
How do i make autocomplete but for optional arguments
yea
oh
its at the example here
i couldnt find any examples for autocompletions for optional arguments
async def render(self, ctx,prompt:str,
size:Optional[int]=100,
color:Optional[str]="white",
ephemeral:Optional[bool]=False
):
was talking about those
i want autocompletion for the color param
discord.Option has a required keyword argument
rip
can i edit a message if its ephemeral
https://docs.pycord.dev/en/stable/api/application_commands.html#discord.Option
There is a description keeard argument
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...
oh i missed that while reading the docs. thanks
So I'm starting a new bot. It's not my first one by any means, but I think I'm forgetting something very basic; I just can't figure out what.
- The bot has the "bot" and "applications.commands" scopes
- I've got py-cord==2.4.1 installed
- I've got no other "discord" or "discord.py" package installed
- The bot is a subclass of
discord.Bot - I have
debug_guildsset in the initializer, and I get no complaints about it in the debug output - I have a command defined in a cog
- I've confirmed (via
printin the initializer) that the cog is being loaded - The bot's
on_connectandon_readyare firing
Despite this, my slash command isn't registering. The cog:
class BasicCog(Cog, name="Basic WoD Commands"):
"""The "Basic" cog contains non-help commands usable by anyone without a
character in the bot (though some commands have enhanced functionality if
the user has a character)."""
def __init__(self, bot: BotchBot):
self.bot = bot
print("basic")
@slash_command()
async def ping(self, ctx: discord.ApplicationContext):
"""Responds with pong."""
await ctx.respond("Pong!")
def setup(bot: BotchBot):
bot.add_cog(BasicCog(bot))
slash_command is imported from discord.commands
did you override on_connect
yay
Knew it was something simple, lol
yeah that happens
Can you get the ip of a member. For exemple to make sure to ban that device and he does not make a other account and come back ?
discord does that for you
you cannot access the ip address of a user
but they are ip banned from your server if they get banned
how do i do a drop menu like this
Here's the dropdown example.
ty @shell radish
hey, i just came home and read this. i think you misunderstood. i want a description for the choices, not for the command itself
like this
you can't
then how was that bot able to?
I actually I misunderstood your question
user is an option
not a choice
avatar is the command
discord.Option.description is exactly what you are looking for
That sets this, not what's highlighted in red
no, that is ApplicationCommand.description
the part in red is the option description. if you click on the option that text will appear where the text circled in yellow is.
when no option is selected like in the image above, as said by squid, that is the comand description
Hi,
I have a question, how can I delete an ephemeral response message from an interaction?
await interaction.message.delete() return Unknown Message
.rtfm interaction.delete
@wary wyvern the latter one
there is no interaction.delete
I can only see interaction.delete_original_response which does not work as well
what's the error, if any
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
could you show the related code for this?
@Bot.event
async def on_interaction(interaction: discord.Interaction):
if(interaction.custom_id == 'close_ticket'):
await interaction.response.send_message('Are you sure you wanna close your ticket?', view=buttonYesNoView, ephemeral=True, delete_after=10)
elif(interaction.custom_id == 'no_ticket'):
await interaction.delete_original_response()
Something like this
Yes, the message with buttons
and it's ephemeral
is the message a followup or an original response
When I use interaction.message.content I get the content successfully but interaction.message.delete() fails
original response
What does interaction.data return
{'custom_id': 'no_ticket', 'component_type': 2}
Is there any reason you are specifically using on_interaction instead of the View class?
I think that was the quick solution cuz I wanted to make the button work after the bot is restarted
where do you send the button
buttonYesNoView
what is that referencing?
yButton = discord.ui.Button(label='Yes', style=discord.ButtonStyle.red, custom_id='yes_ticket')
nButton = discord.ui.Button(label='No', style=discord.ButtonStyle.grey, custom_id='no_ticket')
buttonYesNoView = discord.ui.View(yButton, nButton)
when you try to use interaction.message.delete() what is the error message? With traceback, thanks.
Traceback (most recent call last):
File "C:\Users\HamidReza\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "C:\Users\HamidReza\Desktop\Discord\DDPER\Tickets.py", line 79, in on_interaction
await ticket_callback(interaction)
File "C:\Users\HamidReza\Desktop\Discord\DDPER\Tickets.py", line 130, in ticket_callback
await interaction.message.delete()
File "C:\Users\HamidReza\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\message.py", line 1301, in delete
await del_func
File "C:\Users\HamidReza\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\http.py", line 367, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message```
hmm. Does the message have an ID and what is it's author?
and is it possible that the message has already been deleted
no
I even tried removing that delete_after from the send_response method
Doesn't work
Can you delete ephemeral messages now? You couldn't originally
yes
seems like you can only delete a message with the original interaction token
You can even edit them
So, what's the solution now
so if this was sent from another button, that button's interaction would be used to delete the actual message
I don't think that's new though
you would save the Interaction object that sent the ephemeral message somehow and use that saved Interaction object to delete the ephemeral message
and to delete it you would use the interaction.delete_original_response() coro method
Ok, and thanks for helping π
Log
Args are not shown when the user uses the slash command for example /help 1 it only shows /help
@client.event
async def on_application_command_completion(interaction, *args):
logchnl = client.get_channel()
arguments = ' '.join(args)
embed=discord.Embed(title="/{} {}".format(interaction.command, arguments)
embed.set_author(name=interaction.user.name, icon_url=interaction.user.avatar.url)
on_application_command_completiononly takes one argument,context, not multiple.- You can use
ctx.selected_options
thanks for help
@bot.event
async def on_channel_remove(channel):
if antiraid == "Enabled":
if
the part i need help on is the blank if statement, i want it to basically say "if the person who deleted the channel is a bot"
can anyone help
Is it possible to have a button that does not expire ?
Here's the persistent example.
thank you !
For a slash command, if it times out, does any code that would run otherwise not?
That event doesn't exist
And you'd need to get the audit log to get the person that edited the channel
The slash command timing out doesn't make the process of your command stop
alr
Is there anyway to do so within the library or is that something I have to handle on my own?
You need to first defer the interaction before responding
Since your callback takes more than 3 seconds to respond
To defer do await interaction.response.defer()
And place it at the top of your callback
I'm not sure if this would work since you aren't really responding to the interaction after you defer
don't think so interaction.message.edit responds to the interaction
Its not
Instead of interaction.message.edit() use interaction.response.edit_message()
I see
for some reason discord.Bot isnt getting recognized
Are you getting any errors?
And did you uninstall discord.py, and install py-cord?
AttributeError: module 'discord' has no attribute 'Bot'```
I did
only py-cord isnt installed
Can you show me your pip list?
Not if they only want slash commands. discord.Bot is fine
Can you restart your IDE
yea thats what im aiming for
kk
im using a venv if that helps
still didnt work
i tried to reinstall the lib
let me try without a venv
Can you try printing discord.__version__
2.0.0a
So you are installing your packages to a venv but not running your code in it or vise versa.
I installed the package in both my venv and global env
both dont have the discord.Bot() attribute
Your console should look like this is you are in a venv
(venv) PS C:\Users\USER\Desktop\StatWolfBot>
Yes py-cord is us. pycord is some video manipulation library I think.
can you do pip -V
i actually wanted the python version at the end of the output
forgot to mention π
hmm
Can you show the whole line. of output
Python 3.9.13
hmm no issues there ig
pip 23.2.1 from C:\Users\anis\Desktop\Desktop\Project\Environments\BTF-Client\lib\site-packages\pip (python 3.9)
I just upgraded pip
ah
the yellow warning is annoying
I mean iv made multiple bots before on the same machine and python version
first time facing this problem
Check that your interpreter is set to
C:\Users\anis\Desktop\Desktop\Project\Environments\BTF-Client\test\venv\Scripts\python.exe
it is
im really confused rn
should I change smth in my env variables in windows
or is that just for java
Ive never seen anyone need to change env vars.
If you are not far into the project you might want to just copy/paste the code you have and delete the vevn and create a new one.
I am seeing no issues
I tried opening another project
that was just running like last week
it didnt work
im not sure what went wrong
let me just upgrade python
Somewhere you have py-cord 2.0.0a installed and the project is trying to use that for whatever reason
restarted my pc now it works
I love coding
not really working
now its working
weird
anyways really sorry for the waste of time
I should have "turned it off then on"
before asking for help
thanks all
Its fine. vevns like to act weird sometimes
Can a button's label be bold?
test like this?
Yep
doesnt work
? Can it be that my bot needs 1.4GB ram on 4.8k servers? That is already very much
How many intents do you use?
Member
The bot also needs 2h until the on ready triggers.
Only member intents?
Yes
Do you use AutoShareBot?
Yes
Thatβs not many xD
My Internet is sadly sometimes so bad that I cannot really host a bot
It dies at least every day one time
Dashboard
Invite link
Commands
Bot support server
Discord bot list Vote
Patreon link
Carl-Bot does what the most popular bots do but does it better, faster, and without the meme commands that spam and annoy you. Carlbot has been used to reduce the number of bots needed in a server from 3 to 4 or more⦠to just 1.
950,106,295 total
188,959,305 unique
272,998,048 total
219,596,299 text
53,401,749 voice
3209.22 MiB
8.30% CPU
8393168
4096 shards
0 messages (-0.0/s)
11h 41m 49s
@little cobalt the bot is on 8 Million servers und need 3 Gb ram
How is that possible
Buy a Hoster
Server
thats probably per cluster or even per shard
How can i record audio in voice channel
Here's the audio recording example.
@glossy latch ^
Thxxx
Can some1 help me? My bot on 4.8k servers needs 1.4GB of ram. Is this normal or is pycord not so optimized?
how do i access a cog's function from inside another cog?
I'd say that it is pretty normal
?tag xy
An XY problem is when you're trying to ask about your attempted solution, rather than your actual problem.
You are trying to solve problem X, using solution Y. Instead of asking for help with X, you ask about Y. This only results in frustration as whoever is trying to help you needs to ask several questions before even beginning to help you with your actual issue, wasting both their own, and your time. Always include as much information as you can about your problem, including attempted solutions. If there are solutions you've ruled out, include them along with an explanation as to why you've ruled them out.
[learning from the image] am i able to just use self.bot.get_cog("whatever the cog's name is") in a cog?
but why
i thought it might be useful for calling functions across scripts instead of redefining them
is there a better way of doing this?
yes, create a seperate file that you can call from your cogs
that aside, how would i go about doing this?
if it is possible
Bro carl bot needs 3 gb howw?
yes
as Lala said, that's probably per cluster:
I mean carl also uses pycord so
Oh
So, I'm trying to run this
from .mixins import Hashable
But I do know that I need the .mixins package form somewhere but idk what pip command I should run in my terminal, sorry if this doesn't make sense I'm very new to this
And how is that related to pycord?
I saw this in a pycord documentation webpage
where?
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - Pycord-Development/pycord
What
what
.guide
see that if you are just starting out
Alright, I will
this is the libary source code, not the docs
the docs are at https://docs.pycord.dev
Pycord is a modern, easy to use, feature-rich, and async ready API wrapper for Discord. Features: Modern Pythonic API using async/ await syntax, Sane rate limit handling that prevents 429s, Command...
www.docs π
how do i disable a select menu after clicking on it
There is a example for it
woudn't work
sry
wrong link
Learn all about implementing Select Menus or Dropdowns in your Discord Bot with Pycord.
Wouldn't work either
why not lol
And what is the error?
Is there a method somewhere that will cause all registered commands to be re-evaluated?
Context: for commands defined in a cog that use Options in the command function definition, I would like the available options to be loaded on the cog's initialization rather than when the cog's .py file is loaded.
I don't think so. You can try using autocomplete tho
since that allows for things to be dynamic
Darn. Right now I am working around this by setting up option choices before the cog is loaded but that seems really rancid
No error lol
What's wrong with the example? It just does not disable the select?
Is there a way to safely close the bot (I see the close() method, but it only say it close the connection with discord) ? I just normally kill the process on linux
Sorry for any trouble, but I am new to pycord and am running into an issue. I cant seem to get aplication commands to work, and even when I use the example documentation for slash commands, I get an error: Invalid Form Body
In name: Username cannot contain "discord"
My bot does not contain discord in the username, which was my first thought, and I have a feeling I am doing something wrong. Anyu help possible is appreciated, thanks!
does the any field (e.g. name, description, option) of the slash command contain "discord"?
Oops, sorry -
It turns out my application has discord in the name, and I was thinking of the bot only. My appoligies, thanks for the help though!
yay
iirc, if you used bot.run(), then the close() method will also close the event loop, and then the procress itself shutsdown gracefully
ctrl + c does that too
if you are using some tools to deploy, send a SIGINT to the process
that gracefully closes the bot
Thank you βΊοΈ
How would i go about checking if the current chennel is NSFW?
.rtfm channel.is_nsfw
alr
another question: how would i get the current channels id?
The docs answer these questions
my potato brain cant find the correct section of the docs to look at most of the time so
alr
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 ...
k
Ok so yesterday I asked for help about the documentation but I ended up sending this github source code that I was trying to guide myself trough, I did know that I had seen this in a documentation somewhere and I found it https://docs.pycord.dev/en/stable/_modules/discord/channel.html
So, the only things that is getting me confused is that I have no idea about what package to install to be able to run "from .mixins import Hashable" Im really sorry if this is simple and if I'm wasting anyone's time with this
why are you trying to use hashable
To be able to run this line, which I think is the only way to make a text channel?
class _TextChannel(discord.abc.GuildChannel, Hashable):
I will try again I guess, thank you for replying to me
no but genuinely
I wish I was joking
that is the worst thing I've seen in this channel
Well, I am desesperate, I spent a few hours trying to understand these things already but I guess I will have to search even further
if you think you already know enough python, I would start off at the examples in the GitHub repository and the 'getting started' page in the docs
but I heavily encourage you to learn some more 'vanilla' python
specifically OOP
we have a tag for some resources somewhere
?tag lp
Official Beginner's Guide: https://wiki.python.org/moin/BeginnersGuide
Official Tutorial: https://docs.python.org/3/tutorial/
Shortcuts:
https://wiki.python.org/moin/BeginnersGuide/NonProgrammers
https://wiki.python.org/moin/BeginnersGuide/Programmers
Learn Python:
https://automatetheboringstuff.com/ (for complete beginners to programming)
https://learnxinyminutes.com/docs/python3/ (for people who know programming already)
https://docs.python.org/3/tutorial/ (official tutorial)
http://python.swaroopch.com/ (useful book)
http://www.codeabbey.com/ (exercises for beginners)
thanks
I really don't want to be mean or discourage you and I'm sorry if I did
But you really should start a bit smaller and get more of the basics down before diving into something like a discord bot
Heeeey, i have question about slash commands.
more specifically about the specifics of the register of numbers
@bot.slash_command(name='alpha', description="create code")
@commands.has_any_role("Admins", "Global Moderators", "Regional Moderators",
"Events MC")
async def add(ctx, addcode: Option(int, description="write code")):
data = (addcode)
with open('ba.json', 'w') as file:
json.dump(data, file)
await ctx.respond(f'You create code {addcode}', ephemeral=True)

@deft kestrel Display a list of roles
Does anyone know how to get the Guild from the Id (int) ?
https://docs.pycord.dev/en/stable/api/clients.html#discord.Bot.get_guild
Don't forget you might need to fetch too.
Bots: Attributes activity, allowed_mentions, application_flags, application_id, auto_sync_commands, cached_messages, cogs, debug_guilds, description, emojis, extensions, get_command, guilds, intent...
I'm not exactly sure how discord handles it however I am sure that python gets rid of leading zeros. That is just how integers work.
You would have to take a string and check if the string was only numbers yourself if you want to include leading zeros.
https://www.w3schools.com/python/ref_string_isnumeric.asp you can look at this to
TY, i try it, just never had this problem before.
If you think about how ints are stored in binary.
5 -> 101
You cant add leading zeros.
1010 = 10 not 05
yes it woudn't disable and no errors
someone told me u can make slash commands
visible to certain roles
anyone knoww how that works or can give me a link to it in the docs
thanks
dont think you can make it visible to only certain roles but you can use the has_role decorator to check if the person using the command has the role required
https://docs.pycord.dev/en/stable/ext/commands/api.html#discord.ext.commands.has_role
How can I have multiple options per command. This code returns an error:
@bot.slash_command(
name = "parameter",
options = [
discord.Option(
name="string select",
description = "select a string",
choices = [discord.OptionChoice("One", "one"), discord.OptionChoice("Two", "two")],
required = True,
),
discord.Option(
name="float select",
input_type=float,
description = "Type a float value",
required = True,
),
]
)```
Error: `discord.errors.ClientException: Too many arguments passed to the options kwarg.`
I'm trying to make a command which changes parameters internally, each parameter will have its own option instead of having all different commands
.rtfm slash_options
Target not found, try again and make sure to check your spelling.
Here's the slash options example.
is it possible to mention someone in the footer of an embed?
Is it a good idea to translate errors for users? Also, is it a good idea to translate pydantic (validation) errors?
If you're using localization already why not translate the error too
Fair, but I'll also have to translate all pydantic errors too π
Bot randomly crashed after ~2 weeks of non-stop working
Is it my fault, or just Heisenbugs?
you should add a check for something like this
Idk when and why this was triggered
This is inside pycord π
I have it for anything
This is inside pycord
I don't even know why it crashed the bot, because when you get error in your functions, you just get traceback, but bot keeps working
oh
Your bot doesn't even crash by your mistakes, bot can crash only if something was triggered not by (outside of) pycord (like syntax error not in the function)
So yeah, really odd
how do i fix π
#how-to-get-help And you most likely used wrong bot (iirc bot.slash_command is for prefixed bot (ext.commands), but you probably have normal bot)
completely unrelated but-
show some code
i figured out the error
?
how come if i try to run it in vsc, itll show errors but if i run it in terminal like py main.py itll work with no errors?
bot.slash_command is on discord.Bot and commands.Bot but not discord.Client
Really odd tbh
Maybe your hinter is old or broken
I have a werid situation with my /register command that writes user data to a json file. Specifically, I have a mobile user that whenever they register, the space in their display name gets removed entirely. When I (from desktop) use the same name with an extra space and the exact same register command, the entry contains the space. Is this some weird idiosyncracy of mobile/desktop versions? The circled user's display name is "Don Kush"
I'm very new to python in general, what do you mean? ditch json?
you shouldnt use json as a database
Yeah I was reading a little on the quickstart guide about the different DBs earlier today. Do you have a suggestion on which to use for a complete novice?
Awesome, thanks friend
glad someone got me on the right track before I got too in the weeds
I'm looking to have a function, exit(), ran after my code is stopped, kinda like how signal() works in C. Does anyone know of a library I can use to do that?
I tried using atexit but it doesn't seem to work
Why do you need that?
If you want to use functions before bot is stopped, you can subclass bot class and add your code to func close
I have a list object that i need to serialize into a .json file after my bot has been stopped
thanks! I'll do that
are you using json as a database
or as a form of persistent storage
no just need it to hold a list of like max 10 ints
should i use mysql for this or is that overkill?
I really like to use MongoDB
nah, it's not overkill
You can still use pickledb or Aiosqlite
They are file-based databases, so you can easily use them in your bot
pickeldb - nosql key-value database (basically a dict)
Aiosqlite- sql file database
Aiosqlite*
yeah
wait but doesn't pickledb be potentially unsafe if you're not in full control of the data being stored
what if I just want to serialize and deserialize a single list object
pickledb
but it can execute arbitrary code when loading pickled data, no?
iirc pickledb doesn't allow you to serialize python functions and stuff like that
It has a lot of limits and uses pickle just to serialize json like objects into a file
It's just json into file, but with better handling
hmm
pickleDB is lightweight, fast, and simple database based on Pythonβs own json module. And itβs BSD licensed!
From pickledb pypi
pickleDB got its name from Python's "pickle" module, which it used to use. However, now pickleDB uses the "simplejson" module. It is faster and cleaner. But the name stuck!
eh if you're doing this on bot close, async shouldn't matter
pickleDB got its name from Python's "pickle" module, which it previously used. However, now pickleDB uses the "json" module. It is faster and cleaner. But the name stuck!
From website (they probably changed that)
So yeah
I don't think it's even possible to save python functions and non-basic objects into a file
Doesnβt sound like it, no
tbh just use what you're comfortable with, just not json
what this last line means? π
if I use on_command_error listener somewhere in code, and ask it to send to a specific channel... it will work na?
you can create command-specific error handlers with
@<command_name>.error
if that is present, then on_command_error will not fire for that command
if I want to create a single listener for all commands, like it gets triggered for any command error than happens?
yes
and then make it do something specific
then I have to use
@bot.event
async def on_command_error(ctx: bridge.BridgeContext, exception):
"""
here goes whatever I want to do
"""
await bot.get_channel(12345678901234).send(exception + f"\n was raised during handling a command")
right?
this is my basic idea, pls guide if I am wrong
I'd recommend you to save data using the user id as the key instead of the username though
Yeah, I was coming to this realization too, i was running into walls creating a gift command that users could refer to other users by nickname to transfer currency, i think i need to plan things out a touch more too
What's the point of passing description to the command group if you can't see it anyways?
math = bot.create_group("math", "math commands")
@math.command()
async def add(ctx: discord.ApplicationContext, a: int, b: int):
await ctx.respond(f"This is equal to: **{a + b}**")
@math.command()
async def subtract(ctx: discord.ApplicationContext, a: int, b: int):
await ctx.respond(f"This is equal to: **{a - b}**")
@math.command()
async def add(ctx: discord.ApplicationContext, a: int, b: int):
"""This is the command description for add command"""
await ctx.respond(f"This is equal to: **{a + b}**")
for subtract too in similar way
Yes, it will indeed set the description for the subcommands. But what is the purpose of setting the description for the group if it is not shown anywhere. Sorry, didn't put the question right.
There is no purpose iirc
Slash groups are just slash commands
That's why you can set the description
But the client won't show it anywhere
Or wait
Check the command perms settings in guild settings
Oh! Haha, I see it now
Thanks. Now I know 
I have defined this in my main.py file:
import configparser
scores = configparser.ConfigParser()
scores.read("scores.ini")
@Bot.event
async def on_interaction(interaction):
global scores
if interaction.custom_id == "clicked":
await interaction.response.defer()
user_id = str(interaction.user.id)
server_id = str(interaction.guild_id)
if server_id not in scores.sections():
scores.add_section(server_id)
user_scores = scores[server_id]
clicks = int(user_scores.get(user_id, 0)) + 1
user_scores[user_id] = str(clicks)
if clicks == 1 and interaction.user.id != Bot.user.id:
await interaction.followup.send(
"π WOHOO! You clicked the button once. π I'll let you know how you're doing every π clicks",
ephemeral=True,
)
if clicks % 10 == 0 and interaction.user.id != Bot.user.id:
await interaction.followup.send(
f"You have clicked the button {clicks} times!", ephemeral=True
)
with open("scores.ini", "w") as file:
scores.write(file)
else:
pass
How can i make any other interactions just run the code in their cog.
Why are you using that event?
You should use callbacks for buttons
.guide
Here's the counter example.
Smth like that
i need it to work even after the bot restarts
You can still do that with callbacks
how?
Here's the persistent example.
Set custom id in the button decorator and set timeout to None in the view
I mean that's pretty simple
one sec
Can you show the view class if you have made any
how to set view timeout to none
button = discord.ui.Button(label="Click ME!", emoji=":sos:", custom_id="clicked")
view = discord.ui.View()
view.add_item(button)
message = await ctx.send(embed=embed, view=view)```
It is a parameter in the View init
timeout=None
so what would i change?
view = discord.ui.View:Timeout=None()?
idk lol
Ah. If possible, make a View subclass. That makes persistent views much easier
wdym by that. I dont really use views that often
It's just the same way you pass intents or command prefix to Bot
I'll let you figure it on your own
view = discord.ui.View(Timeout=None)??
Yes
ty so much!
Just timeout T lowercase
ok
so when my bot restarts, the button will still work?
the interaction is still failing
So you can create a view subclass like so
class MyView(discord.ui.View)
@discord.ui.button(label="smth", ...)
async def my_button(self, button, interaction):
# your code goes here
# the logic and responses etc
# the button parameter will let you modify stuff like label etc
# the interaction parameter will allow you to respond n stuff
You can then send your view like this
view = MyView(timeout=None)
await ctx.send(view=view)
And to make this persistent
so do i do view=MyView
You need to setup an on_ready listener and do
view = MyView(timeout=None)
bot.add_view(view)
In the ctx.send?
Yes you can. Make sure to pass an object of the class and not the class itself
- await ctx.send(view=MyView)
+ await ctx.send(view=MyView())
yep! thanks so much
Np!!
would i define MyView inside my cog?
class ClickButton(commands.Cog):
def __init__(self, bot):
self.bot = bot
class MyView(discord.ui.View):```
is it possible to find who pinned the message returned by discord.on_message_edit(before, after)? (https://docs.pycord.dev/en/stable/api/events.html#discord.on_message_edit)
(assuming the edit event was a message pin)
if i wanted to find who pinned what, should i use .on_message_edit?
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...
nope. preferably outside the cog
ok
from what i remember, pinning a message sends another message stating "xyz pinned a message" or something
you can check that message
message.type for it would be https://docs.pycord.dev/en/stable/api/enums.html#discord.MessageType.pins_add
The API provides some enumerations for certain types of strings to avoid the API from being stringly typed in case the strings change in the future. All enumerations are subclasses of an internal c...
you might find the user in message.mentions
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 ORZ
Orz?
π
is there a way to make on_message event handler in a cog only run when a message is sent in certain channels? currently i just return if it was sent in some other channel
return if wrong channel is the only way
negligible. even if it there was some "built-in" way to filter out the channels, it would have been the same working
so dont worry about the thing
what is this? I'm trying to change a role icon using a link of the image, or i can't?
if data.startswith(b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a"):
TypeError: startswith first arg must be str or a tuple of str, not bytes```
```py
@commands.command(hidden=True)
async def roleicon(self, ctx, role: discord.Role, source):
if "https://" in source:
await role.edit(icon=source)
else:
await ctx.send("Send valid image link!")
full error?
Traceback (most recent call last):
File "/home/horizone/.local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 178, in wrapped
ret = await coro(*args, **kwargs)
File "/home/horizone/cogs/testing.py", line 103, in roleicon await role.edit(icon=source)
File "/home/horizone/.local/lib/python3.10/site-packages/discord/role.py", line 473, in edit
payload["icon"] = _bytes_to_base64_data(icon)
File "/home/horizone/.local/lib/python3.10/site-packages/discord/utils.py", line 658, in _bytes_to_base64_data
mime = _get_mime_type_for_image(data)
File "/home/horizone/.local/lib/python3.10/site-packages/discord/utils.py", line 644, in _get_mime_type_for_image
if data.startswith(b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a"):
TypeError: startswith first arg must be str or a tuple of str, not bytes```
are you sure the error is from
if "https://" in source:
await role.edit(icon=source)
?
π
@commands.Cog.listener() async def on_command_error(self, ctx, error): if isinstance(error, commands.BadArgument): #code
as i know
or commands.errors.BadArgument
howw do i get mentions working in an embed
What do you mean with getting it working?
like its displayed as @boreal rain
instead of @halcyon vault
the raww numbers
you cant. discord client renders it. it needs to be cached in the user's client
hmm alright thanks
how do you make it such that a bot response is only shown to the user? is there an annotation somewhere
?tag ephemeral
An 'ephemeral' message is one that's only visible to the person who invoked a command. If you ever got a command error with a blue background, this is an example of one.
To do this, set ephemeral=True when you first use an ApplicationContext. (This includes .defer()ing it; the choice of whether a message is ephemeral or not must be made up front. If you .respond() to a deferred message, setting the ephemeral flag at that time will have no effect.)
This is the equivalent of hidden=True if you're coming from interactions.py
e.g.
await ctx.respond("Imagine a message!", ephemeral = True)
await interaction.response.send_message("Imagine a message!", ephemeral = True)
ooh i see thank you
is there a built-in way to edit and not overwrite permissions ?
e.g. channel.set_permissions(m, connect=False) will reset any other permissions that m already had
how would i make a slash AND normal command? as rn i use bot.slash_command, but i would like those commands to also be able to be used with a prefix.
any way to do so?
.rtfm bridge
discord.ext.bridge.Bot
discord.ext.bridge.Bot.activity
discord.ext.bridge.Bot.add_application_command
discord.ext.bridge.Bot.add_bridge_command
discord.ext.bridge.Bot.add_check
discord.ext.bridge.Bot.add_cog
discord.ext.bridge.Bot.add_command
discord.ext.bridge.Bot.add_listener
discord.ext.bridge.Bot.add_view
discord.ext.bridge.Bot.after_invoke
discord.ext.bridge.Bot.all_commands
discord.ext.bridge.Bot.allowed_mentions
discord.ext.bridge.Bot.application_command
discord.ext.bridge.Bot.application_commands
discord.ext.bridge.Bot.application_flags
discord.ext.bridge.Bot.application_id
discord.ext.bridge.Bot.application_info
discord.ext.bridge.Bot.before_identify_hook
discord.ext.bridge.Bot.before_invoke
discord.ext.bridge.Bot.bridge_command
^ first one
thank u π
are there perhaps any examples of this being used somewhere?
Here's the bridge commands example.
@fringe drum can i still use bot.slash_command if i transform my bot to bot = bridge.bot?
like does it change anything other then allowing bridge commands to be used?
if you want both prefix and slash commands you will need to change to @bot.bridge_command()
no, it doesn't
ye but i dont want to use that everywhere. just on some places. do i need to change my bot = commands.bot to bridge.bot? or can i keep it commands.bot + if i do switch would that change anything on my current bot.slash_command setup?
You can still keep your current setup
ah okay thank u
@bot.bridge_command()
^^^^^^^^^^^^^^^^^^
AttributeError: 'Bot' object has no attribute 'bridge_command'. Did you mean: 'message_command'?
@shell radish
so guess change to bridge.bot?
yeah, changing to bridge.Bot is the only change you would need to make
β€οΈ
is there a method for messages that converts them into strings? py str(message) doesnt work
message.content
And don't need to convert it to string again
You need message content intent
?
?tag intents
https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents
import discord
from discord.ext import commands
# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content
intents = discord.Intents.default()
# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True # Required for prefix commands >= 2.0.0b5
# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()
# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
In version 1.5 comes the introduction of Intents. This is a radical change in how bots are written. An intent basically allows a bot to subscribe to specific buckets of events. The events that corr...
still returns nothing
How do you define the bot?
intents = discord.Intents
intents.all()
bot = discord.Bot()```
where are the intents....
take a look again at this
ohhh thank you all so much sorry for being an idiot 
async def transfer(ctx, player: str, price: int):
this line is causing this error:
File "C:\PYTHON310\lib\site-packages\discord\client.py", line 352, in _run_event
await coro(*args, **kwargs)
File "C:\PYTHON310\lib\site-packages\discord\bot.py", line 793, in on_connect
await self.register_commands()
File "C:\PYTHON310\lib\site-packages\discord\bot.py", line 286, in register_commands
if key2 in match[key][i].keys():
IndexError: list index out of range
with only 'player' it works fine but with player and price it doesnt seem to work
heres the whole command:
@bot.slash_command(name="transfer", description="Allows for the transfer of a player.")
async def transfer(ctx, player: str, price: int):
await ctx.respond(player + price)
that is basic python
str + int
i replaced it with ctx.respond("hello") but still the same error
Full traceback, thanks
Ideally id want to to be /transfer player[] price[]
Im not sure if theres a better way to do this
.
Ignoring exception in on_connect
Traceback (most recent call last):
File "C:\PYTHON310\lib\site-packages\discord\client.py", line 352, in _run_event
await coro(*args, **kwargs)
File "C:\PYTHON310\lib\site-packages\discord\bot.py", line 793, in on_connect
await self.register_commands()
File "C:\PYTHON310\lib\site-packages\discord\bot.py", line 286, in register_commands
if key2 in match[key][i].keys():
IndexError: list index out of range
Logged into discord api as: BudgetBot#6896
can you show your pip list pls?
all of it?
yeah
pip freeze > pip.txt @daring grove
discord, discord
and why py-cord 2.0.0b1
thats as old as my grandma
my grandma is pretty young
whats the newest vers of pycord?
2.4.1
2.4.1
deary me okay
?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
Hey does anyone know how to fix the constant "Invalid interaction application command" error I keep getting? I do a slash command on my bot and it always responds with that text.
restart your app
How so? just restart the python script?
no your actual discord app
thank you so much dude i was having so much trouble with this
yw
Someone helped me yesterday. I tried to make a persistant view. Its not working, heres my code:
import discord
from discord.ext import commands
class PersistentView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(
label="Green",
style=discord.ButtonStyle.green,
custom_id="persistent_view:green",
)
async def green(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message("This is green.", ephemeral=True)
class Test(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.slash_command()
async def test(self, ctx):
await ctx.respond("test", view=PersistentView())
def setup(bot):
bot.add_cog(Test(bot))
i want it to continue to work after the bot restarts however it says this interaction failed
You didnβt add the view to the bot object
So what would i do instead?
to make the button work even after the bot restarts
π
Learn all about implementing buttons in your Discord Bot using Pycord.
your a hero. I have had this issue for the past 2 days. if anyone needs a cog slash command version, here it is:
import discord
from discord.ext import commands
class MyView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None) # timeout of the view must be set to None
@discord.ui.button(label="A button", custom_id="button-1", style=discord.ButtonStyle.primary, emoji="π") # the button has a custom_id set
async def button_callback(self, button, interaction):
await interaction.response.send_message("Button was pressed", ephemeral=True)
class Test(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self, ):
self.bot.add_view(MyView()) # Registers a View for persistent listening
@commands.slash_command()
async def button(self, ctx):
await ctx.send(f"Press the button! View persistence status: {MyView.is_persistent(MyView())}", view=MyView())
def setup(bot):
bot.add_cog(Test(bot))
I have looked at the example in the documentation but I get the warning in the .predicate
Is it possible to do in pycord that if I use Option: discord.TextChannel that only certain selected channels that I want to be displayed? And not all channels that exist
yes
Learn how you can implement Modals in your Discord Bot with Pycord!
how?
make a list of all channels and then exclude what you want.
I don't know what you want to do in general either
bro
there's no tiemout ni there
why else would i come here
yeah suer
that's possible
make a list
Slash
theres a thing for rthat
search the docs
its like u can only choose an option
from a certain list of things
and it shows that list while choosing the option
ah lemme see
in Option() itself
thers this parameter called autocomplete
so it'll be like
Option(autocomplete=channels)
async def channels(self, ctx: discord.AutocompleteContext):
return [LIST OF CHANNELS]
# some command
...
async def foo(self, ctx, a:Option(autocomplete=channels)```
@cyan violet
Thx
np
How would I check if the author has a certain role and based on that allow usage of a command?
.rtfm Guild.get_role
.rtfm Member.roles
Is there an estimated release date for 2.5 at this point, or a list of breaking changes in master that would need to get accounted for? (If I don't have any pre-existing code, can I just pull master and start working with it?)
I've tried to flip through the FAQs and search through here, and the most recent update I can see about it is someone asking about a month ago and being answered "soon / when it's ready" - which is completely fine, I just couldn't find anywhere that had some kind of update on that.
Im not really sure if there will be any breaking changes at 2.5
discord.Activity
discord.Activity.application_id
discord.Activity.assets
discord.Activity.buttons
discord.Activity.created_at
discord.Activity.details
discord.Activity.emoji
discord.Activity.end
discord.Activity.flags
discord.Activity.large_image_text
discord.Activity.large_image_url
discord.Activity.name
discord.Activity.party
discord.Activity.session_id
discord.Activity.small_image_text
discord.Activity.small_image_url
discord.Activity.start
discord.Activity.state
discord.Activity.sync_id
discord.Activity.timestamps
To get discord.User autocomplete in slash commands, does it need additional perms?
I am using
discord.Option(name="assignee", required=False, type=discord.Member)
``` But it's not actually doing anything
what?
What's not clear? I have a slash command that I want to use user-based autocomplete, which I am pretty sure is a thing.
Not sure I understand where you're going with this.
You can have an Option of discord.Role and it will autocomplete Roles. There is one for Users and/or Members. I just want that.
Use discord.Member because it got way more informations
Is there a way to access a user's selected option (select menus) from an interaction?
As you can see, I'm already using discord.Member
It needs to be an Option though beacuse it's not a required field.
you added required=False right?
Not to be rude, but did you not see the code I posted? It literally says required=False in it π
yea, so it would be already optional
or do you want to have role and member in one?
Okay, the point is that the users are not being autocompleted. Hence my question of whether there are other permissions that need enabling. I added User Intents, but that didn't seem to fix it
what type of interaction?
that is weird
with member intents it should work
select menu
you don't even need members intents for it to work
Views I have are accessing self.values for that.
Hm. Any other thoughts as to what the issue could be? It's just acting like a text field
You need intents for it
no you don't
I tested it and I cannot get all the users
I see only 2 users and there are way more at the server
Doesn't it only get users that are in the current channel?
I have 10 users at the channel and can only see 2
or discord is just glitching again?
try commenting out the command, running the bot, uncommenting out the command, and running the bot
maybe the command is de-synced from discord
I remember the time where it took 1h for a global slash command x3
Yeah that was going to be my next try; adding debug guilds
not really any point since global application commands register instantly
I also dont use debug guilds anymore
seems like interaction.data.values contains what I want but I don't know how to access the option's string
which option string? From slash commands, or?
What does your select menu callback look like?
I want to access it through on_interaction because the callback doesnt work after restart
Sadly not. I commented it out, confirmed it was gone, then re-implemented and it's still not showing correctly.
@subcommand.command(name="list", description="...")
async def task_list(
ctx: discord.ApplicationContext,
search: discord.Option(name="search", description="", required=False, type=str),
assignee: discord.Option(name="assignee", description="User to view", required=False, type=discord.Member)
):
Here's the persistent example.
how can I add aliases to a bridge command?
@wary wyvern for views to work after restart
aliases=["text"]
like the user can do any of these:
@sweet gale play
@sweet gale p
!play
!p
/play
I think it's input_type, not type
yeah https://docs.pycord.dev/en/stable/api/application_commands.html#discord.Option.input_type
will it work for bridge commands?
oh thanks
and does slash command support aliases or smthing?
no
only prefix commands support aliases
yea, that's why I wondered. bridge commands will support aliases?
But it should work at bride commands
oh, where exactly I have to add this then?
bridge commands support aliases to the extent that text-based commands support aliases
ohkk, Thanks for all the info :)
@bot.command(..., aliases = ["foo"])
bridge is cut off here because I thought that was obvious
and cogs equivalent
also I wondered if I could ask my wavelink related doubts here coz the official server mods' most of the time say that "we don't support py-cord, so can't help"
π
depends on the type of problem
Oh I see it's the first positional argument.
And also, it needs to be discord.User. I couldn't get it to work with discord.Member. Thanks for the sanity check!
(Related but unrelated, I hope they allow autocomplete filters on User selection someday)
Actually, sorry. One more weird issue - if I submit the command with a target user, something breaks in the core
Traceback (most recent call last):
File ".../discord/commands/core.py", line 124, in wrapped
ret = await coro(arg)
^^^^^^^^^^^^^^^
File ".../discord/commands/core.py", line 894, in _invoke
arg = ctx.guild._get_and_update_member(_data, int(arg), cache_flag)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute '_get_and_update_member'
I've never seen this before. Don't get why it would be a NoneType.
hmm
does it always break
In this app, yes.
(My main app has a couple of autocompletes and has never seen this issue)
Just as a spitball, I'm going to try member intent. I know it's not supposed to care, but it is one difference between the two bots. (Edit: No change, of course)
Strange. ctx.guild is indeed None after being invoked.
The Context knows everything else - author, channel (as a PartialMessagable), channel_id
And knows the selection. It's not having trouble resolving it. It's literally just the fact that it somehow doesn't know where it is π
It knows the guild_id (ctx.guild_id), but ctx.guild is None and ctx.bot.guilds is empty. tf
So I guess the new question is: What situation causes a bot to not know what guild(s) it's even in?
does on_message_edit only listen to messages created after the bot became ready?
.rtfm on_message_edit
um, can someone tell me how to use before_loop and after_loop, I have trouble using it, my tasks has count=2 but neither function are called
do I call it task.before_loop(before_function) or something else?
if i were to use sqlite as my db approximately when should i switch to something like postgres? how much data would be too much?
Target not found, try again and make sure to check your spelling.
.rtfm user.avatar.url
Target not found, try again and make sure to check your spelling.
let me get you a code snippet i have
avatar.url not avatar_url
Target not found, try again and make sure to check your spelling.
Target not found, try again and make sure to check your spelling.
#app-commands
it's an attribute of an attribute
You're right octopus
how would i display a decline trade button on this embed too?
views can have multiple buttons
how would i do that here?
depends on the code for AcceptTrade
you're supposed to combine them into a single view object/class
almost, they shouldn't both be called button_callback
personally, I would use accept_callback and decline_callback
but they can be basically anything
no, that's exactly why only the decline button shows
hm?
if both are called button_callback then the second button overrides the value of button_callback
yeah so only the decline button shows
you said "maybe," I'm asserting that is exactly why
how might i find who clicks the button?
how can I format it as png
like if someone has a certain role they can press it
interaction.user
thanks
v2.0 introduced new Discord features and deprecated some old ones. Part of the redesign involves making application commands and components. These changes include a new Bot class, ui.View, and a ne...
oh never seen this before
Restarting the question about this. It seems like a Pycord assumptions bug, but I also don't know if it is valid that Discord itself doesn't know what Guild a responding bot is part of.
whats the best way to take in a list of mentionables of variable length in a slash_command Option()
two ways, multiple options or a really long string and convert it yourself
long string it is then
alr
async def get_mentions(content):
mentions = []
for x in content.split(" "):
if x.startswith("<@") and x.endswith(">"):
mentions.append(x[2:-1])
return mentions
``` copilot just cooked this up without me even saying what i wanted lmaooo
dont think it works tho lol
how would i get a list of the roles of this person?
ive tried interaction.user.roles but it doesnt seem to work
that should work
Do you have intents?
yeah
which one?
im trying to do this
is there anything wrong with this?
rolewantmanager = "Man City"
do you even get a list at interaction.user.roles?
I do
It was originally ['Man City']
actually hold on
This is what I get
hm
trying to take in a string from a slash_command Option parameter, but as soon as i have a @mention in that string its somehow = "" and hence prints nothing
@bot.slash_command(guild_only=True,description="Host a giveaway!")
async def giveaway(
ctx: discord.ApplicationContext,
....
required_roles: Option(str, "Roles required to enter the giveaway", default='default'),
winners: Option(int, "The number of winners to pick", min_value=1, default=1)
):
print(str(required_roles))
try
if rolewantmanager in [role.name for role in interaction.user.roles]:
Yo
quick question
eh
How do i install pycord
for arch
with pacman package manager
you cannot install it with the pacman manager
that is not for python librarys
Oh really?
[root@archi system]# python -m pip install py-cord
error: externally-managed-environment
Γ This environment is externally managed
β°β> To install Python packages system-wide, try 'pacman -S
python-xyz', where xyz is the package you are trying to
install.
If you wish to install a non-Arch-packaged Python package,
create a virtual environment using 'python -m venv path/to/venv'.
Then use path/to/venv/bin/python and path/to/venv/bin/pip.
If you wish to install a non-Arch packaged Python application,
it may be easiest to use 'pipx install xyz', which will manage a
virtual environment for you. Make sure you have python-pipx
installed via pacman.
[root@archi system]# pip install py-cord
error: externally-managed-environment
Γ This environment is externally managed
β°β> To install Python packages system-wide, try 'pacman -S
python-xyz', where xyz is the package you are trying to
install.
If you wish to install a non-Arch-packaged Python package,
create a virtual environment using 'python -m venv path/to/venv'.
Then use path/to/venv/bin/python and path/to/venv/bin/pip.
If you wish to install a non-Arch packaged Python application,
it may be easiest to use 'pipx install xyz', which will manage a
virtual environment for you. Make sure you have python-pipx
installed via pacman.
py?
that is weird
is python-pip installed?
?
Yes.
PIP is a large suite of tools that are used to automate the installation and management of python packages and modules. It is essentially a package manager for non-standard python packages, those not included in the standard python library. In this article, setting up PIP on ArchLinux is explained.
fixed
Solution was
hold on
mkdir {f} (F being the name you want for your folder, put it in your projects directory)
python -m venv full/path/to/{f}
{f}/bin/pip install py-cord
oh yeah
dont forgor to use this
{f}/bin/python path/to/youwanttoexecute
how would i add a role after a button press to someone from a different command?
i want to use this 'offer' elsewhere essentially
store the user id and create a member object at the button and give the user the role
why is this not timing out after 10 seconds?
you also have to edit it
ah okay thanks
yep i already got it
when you use @commands.guild_only() the slash command is still able to be used in dms (it just shows that the bot did not respond and throws an error about how it's not allowed to be used in dms); is there a way to not have it show as a command in dms, or at least make it unselectable, or show a more descriptive error message?
only if you would add the guild ids
is the bot for a privat server or a public bot?
public
that's because it should be @discord.guild_only()
oh, even in cogs?
yes
okay tq!
Does anyone know what i'm doing wrong? i just copied some random slash command and the response will send but not the actual interaction
ctx.respond and not ctx.send
oh my god im so dumb thats embarassing
thank u stranger <3
another (probably) dumb question but i made this payment method-ish command to help me receive payments but when i press anything other than the x, it fails. but when i press the x it works perfectly fine
Your other buttons don't have a callback?...
yep just realized
sorry about that
π
sorry for the late reply- thank you
i didn't read the cache part before i asked