#Basic Pycord Help (Quick Questions Only)
1 messages · Page 54 of 1
Should I check if the fish dropdown menu already exists and if so remove it and then create it again?
😭 how didd you get it? i need answers
ig
there is railway.app
there are google cloud, aws, azure, oracle free vps. but you need a card for verification
I just bought one x3
Nope xd
What? 😄
why would remove and add the same dropdown?
sorry im really confused now

how can I add a slash command group to a cog/extension?
Here's the slash cog groups example.
thanks
If I select something in the first dropdown then the second dropdown comes up. But if I now change the selection in the first dropdown, then a third dropdown is created underneath instead of updating the second dropdown.
this is throwing an error, it says that the slash command group is not defined
oh wait never mind
I misread it
only accepts discord.Interaction or commands.Context
pager = Paginator(maps_list)
await pager.start(ctx)```
@client.slash_command(description="")
async def maps(ctx):
maps_list = [EMBEDS IN HERE]
pager = Paginator(maps_list)
await pager.start(ctx)```
ctx.interaction
Thanks
How can I solve the problem?
async def callback(self, interaction: discord.Interaction) -> None:
spot = self.user.value
pattern_spot = re.compile(r'^([1-9]\d{0,1}|200):([1-9]\d{0,1}|200)$')
if not pattern_spot.match(spot):
embed = discord.Embed(
title="Fehler",
description="Spot muss im Format '100:100' eingegeben werden. Der Maximalwert beträgt '200:200'"
)
await interaction.response.send_message(embed=embed)
await interaction.response.send_modal(AddSpot(self.bot, interaction.channel))
self.view.add_item(AngelArt(self.bot))
await interaction.response.edit_message(view=self.view)
await interaction.response.send_modal(AddSpot(self.bot, interaction.channel))
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 1049, in send_modal
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before```
How can I restart my bot in VSC?
Ctrl + C
Done that, my bot is still online, do I have to restart discord?
No sometimes it can take a few seconds. If necessary, close the VSC and restart.
This is what I'm getting
Then your bot is not running
If you didn’t specify a guild or guilds then it may take a few mins to sync
Is it possible to get information on linked accounts for guild members? I'd like to autoassign a certain role to people with Twitch "VIP" status
There was something just merged for linked roles. Unsure if you can get other linked accounts though; I don’t fully know how it works
is there any way to have the callback for each button be different? like so that if i click on the second button, it will respond with the number 2, btw im generating these procedurally
Hey guys, what is the most reliable and inexpensive way to keep my bot online. I'm not too sure how to go upon this. (I am using VSC)
railway.app
am i clueless or where is the list index that is out of range?
i click run and immediately error
asking here cause slash command
what happend if you remove : discord.ApplicationContext
same thing
can you show the pip list?
this is all that's in there, it goes on_ready(), this function, then bot.run()
for fun, before this, i tried the dropdown example (which worked) and then basically removed that function and put this one in
is there any way to have the callback for each button be different? like so that if i click on the second button, it will respond with the number 2, btw im generating these procedurally
for knowledge, the error goes away when i include 'description' in slash_command()
here was that full traceback i never shared cause silly me in debug mode
fun
I want to display a message after a button press but it is not working.
async def fourth_button_callback(self, button, interaction):
for child in self.children:
child.disabled = True
await interaction.response.edit_message(view=self)
await interaction.response.send_message("You clicked the sloth button!")```
I assume its due to the await causing issues
nope, unless you create it yourself
errors?
Traceback (most recent call last):
File "C:\Users\Akira\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "C:\Users\Akira\PycharmProjects\helloWorld\buttonTest.py", line 42, in fourth_button_callback
await interaction.response.send_message("You clicked the button!")
File "C:\Users\Akira\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 765, in send_message
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before```
I see that its because it has responded once before that
need to rethink the code on that one
The issue is that you are responding twice. You can edit the message with interaction.edit_original_response
instead of interaction.response.edit_message
I actually want to disable all the active views as a part of a cmd which essentially shuts down the bot.
gl with that
hmm, edited the file but now I'm getting a new error
Traceback (most recent call last):
File "C:\Users\Akira\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "C:\Users\Akira\PycharmProjects\helloWorld\buttonTest.py", line 41, in fourth_button_callback
await interaction.edit_original_response(view=self, content="You clicked the button!")
File "C:\Users\Akira\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 428, in edit_original_response
data = await adapter.edit_original_interaction_response(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Akira\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 215, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook```
Does the ```interaction.edit_original_response``` only allow for one argument?
async def fourth_button_callback(self, button, interaction):
for child in self.children:
child.disabled = True
await interaction.edit_original_response(view=self, content="You clicked the button!")```
oops, it should've been interaction.message.edit
ok, the text is updating but I am getting this now:
Not getting any tracebacks for it so I assume it is maybe fine?
Where did your await interaction.response.send_message("You clicked the sloth button!") go?
well, basically, you need to respond to an interaction
if you are sending a message and editing a message, you would edit the message not as a response, and send the message as a response.
if you are just editing a message, then that should be the response.
so, my bot code looking like this:
async def button(ctx):
await ctx.respond("Which did you complete?", view=MyView()) # Send a message with our View class that contains the button```
means it is looking to respond but their is nothing to respond to since I interacted with it already?
well, buttons presses are also interactions
each time they are pressed, they should also be responded to.
ok, thank you for your help, I got it working for now
async def fourth_button_callback(self, button, interaction):
for child in self.children:
child.disabled = True
await interaction.message.edit(content="You clicked the sloth button!")
await interaction.response.edit_message(view=self)```
Edit both, the content and the view in response.edit_message
Saves you api calls and prevents ratelimits
Also faster
That definitely worked, thanks. If I wanted to call a function upon button press, would that be placed here or in the /slash command?
In the button callback
I receive this in console
You are on cooldown. Try again in 47.35s
<class 'discord.ext.commands.errors.CommandOnCooldown'>
In help command subclassed on commands.HelpCommand
but it sends No command called "..." found.
how does this work?
I need the error but it gives me cooldown error in the
async def on_help_command_error(self, ctx, error)
but it sends that message using
async def send_error_message(self, error)
I have this help command setup with all the other methods overridden but not shown here.
class MyHelp(commands.HelpCommand):
def __init__(self):
attrs = {
'cooldown': commands.CooldownMapping.from_cooldown(1, 60, commands.BucketType.member),
'aliases': ['commands'],
}
super().__init__(command_attrs=attrs)
async def on_help_command_error(self, ctx, error):
print(error)
print(type(error))
Ok.
Is that ideal? , I think its a bug.
I cannot help with this one, I always create a custome help command
you can use internal stuff to do it, but not really recommended
the ViewStore has all the active views. which you can access from bot._connection._view_store
https://github.com/Pycord-Development/pycord/blob/master/discord/ui/view.py#L556
discord/ui/view.py line 556
self._views: dict[tuple[int, int | None, str], tuple[View, Item]] = {}```
also i have no idea how it works, so you are out on your own
what is phyner_guild_id ?
also try running the bot from the terminal rather than vscode. ive found that vscode sometimes hides the full traceback
you can subclass the button and then add them. store the number on a self variable and respond with that in the callback
I saw some bots using Postgresql+redis (aioredis) so what's the reason they use both ?? And should i have to do same to solve "x" problems ?
I figured out another way to get all the views with message_id
as View._message is None
How do I fetch the message from the message id?
I don't have the channel or the guild.
So I accidentally perm deleted my bot's folder, and there were some slash commands registered. Is there any way to remove them from the bot?
remove the slash cmds?
I called the disable_all_items() on the View but I cannot find the message to edit the View with.
I only have the message id.
Postgres is used as a correct, accurate and persistent database. While redis is used as a cache. Redis is usually faster for getting single entries than postgres. Some bots store the postgres database on the cloud and not locally. So redis turns out to be much faster. Although the redis cache data can get stale pretty quickly so you have to update it every 30 mins or smth
You can't fetch the message if you don't have channel id. Try if the message is in bot cache
Create a file with no commands and start the bot
You installed py-cord right
Mhm
You must be having environment issues
Confirm that the python version is correct in vscode
Which python version do you have?
Then try python3.11 -m pip install py-cord
Not really
Oh uh
Try py -3.11 -m pip install py-cord
I don't use python on windows sorry lol
actually it's a custom persistent view, so It's not cached.
So what does mean cache ?? I guess it is those things like, members, guilds, channels etc??
And how can I impliment those setup to make improvements in my bot can you please elaborate?
is there a simple way to allow only integers in discord.ui.InputText?
Cache is sort of a collection of the most important parts (columns) of the database. So stuff that you frequently use are stored there for faster lookup
Tbh it doesn't make sense to have a cache for the db unless your bot is very large
Nope. Discord limitation
Can you explain what are those things?
Ohh
How to make a command's option required?
how do i make so only the the author of the slash command can use the select menu?
Compare the id of the interaction user to the author in your callback
dont set required=False and dont set any default value
Im trying to make a script that sends hello world to a webhook
webhook = discord.Webhook.from_url(webhook_url)
but i get this error : TypeError: Webhook.from_url() missing 1 required keyword-only argument: 'session'
How can i send "hello world" to a webhook?
what does it return if multiple user has same username when looking up by username
I believe you have to pass a aiohttp client session too
hey i have made cogs system and done it according to category and how can i list the commands according to the name of cog
for eg if a cog name in utility then it displays only the commands created within the file
does anyone else have problems with slash commands when using those in cogs?
.rtfm cog.walk
do you want this?
no really. what issues are you facing
i tried the cogs out but atm i'm trying to use slash commands at a cog file.
If i'm using the slash command inside the start file from where i load my cogs in, there the slash command works.
But as soon as i put the slash command into a cog, it doesn't work anymore
slash cmds in cogs are written slightly different than that in main file
Here's the slash cog example.
check that
what for slash commands?
and that too
Doesn't work for me either at the cogs
i used to think that includes both, but i dont see that mentioned in the docs
.rtfm bot.walk
discord.Bot.walk_application_commands
discord.ext.bridge.Bot.walk_application_commands
discord.ext.bridge.Bot.walk_commands
discord.ext.bridge.AutoShardedBot.walk_application_commands
discord.ext.bridge.AutoShardedBot.walk_commands
discord.AutoShardedBot.walk_application_commands
discord.ext.commands.Bot.walk_application_commands
discord.ext.commands.Bot.walk_commands
discord.ext.commands.AutoShardedBot.walk_application_commands
discord.ext.commands.AutoShardedBot.walk_commands
you have that ig
how are you loading cogs
dont do that. load cogs just after you have defined the bot
slash cmds internally rely on the on_connect event to register, which is fired before on_ready
okay
hey isnt there anything like i get the cog and then get the commands of the cog
How do i get the interaction user?
interaction.user
Thanks a lot 😘
np 🙃
And the author in the callback?
ctx.author
you will have to subclass view, override the init, accept the author and assign it to a self variable. check if interaction.author == self.author in the callback
and pass ctx.author while creating the view
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
The above exception was the direct cause of the following exception:
Traceback (most recent call last):``` help getting error
If you can't show your code we can't help you
soup = BeautifulSoup(jsu["descriptions"][a]["descriptions"][6]["value"], 'html.parser')
img_tags = soup.find_all('img')
src_values = []
for img in img_tags:
src_values.append(img['src'])
if gname[1] == "True":
for x in src_values:
await ctx.guild.create_custom_emoji(name="example_emoji", image=x)```
full traceback please
Traceback (most recent call last):
File "C:\Users\Siddharth\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 124, in wrapped
ret = await coro(arg)
^^^^^^^^^^^^^^^
File "C:\Users\Siddharth\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 980, in _invoke
await self.callback(ctx, **kwargs)
File "c:\Users\Siddharth\Desktop\code\steam_bot\main.py", line 144, in sell
await ctx.guild.create_custom_emoji(name="example_emoji", image=x)
File "C:\Users\Siddharth\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\guild.py", line 2747, in create_custom_emoji
img = utils._bytes_to_base64_data(image)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Siddharth\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\utils.py", line 658, in _bytes_to_base64_data
mime = _get_mime_type_for_image(data)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Siddharth\AppData\Local\Programs\Python\Python311\Lib\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
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Siddharth\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
discord\commands\core.py", line 375, in invoke
await injected(ctx)
discord\commands\core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: startswith first arg must be str or a tuple of str, not bytes```
the src_values list is like this ['https://steamcdn-a.akamaihd.net/apps/730/icons/econ/stickers/community02/just_trolling.fb233588789ce024c2edff140301948530fe3b67.png', 'https://steamcdn-a.akamaihd.net/apps/730/icons/econ/stickers/illuminate_capsule_01/cheongsam_2_holo.e0aca4521f3fbb5566e5ae34a08faa1dd723aae4.png']
help 😥
- The error tells you what's wrong
- You just revealed your db password
- Never use f-strings for sql queries
for 3, thank you
for 2, thanks (going to change but its no big deal its a test db)
By not available, thats saying it isnt online right
It means the connection failed. And you should always use parameterized queries unless you want your bot to be destroyed by sql injections
Alright thanks.
Was just looking what parameterized queries actualy was, so an SQL queriy outside of the python right?
Nope
no?
wth would "an SQL queriy outside of the python" even mean lmao
Whatever library you're using has a built-in way to parse parameters into your query. Use that instead of mergeing them to the string yourself
okay thanks
just me being stupid
is psycopg2 supported by asyncio and pycord?
Is there a preferred way to 'cache' messages?
I'm using fetch_message recursively if a message has a reference, and those API hits stack up quickly. I'm looking for a way to cache these, maybe with LRU or something else
Nope. Use asyncpg
It's better
With fetch you do every time a API call and you will get a rate limit
LRU cache looks good. Although you should first check if the msg is in bot cache bot.get_message(id)
YOOOO, tytytytytyty
haha, yea exactly!
any way to stop a button from responding? but not give the interaction failed error?
Disable the Button
I think you can use 'None', not sure tbh
alr ty
o ok
Note that it won't disable the button, just won't do anything (saying again im not sure)
I found this helpful resource https://guide.pycord.dev/extensions/commands/help-command for making pretty help commands. It only mentions prefixed commands though, so I'm wondering if there's a way to turn the help command into a slash 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!
how can i check what voice a specific person is in?
member.voice.channel
.rtfm member.voice
.rtfm voicestate
discord.VoiceState
discord.VoiceState.afk
discord.VoiceState.channel
discord.VoiceState.deaf
discord.VoiceState.mute
discord.VoiceState.requested_to_speak_at
discord.VoiceState.self_deaf
discord.VoiceState.self_mute
discord.VoiceState.self_stream
discord.VoiceState.self_video
discord.VoiceState.session_id
discord.VoiceState.suppress
mmm another dumb database question, is it best practice to create a new connection per command? or do you establish a connection on initialization and ensure it's still up each command?
researched it a bit and i think i'm going with the former unless someone has better insight heh
UI question -- if you need to validate a numeric-ish input from a Modal (I know inputs are strings, but assume they will be cast to floats), is there a good way to display that to the user? Just in the message the view is attached to?
Depends on what database you're using and how frequently you're accessing the db
sqlite likely at max 20 commands in a minute?
For sqlite you can keep a persistent connection
if you're using a server based db it's better to just use a connection pool
ok yeah it's just going to be a local db on a small project
mmm is there a way to pass data in a cog to a check? i cant send self.ok_channels because self isnt defined in the decorator
like trying to have a dynamic list of acceptable command channels
@is_command_channel(channels)
feels like i need to have a global variable to pass, doesnt feel right =T
you can do something like
class Foo:
channels = None
def __init__(self, ...):
channels = channels_list
@bar(channels)
async def spam(self):
...
yup
how would a function know that it's a static variable vs creating a function scope variable? if i were to update the data in a function?
or is the convention never to assign it anywhere accept in init?
sorry this is python stuff not pycord stuff heh
you would use Class.static_attribute to change the value of a static variable
or self.__class__.static_attribute
ok, and you didnt do that in your snippet just as an example right? or is it a special case? sorry, and thanks
well, I didn't do it in my snippet because I forgot one has to mutate the value of a static variable in a special way.
np thanks a bunch i'll figure the rest out 🙂
still having issues, I think it has to do with the check being set up the time it's defined and at that time the data is None, i'm having no issues accessing the static anywhere in the class but still blows up when the check is run =T
I'll probably take a break, need to go play board games and check back with a fresh head
ok, last minute tooling around, just doesnt work because the check is in a separate file, works fine if the check is in the same file as the cog.
i guess I'd have to import the cog's class and access the static variable like that? seems wonky but wouldnt be the first time
what if you use made your own check that could access the static variable
One of the most appealing aspects of the command extension is how easy it is to define commands and how you can arbitrarily nest groups and commands to have a rich sub-command system. Commands are ...
yeah it works in the same file, but I think i'm doing something dumb
like this works
import discord
from discord.ext import commands
#from checks.IsCommandChannel import is_command_channel, NotCommandChannel
class NotCommandChannel(commands.CheckFailure):
pass
def is_command_channel():
async def predicate(ctx):
#if ctx.channel_id in MyCog.CONFIG[str(ctx.guild.id)]['command_channels']:
if ctx.channel_id in MyCog.CONFIG['command_channels']:
return True
raise NotCommandChannel()
return commands.check(predicate)
class MyCog(commands.Cog):
CONFIG = None
def __init__(self, bot):
self.bot = bot
MyCog.CONFIG = {'command_channels': 12345678910}
@commands.slash_command(name = "hello", description = "Say hello to the bot")
@is_command_channel()
async def hello(ctx):
await ctx.respond("Hey!")
async def cog_command_error(self, ctx: commands.Context, error: commands.CommandError):
if isinstance(error, NotCommandChannel):
await ctx.send_response(content=f"You cant perform that command in this channel, {ctx.command} - {ctx.selected_options}")
else:
raise error
but i havent been able to put the check in another file and then do
@is_command_channel(CONFIG)
just says config is none when the check is ran
i looked up some stackoverflow stuff suggesting i wrap the decorator but it's already being wrapped and i think pycord is looking for specific stuff from it and it's making my head spin trying to work from that angle heh
looks like I'd have to do something to recompile the check code at runtime which looks pretty technical heh
How do you create forms with pycord ?
Here's the modal dialogs example.
ooh thanks !
I get this error when sending a view: Forbidden: 403 Forbidden (error code: 50001): Missing Access
NoneType: None
class MyView(discord.ui.View):
@discord.ui.button(label="Modal Test", style=discord.ButtonStyle.primary)
async def button_callback(
self, button: discord.ui.Button, interaction: discord.Interaction
):
modal = MyModal(title="Modal Triggered from Button")
await interaction.response.send_modal(modal)
@discord.ui.select(
placeholder="Pick Your Modal",
min_values=1,
max_values=1,
options=[
discord.SelectOption(
label="First Modal", description="Shows the first modal"
),
discord.SelectOption(
label="Second Modal", description="Shows the second modal"
),
],
)
async def select_callback(
self, select: discord.ui.Select, interaction: discord.Interaction
):
modal = MyModal(title="Temporary Title")
modal.title = select.values[0]
await interaction.response.send_modal(modal)
class RecurrentRoleCog(WriteCog):
def __init__(self, bot):
super().__init__(bot)
@slash_command(guild_ids=guildIds, description="Add a new recurrent time role")
@discord.default_permissions(manage_roles=True)
async def add_recurrent_time_role(self, ctx: discord.ApplicationContext):
view = MyView()
await ctx.send("Click Button, Receive Modal", view=view)
Do you know what can be causing it ?
this is code from the exemple on the git
ctx.respond and do you have intents?
Im not really sure if you need intents for this
hey how do i use walk slash command through the discord.bot thing
i meant cog thing
?
Repeating this
I believe you would have to modify
https://github.com/Pycord-Development/pycord/blob/master/discord/ext/commands/help.py#L1004
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/help.py at master · Pycord-Development/pycord
discord/ext/commands/help.py line 1004
async def send_pages(self):```
And also register the cmd as a Slash cmd
Thanks
Is there a way to get an event if the user clicks cancel in a modal?
nope. discord limitation from what i remember. you will have to rely on timeout
:/ really stupid if you have a command with a max_concurrency...
But thanks :D will do it via the timeout
Is Thread.total_messages_sent an estimation and cached or a real value that is sent by discord? I having some troubles were it is not incrementing.
await ctx.respond(embed=em, ephemeral=True)
?? doesnt work if anyone can help me would be lovely
.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.
unexpected key word.. ephemeral.
Show pip version
pip?]
pip 22.3.1 from C:\Users\
await ctx.send(embed=em, ephemeral=True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Messageable.send() got an unexpected keyword argument 'ephemeral'
its mabey just a respond?
like ctx.respond instead
nvm its a respond already
Do you know basic python?
Sorry i meant pip list 💀
Look at the two errors
Yea code different from error. He is using ctx.send not ctx.respond
is there a simple way to schedule a coroutine to a certain time (eg 5min) ?
i've searched but haven't found anything convenient
Do you mean you want to loop it every 5 mins?
nope just once
await asyncio.sleep(5*60) ?
I would create a function that accepts a time to wait in seconds and a coroutine. In the function, i would sleep for the time and then await the coroutine
also i can just run the said function and it will not freeze right ?
(sorry for the dumb questions but i wanna make sure)
well it does, i will search further by myself, thx for your help
its not bad at all. Although there are some low level loop calls which offer a similar behaviour, it is always recommended to use higher level asyncio
how can i make a member select menu?
how many members do you wanna add to it?
just one
add, not select
then is that a select menu?
yep
Are you sure that the choices that someone wants to select from, only contain one person?
app_commands?
do you use discord.py
this is the py-cord server not discord.py
you would have to check it at your own
else no
pls go to the discord.py server
but it would be interaction.user
I disable all button, but they dont go gray, they stop working tho as I want
How would I make sure they go disable
you need to edit the message after disabling them
another stupid question
how can i update the permissions of a voice channel im in?
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 ...
how did you define that button?
hmm ic, so it wasn't a child of the view when the view was constructed.
class MyView(discord.ui.View):
def __init__(self):
super().__init__(
ButtonCallModal(
DateModal(
... ,
title="Start date form", update_co=self.on_update
),
label="Select start date (default = now)", style=discord.ButtonStyle.primary
),
ButtonCallModal(
TimeModal(
...,
title="Start time form", update_co=self.on_update
),
label="Select start time (default = 00h00:00s )", style=discord.ButtonStyle.primary
),
ButtonCallModal(
DeltaModal(
...,
title="Time interval form", update_co=self.on_update
),
label="Select time interval", style=discord.ButtonStyle.primary
),
discord.ui.Button(label="Approve", style=discord.ButtonStyle.success, disabled=True, row=2)
)
self.interaction = None
self.data = {}
self.children[3].callback = self.approve_callback
here is the code
for init
it was a child of the view when constructed !
could you print the value of self.children in any one of the callbacks??
yess !
[<ButtonCallModal style=<ButtonStyle.primary: 1> url=None disabled=False label='Select start date (default = now)' emoji=None row=1>, <ButtonCallModal style=<ButtonStyle.primary: 1> url=None disabled=False label='Select start time (default = 00h00:00s )' emoji=None row=1>, <ButtonCallModal style=<ButtonStyle.primary: 1> url=None disabled=False label='Select time interval' emoji=None row=1>, <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Approve' emoji=None row=2>]
there is the 4 buttons
plus that approve button start as disable, and is enable when all the data is set
but I cant redisable it
try using ```py
for child in self.children:
child.disabled = True
instead of `self.disable_all_items()`
same effect
it is possible you can only disable one time a button ?
could you print the value of self.children again after this
maybe
[<ButtonCallModal style=<ButtonStyle.primary: 1> url=None disabled=False label='Select start date' emoji=None row=1>, <ButtonCallModal style=<ButtonStyle.primary: 1> url=None disabled=False label='Select start time (default = 00h00:00s )' emoji=None row=1>, <ButtonCallModal style=<ButtonStyle.primary: 1> url=None disabled=False label='Select time interval' emoji=None row=1>, <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Approve' emoji=None row=2>] [<ButtonCallModal style=<ButtonStyle.primary: 1> url=None disabled=True label='Select start date' emoji=None row=1>, <ButtonCallModal style=<ButtonStyle.primary: 1> url=None disabled=True label='Select start time (default = 00h00:00s )' emoji=None row=1>, <ButtonCallModal style=<ButtonStyle.primary: 1> url=None disabled=True label='Select time interval' emoji=None row=1>, <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Approve' emoji=None row=2>]
ooh yeah, he dose not get disable
it is still as false
for last button

what is self.on_update()?
it just update a embed
async def on_update(self):
self.update_data()
year = self.data.get("year")
month = self.data.get("month")
day = self.data.get("day")
hours = self.data.get("hours")
minutes = self.data.get("minutes")
seconds = self.data.get("seconds")
days_delta = self.data.get("days_delta")
hours_delta = self.data.get("hours_delta")
minutes_delta = self.data.get("minutes_delta")
seconds_delta = self.data.get("seconds_delta")
current_date = None
if year is not None and month is not None and day is not None:
current_date = date(year=year, month=month, day=day)
current_time = timedelta(seconds=0)
if hours is not None and minutes is not None and seconds is not None:
current_time = timedelta(hours=hours, minutes=minutes, seconds=seconds)
current_interval = None
if days_delta is not None and hours_delta is not None and minutes_delta is not None and seconds_delta is not None:
current_interval = timedelta(days=days_delta, hours=hours_delta, minutes=minutes_delta, seconds=seconds_delta)
if current_date is not None and current_time is not None and current_interval is not None:
self.children[3].disabled = False
embed = discord.Embed(title="Create a reccurent time role",
description=f"Use the button to set information \n Current value: **delete the role __ starting at {current_date} at {current_time} each {current_interval}**")
embed.set_footer(text="This is a premium feature. Server under 200 member can still use it")
await self.interaction.edit_original_response(embed=embed, view=self)
oooh, I see the problem, I put disable at false in that method 😄
I am dumb

thanks you for your help !
thanks
but i dont know how to select the channel
what do you know about the channel?
wdym?
i mean like i did this
voice = ctx.author.voice
i know the voice
https://github.com/Pycord-Development/pycord/blob/master/examples/views/role_select.py
just like this but @discord.ui.user_select
voice.channel should give you the channel then
no i mean like where should i add it in the line
await set_permissions(name,view_channel=True)
Can I only reopen the modal via a button or can I have it reopen automatically after 5 seconds?
class AddSpot(discord.ui.Modal):
def __init__(self, bot, interaction):
super().__init__(
title = "Trage deinen Spot ein",
timeout=300,
)
self.bot = bot
self.interaction = interaction
self.user = discord.ui.InputText(
label="Spot eintragen",
min_length=2,
max_length=30,
required=True,
placeholder="Trage deinen Spot im Format 100:100 hier ein"
)
self.add_item(self.user)
async def callback(self, interaction: discord.Interaction) -> None:
spot = self.user.value
pattern_spot = re.compile(r'^([1-9]\d{0,1}|200):([1-9]\d{0,1}|200)$')
if not pattern_spot.match(spot):
embed = discord.Embed(
title="Fehler",
description="Spot muss im Format '100:100' eingegeben werden. Der Maximalwert beträgt '200:200'"
)
await interaction.response.send_message(embed=embed)
await interaction.response.send_modal(AddSpot(self.bot, interaction.channel))
self.view.add_item(AngelArt(self.bot))
await interaction.response.edit_message(view=self.view)```
await voice.channel.set_permissions(...)
can you please elaborate
...
ah i saw my mistake
no i deleted a part for some reason
I open this modal. A text is entered there and it is checked for the format.
If the required format was not entered, a message appears that the format was wrong and then the modal should open again to be able to enter the value again.
oh haha
ah. you cant send a modal as a response to another modal (discord limitation)
Although you can send a message with a button that sends a modal
smart to have it recursive like you did
Exactly that was my first idea but just wanted to ask if it can be done differently 🙂
But thanks! 🙂
np 👍
How can I fix the error?
AttributeError: 'AddSpot' object has no attribute 'view'```
```py
class AddSpot(discord.ui.Modal):
def __init__(self, bot, interaction):
super().__init__(
title = "Trage deinen Spot ein",
timeout=300,
)
self.bot = bot
self.interaction = interaction
self.user = discord.ui.InputText(
label="Spot eintragen",
min_length=2,
max_length=7,
required=True,
placeholder="Trage deinen Spot im Format 100:100 hier ein"
)
self.add_item(self.user)
async def callback(self, interaction: discord.Interaction) -> None:
spot = self.user.value
pattern_spot = re.compile(r'^([1-9]\d{0,1}|200):([1-9]\d{0,1}|200)$')
if not pattern_spot.match(spot):
embed = discord.Embed(title="Fehler",
description=f"Spot muss im Format '100:100' eingegeben werden. Der Maximalwert beträgt '200:200'",
color=discord.Color.blurple()
)
await interaction.response.send_message(embed=embed, view=ModalAgain(self.bot))
self.view.add_item(AngelArt(self.bot))
await interaction.response.edit_message(view=self.view)```
Just self
Self is already your view
no, self is the modal, not the view
what are you trying to do?
modal is not a view. you would need to create a new view
Oh lol. Thought it was ui.View 
After I have checked the content in the modal and the format is correct, a dropdown menu should be called.
where is self.view being created?
I'm preparing to ditch the commands module in favor of the new integration for slash commands, is there anything I should be aware of?
Other than that prefixes won't work anymore
we're here if you have any issues
otherwise have fun
Fair, just didn't know if there was a standard boilerplate of "while you're fixing the code, don't do this"
Here:
class Setup_SpotInsert(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.persistent_views_added = False
@commands.Cog.listener()
async def on_ready(self):
if not self.persistent_views_added:
self.bot.add_view(InsertSpot(self.bot))
self.persistent_views_added = True
@slash_command(description="Spot System einrichten")
async def setup_spotinsert(self, ctx):
embed = discord.Embed(title=f'Herzlich Willkommen!',
description=f"""Wenn du einen Spot eintragen möchtest drücke bitte auf den "📃 Spot eintragen" Button!\n Anschließend wirst du durch den Prozess geführt.""",
color=ORANGE)
embed.set_thumbnail(url=f"{ctx.guild.icon}")
await ctx.respond(embed=embed, view=InsertSpot(self.bot))```
nothing much. somethings that are good to know are that you have to send a response within 3 seconds. if you might take longer (eg you have some api call), you should first defer the interaction, do your stuff, and then send a followup
I'm reading the core api, is @bot.slash_command() necessary? I thought it was just bot.command for the core api
If you're using a discord.Bot instance, bot.command will get registered as a slash command, otherwise it'll be a prefixed command if you're using commands.Bot instance
Straight up, is there even an issue with still using the commands module? I guess I heard it was getting deprecated but I never confirmed this.
There's no point using the commands module if you're using application commands other than permissions checks
Core doesn't have permissions checks? O: oh.
Suppose I could code my own but that's like, overhead and stuff...eh. Thanks for the help, maybe I'll hold off and just use slash_command.
Oh. I'll have to look into it O:
oh and dont forget to check out the guide
.guide
pretty cool too
I mean, I already have the bot made, just trying to figure out what I want the next version to be. Thanks though, I'll check it out :D
Right now I'm integrating openai, which is fun.
nice
from what i remember, openai uses requests library, so you might want to wrap its function calls inside asyncio.to_thread
That's...a really good idea, actually. I'm utilizing both GPT-3 and the content filtering endpoints so 🤔
can anyone tell what am i doing wrong?
its supposed to be a temp vc but it doesnt make a vc
does that event even exist
wdym?
no i made it up
then how will it run-
That's not how cog listeners work :l
you can specify a name in the decorator tho
i have a main file somewhere else...
Can I get an int value instead of a string?
i can only find discord.py tutorials online lmao
?tag file
No tag file found.
Sometimes you have to do things without tutorials
Cog listeners "listen" for an event, in the most bastardized way I can put it.
nope. discord accepts a string. you can convert it to an int tho
.localfile
waa
one sec
how can i do them without knowing how?
How do i make my bot start "typing" in a channel? I remember using async with ctx.typing(): but is there any better way? my bot does not support slash commands as the client doesn't want slash commands
Learn how to program
The following section outlines the API of Pycord. Table of Contents: Version Related Info, Client Objects, Application Commands, Cogs, Application Info, Voice Related, Event Reference, Utility Func...
API reference is your best friend.
?tag localfile
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)```
Not so helpful... >.>
It's the truth
its useful to know how to program before using a lib like pycord
damn
didnt know i had to do that
I didn't say it wasn't. I said it wasn't helpful. :D
it is the same as async with channel.typing():
alright thx
We have enough resources like the docs, examples and guides. Don’t be lazy.
I'm not the one it was directed at lol. I just said it wasn't helpful.
I have the API reference bookmarked for a reason. :P
Ye because you won’t get help otherwise. We don’t teach programming
@uneven beacon
It doesn't make sense to use a complex library without knowing the basics first. It's like trying to play a really difficult song on the guitar without knowing the basic techniques first.
If it doesn’t even was in response to you then you aren’t in any position to say so as we literally wrote that fact down in the help rules ;)
bro
i read the on_voice_stats_update part (the thing i wanted to know about) about a couple of times before asking it here
did that before
Then we have https://pycord.dev/tias for ya
ask bill wurtz to voice it for you
train an ai to sound like bill wurtz to voice it
hey!
im new to pycord
i was just wondering how can i use move_to in an event?
async def on_voice_state_update(member,ctx):
await member.move_to(temp)
it gives me an error
'voice' object has no attribute 'move_to'
ah
then what is it?
Read the docs
i saw it
thanks for the help
what libary should i use for flask discord oauth2?
use quart and make your own
quart implements asyncio
flask is also with asyncio
https://github.com/discord/discord-oauth2-example/blob/master/app.py
is this still recommend to use and safe?
it works
youtube, xy, wavelink, virtualembed, usercmd, unofficialguide, um_cmds, tryitandsee, tokens, token, timer, tias, tcr, tca, tags, tagrules, swasvid, subcommands, sslfix, sqli, solved, snowflake, slashcommandmention, rie, restartcmd, requests, replit-install, replit, removeall, pythonserver, python, paste, partial_objects, oracle, option, oop, official, objects, notpycord, norepl, nojson, nohelp, nohello, name-conventions, mybot, msgcmd, mongodb, modal, missing_access, message-content, lp, localfile, learnpython, json, intents, install_slash, install_git, install, inline-fields, importerror, idw, ide, how2sql, helpgist, guide, getalpha, get_x, get-help, fork, forbidden, exception, examples, ex, ephemeral, eh, docs, discord.app, discord.Bot, deploy, commandnoshow, colors, codeexamples, codeblock, closing, client, buttons2, buttonlimit, bridge, breaking-changes, botvar, bitwise, asset, applicationcommands-registration-delay, announcement_channel_options, aiohttp, activedevbadge, Woc, Timestamps, DMChannel
The library name is py-cord not pycord
yea i was thinking the error is from a diff part
view=like() how to add dislike
You can only add one view to a message. You can have multiple buttons in one view tho.
how do i determine if a member has a certain permission? i coudnt find anything in the docs, copilot suggested ctx.author.has_permission("permission") but that didnt work either
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 ...
ty
You can do fastapi too
bridge.bridge_command()
async def play(self, ctx, *video):
this command works as a prefixed command(*args for spaced arguments) but doesnt as a slash command i think because having infinite args for a slash command doesnt make sense(error: discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: Voice.play() got an unexpected keyword argument 'video') is there a easy way around this or is the best option to just not use bridge in this case
Wdym by infinite args?
Also, what is voice.play?
It doesn't seem to be related to bridge cmds at all
its a bridge.command in a cog called voice
the *video
Can you show code and full error traceback
Why would you need * for it tho 🤔
Also, check out Greedy
.rtfm greedy
discord.ext.commands.Greedy
discord.ext.commands.Greedy.append
discord.ext.commands.Greedy.clear
discord.ext.commands.Greedy.converter
discord.ext.commands.Greedy.copy
discord.ext.commands.Greedy.count
discord.ext.commands.Greedy.extend
discord.ext.commands.Greedy.index
discord.ext.commands.Greedy.insert
discord.ext.commands.Greedy.pop
discord.ext.commands.Greedy.remove
discord.ext.commands.Greedy.reverse
discord.ext.commands.Greedy.sort
was the only way i could figure out to take a argument with spaces
relevent code
@bridge.bridge_command()
async def play(self, ctx, *video):
args = list(video)
channel = ""
for arg in range(len(args)-1):
if args[arg] == "-channel" or args[arg] == "-c":
channel = discord.utils.get(ctx.guild.channels, name=args.pop(arg+1)).id
args.pop(arg)
break
error:
Ignoring exception in command play:
Traceback (most recent call last):
File "/home/ion/.local/lib/python3.11/site-packages/discord/commands/core.py", line 124, in wrapped
ret = await coro(arg)
^^^^^^^^^^^^^^^
File "/home/ion/.local/lib/python3.11/site-packages/discord/commands/core.py", line 976, in _invoke
await self.callback(self.cog, ctx, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Voice.play() got an unexpected keyword argument 'video'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/ion/.local/lib/python3.11/site-packages/discord/bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/ion/.local/lib/python3.11/site-packages/discord/commands/core.py", line 375, in invoke
await injected(ctx)
File "/home/ion/.local/lib/python3.11/site-packages/discord/commands/core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: Voice.play() got an unexpected keyword argument 'video'
It's not like that. It's (self, ctx, *, video)
Try that
Also typehint video as str
that fixes it
whats the difference between *video and *,video?
*video is just a variable name
While pycord interprets the other one as you saw above
Hello there!
Is is possible to build a message or a modal, where both buttons and textinputfields are present? In the Modal I can insert Textinputfields, but no buttons and in a message it is vice versa, so that I can not insert Inputtextfields in a view. Somebody knows how to implement this? 😦
Discord only alows text input as of now. I think they are working on an update to allow buttons.
Traceback (most recent call last):
File "/home/ec2-user/.local/lib/python3.9/site-packages/discord/client.py", line 377, in _run_event
await coro(*args, **kwargs)
File "/home/ec2-user/.local/lib/python3.9/site-packages/discord/bot.py", line 1164, in on_connect
await self.sync_commands()
File "/home/ec2-user/.local/lib/python3.9/site-packages/discord/bot.py", line 719, in sync_commands
registered_commands = await self.register_commands(
File "/home/ec2-user/.local/lib/python3.9/site-packages/discord/bot.py", line 599, in register_commands
registered = await register("bulk", data, _log=False)
File "/home/ec2-user/.local/lib/python3.9/site-packages/discord/http.py", line 366, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In options.1: Required options must be placed before non-required options
How do I check which bridge command this is?
how can i fix this? ( its a temp vc event )
1-the delete part is broken
2-i want to make the vc get deleted when it hase 0 members in it
Above that there should be more error?
there isn't much
Only this Ignoring exception in on_connect
I guess look through all of your command functions and make sure all required options are before optional options.
I don't get it, what does it mean?
Does it refer to this?
async def command(arg2=None,arg1):
To fix the error you need to use the delete function on the channel object. There is no such thing as guild.delete_channel
.rtfm guildchannel.delete
Yes, the first is optional and will defualt to none the second is required. All required need to go first. That includes Options, if you specify requied=false it needs to go after the rest.
...
You can check if no one is inside with this
https://docs.pycord.dev/en/master/api/models.html#discord.VoiceChannel.members
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 ...
ohhhh thanks : D
i read the article
but it doesnt tell a way to use it..
That would delete the guild. You want to delete the channel.
chan is a guildChannel object. You need to call delete on it.
oh i had a typo
sorry
A "property" is always used like this instance_of_class.property
In your case you want to do chan.members
ah i see
but where should i use it?
im kinda new to pycord...
Ignoring exception in on_connect
Traceback (most recent call last):
File "/home/ec2-user/.local/lib/python3.9/site-packages/discord/client.py", line 377, in _run_event
await coro(*args, **kwargs)
File "/home/ec2-user/.local/lib/python3.9/site-packages/discord/bot.py", line 1164, in on_connect
await self.sync_commands()
File "/home/ec2-user/.local/lib/python3.9/site-packages/discord/bot.py", line 719, in sync_commands
registered_commands = await self.register_commands(
File "/home/ec2-user/.local/lib/python3.9/site-packages/discord/bot.py", line 599, in register_commands
registered = await register("bulk", data, _log=False)
File "/home/ec2-user/.local/lib/python3.9/site-packages/discord/http.py", line 366, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 64: Application command names must be unique
now what's this 64, Is this the command serial number?
That will give you a list of all members in the voice channel. If the length of that list is 0 you know it is empty
Im not sure, but somewhere you have 2 commands named the same thing. Do you by chance have a help command (/help)?
i know that
i mean like i should use that line in an if?
That would make the most sense so you could compare it to 0.
But a property is basically a variable for a class instance. You can use it in an if statement or pass it to a function and so on.
Another 2 things you are using this decorator @bridge.bridge_command?
And you are not running add_bridge_command or similar
I'm not running add_bridge_command yes.
and I'm using @bridge.bridge_command
thanks
is there an article about properties and a couple of examples so i can understand it better?
For making discord bots you will want to understand object oriented programming (OOP) this might help
https://realpython.com/python3-object-oriented-programming/
This includes properties.
ok, thx. 🙂 So is it possible to use text input fields anywhere else than in a modal? My Use case is the following: I need to read in user input within a channel (not via private message), such that no one else in the channel can see this message.
Unfortunately no
Buttons/select menus can be used on a message
Text input can be used in a model
Options, autocomplete, "text input" (as in the argument takes a string) can be used in a command.
I think discord is working on adding more features to components but we have not got a major update in a few months relating to components so I'm not sure how long you will have to wait.
Trust me I am waiting for some of these features on my bot as well.
I have seen someone do a workaround using private threads and wait_for
hey
i made a temp vc event but i cant make it to delete the channels it has made
it doesnt even give any errors
Hey, how can I deafen the bot when it joins a voice channel?
Say you send view1 ephemerally once you click it, it'll send in view2 ephemerally too, I have noticed that once view1 gets timed out, view2 will stop interacting, is this an intended cause?
bruh why this isnt working
.rtfm guild.clone
Target not found, try again and make sure to check your spelling.
Cause it doesn't exist? Xdnt?
Sounds like an error with your code. Views are separated shouldn't depend on each other
bruh
then how should i do it?
i just want to clone a channel...
I mean you just have to create another channel with the same name and permissions
.rtfm channel.clone
Or use it on the correct object 
is it stpud to ask .... what will be the correct object?
If you can't read the embed, that's not my problem
i did but i didnt understand it
maybe a sample would help?.....
.rtfm context.channel
I've used bridge commands
How can I edit a button if there are multiple instances of ToggleButton in my view?
class ToggleButton(discord.ui.Button):
def __init__(self, label: str, value: bool, emoji: str or None):
super().__init__(
label=label,
style=discord.ButtonStyle.red if value else discord.ButtonStyle.green,
emoji=emoji
)
self.value = value
async def callback(self, interaction: discord.Interaction):
# change the button's style
...
.
self.style?..
Why are you getting the channel when you already have it in the event?
That doesn't edit the button
yes it does
uhhhh
good point
but i dont think that solves my issue
You need to edit the message and pass the view again. It doesn't magically update
on_voice_state_update doesn't have a ctx
It's member, before, after
.rtfm on_voice_state_update
and channel.members is never going to be None.
Yeah, and using await interaction.edit_original_response(view=self.view) says unknown webhook
oh
then how should i know when noone is in the voice?
Check if the list is empty? Read through the docs before asking questions here please
maybe i did and i couldnt find the thing i was looking for?
i changed ctx with member now it doesnt even move / create the vc
interaction.response.edit_message?
That works the first time you click it, then it goes back to the unknown webhook error
.rtfm self_deafen
Target not found, try again and make sure to check your spelling.
.rtfm self_deaf
Hmm, I don't have any errors on my end, I'll double check
Does adding more shards to a bot require a restart?
shards?
iirc, no
alright good
THE PROBLEM THAT I DONT HAVE A CARD
Then you need to get a card, or deal with using crappy hosts
Parents?
Freinds?
Freinds parents?
All probably have cards u could use
MY COUNTRY DOESNT SUPPORT ONLINE PAYMENTS
there are only card that u can only use in algeria and no other countries
okay relax, you could buy a raspberry pi
whats that?
A single chip computer that's out of stock basically everywhere
oh rip
I guess your only options are self-hosting or using a shitty free host
or find a way to bypass your restrictions
gimme an example of a shitty free host
🤷♂️

replit
I know one but it does have limitations
oh hell no
google discloud, I really don't know how good is it compared to other free ones but it's alright
there are discloud :0
is you're bot public or for one server
uh in more than 1000+ server
i was parterned with a discord server for free hosting
and now they canceled the deal
now im broke ;-;
you're bot won't get in many new servers as of yet if it's new
your*
its not new
i was using a host from a parterned servr
now they canceled the deal
and you'll probably struggle finding a free host that can handle more than 1k servers
not nessesary but sure
i guess discloud is good
necessary* 
idk if discloud going to handle that but sure

Never heard of it, sounds pretty sketchy
I haven't used it much and idk what specs are good
yes
means you have azure right?
no?
google cloud?
no
dang it
you can have free rdp if you verify an azure account
you cold host bot with it but no credit card :0
bot.guilds returns a list of the guilds the bot is in
[tls @ 0x562f44513cc0] Error in the pull function.
[https @ 0x562f445115c0] Will reconnect at 3014640 in 0 second(s), error=Input/output error.
is this a pycord error?
just randomly happens to my bot
every ~10 minuts
No
how do i delete a message that was in dms and i know the id?
Is there a way to ephemerally respond to an on_raw_reaction_add()/RawReactionActionEvent?
Unfortunately not, since ephemeral messages are based on interactions (e.g. slash commands, buttons, etc)
How do I add a check to a cog?
create the check and below the @commands.slashcommand() just do your @check()
or is it a check for all commands?
I know how to add a check to an individual command. I've read that it's possible to do a "cog-wide" check
Yes
hmm yea, it's clear from the documentation for a bot, but cant do self on the check
I did find Cog.cog_check, but I'm wondering if there's anything like a Cog.add_check type feature
like dynamic checking?
Not really. Same as Bot.add_check, only scoped to individual cogs
It might be possible, though, for me to just do self.cog_check = commands.guild_only (or whatever individual check I want)
oh you'd do self.cog_check(guild_only) right?
not too experienced to know if a check IS an commands.Context though but that should be a quick check on a test
I'll play around with it in a bit
It looks to me like you have to implement it yourself, but I suppose I could be misreading it
oh yeah that makes sense you just implement the function in your cog
it's like capturing check errors, but i guess you can only have one cog_check function
Is there a limit on the total amount of slash commands you can have on a discord bot?
You can have 100 global commands, and each command can have up to 25 sub-command groups. Each sub-command group can have up to 25 sub-commands.
100 x 25 x 25 = 62.5k
Of course, "slash commands can have a maximum of 4000 characters for combined name, description, and value properties for each command and its subcommands and groups", so you're not likely to hit that 62.5k command limit (because every command would have an average of 6.4 characters).
You can also multiply this number by two if you register the bot's commands in every guild as guild commands.
How do sub commands work?
Here's the slash groups example.
Thanks! How do I use them in a cog?
Here's the slash cog groups example.
Doth bridge have a commandnotfound handler
You need to wrap the code into a code block.
What is this
A response message...telling you that you need to wrap your code in a code block.
Ofc, but the bot itself
A support bot...
Does it just straight up run code?
No
lol
is there an event that will listen for the trigger of any other event? Im looking for a simple way to keep track of how often my bot is "detecting" something with a listener, other than adding a function to each command that writes the count data to a file.
len(bot.guilds)
bot is your client object.
Can I define how long a modal's text input must be?
the simplest method i can think of would be to change the description of the text field to show the character limit, then check if the response is greater than that limit, if it is then produce an error. Im not sure there is an official method of doing this.
are you saying you want smth like this 💀
@bot.event
async def on_event(...) #fake example. not a real thing
...
ngl i never thought of this lmao
did i interpret your question correctly? or did you mean something else?
this is exactly what im looking for! how did I not think of this? haha
wait
yea but that would not work lol
yeah just realized that XD
okii
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...
it's the simplest way to implement
this looks perfect, ill give it a go
Although it has almost all the events, so filter out the ones you want
I want all! haha
lmao alr
So im not sure if im implementing this properly? Could you explain the proper way to use this?
My attempt:
@commands.Cog.listener()
async def on_socket_event_type(on_presence_update):
try:
try:
with open("interaction_count") as e:
num = int(e.read())
except:
num = 0
num = num + 1
with open("interaction_count", "w") as f:
f.write(f"{num}")
except:
print(f"Failed to count this interaction!\n\n{traceback.format_exc()}")```
Error:
```TypeError: Listeners.on_socket_event_type() takes 1 positional argument but 2 were given
Ignoring exception in on_socket_event_type
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 377, in _run_event
await coro(*args, **kwargs)```
you would need self as the first parameter. also the next parameter would be event_type which is a string. it would only be the name of the event
ahh that would make sense
so smth like async def on_socket_event_type(self, event_type: str):
also, dont use a text file. use a database
I see, that makes a lot more sense
this was just to get it working, thanks!
i suggest sqlite. dont use txt or json
Even more odd.. ive completely removed the on_socket_event_type yet it still continues to trigger this errored event somehow 🤔 there's definitely not multiple sessions running so i dont even know where its pulling this error from now... time to do some digging
I even attempting using an old backup of the file the command was in what the heckkk. on_socket_event_type no longer exists in my bot yet is still producing errors 
wow so i used the same code on a separate test bot and do not get the error. But it seems my main bot cannot get rid of this error for some reason. I even changed the token thinking maybe there were multiple sessions running.
I notice an error loading the cog on startup, it seems the cog is never being unloaded when the bot goes offline somehow... I get a cog already loaded error on startup.
I am making a command that muste a message at the beginning and at the end of the method I modify the first message, but I get an error.
@commands.slash_command
async def prueba(ctx):
# send menssge "test"
message = await ctx.send("test")
# safe id
message_id = message.id
# code
# ...
# modify by id
await ctx.message.channel.fetch_message(message_id).edit(content="final test")
hi
i need some help in
https://discord.com/channels/881207955029110855/1069923002252267601
() at the end and use ctx.respond
6
@proud mason any alternative method? i need to check it directly from the modal, not after submitting
Don't cross post
Its possible to specify length in inputtext object.
https://docs.pycord.dev/en/master/api/ui_kit.html#discord.ui.InputText.min_length
The library has helpers to help create component-based UIs. Shortcut decorators: Objects: Attributes children, disable_on_timeout, message, timeout. Methods cls View.from_message, def add_item, def...
How can I make it so that when I change the letter in 'LetterFish', the dropdown menu of 'Fish' is refreshed instead of being resent as a message?
class BuchstabeFischView(discord.ui.View):
def __init__(self, bot: discord.Bot):
self.bot = bot
super().__init__(BuchstabeFisch(self.bot))
class FischView(discord.ui.View):
def __init__(self, bot: discord.Bot, selected_letter: str):
self.bot = bot
self.selected_letter = selected_letter
super().__init__(Fisch(self.bot, self.selected_letter))
class BuchstabeFisch(discord.ui.Select):
def __init__(self, bot: discord.Bot):
self.bot = bot
options = [discord.SelectOption(label=letter) for letter in ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y"]]
super().__init__(
placeholder="Wähle den Anfangsbuchstaben von deinem Fisch aus",
min_values=1,
max_values=1,
options=options,
)
async def callback(self, interaction: discord.Interaction):
selected_letter = self.values[0]
await interaction.response.send_message(view=FischView(self.bot, selected_letter))
class Fisch(discord.ui.Select):
def __init__(self, bot: discord.Bot, selected_letter):
self.bot = bot
options = [discord.SelectOption(label=fish) for fish in bot.fische if fish.startswith(selected_letter)]
super().__init__(
placeholder="Wähle deinen Fisch aus",
min_values=1,
max_values=1,
options=options,
)
async def callback(self, interaction: discord.Interaction):
await interaction.response.send_modal(AddSpot(self.bot, interaction.channel))```
You can edit the message with the dropdown.
how can i fix this?
Would it work like that?
if message:
await message.edit(view=FischView(self.bot, selected_letter))
else:
message = await interaction.response.send_message(view=FischView(self.bot, selected_letter))```
That looks like it would work, just dont get message confused with self.message because they would be different
No channel in that guild exists with the name you provided.
I do not understand exactly what you mean 🤔
Your code looks like it will work ignore what I said, I just made it confusing.
Then how do I define message beforehand?
class BuchstabeFisch(discord.ui.Select):
def __init__(self, bot: discord.Bot):
self.bot = bot
options = [discord.SelectOption(label=letter) for letter in ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y"]]
super().__init__(
placeholder="Wähle den Anfangsbuchstaben von deinem Fisch aus",
min_values=1,
max_values=1,
options=options,
)
async def callback(self, interaction: discord.Interaction):
selected_letter = self.values[0]
if message:
await message.edit(view=FischView(self.bot, selected_letter))
else:
message = await interaction.response.send_message(view=FischView(self.bot, selected_letter))```
you know that the limit are 25 fields?
I guess you could do self.attached_message = None in the __init__ The name is changed so you do not override the built in self.message
there is no z
oh, nvm
Try useing ID instead of name and also try this
https://docs.pycord.dev/en/stable/api/utils.html#discord.utils.get_or_fetch
How can I edit the message correctly?
Do I have to bold the message first to be able to edit it?
if self.attached_message:
await self.attached_message.edit(view=FischView(self.bot, selected_letter))```
``` File "c:\Users\User\Documents\Coding\OnlyFrames\cogs\spot.py", line 64, in callback
await self.attached_message.edit(view=FischView(self.bot, selected_letter))
AttributeError: 'Interaction' object has no attribute 'edit'```
What is self.attached_message
You use interaction.edit_original_response to edit the msg
What am I doing wrong?
class BuchstabeFisch(discord.ui.Select):
def __init__(self, bot: discord.Bot):
self.bot = bot
self.attached_message = None
options = [discord.SelectOption(label=letter) for letter in ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y"]]
super().__init__(
placeholder="Wähle den Anfangsbuchstaben von deinem Fisch aus",
min_values=1,
max_values=1,
options=options,
)
async def callback(self, interaction: discord.Interaction):
selected_letter = self.values[0]
if self.attached_message:
await interaction.edit_original_message(view=FischView(self.bot, selected_letter))
else:
self.attached_message = await interaction.response.send_message(view=FischView(self.bot, selected_letter))```
i can only save the id as an int
but its giving me this error
How do I keep a variable when using for example button interactions?
Like for example a page counter, or the time since you pressed the button. How do I keep the session going and just wait for a response without discarding where the execution currently is.
asking this as a quick question as I assume I just need the right link to where to read up
same issue with get_or_fetch
I mean use id instead of name when getting the channel.
Subclassing the view and using an instance varible.
WoW! I have zero clue what that means, but I'll get to readying, thank you
Don't use the example I just showed its not a good one
Here's the tic tac toe example.
This is a good example at line 60ish ^
like this?
1st line yes. But the next line put it back how it was. No id. You already have the ID you need to object.
I have now solved it like this. How can I make it so that I can always delete and recreate the message when I change the selection in the dropdown menu?
class BuchstabeFisch(discord.ui.Select):
def __init__(self, bot: discord.Bot):
self.bot = bot
self.attached_message = None
options = [discord.SelectOption(label=letter) for letter in ["A", "Ä", "B", "C", "D", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "Ö", "P", "Q", "R", "S", "T", "U", "V", "W", "Z"]]
super().__init__(
placeholder="Wähle den Anfangsbuchstaben von deinem Fisch aus",
min_values=1,
max_values=1,
options=options,
)
async def callback(self, interaction: discord.Interaction):
selected_letter = self.values[0]
if self.attached_message:
await self.attached_message.delete_original_response()
await interaction.response.send_message(view=FischView(self.bot, selected_letter))
else:
self.attached_message = await interaction.response.send_message(view=FischView(self.bot, selected_letter))```
Make sure channel is an int
But I gtg now
how?...
idk. use interaction.edit_original_response
the error and code dont seem to match
change it to this
if self.attached_message:
await self.attached_message.delete_original_response()
self.attached_message = await interaction.response.send_message(view=FischView(self.bot, selected_letter))
what is channel ?
channel = f'{member.name}`s room'

ok so
since you have the name and not the id, you would have to use utils.get
my bad for asking you to switch
use utils.get on guild.voice_channels
.rtfm guild.voicee_ch
Target not found, try again and make sure to check your spelling.
.rtfm guild.voice_ch
Oh thank you, clear logical
||when your keyboard is broken 💀||
If I have several dropdown menus one after the other and want to have all selected contents at the end, can I solve the whole thing more elegantly than passing the values from each dropdown to the next view?
hey, how would i setup an error handling for missing permission?
figured it out
nvm, i cant seem to figure out how i can remove the this command did not respond
im getting this error this is my code
Yeah i read that
but where am i even sending an empty message
okay
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.
.rtfm member.send
What do you mean? You are getting a specific user. And responding if they are online or offline
So what is wrong
Lowercase s in status
And it's not a coroutine
.rtfm user look at the attributes and you will see everything
discord.User
discord.User.accent_color
discord.User.accent_colour
discord.User.avatar
discord.User.banner
discord.User.bot
discord.User.can_send
discord.User.color
discord.User.colour
discord.User.create_dm
discord.User.created_at
discord.User.default_avatar
discord.User.discriminator
discord.User.display_avatar
discord.User.display_name
discord.User.dm_channel
discord.User.fetch_message
discord.User.history
discord.User.id
discord.User.jump_url
I am very new to this. I have the latest version of python as well as pycharm. when I try to make a new project it dose not allow me to code. I think it is the configuration but I am not sure
Is there any way to check if I have 1 or 2 dropdown menus in a view?
I want to continue if there is only one dropdown menu after selecting a property and if there are 2 dropdown menus I want to continue only after selecting something in the second dropdown menu.
class FischView(discord.ui.View):
def __init__(self, bot: discord.Bot, selected_letter: str, gewaesser):
self.bot = bot
self.gewaesser = gewaesser
self.selected_letter = selected_letter
super().__init__(Fisch(self.bot, self.selected_letter, gewaesser))
@discord.ui.button(label='➕ Weiteren Fisch hinfügen', custom_id="TestButton", style=discord.ButtonStyle.primary)
async def start_button(self, button: discord.ui.Button, interaction: discord.Interaction):
self.add_item(Fisch2(self.bot, self.selected_letter, self.gewaesser))
await interaction.response.edit_message(view=self)
class Fisch(discord.ui.Select):
def __init__(self, bot: discord.Bot, selected_letter, gewaesser):
self.bot = bot
self.gewaesser = gewaesser
options = [discord.SelectOption(label=fish) for fish in bot.fische if fish.startswith(selected_letter)]
super().__init__(
placeholder="Wähle deinen Fisch aus",
min_values=1,
max_values=1,
options=options,
)
async def callback(self, interaction: discord.Interaction):
await interaction.response.send_modal(AddSpot(self.bot, interaction.channel, self.gewaesser, self.values[0]))
class Fisch2(discord.ui.Select):
def __init__(self, bot: discord.Bot, selected_letter, gewaesser):
self.bot = bot
self.gewaesser = gewaesser
options = [discord.SelectOption(label=fish) for fish in bot.fische if fish.startswith(selected_letter)]
super().__init__(
placeholder="Wähle deinen Fisch aus",
min_values=1,
max_values=1,
options=options,
)
async def callback(self, interaction: discord.Interaction):
await interaction.response.send_modal(AddSpot(self.bot, interaction.channel, self.gewaesser, self.values[0]))```
Wdym by does not allow you to code 💀
view.children has all the items. You can check it's length. Or iterate over it if you have other stuff in it too
.rtfm view.children
Target not found, try again and make sure to check your spelling.
discord.ui.View
discord.ui.View.add_item
discord.ui.View.clear_items
discord.ui.View.disable_all_items
discord.ui.View.enable_all_items
discord.ui.View.from_message
discord.ui.View.get_item
discord.ui.View.interaction_check
discord.ui.View.is_dispatching
discord.ui.View.is_finished
discord.ui.View.is_persistent
discord.ui.View.message
discord.ui.View.on_check_failure
discord.ui.View.on_error
discord.ui.View.on_timeout
discord.ui.View.refresh
discord.ui.View.remove_item
discord.ui.View.stop
discord.ui.View.to_components
discord.ui.View.wait
can i do a slash command that is a reply to a message?
like i want to click reply, then type a slash command as the reply
i've tried already but the slash command doesn't pop up, only the builtins do
You can't
Why does my loop not start and I always get the error message that my Channel_ID is missing although both values are printed correctly?
Unhandled exception in internal background task 'update_events'.
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/ext/tasks/__init__.py", line 169, in _loop
await self.coro(*args, **kwargs)
TypeError: update_events() missing 1 required positional argument: 'channel_id'
@bot.event
async def on_ready():
bot.waters = await dab.get_waters()
bot.fische = await dab.get_fisch()
for guild in bot.guilds:
data = await dab.get_calender(guild.id)
if data[0] != None:
channel_id = data[0]
print(guild.id)
print(channel_id)
calender.Calender.update_events.start(guild.id, channel_id)
class Calender(commands.Cog):
def __init__(self, bot):
self.bot = bot
@tasks.loop(minutes=10)
async def update_events(self, guild_id, channel_id):
I want to pass an argument to a select list so that it is different every time the command is run. Is that possible?
Yes. Pass it to the init
class ThisView(discord.ui.View):
def init(self, select_list):
super().init()
self.assignments = select_list
for item in self.assignments:
discord.ui.View.add_item(self, discord.ui.Select())
@discord.ui.select(
placeholder="Select an assignment",
options=[discord.SelectOption(label="Select:", value="Select")])
@full basin how would i do it here?
Why are you "creating" new selects for each item
Don't you want different select options depending on the items passed?
You have to subclass the select menu
how do i do that?
Just like you subclassed the View but now a Select?
.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)
It's useless for me to help you out if you don't know what it does.
Try learning the basics of python and OOP.
That’s not supported in the command. That will take so long to add, so I’m not going to add it.
👍
i wish there was a way to get the username of a webhook message
I may be overthinking it, but is there a way to hide a button without outright removing it (so I don’t have to try inserting it back in)?
I have other UI elements that may change the availability of the button and while I can disable it, it would look better if it’s just hidden
pop it from self.children?
that would make it easy to insert again
I’d have to reference it by position in self.children when inserting it back?
yeah
unless you append it
No, need a specific position. Thanks for the thought!
Ick. Continuing on this path, is there any better ways of getting an element other than the children list? Definitely not super elegant.
oh wait, I guess I can at least search it by name since it's directly defined by decorator, as far as collecting the index.
I'm sure my logic is terribad (help? in my defense, it's super late), but unless I'm doing something super-wrong, this does seem a little overcomplicated. But it does look kinda nice; the button displays when relevant and doesn't otherwise.
class MyView(discord.ui.View):
...
def toggle_value_button(self, hide=True):
if hide:
if self.hidden.get(self.token_value):
return
value_button_idx = self.children.index(self.token_value)
value_button = self.children.pop(value_button_idx)
self.hidden[value_button] = value_button_idx
else:
# Restore it
idx = self.hidden.get(self.token_value)
if not idx or self.children[idx] == self.token_value:
return
self.token_value.disabled = False
self.children.insert(idx, self.token_value)
del self.hidden[self.token_value]
...
@discord.ui.button(label='Value', custom_id='value_button', style=discord.ButtonStyle.primary, emoji='🪙', row=2)
async def token_value(self, button: discord.ui.Button, interaction: discord.Interaction):
modal = TokenAmountModal(view=self, input_type='value')
await interaction.response.send_modal(modal)
Why does my loop not start and I always get the error message that my Channel_ID is missing although both values are printed correctly?
Unhandled exception in internal background task 'update_events'.
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/ext/tasks/__init__.py", line 169, in _loop
await self.coro(*args, **kwargs)
TypeError: update_events() missing 1 required positional argument: 'channel_id'
@bot.event
async def on_ready():
bot.waters = await dab.get_waters()
bot.fische = await dab.get_fisch()
for guild in bot.guilds:
data = await dab.get_calender(guild.id)
if data[0] != None:
channel_id = data[0]
print(guild.id)
print(channel_id)
calender.Calender.update_events.start(guild.id, channel_id)
class Calender(commands.Cog):
def __init__(self, bot):
self.bot = bot
@tasks.loop(minutes=10)
async def update_events(self, guild_id, channel_id):
Where do you start it?
ctx and discord interaction don't seem to go together. what can I use instead of ctx?
For what?
For example to get a guild icon
The @bot.Event is in the Main.py and the class Calender is in the calender.py cog
It can happend, that the icon is none
I know, but I'm looking for something like ctx
That works fine with interactions
But where do you start the "update_event"
For slash commands?
Yes
Here's the slash basic example.
Thanks
When I restart the bot it should start the loop automatically.
No?
module 'discord' has no attribute 'ApplicationContext'
Can you show the pip list?
Why no?
did you add to the task "await self.bot.wait_unitil_ready()"?
Yes
The full pip list pls
?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
Wait a sec. I got a package
I really should switch to my pc...
It seems to work now. Thanks ❤️

I will. Thank you
Pretty sure you can't start the loop from main.py if it is in a cog
Either start the loop in cog init or in an on ready listener in the cog
Replit automatically installs discordpy whenever I run the repl
How can I stop this from happening?
?tag replit
Read this to find out how you can install Pycord in Replit
Old instructions: https://web.archive.org/web/20211128084858/https://namantech.me/pycord/installation/#replit
New instructions: #998272089343668364 message
Okay if I do that in the init then the loop is not started automatically when the bot is restarted or do I have that wrong?
For this I am then forced to fall back on a listener in the class or?
Thanks. I tested everything and It works perfectly! Thank you ❤️
Do you have the presence intent?
Do you load the cogs when your bot restarts?
Yes:
if __name__ == "__main__":
for filename in os.listdir("cogs"):
if filename.endswith(".py"):
bot.load_extension(f"cogs.{filename[:-3]}")
load_dotenv()
bot.run(os.getenv("BOT_TOKEN"))```
So yes. The task loop will restart
If I start it in the init in the cog?
Yes
But I need the query if the Guild ID and the Channel ID are in the database because otherwise the loop can't start because the data is missing. What is the best way to do this in the init?
for guild in bot.guilds:
data = await dab.get_calender(guild.id)
if data[0] != None:
channel_id = data[0]
calender.Calender.update_events.start(guild.id, channel_id)```
Attach the database to a bot var
.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
Just like that in main.py right?
@bot.event
async def on_ready():
for guild in bot.guilds:
data = await dab.get_calender(guild.id)
if data[0] != None:
bot.channel_id = data[0]
bot.guild_id = guild.id ```
No. Attach the database to a bot var
smth like bot.dab = dab
And then use the database in the cog init
Oh wait. You can't await in init
So you need a task loop to start a task loop 💀
Okay, so an on_ready event after all?
Then just like that?
class Calender(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
for guild in self.bot.guilds:
data = await dab.get_calender(guild.id)
if data[0] != None:
channel_id = data[0]
self.update_events.start(guild.id, channel_id)```
Oh yeah that works
It worked but after restarting the bot I now get this error message:
I do not know why I have not changed anything 😄
File "/home/Bot/Bot/utils/database.py", line 49, in get_calender
await cursor.execute("SELECT Calender_ChannelID, Calender_MessageID FROM config WHERE GuildID = %s", (guild_id))
File "/home/Bot/.local/lib/python3.8/site-packages/aiomysql/cursors.py", line 239, in execute
await self._query(query)
File "/home/Bot/.local/lib/python3.8/site-packages/aiomysql/cursors.py", line 457, in _query
await conn.query(q)
File "/home/Bot/.local/lib/python3.8/site-packages/aiomysql/connection.py", line 469, in query
await self._read_query_result(unbuffered=unbuffered)
File "/home/Bot/.local/lib/python3.8/site-packages/aiomysql/connection.py", line 672, in _read_query_result
await result.read()
File "/home/Bot/.local/lib/python3.8/site-packages/aiomysql/connection.py", line 1153, in read
first_packet = await self.connection._read_packet()
File "/home/Bot/.local/lib/python3.8/site-packages/aiomysql/connection.py", line 618, in _read_packet
raise InternalError(
pymysql.err.InternalError: Packet sequence number wrong - got 1 expected 7
If I remove the on_ready event again everything works without error message but the loop does not start again.
Hmm smth with aiomysql
Try searching on google
I use the following to connect to the database. Is this where my error lies?
On the internet it says something about single and multithreading 🤔
async def get_db_conn():
if not hasattr(get_db_conn, "conn"):
get_db_conn.conn = await aiomysql.connect(host=host,port=port,user=user,password=password,db=db)
return get_db_conn.conn```
Oh hmm
How do you get dab? Try using bot vars instead of global variable or importing dab
I have a database.py where the connection is inside and with the functions I then access the connection:
async def get_db_conn():
if not hasattr(get_db_conn, "conn"):
get_db_conn.conn = await aiomysql.connect(host=host,port=port,user=user,password=password,db=db)
return get_db_conn.conn
async def get_calender(guild_id):
db_con = await get_db_conn()
async with db_con.cursor() as cursor:
await cursor.execute("SELECT Calender_ChannelID, Calender_MessageID FROM config WHERE GuildID = %s", (guild_id))
result = await cursor.fetchone()
await cursor.close()
return result```
Since I have to read out something from the database every now and then.
I'm just wondering if I should switch the whole thing to multithreading so that multiple accesses to the database are possible at the same time?
Would this solve my problem?
async def get_db_conn():
if not hasattr(get_db_conn, "conn"):
get_db_conn.conn = await aiomysql.connect(host=host,port=port,user=user,password=password,db=db, loop=loop)
return get_db_conn.conn
async def get_calender(guild_id):
async with get_db_conn(asyncio.get_event_loop()) as db_conn:
async with db_con.cursor() as cursor:
await cursor.execute("SELECT Calender_ChannelID, Calender_MessageID FROM config WHERE GuildID = %s", (guild_id))
result = await cursor.fetchone()
await cursor.close()
return result```
What lib do you use for db?
import aiomysql```
You might need to look at pooling your connections. Search up "connection pool in aiomysql"
How your code is it is a small change to use pools.
Okay and with pools I can use multiple connections to DB at the same time?
Yes it is a "pool" of available connections that you use than return to the pool.
Okay that works 🙂
async def get_db_conn():
if not hasattr(get_db_conn, "conn"):
get_db_conn.conn = await aiomysql.create_pool(host=host,port=port,user=user,password=password,db=db, minsize=1, maxsize=10)
return get_db_conn.conn
async def get_calender(guild_id):
pool = await get_db_conn()
async with pool.acquire() as db_con:
async with db_con.cursor() as cursor:
await cursor.execute("SELECT Calender_ChannelID, Calender_MessageID FROM config WHERE GuildID = %s", (guild_id))
result = await cursor.fetchone()
return result```
And to make it simpler you can have get db conn return a connection instead of the whole pool
Now that I’m awake when others are, any thoughts to this approach? Can I simplify this (or maybe redo it a different way I’m not considering)?
The context is removing a button when not needed and restoring it otherwise. Now that I’ve slept, I realize maybe I don’t even need to store the button (just the location) since the instance isn’t removed from self?
How can I do that? 🙂
So ?
async def get_db_conn():
if not hasattr(get_db_conn, "conn"):
get_db_conn.conn = await aiomysql.create_pool(host=host,port=port,user=user,password=password,db=db, minsize=1, maxsize=10)
pool = get_db_conn.conn.acquire()
return pool
async def get_calender(guild_id):
async with get_db_conn() as db_con:
async with db_con.cursor() as cursor:
await cursor.execute("SELECT Calender_ChannelID, Calender_MessageID FROM config WHERE GuildID = %s", (guild_id))
result = await cursor.fetchone()
return result```
You could manually add the item to the view. This seems a lot less complicated that what you have.
.rtfm view.add_item
That looks right, but if it dosent work switch back to what you had and disregard my suggestion.
Okay 😄
Thank you!
Does not work 😄
Add_item doesn’t have a position. The button needs to go in a specific slot
I was avoiding hardcoding the slot just in case other layout changes happened
how would i check if a member has permission over another member
so basically just checking if said member is able to ban/kick/timeout the other member
nvm i figured it out
im an idiot lmao
I'm guessing that in the case of discord generating an embed for a link that you can't listen to on_message and just look for .embeds[0] because the adding of the embed doesn't happen immediately? Can't figure out why else message.embeds[0].description wouldn't seem to work in on_message
Is there any way to disable + edit the button's label after submitting a modal?
Yes. Just set the properties on the button in your callback.
I am still sorta figuring it out, but I think you have to pass in your View as an argument to your Modal constructor so it can access it.
So something like
self._view.mybutton.disabled = True
i need help 🥹 . My bot give me this error: discord.errors.InvalidArgument: Could not resolve appropriate move position
But whyy?
piece of my code: await ctx.channel.move(category=get(ctx.guild.categories, name="closed"))
Can you try if that works with fetch message. Just checking if link embeds even show up in message.embeds
I realized what I was looking for wasn't in embeds[0]
it seems to work as I'd expect after I changed that
Turns out the problem was between keyboard and chair all along
-
In modal callback:
Add self.stop at the end -
In button callback :
Add modal.wait after sending the modal https://docs.pycord.dev/en/stable/api/ui_kit.html#discord.ui.Modal.wait
Then disable the button and edit original response with the updated view
Do you have the id of the category? If you do, use ctx.guild.get_channel(id) and try if that fixes it
Also, full traceback please
How can i receive inputs along with my slash commands?
how would i set the colour of my embed?
.rtfm Embed.colour
async def test(self, ctx):
try:
server_list = []
for server in ctx.bot.guilds:
server_list.append(f"Name: {server.name}, Member Count: {server.member_count}")
if len(server_list) > 2000: #split into two messages if more than 2000 servers
await ctx.send("\n".join(server_list[:2000]))
await ctx.send("\n".join(server_list[2000:]))
else:
await ctx.send("\n".join(server_list))
except Exception as e:
await ctx.respond(":warning: There was an error, this has been reported to staff.")
print(e)```
400 Bad Request (error code: 50035): Invalid Form Body
In content: Must be 2000 or fewer in length.
Read the error?
Check out slash options
Here's the slash options example.
It turns out it works on subsequent repostings of the same link which tricked me, possibly because the discord server caches the to-be contents of the link embed, so it shows up in embeds[0]. Maybe there's no way to do it cleanly through pycord without fetching each message, which I think is an API call for each, which seems undesirable
is there a way to make a task loop to ack like the listener on_message. so the task starts when start command is sent and stops when the stop command is sent?
Well, you could do my_task.start() when the start command is run and my_task.stop() when the stop command is run
However, if the task is still executing some code, it will continue until it is complete, but it won't run again after stop is run if that makes sense
I more meant the on_message imitation part
wdym?
But thank you
yw

