#Basic Pycord Help (Quick Questions Only)
1 messages · Page 58 of 1
I think you can pass an alias kwarg that will the picked up by the prefix version
?
.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.
If you're going to ask a question in this channel, at the very least ask a question. Just posting random JSON data is absolutely useless.
Thank you for the feedback, so quickly.
So if I have an issue with it, then I have to create a new post ..? 👼
If you want
If you think the issue needs an extensive conversation. If it's just a quick question, making a post isn't necessary.
hello, how could i do that ?
@option(
name="minimum"
name_localizations={"fr":"minimum"},
description="The minimum number",
description_localizations={"fr": "Le nombre minimal"},
min_value=0
)
@option(
name="maximum"
name_localizations={"fr":"maximum"},
description="The maximum number",
description_localizations={"fr": "Le nombre maximal"},
min_value=#value of minimum + 1
)```
with a slash command?
yup
discord.option or what do you mean?
add min and max_value to one
yes but i want minimum var to be anything 0 but even 1000
to make bingo between 0 and like 500 or 400 and 600 or anything
Attribute error: FFmpegPCMAudio object has no attribute '_process'
No idea ☠️
@bot.slash_command()
async def play(ctx, url: str):
if ctx.author.voice is None:
await ctx.respond("You're not in a voice channel!")
return
channel = ctx.author.voice.channel
voice_client = get(bot.voice_clients, guild=ctx.guild)
if voice_client is None:
await channel.connect()
voice_client = get(bot.voice_clients, guild=ctx.guild)
if voice_client.is_playing():
voice_client.stop()
source = FFmpegPCMAudio(url)
voice_client.play(source)
Could you show the full error message?
And from what is the FFmpegPCMaudio?
I tried to make a SlashCommandGroup with parent set to another group, but it's commands won't register (it's been over 24h), new commands added to the parent are added immediately. My groups: py ms = SlashCommandGroup("ms", "ETL MasterServer tools") favorites = SlashCommandGroup( "favorites", "Show, add or remove your server favorites.", parent=ms) Example command: ```py
@favorites.command()
async def show(self, ctx) -> None:
"""Show your server favorites."""
await ctx.respond("Here's your favorites")
from discord import FFmpegPCMAudio
Not exactly possible because you can't have this stuff dynamic. But you can play around with autocomplete to achieve this.
Did you install FFMpeg?
Module? Yeah
no not the python module. im pretty sure you also need the ffmpeg binary package
i think you can download it using apt
No tag role_select found.
i have a quick question, is there a way to limit which roles are selectable in a role_select dropdown?
I don't see anything regarding that in the example
i dont think thats possible
@message_group.command(name="edit", description="Edits the message specified!")
async def message_edit(self, ctx: discord.commands.context.ApplicationContext,
msg: discord.Option(discord.Message, "Please enter the message link or ID!", required=True)
):
try:
if msg.author != self.client.user:
await ctx.respond("Can't edit this message!", ephemeral=True)
logger.error(f"Message not sent by bot! (Message ID: {msg.id})")
return
except discord.ext.commands.errors.MessageNotFound:
await ctx.respond("Can't find this message!", ephemeral=True)
logger.error(f"Message not found! (Message ID: {msg}")
return
Why does it still raise discord.ext.commands.errors.MessageNotFound: Message "asdsd" not found. instead of logging the error and responding to the user?
okay
Alternatively, would there be a cleaner way of catching this error? Maybe by preventing the user from inputting an invalid message link/id in the first place?
can you show full error?
discord.Message is not a valid slash command option type. it might be possible that the library is trying to find it for you
in that case, you need an error handler
that gist is for dpy but it works for pycord too
Ignoring exception in command message edit:
Traceback (most recent call last):
File "C:\Users\User\Documents\Programming\AIM\venv\Lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\User\Documents\Programming\AIM\venv\Lib\site-packages\discord\commands\core.py", line 375, in invoke
await injected(ctx)
File "C:\Users\User\Documents\Programming\AIM\venv\Lib\site-packages\discord\commands\core.py", line 124, in wrapped
ret = await coro(arg)
^^^^^^^^^^^^^^^
File "C:\Users\User\Documents\Programming\AIM\venv\Lib\site-packages\discord\commands\core.py", line 1312, in _invoke
await command.invoke(ctx)
File "C:\Users\User\Documents\Programming\AIM\venv\Lib\site-packages\discord\commands\core.py", line 375, in invoke
await injected(ctx)
File "C:\Users\User\Documents\Programming\AIM\venv\Lib\site-packages\discord\commands\core.py", line 124, in wrapped
ret = await coro(arg)
^^^^^^^^^^^^^^^
File "C:\Users\User\Documents\Programming\AIM\venv\Lib\site-packages\discord\commands\core.py", line 950, in _invoke
arg = await converter().convert(ctx, arg)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\Documents\Programming\AIM\venv\Lib\site-packages\discord\ext\commands\converter.py", line 409, in convert
guild_id, message_id, channel_id = PartialMessageConverter._get_id_matches(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\Documents\Programming\AIM\venv\Lib\site-packages\discord\ext\commands\converter.py", line 356, in _get_id_matches
raise MessageNotFound(argument)
discord.ext.commands.errors.MessageNotFound: Message "123" not found.
yep thats exactly whats happening. Library is trying to use the converter and find it for you
intended behaviour
I had it without the try exept statement first, but it raised the Exception, added it and it's still the same
So ig there's no actual way of catching it?
did you even see how you are supposed to catch and handle the errors?
you have to use the error decorator
or a command error event listener
oops, didn't even look at it, I'll do this now, thank you
regarding the discord.Message, would you recommend changing it to an int? I had it as discord.Message cause it made it easy to access things like msg.author
the issue with using discord.Message is that if a user passes id of an older message, which isnt in bot's cache, then it will raise MessageNotFound. this might be an issue depending on your use case
if you accept an int, you can check if msg is in cache. it not you can fetch it. that way, you are certain to not have cache issues
awesome (Well explained btw 👍 )
np 🙃
Pass it to your buttons init function and assign it as an attribute to the class
super().__init__(timeout=10)
self.ctx = ctx```
minus the timeout
though probably a good idea unless you want it forever active
Timeout defaults to 180 seconds. You need to explicitly set it to None to remove the timeout
thanks, good to know
And how does your code look?
That is not how it works
You assigned ctx to self.ctx
1st parameter of callback is button, not ctx
you can get the person who clicked the button from interaction.user
When you assign something to self. You can access that attribute from anywhere within the class instance.
Through self.<attribute>. But yeah, like Om is saying you don't even need ctx in your case.
Although that may or may not be your intended approach (as person who ran the cmd might be different from the person that clicked the button)
^ you do need to check if the author of the command is the interaction.user as well
how can I have it reset directly after a successful interaction? It's not very advantageous with a ticket system (as it is in the picture).
there is a similar example on github if you are interested
Here's the confirm example.
is this a select menu?
yes
you can create fresh view and edit the message with that if you want
Although there can be a better approach which im not aware of
How do you mean?
well, create a new view in the select menu callback, and do interaction.message.edit(view=new_view)
You would have to stop the interaction and return a message saying something like "You are not allowed to use this button" or something.
aka returning the callback before anything happens
you can also send the view in an ephemeral message so you can avoid this altogether
discord.ui.button
discord.Button
discord.Button.custom_id
discord.Button.disabled
discord.Button.emoji
discord.Button.label
discord.Button.style
discord.Button.to_dict
discord.Button.type
discord.Button.url
discord.ui.Button
discord.ui.Button.callback
discord.ui.Button.custom_id
discord.ui.Button.disabled
discord.ui.Button.emoji
discord.ui.Button.from_component
discord.ui.Button.is_dispatchable
discord.ui.Button.is_persistent
discord.ui.Button.label
discord.ui.Button.refresh_component
first parameter button, second is interaction (ignoring self)
uh
what did you do?
did you do view.add_item(ctx)
Tried it using int:
Discord can't take ints that large
it needs to be a string, parsed to an int in Python
okay :(
Read and implemented this, it's still not logging the errors tho
www.paste.org - allows users to paste snippets of text, usually samples of source code, for public viewing. A place where lack of code gets binned; sharing code iterations since 2006.
Still same error 🤧
uid = int((message.channel.history(limit=2, oldest_first=True)).flatten()[1].content) this is giving me an error: coroutine object is not subscriptable. i tried awaiting it but it just gives me another error
.rtfm channel.history
It's a coroutine. You must await it.
i did that to begin with but it gave me this error: TypeError: object HistoryIterator can't be used in 'await' expression
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 ...
it gives examples of iterating over history but is there a way to just get the one in a certain index like how i showed before?
Literally scroll down 3 centimeters lmao
i cant find it
yeah i actually cant
The example tells you exactly how to get the history as a list
what example???
I cant find it
Did you click the link?
yes
oh ok ty
it did not show
Ah, it just magically disappeared from the website 
Oh your browser just doesn't scroll for you
i think the event for app cmds is on_application_commmad_error
what browser/os is that
opera on windows 11 works fine with docs
oh
maybe
anyway thank yall it worked
Thx, I’ll give it a try
Why do you need the bot instance if you're in a cog?
Here's the slash cog groups example.
no
i get the ValueError: View is not persistent. Items need to have a custom_id set and View must have no timeout error even when there is no timeout and every item has a custom id, how do i fix this?
Code
https://guide.pycord.dev/interactions/ui-components/dropdowns#persistent-views
https://guide.pycord.dev/interactions/ui-components/buttons#persistent-views
Learn all about implementing Select Menus or Dropdowns in your Discord Bot with Pycord.
Learn all about implementing buttons in your Discord Bot using Pycord.
do you have intents?
You're trying to register commands in a guild that your bot isn't it
Anything?
you should use ms.create_subgroup https://docs.pycord.dev/en/master/api/application_commands.html#discord.SlashCommandGroup.create_subgroup
I'm trying to get the id for my slash command but i cant see to find out how, any pointers?
2 ways, go into your server settings > integrations > find your bot > find your command and right click on it
i know the manual way lol im trying to do it without having to do that.
surely theres got to be a way the bot can get its own slash command ids
yeh lol
yes, slash commands have an attribute called id
create a new post, thanks
any docs links? struggling to find relevant info
.rtfm applicationcontext.command
Target not found, try again and make sure to check your spelling.
.rtfm applicationcontext.
discord.ApplicationContext.app_permissions
discord.ApplicationContext.author
discord.ApplicationContext.can_send
discord.ApplicationContext.channel
discord.ApplicationContext.channel_id
discord.ApplicationContext.cog
discord.ApplicationContext.defer
discord.ApplicationContext.delete
discord.ApplicationContext.edit
discord.ApplicationContext.fetch_message
discord.ApplicationContext.followup
discord.ApplicationContext.guild
discord.ApplicationContext.guild_id
discord.ApplicationContext.guild_locale
discord.ApplicationContext.history
discord.ApplicationContext.invoke
discord.ApplicationContext.locale
discord.ApplicationContext.me
discord.ApplicationContext.message
discord.ApplicationContext.pins
Target not found, try again and make sure to check your spelling.
alas, some attributes are missing like always
_> F
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...
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...
how do you disable the buttons in a view from a modal callback (one of the buttons sends the modal)?
# pseudocode
send_modal()
button.disable = True
edit_message(view=self)
im trying to disable the buttons once the modal is submitted
then await modal.wait()
just to check does that wait for a response from the modal?
either that or the modal times-out
it will return True if timed-out and False if submitted
ah sweet, thank you sm :)
if it's the current command, use ctx.command
if you want a different command, use bot.get_application_command(name)
class SubmitModal(discord.ui.Modal):
def __init__(self, title="Submition Confirmation"):
super().__init__(
discord.ui.InputText(
label="Start Date",
style=discord.InputTextStyle.singleline,
),
discord.ui.InputText(
label="End Date",
style=discord.InputTextStyle.singleline,
),
discord.ui.InputText(
label="Reason",
style=discord.InputTextStyle.long,
),
title=title
)
async def callback(self, interaction: discord.Interaction):
db = sqlite3.connect('Ares.sqlite')
cursor = db.cursor()
cursor.execute(f"INSERT INTO Medbay(ChannelID, MemberID, Type, Status, StartDate, EndDate, Reason) VALUES({interaction.channel.id}, {interaction.user.id}, '{interaction.channel.category}', 'pending', '{self.children[0].value}', '{self.children[1].value}', '{self.children[2].value}')")
db.commit()
cursor.close()
db.close()
class MedbaySubmitButtons(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
```
@discord.ui.button(label="Submit", style=discord.ButtonStyle.blurple, custom_id="MBV2Submit")
async def submit(self, button: discord.ui.Button, interaction: discord.Interaction):
db = sqlite3.connect('Ares.sqlite')
cursor = db.cursor()
cursor.execute(f"SELECT MemberID FROM Medbay WHERE MemberID = {interaction.user.id} AND Ongoing = {1}")
result = cursor.fetchone()
if result is not None:
await interaction.response.send_message("You already have a medbay request open. You can only have 1 ticket open at once.\n*If this is a mistake contact the dev team imediatly*", ephemeral=True)
return
user = interaction.user
## await interaction.channel.send(view=medbayconfirmButtonsView())
#await interaction.response.send_message(f"Processing...", delete_after=0.01)
submit=discord.Embed(
title="**Medbay Submission**",
description=f"{user.mention}\nYour medbay request has been submitted and is now awaiting approval.",
)
await user.send(embed=submit)
embed2=discord.Embed(
title="Ticket Controls",
description="Please use the buttons below to approve or deny the request."
)
#await interaction.channel.send(embed=embed2, view=MedbayAprovalButtons())
modal=SubmitModal(title="Submition Confirmation")
await interaction.response.send_modal(modal)
await modal.wait()
if await modal.wait() == False:
for child in self.children: # loop through all the children of the view
child.disabled = True
button.label = "Submitted"
button.style = discord.ButtonStyle.green
# edit the message to reflect the changes
await interaction.response.edit_message(view=self)
await interaction.channel.send(embed=embed2, view=MedbayAprovalButtons())
get no error bur buttons aren't edited
you're waiting twice
you should do x = await modal.wait() and then check that
that code will fail anyway because 1) you don't respond with the callback interaction and 2) you're responding to an interaction twice
is there any reason that last if block can't be in the modal callback?
there are 2 buttons in the view that sends the modal. want to disable both and edit the first button to green and the label to submitted
tried to do it in the modal call back and couldnt figure it out at all
i'd say add a new attribute to your modal __init__ to pass the buttons through
then you can access them in the callback easily
though wait isn't necessarily bad, but sometimes it overcomplicates things when dealing with timeouts
i tried that and in all honesty i have no clue how that works i spent most of this afternoon trying to get that to work with no success
You probably need to learn more about OOP concepts then
yup. cant get my head round it
well for example, this is your own code py class SubmitModal(discord.ui.Modal): def __init__(self, title="Submition Confirmation"): super().__init__(...) you've already added your own title attribute, which you pass into super as it's necessary for the Modal class. However, arguments you add here don't have to be super'd; they can simply exist as an attribute of your custom class```py
class SubmitModal(discord.ui.Modal):
def init(self, title="Submition Confirmation", bot=None):
super().init(...)
self.bot = bot
...
async def some_function(self):
return self.bot.name
if you've ever made a cog, you've probably read self.bot = bot dozens, if not hundreds of times; all you're doing is picking and choosing attributes
ah okie.
so if i pass btn as an argument, and add self.btn = btn in the __init__. how do you make the btn arg = the buttons in the view?
well it refers to the same object; you aren't creating a new btn, self.btn would be equal to the original btn you passed in
this is where i get confused
So let's go with your example ```py
class SubmitModal(discord.ui.Modal):
def init(self, title="Submition Confirmation", btn=None):
super().init(...)
self.btn = btn
async def callback(self, interaction):
...
self.btn.disabled = True
await interaction.response.edit_message(...)
...
button = discord.ui.Button(label="...")
modal = SubmitModal(btn=button)
```this code is bs but just for the sake of demonstration; we've defined a variable button which is a new Button. When we call SubmitModal, we pass button in which is assigned to self.btn inside the Modal. You can consider self.btn is button, so doing anything to self.btn is the same as doing the same action on button.
But in the context of editing a View, this is a bad approach and may be where you're getting confused.
A better method would be to pass the entire view as a variable and work on view.children, like you were already doing after your wait ```py
class SubmitModal(discord.ui.Modal):
def init(self, view, title="Submition Confirmation"): # view is required
super().init(...)
self.view = view
async def callback(self, interaction):
for button in self.view.children:
... # do stuff with the buttons, or use view.disable_all_children()
self.view.children[0].label = "..."
await interaction.response.edit_message(...)```
ah okie, sort of starting to understand how it works, any recommendations on how to more comfortable with OOP?
thank you for the help, sorry it took so long
it's all good, there are sites like realpython which have pretty in depth explanations that are always an interesting read. For me, i kinda just got used to it after working on bots for so long...
fair enough, practice usually is the best way.
tysm
Show your pip list
The package name is py-cord, not pycord
so just learned about the slash command reset limit (200 creations per day per guild)
what is the proper way to test if not simply restarting bot that happens to have a multiple slash commands per startup?
ok it works thanks @limber urchin :D
Reload your cogs instead of restarting the entire bot
Bit late lol
channel didn't scroll 
hi, thanks, back from a bit of reading and moving things around
so moved my @ bot.slash_commands into a commands.Cog class now
but then i'm like what's the correct way to reload cog? i see this load and reload_extension but how to trigger reload extension correctly?
I'm guessing load extension is same as restarting bot and recreating the commands
Hi, I'm wondering if I set view=None, will the on_timeout function still run, and if so, how to stop the on_timeout function from running for a particular button.
please, don't, use, global
why
its bad practise

you don't need globals for that, at all
then pass that in as a function param
not too hard
are you using those variables in the same class as that button callback?
it's basic OOP, if you don't know that you shouldn't be making a bot
Does it work tho? I'm making a plus and minus button. If the value a is greater than 0 than it will keep sending more buttons. How do I keep track of value a using function param

make sure you don't hit the 25 button limit
It might "work" but it's a terrible solution and not sustainable
Assign it as a class attribute?
global makes things really... really crap to maintain
its great at first but then things go to hell
don't "lol" me, its good advice
anyways, your original question, why not https://tryitands.ee ?
anyway I was asking if on_timeout will run if view=None
^
there's no harm trying to see if it'll work, just spin up a test bot and test away
although from what I've seen with my own bots, no it won't fire if that view is not longer existent, but always double check
what is the 25 button limit, are you talking about button rows and columns 
yes, there is a limit of 25 buttons
set by discord, pycord can't do anything about it
5 buttons per row and 5 rows
5x5 = 25
no
thank you
hey so I want to import the "code" parameter that's in a different file, but I'm not sure how to
What? You don't import parameters.
well is there anyway I can define the code parameter from that function?
.botvar
Need to keep track of a variable between functions? No problem!
⚠️ Careful what you name it though, else you might overwrite something ⚠️
Just add it to your commands.Bot or discord.Client instance like so:
bot = commands.Bot(...)
bot.my_variable = 0
async def foo():
bot.my_variable += 1
# In a cog
@commands.command()
async def counter(self,ctx):
await ctx.send("Current Counter is at {}".format(ctx.bot.my_variable))
This also allows you to access this from other cogs/extensions/functions. Anywhere you have access to the bot instance
Is this what you are looking for?
You pass parameters when calling the function
You're calling the function
code is just the parameter name on the Code function
but I have to enter the "code" parameter when calling the function, I get a "missing 1 required positional argument: 'code'" error if I don't
and if I do, it's just undefined, so idk what to do
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)
If you don't know how functions work, you shouldn't even be coding a Discord bot.
You should be learning basic python before learning Pycord.
now we can refer to the “most recent pin” when someone doesn’t know basic python 
For this thread specifically
yeah
Is it possible for a command to make a certain work time. That is, at 12:00 it turns on, and at 18:00 it turns off?
when the command is ran, check the time of the system. if it's not between that window then just dont do anything
Anyways, I have a question. is it possible to get code from a message? Like if a user sends a code block with ```, is there any way to just grab that from like context.
no direct way
ctx.message.content should have all the content in a string
Try getting it using regex
Ah alrighty.
Show pip list
Also guilds ids should a be list of ints
Check all your commands
It should be guild_ids=[123]
Not guild_ids=123
Are these things on the side just called "App commands"? Can someone point me to some documentation on how I can make one?
Those are context menu commands
Specifically message commands and user commands
I believe the guide has something on it
.guide
.rtfm user_command
.rtfm message_command
Ah. also is it possible to add it so the button only appears on a message you've posted yourself?
Check the docs too
Nope. Doesn't look possible. Discord limitation
ah alrighty.
You can reply with "wrong message selected" or smth if the message.author is not bot.user
Ah all good.
Gotcha.
Also I'm curious, do slash commands not work on replied messages?
I noticed that I have the reply window open and there are no slash commands.
This is the case on any server.
I wanted to have the user be able to reply to a message with the slash command to like give them a thanks.
Again, discord limitation
All good. Just making sure that was the case.
You could have a message command (and send a modal to input any text)
Ah, well I guess I could see if a user adds a reaction to a message. That would probably be a good idea.
Be careful if you remove reactions. That can easily get you ratelimited
oof true.
yarl aiohttp python-dotenv typing_extensions setuptools_scm discord py-cord
wait also, is getting the last message from a member going to be a hard task?
Damn that would actually be very annoying if you had a prefix command that required you to reply to a message and wanted to switch to Slash Commands
But then again we do have these message menus so I guess that makes up for that.

Maybe lol
Uninstall discord
If you don't store messages locally, yes it will be hard
Cuz you will have to search through channel history
If you want user's last message in the guild from any channel, you will have to search through history of all channel
how do I fix discord.errors.HTTPException: 400 Bad Request (error code: 30034): Max number of daily application command creates has been reached (200)
Like I know what the error means, but is there a workaround
oof.
Hey, do you know which part of Pycord allows to achieve this kind of menu with slash commands?
Or is it just the autocompletion? 🤔
if its more than 25 Items yes
Ah, I see
Thanks
how do i ensure the bot files for sharding on numerous servers are the same?
like if i do an update (possibly through git?), all shards should get real-time updates on files and reload cogs for example
have a shard manager? depends on how you deploy your bot
im currently deploying through scripts using google cloud platform
can you explain what is a shard manager
like a script that connects to each server and start/stops/restarts the instance. i would use git pull before starting the bot so latest code is used everytime
you could run this script using github actions
Because interaction.user will never be in the players list, you're storing ids
also, dont define player in the global scope
create it inside the slash command and pass it to the view using its init
override the init like so
def __init__(self, players):
and set self.players to players
and pass it while creating the view view = MyView(players)
so what do you not know
lol thats simple classes stuff
its really good to learn oop
Learning basic OOP is essential if you want to make a bot with py-cord.
And if you don't know it, you won't understand like 80% of answers given to you here
How do I create and add a role with admin permissions to a command
And give it to a user
with one command
.rtfm create_role
The code where I send the embed with the select menu into the channel is in my TicketSystem.TicketMSG_Command file. Where the user opens the ticket via the menu is in my TicketSystem.Views.MainTicketView file. Now how can I edit the select menu; I mean the select menu to edit is in a completely different file.
Code:
ticketmsg = self.client.get_channel(1064794830296850453)
await ticketmsg.send(embed=em, view=TicketViewCreateTicket())
I had already tried:
from TicketSystem.TicketMSG_Command import TicketMSG(TicketMSG is the name of the class).from TicketSystem.TicketMSG_Command import ticketmsg
But i get errors
What are you trying to do? Sorry i forgot
And this
I have written down there
You want to edit the select menu from the select menu callback?
yes, but the message that my bot is supposed to edit (with a new select menu so that you no longer have a selection) is in a different file.
or is there already an option here for the user's selection not to be saved?
because i want to not have the user's selection saved after the interaction.
Image: https://cdn.discordapp.com/attachments/998272089343668364/1076530969550528512/image-10.png
sure i'll try to follow it here then, thanks for the feedback.
I have asked the question before about the decorators @channel.before_invoke, @channel.after_invoke.
It worked as inteded with the prefixed command, but it does not work as inteded for the SlashCommandGroup. any ideas ?
https://pasteio.com/xW9VDE8tPQeb
I think you can set select.values to an empty list and then edit the message using interaction.message.edit
but the interaction of the user is in another file
(or interaction.response.edit_message)
How? You get interaction in select menu callback parameters
Do you override the on connect event?
.slashnoshow
Checklist for Application Commands Not Showing Up:
• Does your bot have the application.commands scope?
• Are you loading cogs before on_ready and on_connect?
• Is on_connect not overridden?
• Did you update to the newest version of py-cord (tag: install)?
• Is User Settings > Accessibility > Chat Input > Use legacy chat input turned off?
• Did you share your code and errors?
• Do you still have libraries that conflict with the discord namespace (e.g. discord.py)?
no, i got it
thanks!
probably should delete it since its resolved
boop
yes, so: The message to be processed with a new view is in the TicketMSG_Command.py file. If the user now uses the select menu on the message, he will receive a response from the select menu callback from the file MainTicketView.py. But now I want to edit exactly the message from the TicketMSG_Command.py file with a new view. I can't get any further there.
Alright
ok this is getting a bit confusing, but
do you want to continue some code in the command after the select menu has been interacted with?
am confused haha what do you mean? 😂
alr let me write an example (will make a new tag too ig lol)
okay: D
# View
class MyView(discord.ui.View):
def __init__(self, name: str):
super().__init__()
self.name = name
@discord.ui.string_select(...)
async def button1(self, select: discord.ui.Select, interaction: discord.Interaction):
await interaction.response.send_message(f"{self.name} chose {select.values[0]}")
self.stop() # this is the view.stop
#command
@bot.command(...)
async def my_cmd(ctx: discord.ApplicationContext, name: str):
view = MyView(name)
await ctx.respond("Please select", view=view)
# wait till view.stop is called
await view.wait()
embed = discord.Embed(description=view.children[0].values[0], ...)
await ctx.respond(embed=embed)
Possible you want to do this?
kinda more of a python question but what would the best way to handle me wanting to call a cog function off of on_ready()? since it's like a static function (no self) and cant call an instance function, should I just use a decorator to wrap self into the function?
the core of the question is i want to ensure my connection to my sqlite db is still ok in case of an interruption ie sleeping computer
or i guess the connection could be static, dunno
call a cog function off of on_ready()
wdym by that? do you mean call a method of a cog in an on_ready listener?
yeah I want to do something like self.check_db_connection() but cant due to no self variable
where is the on_ready listener? in the same cog or different?
same cog
and just call the cog function from like the bot level?
??? heh
i have no idea what you meant by that 
I'll try and poke around at it more see if i can answer my own question maybe i'm being dumb, or i might be able to explain it better
yeah I dont know if that made sense either -.-
that made slight sense
are cogs basically singletons? i cant understand an instance where there would be multiple instances, maybe in sharding? (which i havent read up on)
uh does singleton mean only 1 object of the class?
if so, then yes
yes
i guess i could just handle the db connection as a static of the class then :T
does my original question make sense of checking the db connection on a on_ready()? or am i just going off on the wrong path?
So I would have to do both in one file or what?
yea there isnt any valid situation where you would need more than 1 object of the specific cog class. v3 changes this as gears (analogous to cogs) isnt class based
yea its fine, although dont forget that ready can fire multiple times
ok
not really. they can be in separate files
and with view.stop and view.wait it should work?
it should
ok, I'll try it tomorrow then 😄
well, it looks like I have to go with opening a db connection per transaction because if i dont close the connection to the db using aiosqlite then the bot just halts and wont even stop with ctrl c
and if there's an error that occurs it does the same, guess i'll have to be careful with that heh
hey, with buttons, how do i use server emojis?
Please show your code
Your Mybutton class is fine.
However you generally would not have your cog (Simonsays) inherit from a view that does not make much sense. Also to use players you need an instance of the class the definition of the class here players = Mybutton.players. (Instance is when you do mybtn_instance = Mybutton(player_string) like what you have in ctx.respond)
Overall I recommend brushing up a little bit on how classes work in python.
Pass the emoji object. You can find the custom guild emojis with
https://docs.pycord.dev/en/stable/api/models.html#discord.Guild.emojis
You could also use utils.get if you know the ID of the specific emoji.
https://docs.pycord.dev/en/stable/api/utils.html#discord.utils.get
players would than be a instance of Mybutton so to get the list of players you would need to do players.players but yes that would be how you would do it.
i ended up just passing the id in like this: emoji="\<:Support1:1051193606435770451\>"
without the \
is there a way to get message links btw? like say i put a message link into the bot, itll automatically find the message and get the content etc?
If it works 👍 that Is fine. I was not aware that was possible XD
me neither, i just thought may as well give it a try lol
#998272089343668364 message
First ID is guild ID
Second ID Is Channel ID
Third Message ID
Just take the link as text and extract the 3 IDs
ah okay thanks
random question, after my bot ahs been on for a long time (over 30 mins) all interactions stop working
is there a way to fix this?
interaction as in view components and/or app commands?
?tag persistent
No tag persistent found.
/exmaple
Here's the persistent example.
Learn all about implementing buttons in your Discord Bot using Pycord.
yes
k
is there a way to get the current page group of a paginator
i only see current_page
nevermind
How can I access a variable here that is set in another .py file ?
I want to display the embed with a button. When I press the button a new view appears with a dropdown menu and the embed is cleared. If I selected something in the dropdown menu, the embed should be sent again and the button should be disabled.
Does my approach make sense or is there a better way?
def __init__(self, bot: discord.Bot:
self.bot = bot
self.embed = discord.Embed(title="Fertig",
description=f"Fertig",
color=discord.Color.blurple()
)
super().__init__(timeout=None)
if bot.check[0]['wetter'] == True:
@discord.ui.button(label='Wetter', custom_id="Wetter_Button", style=discord.ButtonStyle.primary, disabled=True)
async def wetter_button(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.defer()
else:
@discord.ui.button(label='Wetter', custom_id="Wetter_Button", style=discord.ButtonStyle.primary)
async def wetter_button(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.defer()```
.botvar
Need to keep track of a variable between functions? No problem!
⚠️ Careful what you name it though, else you might overwrite something ⚠️
Just add it to your commands.Bot or discord.Client instance like so:
bot = commands.Bot(...)
bot.my_variable = 0
async def foo():
bot.my_variable += 1
# In a cog
@commands.command()
async def counter(self,ctx):
await ctx.send("Current Counter is at {}".format(ctx.bot.my_variable))
This also allows you to access this from other cogs/extensions/functions. Anywhere you have access to the bot instance
In my case I always get "bot" is not defined.
when the new view appears, do the buttons get removed?
subclass discord.ui.Button and programmatically add the buttons in view init
using view.add_item
So I have a view with an embed. Buttons are displayed under the embed.
If I now press one of these buttons, the embed is deleted and the dropdown menu associated with the button appears.
If I now select something in this dropdown menu, the embed below should be sent again and the button should be disabled.
I get this error. How can I fix it?
Error:
TypeError: __init__() missing 1 required positional argument: 'name'```
the error is obvious
TicketViewCreateTicket(name)
what
was related to my question, all good
This is my view with my embed:
class OptionalView(discord.ui.View):
def __init__(self, bot: discord.Bot, spotdaten):
self.bot = bot
self.spotdaten = spotdaten
self.embed = discord.Embed(title="Fertig",
description=f"Fertig",
color=discord.Color.blurple()
)
super().__init__(timeout=None)
@discord.ui.button(label='Wetter', custom_id="Wetter_Button", style=discord.ButtonStyle.primary, disabled=True)
async def wetter_button(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.channel.send(view=await WetterView(self.bot, self.spotdaten))
await interaction.response.defer()```
And after the button click, this view will be called:
```py
class WetterView(discord.ui.View):
async def __new__(cls, *args, **kwargs):
obj = super().__new__(cls)
await obj.__init__(*args, **kwargs)
return obj
async def __init__(self, bot: discord.Bot, spotdaten):
self.bot = bot
super().__init__(await Wetter(self.bot, spotdaten))```
Here a ui.Select is created and after I have selected something there the OptionalView is called again and appears under the select menu.
The whole thing should now be so that the button is disabled and you can no longer click on it.
how do i have to declare this?
class on_ready(commands.Cog): # für das Select Menü ein extra on_ready Event im Cog!
def __init__(self, client, name:str):
self.client = client
self.name = name
@commands.Cog.listener(
'on_ready'
)
async def listener(
self
):
self.client.add_view(
TicketViewCreateTicket(name)
)
What are you doing?
this
the select menu should also still work after bot start
First of all self.name and not name
hhm, no, the selection remains selected.
well, I'll just leave it like that for now.
if you want the select menu to reset/unselect after you click it just send a message edit with view being the same view
did you just copy the example 💀
Can I somehow provide the dict 'spotdaten' outside of a function so that I can make this if query?
class OptionalView(discord.ui.View):
def __init__(self, bot: discord.Bot, spotdaten):
self.bot = bot
self.spotdaten = spotdaten
self.embed = discord.Embed(title="Fertig",
description=f"Fertig",
color=discord.Color.blurple()
)
super().__init__(timeout=None)
if 'wettercheck' not in self.spotdaten[1]:```
nope
unless you define spotdaten at the top of your file (after imports) so it's a regular variable
but that would assume it's always the same
I want to check if the button is already pressed or not when I call the view. If yes then it should be disabled and if no it should be active.
But at the moment I have no idea how to do this.
Yea like i said, don't add the button using the decorator
Add it in the init using view.add_item
Then it should work like this or?
class OptionalView(discord.ui.View):
def __init__(self, bot: discord.Bot, spotdaten):
self.bot = bot
self.spotdaten = spotdaten
self.embed = discord.Embed(title="Fertig",
description=f"Fertig",
color=discord.Color.blurple()
)
super().__init__(timeout=None)
if 'wettercheck' not in self.spotdaten[1]:
self.add_item(WetterButton(self.bot, self.spotdaten))
else:
self.add_item(WetterButton(self.bot, self.spotdaten, disabled=True))```
looks right
.tias
how can i fix this?
AttributeError: 'InteractionResponse' object has no attribute 'send_mesage'```
Use asyncio.to_thread
asyncio and threading.Thread don't go together
^
Have you tried "reading the error"?
forgot an s 😂🙈
can u give me an example i don't understand

what are you trying to do?
in an async program, there should be only 1 event loop
it should be the main thread
get data from requests and send it
there shouldnt be other threads too
use aiohttp
but when i try to run multiple command it stuck on first command
are you using time.sleep?
no
i mean when using requests library
and wait for response, other command will need to wait for the first command to be done
?tag requests
Why you should not use the requests library for your bot
requests is a popular HTTP library for Python. It is however not a good option for Discord bots, since it is not async and blocking.
This essentially means that your bot will not be able to execute any code at all while a request is happening. Since requests usually take a few seconds to complete, this can have a detrimental effect on your bot's performance. E.g if a user executes a command that performs a request taking 5 seconds to complete, no one else will be able to use your bot for those 5 seconds.
Please look at using a HTTP library that has async support, such as aiohttp or httpx
ok
when i try to run 2 command at the same time the other command not respond
do you know what ctx.respond returns?
no:
ah
it's respond the message from slash command
*when interact the slash command
so what is it returning?
a message
no
no?
It returns in Interaction
oh so?
use stuff like ctx.edit or https://docs.pycord.dev/en/master/api/models.html#discord.Interaction.edit_original_response
ok
Hi guys - is there a wrong way of shutting down my bot? Talking especially regarding developement - I've created a second bot account and all, but regarding the "rapid restarting" via pycharm - is there anything i should look for?
try ctx.edit
view.children is a list of items in sequential order. get the button at the correct index and set disabled = True. edit the message with the updated view
since you are subclassing View, self is your view object
it is better to use the hot loading functionality of cogs rather than restarting your bot instance everytime
but if i made changes to main.py i need to restart - are there any tips on proper way? like first shutdown instead of restart or something like this?
Will have a look at the hot loading, thanks
ok
there is no "proper" way as such. ctrl + c in terminal works. the stop button in vsc works. not sure about pycharm
thanks =)
if you wanna know technically, anything that calls SIGINT should be fine
full error?
yes that's full error
in terminal it don't throw anything
yes
are you not raising error in the last else block?
yes
then raise, and see the full traceback for this one
full error?
Hi guys, somehow my slash commands wont get recognized anymore - is there something i missed in the upgrade to 2.4 that needs to be changed? Here for example is an basic ping command that wont show up anymore on Discord
mako/cogs/utils.py
class Utils(commands.Cog):
def __init__(self, bot):
self.bot = bot
@discord.command()
async def ping(self, ctx) -> None:
await ctx.respond(f"Pong! {round(self.bot.latency * 1000)}ms.")
def setup(bot):
bot.add_cog(Utils(bot))
@bot.event
async def on_ready() -> None:
...
...
load_cogs()
def load_cogs() -> None:
for file in os.listdir("mako/cogs"):
if file.endswith(".py"):
extension = file[:-3]
try:
bot.load_extension(f"mako.cogs.{extension}")
print(f"Loaded Extension {extension}")
except Exception as e:
exception = f"{type(e).__name__}: {e}"
print(f"Failed to load extension {extension}\n{exception}")
I have 3 commands above the on_ready - these work and will show up in discord when opening the command prompt:
@bot.command()
async def reload_utils(ctx):
bot.reload_extension('mako.cogs.utils')
await ctx.respond('Reloaded Utils')
Or is this just some Discord stuff - because sometimes also my main bot wont show up in the list
You don't load cogs on on_ready
You do it on the bot initialization
so before the bot.run you mean?
hi im getting this error:
TypeError: object.__init__() takes exactly one argument (the instance to initialize)
the code that its erroring on is this:
super().__init__(timeout=None)
Thats some easy fix - thanks for your help
Full init and traceback
dont even know why i changed it - had it that way before ^^
the thing is it allows it without the timeout arg but not with
one second
File "C:\Users\Rio\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\cog.py", line 743, in _load_from_module_spec
setup(self)
File "C:\Users\Rio\Documents\GitHub\DBMain-Bot\modules\events\Tickets.py", line 130, in setup
bot.add_cog(tickets(bot))
File "C:\Users\Rio\Documents\GitHub\DBMain-Bot\modules\events\Tickets.py", line 19, in __init__
super().__init__(timeout=None)
TypeError: object.__init__() takes exactly one argument (the instance to initialize)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Rio\Documents\GitHub\DBMain-Bot\main.py", line 29, in <module>
bot.load_extension(f"modules.events.{file[:-3]}",store=False)
File "C:\Users\Rio\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\cog.py", line 867, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\Rio\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\cog.py", line 748, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'modules.events.Tickets' raised an error: TypeError: object.__init__() takes exactly one argument (the instance to initialize)
Show the class
class tickets(commands.Cog):
def __init__(self, bot):
self.bot = bot
global bot1
bot1 = bot
super().__init__(timeout=None)
ignore the jankiness in the first few lines
Cog doesn't not have a timeout kwarg?
wait
have i put the code in the wrong place
i was working on this at 4am and i just got home from college
i mean its not as bad as what i did last night
How can I send the second await command with the view only after I have completely run the first view?
await interaction.channel.send(view=await SchnurTypView(self.bot, self.spotdaten))
await interaction.channel.send(embed=self.embed, view=OptionalView(self.bot, self.spotdaten))```
assign the view object to a variable, and use await view.wait()
.tag viewwait
# View
class MyView(discord.ui.View):
def __init__(self, name: str):
super().__init__()
self.name = name
@discord.ui.string_select(...)
async def button1(self, select: discord.ui.Select, interaction: discord.Interaction):
await interaction.response.send_message(f"{self.name} chose {select.values[0]}")
self.stop() # this is the view.stop
#command
@bot.command(...)
async def my_cmd(ctx: discord.ApplicationContext, name: str):
view = MyView(name)
await ctx.respond("Please select", view=view)
# wait till view.stop is called
await view.wait()
embed = discord.Embed(description=view.children[0].values[0], ...)
await ctx.respond(embed=embed)
So?
view = await SchnurTypView(self.bot, self.spotdaten)
await interaction.channel.send(view=view)
await view.wait()
await interaction.channel.send(embed=self.embed, view=OptionalView(self.bot, self.spotdaten))```
yep looks right (other than indentaion)
oh and dont forget to call view.stop (or self.stop) in the view
Where do I have to put the stop?
class SchnurFarbeView(discord.ui.View):
async def __new__(cls, *args, **kwargs):
obj = super().__new__(cls)
await obj.__init__(*args, **kwargs)
return obj
async def __init__(self, bot: discord.Bot, spotdaten):
self.bot = bot
super().__init__(await Schnurfarbe(self.bot, spotdaten))```
So I don't get an error message but the next view is not displayed when I have selected something in the select menu.
class Schnurfarbe(discord.ui.Select):
def __init__(self, bot: discord.Bot, spotdaten):
self.bot = bot
self.spotdaten = spotdaten
options = [discord.SelectOption(label=farbe) for farbe in schnurfarbe_sortiert]
super().__init__(
placeholder="Wähle die Farbe deiner Hauptschnur aus",
min_values=1,
max_values=1,
options=options,
)
async def callback(self, interaction: discord.Interaction):
.
.
.
self.view.stop() ```
??? 
create_tickets = await guild.fetch_channel(CREATE_TICKETS)
history = create_tickets.history()
for message in history:
Anyone know why I can't iterate through history like this?
nvm, figured it out. I impelements AsyncIterator, so I should async for message in history. Ty!
hi, i want to fill an bot admin table with guild and userid
But when i try to pass the userid to the command i get an errror telling me i should insert an valid number
it seems it is too long, any quick ideas on how i could manage to fix this?
type casting into str maybe, do you know of any "cleaner" solution?
for real tho, just use string since less memory
your db might have a type like 'bigint'
allowing for larger integers
int()
and if that doesn't work it's not a channel id
How do I go about making command group in a cog? @commands.group()?
command as in text commands or slash commands?
text/prefix command
yeah, @commands.group()
and if I want to make subgroup it's the same as commands outside of cog as well? So instead of @commands.group() it's @name_of_parent.group()?
I'm asking because that's what I've been doing but it logs error about no such command existing :(
Hijacking this line of conversation too, how do you make a slash command subcommand group within a cog? Same thing?
Here's the slash cog groups example.
Diffrence between ctx and interaction
ctx is context, interaction is interaction
What’s what’s better to use
well it's not about what's "better", they're implemented in different scenarios
ctx is associated with commands and if it's a slash command, you'll also have access to ctx.interaction
well, applicationcontext wraps interaction, just like how context also wraps message
Can I embed icons in pagination to create a voting system?
E.g. a sentence and then behind it 2 icons that you can click for positive or negative?
So that I can output 5 sentences per page and behind each sentence then query by icon whether positive or negative?
do you mean buttons?
I thought of something like this:
Text ❌ ✅
Text ❌ ✅
Text ❌ ✅
Text ❌ ✅
◀️Button Button▶️
And on the X and hook I wanted to let vote
well you can't really interact with embed content/text itself
your concept would require you to attach new buttons for your voting system
or use reactions, but if the votes are meant to be different per page then it wouldn't work
So I only have the possibility to make 1 text per page and under the embed 2 buttons for the voting and underneath are the buttons to scroll from the paginator?
pretty much
If each page should be voted individually then I have to use buttons right?
if you're using ext.pages, the Paginator has an option to attach a custom view alongside the page buttons
yeah
What do you mean exactly?
do you use https://docs.pycord.dev/en/master/ext/pages/
This module provides an easy pagination system with buttons, page groups, and custom view support. Example usage in a cog: API Reference: Page: Attributes content, custom_view, embeds, files. Metho...
Then I can design it that way right?
Okay I will have a look and try my luck 🙂
Thanks!
whats the difference between bot.command and bot.slash_command
at which one?
?tag client
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
discord.Bot
bot.slash_command is an alias for bot.command
ok, and how would I use cogs for different files
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
try:
bot.load_extension(f'cogs.{filename[:-3]}')
except Exception as e:
print(f'Failed to load extension {filename}: {e}')```?
that works
and then like this in the file?
class uptime(commands.Cog):
def __init__(self, client):
self.client = client
@client.slash_command(name="uptime", description="Get the bot's uptime")
async def uptime(ctx):
now_time = time.time()
uptime_seconds = now_time - start_time
uptime_hours, remainder = divmod(uptime_seconds, 3600)
uptime_minutes, uptime_seconds = divmod(remainder, 60)
uptime_string = "{:02.0f}:{:02.0f}:{:02.0f}".format(uptime_hours, uptime_minutes, uptime_seconds)
await ctx.respond(f"Uptime: `{uptime_string}`")
def setup(client):
client.add_cog(uptime(client))```
or should I change it
discord.Cog
here? class uptime(discord.Cog):
yes
and then last question lmao, if I have a class outside of the one that gets setup like this, is it ok? because Im getting an error about registering commands or something
import os
import discord
from discord.ext import commands
import logging
color = 0x2a2c31
logger = logging.getLogger(__name__)
class giveawaymodal(discord.ui.Modal):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.add_item(discord.ui.InputText(label="Length", required=True, min_length=2, style=discord.InputTextStyle.short))
self.add_item(discord.ui.InputText(label="Winners", required=True, min_length=1, max_length=2, style=discord.InputTextStyle.short))
self.add_item(discord.ui.InputText(label="Prize", required=True, min_length=1, max_length=128, style=discord.InputTextStyle.short))
self.add_item(discord.ui.InputText(label="Description", required=False, max_length=1000, style=discord.InputTextStyle.long))
async def callback(self, interaction: discord.Interaction):
try:
embed = discord.Embed(title="Giveaway Created", color=3092790)
embed.add_field(name="Length", value=self.children[0].value)
embed.add_field(name="Winners", value=self.children[1].value)
await interaction.response.send_message(embeds=[embed], ephemeral=True)
except Exception as e:
logger.exception(f"An error occurred while creating a giveaway: {e}")
await interaction.response.send_message("An error occurred while creating a giveaway.", ephemeral=True)
class creategw(discord.Cog):
def __init__(self, client):
self.client = client
@client.slash_command()
async def create_gw(self, ctx: discord.ApplicationContext):
"""Shows an example of a modal dialog being invoked from a slash command."""
modal = giveawaymodal(title="Create Giveaway")
await ctx.send_modal(modal)
def setup(client):
client.add_cog(creategw(client))```
```Ignoring exception in on_connect
Traceback (most recent call last):
File "C:\Users\oriel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "C:\Users\oriel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 1164, in on_connect
await self.sync_commands()
File "C:\Users\oriel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 719, in sync_commands
registered_commands = await self.register_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\oriel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 588, in register_commands
data = [cmd["command"].to_dict() for cmd in filtered_deleted]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\oriel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 588, in <listcomp>
data = [cmd["command"].to_dict() for cmd in filtered_deleted]
^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\oriel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 844, in to_dict
"options": [o.to_dict() for o in self.options],
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\oriel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 844, in <listcomp>
"options": [o.to_dict() for o in self.options],
^^^^^^^^^^^
File "C:\Users\oriel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\options.py", line 333, in to_dict
"type": self.input_type.value,
^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'value'
ProGiveaways#1875 is ready and online!```
read the error
Here's the slash cog example.
ok thanks lmao
oh last question, do I need to specify guild ids or have that in the code
Here's the slash basic example.
so no ok thanks
I'm having trouble understanding whats wrong with it
what is the py-cord version?
2.4.0
can you show the pip list
my entire pip list
aiosignal 1.3.1
aiosqlite 0.18.0
asgiref 3.6.0
astunparse 1.6.3
async-timeout 4.0.2
attrs 22.2.0
bcrypt 4.0.1
beautifulsoup4 4.11.2
bleach 6.0.0
boto3 1.26.57
botocore 1.29.57
braceexpand 0.1.7
bs4 0.0.1
button-paginator 1.0.1
certifi 2022.12.7
cffi 1.15.1
charset-normalizer 2.1.1
click 8.1.3
cloudinary 1.31.0
colorama 0.4.6
discord-py-slash-command 4.2.1
DiscordUtils 1.3.4
dnspython 2.3.0
docopt 0.6.2
email-validator 1.3.1
ffmpeg-python 0.2.0
Flask 2.2.2
Flask-Cors 3.0.10
frozenlist 1.3.3
future 0.18.3
gevent 22.10.2
greenlet 2.0.1
humanfriendly 10.0
idna 3.4
imageio-ffmpeg 0.4.8
import-expression 1.1.4
itsdangerous 2.1.2
Jinja2 3.1.2
jishaku 2.5.1
jmespath 1.0.1
line-profiler 4.0.2
MarkupSafe 2.1.2
multidict 6.0.4
numpy 1.24.1
oauthlib 3.2.2
pandas 1.5.3
pip 23.0
pipreqs 0.4.11
py-cord 2.4.0
pycparser 2.21
pymongo 4.3.3
pyreadline3 3.4.1
python-dateutil 2.8.2
python-dotenv 0.21.1
pytz 2022.7.1
requests 2.28.2
requests-oauthlib 1.3.1
s3transfer 0.6.0
setuptools 66.1.1
six 1.16.0
soupsieve 2.4
tweepy 4.12.1
urllib3 1.26.14
webencodings 0.5.1
websocket-client 1.5.1
websockets 10.4
Werkzeug 2.2.2
wheel 0.38.4
yarg 0.1.9
yarl 1.8.2
zope.event 4.6
zope.interface 5.5.2```
you dont use env?
- 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
alr
ive done all of this, same error
close the terminal and restart the editor
same issue
did you uninstall this?
Do you mean it’s not in requirements.txt, or that it’s not in pip freeze
Last line inside the callback
View.stop should be inside the callback
Guys, how to make a discord button open a url
.rtfm discord.ButtonStyle.link
?
thats cool
how does it not help?
nvm, the internet was lagging, so the bot's message didn't show up
And don't cross post, stick to your own post or this channel. Not both
*__**`Sorry`**__*
Ok, so now I am able to change the style of the button. How can I add a url to the button though?
I have this so far
def init(self):
super().init(timeout=None)
@discord.ui.button(label="Upload Audition Now",
style=discord.ButtonStyle.link
)
async def hello(self, interaction: discord.Interaction, button:discord.ui.Button):
await interaction.response.send_message("opened link")
```
Anyone have any ideas?
set the url kwarg in your decorator
what is a kwarg
The decorator doesn't take url kwarg
really?
Link Buttons dont have a callback so
Oh, fair enough
@green hornet you have a thread
ok
#1077460125872312371
yes
@green hornet
yes, I should have told you guys to switch to the thread, sorry
How can I wait long after a slash command? I'm calling a neural network method that works for a long time, which discord will not tolerate
.rtfm Context.defer
hmm?
Defer it
It's not clear, but it's very interesting. Can I have the full path of the function and where to insert it
Why do you need the function path?..
It's a context method
You just context.defer() at the start of your callback
Code
Badcode version 1:)))
If you're getting interaction then that's a not a slash command
Ita a button or any other ui thing
.rtfm Response.defer
Same logic
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: InteractionResponded: This interaction has already been responded to before
Ok, error. 
I have this with my slash commands, those two options come from:
async def holyc(self, ctx: Context, style: str = None, delete: bool = True):
These two options are made by the bool I guess. how can I create my own options there?
Like I can create custom options, how do I create custom values under said options
WHAT THE HECK
I've done nothing wrong
and I'm getting
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
and i can't trace the error because it gets raised in pycord not my bot :/
screw it im just gonna defer it and see what happens
How can I disable Discord converting 2 regional indicators to a flag, as with my bot on mobile it does that when sending text with the indicators, but not on desktop
You are taking longer than 3 seconds to respond
Pass list of options to the choices kwarg
Here's the slash options example.
Is there a way to gatekeep listeners in cogs with roles or it must be inside the listener with ifs?
Inside with ifs
Are you listening for a specific message or any message from a person with a role. (Or other event)
Any message with specific role
Yeah, ifs are the only way.
No.

Is it possible, if I create a new room via a button click, that the user is then also directly in this room to be able to write there or do you always have to manually click on the room then on it?
you have to click
Okay, and if I delete a channel, I can't prevent the top channel from being displayed automatically, can I?
How can I check whether a channel with a certain name already exists on the interaction.guild?
My channel with the name in my server already exists, yet the bot allows to create a new ticket channel.
Code: https://pastebin.com/HBRBjMGf
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.
?tag paste

If you want to check channels based on name, use utils.get
.rtfm utils.get
I'm already doing that, aren't I?
Oh hmm. Print tickket and see what it is. Check if the names are exactly same
is that what you mean?
Is it possible with a button to get user ID. And if so, tell me the correct code.
There's literally inconsisent indentation
You get interaction.user
.rtfm Interaction.user
Didn't know replit coded for you
Then it's not a replit error
You have inconsistent indentation
Hi everyone!
Nowadays it is easily possible to play a sound. My problem is that I want to play two sounds at the same time but I have to wait until the first one is finished to play the second one, any idea how to do that?
depends on what library you are using to play sound. you might need to merge the audio to play it
||try asking this to chatgpt||
I have to create a kind of virtual cable that plays a sound non stop as long as the bot is connected on which I can play sounds.
ChatGPT does not help me much
I have no idea whats going on
Then why you answer lmao
@commands.has_permissions(administrator =True)
@commands.guild_only()
@game.command(name='teamlist', description='Displays TimList.',guild_ids=[944934277777326090,769823680695107594])
async def teamlist(self , ctx: discord.ApplicationContext,*,time: Option(str,max_length=17, description='Start time')):
cursor.execute(f"SELECT rowid,* FROM teamlist WHERE server_id = {ctx.guild.id}")
item = cursor.fetchmany(19)
class MyView(discord.ui.View):
@discord.ui.button( label="Confirm",style=discord.ButtonStyle.success)
async def button_callback(self, button, interaction):
user = interaction.user
for child in self.children:
child.disabled = False
await interaction.response.edit_message(view=self)
await ctx.send(f"доработаю{user.id}")
await ctx.respond("Done.",ephemeral=True)
a = ""
i = 0
for el in item:
i+=1
if i<17:
a += f"**{i}**. {el[1]} | {el[2]} | <@{el[3]}>\n"
else:
a += f"Reserve🔴**{i}**. {el[1]} | {el[2]} | <@{el[3]}>\n"
#await ctx.send(f":scroll: TEAM LIST :scroll:\n🕐Time: {time}\n \n{a}")
embed1 = discord.Embed(title =f":scroll: TEAM LIST :scroll:",description=f"**🕐Time: {time}**\n \n{a}", colour = discord.Colour.embed_background())
await ctx.send(embed = embed1,view=MyView())
#tlist = await ctx.send(embed = embed1)
#await tlist.add_reaction("✅")
db.commit()
Hi all. I need a code to get ID from the button, it turned out to be some kind of garbage. Or is everything right?
Is the code correct? Or can it be simplified?
- I don't know what your code does.
- It's messy and mixed with command attributes and callback attributes
What's the issue with doing that? I need the class in my command so that I can get an Option variable.
How do I make buttons
Learn all about implementing buttons in your Discord Bot using Pycord.
Ty
Can I make a button add a role
Yes
Hardcode it and see if it works
And please don't call your variables str. That's already a keyword in Python-
defining classes is an expensive task and is a waste of resources if you do it inside the command. it will only cause you added lag and bugs. there will be scope conflicts with the self variable as you start using even slightly advanced functionality in the buttons. defining view classes outside the cog (or in a separate file) gives you all the features while protecting you from thee above mentioned issues
you should rather pass the option to the view init
check this out https://stackoverflow.com/a/39644525/13088701
Hey, I'm a little bit confused because I can't find any documentation for AuditLog-Events regarding timeouts... Neither does AuditLogDiff or AuditLogAction contain anything with communication_disabled_until or something similar... Do I oversee anything or is this a missing feature in the library? 🤔
im trying to ping user on reply but it just dont turn yellow
message = await ctx.followup.send(f"<@{ctx.user.id}>", embed=embed, view=view, allowed_mentions=discord.AllowedMentions(users=True, everyone=False, roles=False))
Just use ctx.user.mention.
Oh I see
Is there a reason you're using followup.send instead of just ctx.respond?
i defer it
ill try respond
You can still respond even if you defer
try without allowed mentions
Well, why are you using allowed mentions anyways?
i did it didnt work so i added it
Are you sure it isn't just a bug with your client? Have you looked at your phone for instance?
i even tried replied_user=True
oh ill try that
it works on phone
so oopsies
ig my discord bugged
Try CTRL + R to reload your client
Yep it's yellow now haha thanks
I have now printed it.
In Appendix 1 you can see the channel name in Discord itself.
Appendix 2 shows what was printed in the console.
Appendix 3 shows the code for it.
The "m" is made small in discord. Should I therefore rather use the ID, i.e. that the channel is then called what the user ID of the member is?
you should convert tickket to lowercase, and replace spaces with -
discord does some formatting with text channel names, thats why you are facing these errors
you could use the user id, but that can be difficult to read and identify for your bot's users
how would that look? 🙂
or you could do ticket-1 ticket-2 etc and use a db to store stuff
would now have said with the user id
yea i meant user id
some_str.lower() and some_str.replace(" ", "-")
thats basic python ngl
you couldve googled
lel
read pins
You should be learning basic python before learning Pycord.
Oh, that's how I do it, yes. But I think I'll try that first with the user ID. For example, if the user changes his name/tag.
cool 👍
^^
Hi there!
I have a problem, the py-cord update removes the spaces on my buttons when they are not between the letters. This is a real problem, is there a solution?
From this
to this
which update, 2.4.0? which version were you on before?
from 2.2.2 to 2.4.0
Try 2.3.0
figure out which version broke it (https://github.com/Pycord-Development/pycord/releases)
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - Pycord-Development/pycord
since there were a lot of updates from 2.2.2 to 2.4.0
I have the impression that the problem comes from python, my pc and my server have the problem, it's strange I didn't have this problem until 21 days ago and I haven't touched anything since.
so reverting pycord back to 2.2.2 doesnt fix the issue? then it could be a change from discords end
Got it like this now. But it doesn't work either. Am I doing something wrong?
if 'Ticket1' in select.values:
cat = client.get_channel(985994142704353290)
tickket = f'ticket-{interaction.user.name.lower().replace(" ", "-")}'
print(tickket)
channelll = discord.utils.get(interaction.guild.channels, name=tickket)
print(channelll)
if channelll:
existiert = discord.Embed(
title=' - Leider kein Ticket erstellt',
description=f'Du kannst kein neues Ticket öffnen, weil du **grade schon ein offenes Ticket** auf diesem Server hast.',
color=0x2b2c30
)
await interaction.response.send_message(embed=existiert, ephemeral=True)
else:
ticket_channel = await interaction.guild.create_text_channel(
f'ticket-{interaction.user}',
topic=f' - Dieses Ticket wurde von {interaction.user} erstellt.',
category=cat
)
can you show the prints now?
and the channel name in discord
I just got no more print when I executed the command
I'll try again tomorrow. Then let me know
hmm
Could you show me what you mean specifically?
check the example
Here's the slash options example.
I'm sorry.
examples/app_commands/slash_options.py line 15
@option("gender", description="Choose your gender", choices=["Male", "Female", "Other"])```
np 👍
ok
Is it await add roles
.tias
Alr
You really have to try the stuff at your self and stop asking every time...
Alr
any way to set a bot's font? I want to use a monospaced font, but not in a code block (because discord timestamps arnt parsed in them) I know you can copy/paste fonts into discord, but dunno how that would be done in a bot, if possible
Just copy and paste the text into the code?...
not really a viable answer
Your question doesn't make sense
You want to send responses with some font
Get the formatted text and paste it in the code
Don't know what else you expect
I suppose you can use emojis for each of the characters and punctuations you are using in your bot, but that racks up character usage really quickly.
how do I edit an embed with pycord
await foo.edit(embed=new_embed) where foo is something that has an edit method
weird, its saying that Embed has no attribute edit
^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Embed' object has no attribute 'edit'```
yeah it doesn't
so how would I.
depends on how you send the embed
so basically its a modal that sends 2 embeds and when u click a view on that embed its supposed to update a value on the embed and it all works accept the editing part
so await interaction.edit_original_message(...)
ohh
yea that didnt work, Im passing in the embed with the view so the embed should be: py class EnterGiveaway(discord.ui.View): def __init__(self, public_embed): super().__init__() self.public_embed = public_embed
so self.public_embed
is there a way to edit it by id
...
sorry I'm learning
where are you getting the ID
I'm not but is it possible to
what ID are you getting
or planning to
the message id possibly if thats possible
ok
actually I don't think thats possible
why
I just have it set up odd I guess, I don't pass in anything like that I think
;-;
this is how I send the embed await interaction.channel.send(embeds=[public_embed], view=enter_giveaway_view) and then in a different class ```py
class EnterGiveaway(discord.ui.View):
def init(self, public_embed):
super().init()
self.public_embed = public_embed`
@discord.ui.button(label="Enter Giveaway", style=discord.ButtonStyle.primary, emoji="🎁")
async def button_callback(self, button, interaction):
entries_field = self.public_embed.fields[-1]
entries_text = entries_field.value
current_entries = int(re.search(r'Entries: **(\d+)**', entries_text).group(1))
new_entries = current_entries + 1
new_entries_text = re.sub(r'Entries: **\d+**', f'Entries: {new_entries}', entries_text)
new_embed = discord.Embed(
title=self.public_embed.title,
description=self.public_embed.description,
color=self.public_embed.color
)
for field in self.public_embed.fields[:-1]:
new_embed.add_field(name=field.name, value=field.value, inline=field.inline)
new_embed.add_field(name=entries_field.name, value=new_entries_text, inline=entries_field.inline)
await interaction.edit_orginal_response(embed=new_embed)
Thats what I'm trying to do but the edit wont work
Okay so basically I can't find anything in the docs about this so if there's actually a page just direct me there thx
anyway
How do you add categories in the help command
Pycord's commands extension comes with a built-in help command. In this guide, we will take a look at them as well as learn how to create your own. Let's dive in!
thx
is it possible to somehow make it so that there is a code that writes out my plan sheet or ban plate and after the expiration of time - this plate was deleted, let's say I issue a ban to a person for 2 days and after 2 daysBan is removed.
is there a tag that shows all the attribute
do you mean rtfm?
try it out in #883236900171816970
so theres a rtfm attribute
uh waa?
a list of all ctx
is there a tag
what did you mean by this?
all attributes and methods of ctx? the docs has that. and rtfm command on @winter condor shows links to the docs
.rtfm commands.Context
discord.ext.commands.Context
discord.ext.commands.Context.author
discord.ext.commands.Context.can_send
discord.ext.commands.Context.channel
discord.ext.commands.Context.clean_prefix
discord.ext.commands.Context.cog
discord.ext.commands.Context.fetch_message
discord.ext.commands.Context.guild
discord.ext.commands.Context.history
discord.ext.commands.Context.invoke
discord.ext.commands.Context.me
discord.ext.commands.Context.pins
discord.ext.commands.Context.reinvoke
discord.ext.commands.Context.reply
discord.ext.commands.Context.send
discord.ext.commands.Context.send_help
discord.ext.commands.Context.trigger_typing
discord.ext.commands.Context.typing
discord.ext.commands.Context.valid
discord.ext.commands.Context.voice_client
check it on the docs page
is user not apart of those things
user isnt defined
oh
on_ready doesnt give you any arguments
channel ids are an int
dont use a while True loop
use on_reaction_add event
dude there is so much wrong with your code
ik i said oh
looks like you are using stuff from very old dpy tutorials
slow bot 
Hey, anybody know how I can add the current Unix timestamp in seconds to a number?
Current code:
def convert(time):
pos = ["s", "m", "h", "d"]
time_dict = {"s": 1, "m": 60, "h": 3600, "d": 3600 * 24}
unit = time[-1]
if unit not in pos:
return -1
try:
val = int(time[:-1])
except:
return -2
return val * time_dict[unit]
time = convert(duration)
embed.add_field(
name=f"Ends:",
value=f"<t:{discord.utils.utcnow() + time}:R>"
)
utcnow().timestamp
Also try using datetime.datetime.now instead of utcnow
Sometimes i have found weird stuff when using UTC time instead of local time
Oh btw
There is this cool library called time_str that does what you want but much better
embed.add_field(
name=f"Ends:",
value=f"<t:{discord.utils.utcnow().timestamp + time}:R>"
)
Use int(time.time()) it gives you the current Unix time in seconds (but also you could've just wrapped it with int since integers are convertible to floats)
what are my options if i have 29 choices for the user to pick from?
it supports a maximum of 25
Autocomplete
Here's the slash autocomplete example.
Thank you
I was also looking at select menus, do you think they'd be a better fit?
Oh but what if they are also limited to 25
hi, when getting the channel history with ```py
async for message in msg.channel.history(limit=x):
I'd like to get about a 100k messages this way - so 100 is pretty low :')
Can you send that to me? I don't wanna lose it. Also, can you provide a message link to this message?
Sadly, no IIRC. You will get rate limited by Discord, and bots can only see so far back due to Discord limitations.
can i define my select callback function in a seperate py file?
Why would that be needed
yea they are 💀
ty :) Discord / Cloudflare won't tempban me for fetching this amount tho, right?
It won't let you do it at all bro
@proud mason
This is printed in the console.
and this is the name of the channel on discord itself.
Hmm you are missing the 1385 at the end
Use str(interaction.user).lower()...
yes, but it should be different for each user. My user tag should not always be there.
so is that how I have to do it?
tickket = f'ticket-{(interaction.user).lower().replace(" ", "-")}'
is it possible to check if a command has already been defered?
tickket = f'ticket-{(interaction.user).lower().replace(" ", "-")}'
AttributeError: 'Member' object has no attribute 'lower'
