#Basic Pycord Help
1 messages · Page 32 of 1
that is so awful omg
did no one ever think of changing this lmao
or is this a discord limitation
¯_(ツ)_/¯
embeds really need some love
they're good enough
@vestal folio bitte versuch mehr die docs zu benutzen, sonst lernst du es nicht zu finden
sehr wahr
Die Suche ist seltsam
Wenn man nach was bestimmtem sucht bekommt man alles mögliche
Es gibt sogar ein * FELD* das nennt sich suche
Die hab ich verwendet
und deine IDE hat auch autocomplete
das setzt vorraus dass man weiß dass die methode der guild gehört
das ist bei den docs nicht der fall :)
man kann auch falsch suchen
außerdem bekommt man in internationalen discords üblicherweise schneller hilfe wenn man english spricht :>
it is, but i got it
Use typing. Plsss
Like ctx: discord.ApplicationContext
It will look 10 times better and help you a lot
i love the "who asked" reaction when its literally a big help
i mean still no way
like there is a lib in js
i repeat again,
- against the ToS
- no point in doing that
and if you really wanted to, you would've just googled it
Congrats on being dumb enough to ask how to break the ToS in a server with discord staff
I dont think they read the chat here
Otherwise more people would get slappin here
Funny enough pycord (or discord py) was capable to this stuff earlier, even when its not documented.
Unless lala or the core devs didnt removed it
But ill not grappin in my toybox to tellin you how
when did pycord make interaction: discord.Interaction not valid for slash commands? I used to have a bot where this worked, I came back to it and now i guess using pycord 2.5 these commands no longer work so i've started to switch over to ctx: discord.ApplicationContext
related question, i have some code to send a modal that's initially triggered by a slash command, it used to work since the modal wanted an Interaction, but now since attaching the a cog w/ "Interaction" slash commands errors, i've had to change it over, and now i'm stumped, as await self.sendModal(ctx, poll, name, title, self.bot) doesn't seem to like me using ctx instead of interaction
because it's not an interaction in that way
It's literally the same thing passed lol, doesn't matter what name you give the variables
hm ok
my ide warned me that it was unexpected, ill just try to run it and see what happens
anyway i was just confused because these commands definitely used to work probably like 8 months ago
we use discord.ApplicationContext for commands
Is there a way to create polls in pycord? Or is it not implemented yet?
is there a way to add a single callback to all buttons in a view?
that for example grabs the custom id of the button that was pressed
button.callback = function() should do it
embeds has a maximum of 10 elements.
what does this mean?
pages_indv = [
build_embed(
title=f"{response[i]}",
description='desc')
for i in range(0, len(response), 20)
]
pages_grp = [
pages.Page(
embeds=pages_indv[i],
custom_view=ViewListPaginator(response[i:i+20]),
) for i in range(0, len(pages_indv))
]
group = [
pages.PageGroup(
pages=pages_grp,
label="All",
default=True,
author_check=True
),
pages.PageGroup(
pages=pages_grp,
label="All - 2",
default=False,
author_check=True
),
]
paginator = pages.Paginator(
pages=group,
show_menu=True
)
await paginator.respond(ctx.interaction)
Thats how im doing it
?
related to this error
solved
i was passing the embeds without it being a list
pages_grp = [
pages.Page(
embeds=pages_indv[i],
custom_view=ViewListPaginator(response[i:i+20]),
) for i in range(0, len(pages_indv))
]
fixing:
pages_grp = [
pages.Page(
embeds=[pages_indv[i]],
custom_view=ViewListPaginator(response[i:i+20]),
) for i in range(0, len(pages_indv))
]```
there is a PR but as the API has not been confirmed yet there could still be breaking changes so the PR will not be merged until there is not possibility of breaking changes
class ViewListPaginator(View):
def __init__(self, response):
super().__init__()
# row definido aqui
item_list = [Button(label=f"{i+1}",custom_id=response[i]["id"]) for i in range(0, len(response))]
for item in item_list:
item.callback = button_callback
self.add_item(item=item)
async def button_callback(self, interaction:Interaction):
print(self.custom_id)
Error:
File "C:\Codes\YoruScans\venv\Lib\site-packages\discord\ui\view.py", line 426, in _scheduled_task
await item.callback(interaction)
^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: button_callback() missing 1 required positional argument: 'interaction'```
the function button_callback has interaction argument already
any hints on solving this?
oh thanks!
Hi, is it possible to start bot with some proxy between me and discord??
connect your vps to a proxy
https://paste.pythondiscord.com/AYVQ no errors and no prints pls help
i am tring to send an image but i am getting a n response
await ctx.respond(file=discord.File(fp=f"test.png"))
wie kann ich ein e art kanal auswahl in slash command setzen
so was nur in slash commands
you know if you would ask that in english many would help you way faster
ich hab keine lust auf Englisch
dann musst du wohl warten
discord.Option
discord.Option.autocomplete
discord.Option.channel_types
discord.Option.choices
discord.Option.default
discord.Option.description
discord.Option.description_localizations
discord.Option.input_type
discord.Option.max_length
discord.Option.max_value
discord.Option.min_length
discord.Option.min_value
discord.Option.name
discord.Option.name_localizations
discord.Option.required
Und dann einfach nen Channel
wiedermal wäre es schneller gewesen die Docs zu lesen
i am not able to send a image and it's giving me a error
NotFound: 404 Not Found (error code: 10062): Unknown interaction
async def test(self, ctx):
img=discord.File(fp="ac.png")
await ctx.respond(file=img)
try with await ctx.defer() as the first line
your internet might be too slow to send it in time
yes it's slow..
thenks, you fixed it
Hi, Im trying to make /ping command. that working but bot response message "The application did not respond". Don't have any error log in console.
My code:
# commands/ping.py
from discord.ext import commands
class Ping(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.slash_command(name="ping", description="Check bot's latency")
async def ping(self, ctx):
latency = round(self.bot.latency * 1000) # Convert to milliseconds
await ctx.send(f'Pong! Latency is {latency}ms.')
def setup(bot):
bot.add_cog(Ping(bot))
#bot.py
# ...
for filename in os.listdir('./commands'):
if filename.endswith('.py'):
bot.load_extension(f'commands.{filename[:-3]}')
print(f'Loaded: {filename[:-3]} command')
# Run the bot
bot.run(TOKEN)
You never respond
you just send a message to the channel
use ctx.respond
Thank you, I got it. That working now 😄
I'm getting this error and none of it is my code aside from the bot.run(TOKEN):
Traceback (most recent call last):
File "/app/main.py", line 263, in <module>
bot.run(TOKEN)
File "/usr/local/lib/python3.10/site-packages/discord/client.py", line 766, in run
return future.result()
File "/usr/local/lib/python3.10/site-packages/discord/client.py", line 745, in runner
await self.start(*args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/discord/client.py", line 709, in start
await self.connect(reconnect=reconnect)
File "/usr/local/lib/python3.10/site-packages/discord/shard.py", line 475, in connect
raise item.error
File "/usr/local/lib/python3.10/site-packages/discord/shard.py", line 180, in worker
await self.ws.poll_event()
File "/usr/local/lib/python3.10/site-packages/discord/gateway.py", line 603, in poll_event
await self.received_message(msg.data)
File "/usr/local/lib/python3.10/site-packages/discord/gateway.py", line 555, in received_message
func(data)
File "/usr/local/lib/python3.10/site-packages/discord/state.py", line 818, in parse_interaction_create
interaction = Interaction(data=data, state=self)
File "/usr/local/lib/python3.10/site-packages/discord/interactions.py", line 171, in __init__
self._from_data(data)
File "/usr/local/lib/python3.10/site-packages/discord/interactions.py", line 201, in _from_data
self._guild = Guild(data=self._guild_data, state=self)
File "/usr/local/lib/python3.10/site-packages/discord/guild.py", line 307, in __init__
self._from_data(data)
File "/usr/local/lib/python3.10/site-packages/discord/guild.py", line 515, in _from_data
cache_joined = self._state.member_cache_flags.joined
AttributeError: 'Interaction' object has no attribute 'member_cache_flags'
what are you doing that causes that
Show your pip list
It just happens on a shard reconnection
there is already a topic about it #1218470644216234045
stay in one channel pls
Bruh
APScheduler==3.9.1
git+https://github.com/Pycord-Development/pycord.git
GitPython==3.1.42
PyYAML==6.0.1
python-dateutil==2.8.2
aiohttp==3.9.3
rsa==4.9
I was going to delete this question from there since I don’t think it’s related
master is probably broken
is this https://discord.com/channels/881207955029110855/1230482053104144475 a bug we should report somewhere?
Hi, does pycord support user applications ?
Not yet.
thanks
Soon
thanks
is it possible to only display certain arguments of a command if another one was set with a specific value?
example:
mode has image and text as options, I want to display the aspect_ratio argument only if mode has been set to image
no
you are not the first one I saw with that Idea
I also had it in mind
depending on the exact setup, you can maybe create command groups
yeah I'm using command groups already xD
I'll just separate the command into 2
thanks!
alright ^^
I just have the conditional argument as optional for the command and handle it accordingly
Should I open an issue on GitHub?
@shell radish ?
is there a way to know which commands it is ?
Ignoring exception in on_connect
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 400, in _run_event
await coro(*args, **kwargs)
File "/home/container/.local/lib/python3.11/site-packages/discord/bot.py", line 1178, in on_connect
await self.sync_commands()
File "/home/container/.local/lib/python3.11/site-packages/discord/bot.py", line 735, in sync_commands
registered_commands = await self.register_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/bot.py", line 599, in register_commands
registered = await register("bulk", data, _log=False)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/http.py", line 373, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 1.options.0.options.4: Option names are not unique in locale en-GB
In 1.options.0.options.5: Option names are not unique in locale en-GB
In 1.options.0.options.7: Option names are not unique in locale en-GB
probably the one you just changed
that's the point, i changed every single one ;)
time to do so one by one
neverrrrrrrrr
then do it binary search style
im way too lazy to do that 19 times
i will do a for command in ... bot.sync_commands
It's possible it's wrong for all of them :)
it tell me only for 3
In 1.options.0.options.4: Option names are not unique in locale en-GB
In 1.options.0.options.5: Option names are not unique in locale en-GB
In 1.options.0.options.7: Option names are not unique in locale en-GB
wait
Options 4,5,6 not command
i have no command with 4 options
does subcommands appear has option ?
Sorry, I'm not sure on that one
Hi guys. Any example of ephemeral=True response with ctx.defer()? Without defer() it works fine. Thanks for the help!
you have to also add it to the defer
Do you can send me example? 🙏🏻
literally just pass it in the defer like you do in your message
Thanks, but this works for the whole command. I have if/else statements and I want to allow sending in one ephemeral=True, but not in the other. Is it possible to do this with ctx.defer()?
you cant un-ephemeral something, no
if the defer is ephemeral the response has to be, too
Yes, I mean this one
So it's impossible?
depending on your code, you can try to defer as late as possible before the things that take a lot of time
Like, do pre-checks to then correctly defer ephemerally or not if possible
Thanks man. U helped me!
Have a nice day
np
After the bot is running for less than 1 day, it crashes. I get this error message:
this is only happening with the new version py-cord==2.5.0
its a problem with bridge stuff
I think you need to replace Option with discord.BridgeOption
which ones ?
the decorator, or the ones in the Type
no idea about the decorator
ideally you shouldnt mix the way you do it anyway tho
but change the typehint versions and see if it works
yeah I have both, some is old code that I did not want to change all 😄
Is it not the same issue I had here?
#1132206148309749830 message
oh that is exactly this yes
so there is a fix in master
Apparently. I haven’t had mine crash randomly since. Just fun shard reconnections for seemingly no reason
dev branch will be dev branch
Which commit did you use ?
I’ve just been using the latest
I see will try that thank you !
Correction the reconnections have been happening since before I switched from 2.5.0 so I wouldn’t blame it on the dev branch
class MyModal(discord.ui.Modal):
def __init__(self, interaction: discord.Interaction, verifyconfigmodal, db_conn: psycopg2.extensions.connection, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.db_conn = db_conn
self.guild_id = interaction.guild.id
cursor = db_conn.cursor()
sql_query = f"""
SELECT verification_questions, channel_id
FROM guild
WHERE guild_id = '{self.guild_id}';
"""
cursor.execute(sql_query)
result = cursor.fetchone()
cursor.close()
if result:
verification_questions, channel_id = result
if isinstance(verification_questions, list):
questions_list = verification_questions
elif isinstance(verification_questions, str):
questions_list = verification_questions.split(';')
self.add_item(discord.ui.InputText(label=question1, placeholder="Example: coolEp1cGamer69"))
self.add_item(discord.ui.InputText(label=question2))
self.add_item(discord.ui.InputText(label=question3))
self.add_item(discord.ui.InputText(label=question4))
This is the code I am trying to add to my app, I want to get the values inside the table in sql and assign them to the label inside a modal, this is the traceback im getting:
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
In data.components.1.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
In data.components.2.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
In data.components.3.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
I assume its a problem with the sql data being assigned to the label, how would i fix this
Are your self.add_items indented correctly? You might be adding the input text to the view by accident
how should they be indented?
wait, nevermind, discord was just making them wrap lines
so the error is saying you are trying to put an input text on a view. You must have excluded some code in your message, so I think my original point stands. The self.add_items should be indented into the __init__ of the modal
This is the rest of the modal code:
async def callback(self, interaction: discord.Interaction):
embed = discord.Embed(title="Verification Questions:", color=0xe91e63)
embed.add_field(name="Username:", value=self.children[0].value, inline=False)
embed.add_field(name="Age:", value=self.children[1].value, inline=False)
embed.add_field(name="How did you find this server?", value=self.children[2].value, inline=False)
embed.add_field(name="Will you follow the rules?", value=self.children[3].value, inline=False)
username = interaction.user.id
channel = bot.get_channel(placeholder)
await interaction.response.send_message("Thank you, we will review your submission!", ephemeral=True)
await channel.send(embed=embed, view=StaffVerify(username))
and this is the class that sends the modal:
class MyView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.add_item(discord.ui.Button(label='Help', style=discord.ButtonStyle.link, url='https://mercury-bot.vercel.app'))
@discord.ui.button(label="Verify", custom_id="button-1", style=discord.ButtonStyle.success)
async def button_callback(self, button, interaction):
guild_id = interaction.guild.id
interaction.response.defer()
db_conn = psycopg2.connect(
database="placeholder",
host="placeholder",
user="placeholder",
password="placeholder",
port="placeholder")
modal = MyModal(interaction, verifyconfigmodal=None, db_conn=db_conn, title="Verify!")
await interaction.response.send_message(embed=None, view=modal)
to send a modal interaction has its own method
interaction.response.send_modal which only takes the modal
and you cant defer the interaction in the button, modals cant be a follow up (plus, defer is a coroutine aka awaitable)
is it possible to remove a timeout for a user
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
yep i read the docs haha
How to pycord ?
Isn’t remove_timeout ?
Or both work
How can i solve ssl 1006?
(tried with .tag sslfix) but doesn't work
im using win10
how do I pass an image as argument to a slash command?
I've been using Option but idk what type I must pass there for it to accept (if possible)
discord.Attachment is the proper type
thank you!
I'm trying to get pycord to run the basic example script but I run into No module named 'discord'
I'm on win10
Have you installed pycord
yes, I actually just fixed the error. Now I'm getting that token must be of type str, not NoneType
I'm not exactly where I'm supposed to put the .env file with my token in it
Show your code without the token
basically you tojen is not in the getenv
where do I put the .env file so it’ll get found?
I have that in my .env already
you have token = or TOKEN =
you need to have the TOKEN like that
TOKEN
archivist_token.env
name it .env
or u can do
load_dotenv('archivist_token.env')
@sonic onyx does it work now ?
Yea it seems to be working
How can i purge messages since an id?
Like idk every message after message id 2 in my discord channel
fetch the message
get the message datetime
then use channel history with before=message time
and delete
message.created_at
.
How to get the shard_id of the instance ?
my goal :
for guild in self.bot.guilds:
if guild.shard_id != self.bot.shard_id:
continue
self.bot.shard_id return always None, even if the bot have more than 1 shard
?
Did you read it? There is no shard_id attribute
There still is or it will raison the error bot has no attribute shard_id
And whatever I wanna find a way to find the shard_id of the instance even if it’s doesn’t come from shard_8:
that's not how it works
what do you even need
you already have the shard id of the guild no?
Im using a loop function
That is trigger for each instance
So with only fro guild in self.bot.guilds, it will do the action 4 times for each guilds
And not only 1
Hey everyone,
Are there any listeners/decorators I can use to run a piece of code every time a slash command is being executed? Let's say I want to log every command used, do I have to include the logging function call in every slash command I write or is there a more generic approach like a listener (similar to let's say on_message)?
discord.on_application_command
discord.on_application_command_completion
discord.on_application_command_error
discord.Bot.on_application_command_error
discord.Bot.invoke_application_command
discord.on_unknown_application_command
discord.Permissions.use_application_commands
discord.ext.commands.Bot.on_application_command_error
discord.ext.commands.Bot.add_application_command
discord.ext.commands.Bot.get_application_command
discord.ext.commands.Bot.walk_application_commands
discord.ext.commands.Bot.invoke_application_command
discord.ext.commands.Bot.remove_application_command
discord.ext.commands.Bot.process_application_commands
seems like this issue has been fixed
💀
white mode on notepad++ is WILD 💀
white mode is default
Can someone explain to me the best way to make commands both as slash and normal command? Most efficient?
bridge
How?
Concept
With normal i mean !help btw
i would call slash commands normal by now :>
Oh okay. Does this also work with discord.Option?
you need BridgeOption
async def set(self, ctx, channel: discord.Option(discord.TextChannel, description="The channel where the flagquiz should be set.", required=True)):```
How will this work then
discord.BridgeOption :>
And its everything the same. Only instead of option bridgeoption?
read and see :>
What with command groups?
i dont think those have a way to be bridged
https://docs.pycord.dev/en/stable/ext/bridge/api.html#discord.ext.bridge.Bot.bridge_group and yet they do
The reference manual that follows details the API of Pycord’s bridge command extension module. Bots: Bot: Methods def add_bridge_command,@ bridge_command,@ bridge_group. AutoShardedBot: Event Refer...
use the docs :)
flagquizslash = discord.SlashCommandGroup(name="flagquiz", description="Manage the flagquiz settings.")``` i have it like this rn
https://docs.pycord.dev/en/stable/ext/bridge/api.html#discord.ext.bridge.BridgeCommandGroup use the docs
The reference manual that follows details the API of Pycord’s bridge command extension module. Bots: Bot: Methods def add_bridge_command,@ bridge_command,@ bridge_group. AutoShardedBot: Event Refer...
sänks
flagquiz.py konnte nicht geladen werden. Extension 'cogs.flagquiz' raised an error: TypeError: BridgeCommandGroup.__init__() missing 1 required positional argument: 'callback'``` 
seems like you need to read the docs more :3
I dont get it lol
Some Docs are bad
callback? Like?
Extension 'cogs.flagquiz' raised an error: TypeError: Callback must be a coroutine.``` 
dont call it, just name it
Wdym
The hell are you trying to do
bridge group lol
Bridge commands 
functionname
no ()
flagquizslash = bridge.BridgeCommandGroup("flagquiz", name="flagquiz", description="Manage the flagquiz settings.")```
so what should i set
group(functionname,...)
That's what toothy said 4 times
And where do I define the function? Does it have to be the Cog name?
I thought it was for the default command function but groups don't have like a default command so now I'm confused myself
I really don't know much about bridge so dark knows maybe
@lofty parcel 
Prefixed groups do have a default command
ah
Dark how i have to do this
Just use bridge_group
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - Pycord-Development/pycord
How in a Cog?
bridge.bridge_group?...
Extension 'cogs.flagquiz' raised an error: AttributeError: 'AutoShardedBot' object has no attribute 'bridge_commands'
@bridge.bridge_group(name="flagquiz", description="Manage the flagquiz settings.")
Im not dumb
I doubt autoshardedbot supports bridge commands
@errant trout do you happen to know. Dismiss
ah
@frail ocean
The reference manual that follows details the API of Pycord’s bridge command extension module. Bots: Bot: Methods def add_bridge_command,@ bridge_command,@ bridge_group. AutoShardedBot: Event Refer...
Are you using the bridge auto sharded bot?
Or discord.AutoShardedBot
holy shit this library has so much stuff I don't know of
I'm surprised too
One supports bridge? The other doesnt?... lmao?
Anything else?
It quite literally inherites from commands.AutoShardedBot
With the addition of the bridge bot base
The library is literally open source you can check it by yourself
Ignoring exception in on_message
Traceback (most recent call last):
File ".venv\lib\site-packages\discord\ext\commands\core.py", line 774, in _parse_arguments
next(iterator)
StopIteration
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File ".venv\lib\site-packages\discord\client.py", line 400, in _run_event
await coro(*args, **kwargs)
File "\main.py", line 263, in on_message
await client.process_commands(message)
File ".venv\lib\site-packages\discord\ext\commands\bot.py", line 386, in process_commands
await self.invoke(ctx)
File ".venv\lib\site-packages\discord\ext\bridge\bot.py", line 144, in invoke
await ctx.command.invoke(ctx)
File ".venv\lib\site-packages\discord\ext\commands\core.py", line 1531, in invoke
await self.prepare(ctx)
File ".venv\lib\site-packages\discord\ext\commands\core.py", line 881, in prepare
await self._parse_arguments(ctx)
File ".venv\lib\site-packages\discord\ext\commands\core.py", line 776, in _parse_arguments
raise discord.ClientException(
discord.errors.ClientException: Callback for flagquiz command is missing "ctx" parameter.```
read :3
Start using your brain cells
Love you guys
Is this a bug? In fact, there is an attribute description and I can get a description of the slash command, but for some reason PyCharm tells me that it doesn’t exist
Is there a way to check if the command is run as slash command or messae command
does it work?
Yes
Did you typehint ctx?..
ctx: discord.ApplicationContext
Read the docs. Find out.
.rtfm BridgeContext
call me crazy but no, ctx.command does not have a description attribute
but for some ungodly reason it does work
But I can get it and description works :DD
seems like you can make your first github issue :)
My suspicion is that it's not an ApplicationCommand but a SlashCommand
which would mean this is wrongly typehinted
oh no i see the issue
slashcommand is a subclass of applicationcommand
so i'm unsure where the wrongness is now
i guess applicationcommand is the right typehint
if the highlight bugs you you could do command: discord.SlashCommand = ctx.command
lmao first time I ever use notepad++ and I already get shit on for light mode
notepad++ 😨
please get vs code its so much better 😭 and get the exstension prettier its so good

?
exactly
what does even typehint has to do 💀
everything..?
Idk if you mean it like the return of a function or definining the argument
if you dont typehint ctx as what it is, the IDE can't know at all what is supposed to be passed there
Can you elaborate?
If you mean defining what is with the type
that is typehinting
as I said everything just seems broken af
not even the docs or the source code have it
can't find the method to make my bot leave a VC. can anyone help me?
idk im just kidding
AA
Objects: Attributes average_latency, channel, endpoint, guild, latency, loop, session_id, source, token, user. Methods async disconnect, def is_connected, def is_paused, def is_playing, async move_...
@lone hound
Can someone help with this error, not sure how to fix:
class VerifyModal(discord.ui.Modal):
def __init__(self, interaction: discord.Interaction):
super().__init__(timeout=None)
self.db_conn = db_conn
self.guild_id = interaction.guild.id
cursor = db_conn.cursor()
sql_query = f"""
SELECT verification_questions, channel_id
FROM guild
WHERE guild_id = '{self.guild_id}';
"""
cursor.execute(sql_query)
result = cursor.fetchone()
cursor.close()
if result:
verification_questions, channel_id = result
if isinstance(verification_questions, list):
questions_list = verification_questions
elif isinstance(verification_questions, str):
questions_list = verification_questions.split(';')
self.add_item(discord.ui.InputText(label=question1, placeholder="Example: coolEp1cGamer69"))
self.add_item(discord.ui.InputText(label=question2))
self.add_item(discord.ui.InputText(label=question3))
self.add_item(discord.ui.InputText(label=question4))
async def callback(self, interaction: discord.Interaction):
print("it works mommy!")
class MyView(discord.ui.View):
def __init__(self, bot: commands.Bot):
super().__init__()
self.bot = bot
@discord.ui.button(label="Send Modal", custom_id="send_modal")
async def send_modal(self, button: discord.ui.Button, interaction: discord.Interaction):
modal = VerifyModal(title="Modal via Button")
await interaction.response.send_modal("Click the button to open the modal", view=modal)
Traceback:
modal = VerifyModal(title="Modal via Button")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: VerifyModal.__init__() got an unexpected keyword argument 'title'
Your init isnt designed to take a title kwarg
class MyView(discord.ui.View):
def __init__(self, bot: commands.Bot, **kwargs):
super().__init__(**kwargs)
self.bot = bot
@discord.ui.button(label="Send Modal", custom_id="send_modal")
async def send_modal(self, button: discord.ui.Button, interaction: discord.Interaction):
modal = VerifyModal(title="Modal via Button")
await interaction.response.send_modal("Click the button to open the modal", view=modal)
Like this?
try it and see
you need to pass positional arguments before keword arguments, you have bot as a position argument
so like
self.title = title
?
pass bot to your view.
no, in your init your arguments are
self -> no need to do anything
bot -> you need to pass bot to the modal
**kwargs -> all additional keyword arguments will be put in a dict here
why the bot get blocked from accessing discord api
can you show the error or message you received
also if thats your entire view, you dont need bot lol
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/ext/bridge/bot.py", line 144, in invoke
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 959, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 189, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward.
Ignoring exception in command None:
yea you've been ratelimited, good job
You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently.
why?
do you have a lot of code?
or at least, went above its limits
yup
does your bot ever edit channels quickly, or really do anything quickly
edit users nickname and sends logs quickly
edit channels, edit bot status, and send DMs are big ones
does it mass edit peoples nicknames?
well it says you exceed rate limits frequently sooo
about how quickly does the bot send logs?
i removed the code of edit nicknames and logs and still get ratelimited
thats not how it works
the ratelimit takes time to expire.
Basically discord was like you are sending too many requests so we are going to block all requests for x amount of time
just wait like an hour and see if it still says that
x could be 24 hours or more
Normally pycord handels ratelimits for you unless you are doing things way to fast
or are doing weird stuff too much
can you show us the code of anything your bot does repeatedly, like outside commands
i can't rn because i'm using phone rn but the errors has effects on this problem ?
any errors that dont mention ratelimits might be the problem and when possible you should send them here
okey thank you
okay so I simplified all of my code down to just what I want to do in a seperate file, Im using the base code provided by the modal dialogs page and Im getting that title error. The modal is supposed to get the data from sql depending on the guild Id and put that data into the dialogs
class VerifyModal(discord.ui.Modal):
def __init__(self, interaction: discord.Interaction):
super().__init__(timeout=None)
self.db_conn = db_conn
self.guild_id = interaction.guild.id
cursor = db_conn.cursor()
sql_query = f"""
SELECT verification_questions, channel_id
FROM guild
WHERE guild_id = '{self.guild_id}';
"""
cursor.execute(sql_query)
result = cursor.fetchone()
cursor.close()
if result:
verification_questions, channel_id = result
if isinstance(verification_questions, list):
questions_list = verification_questions
elif isinstance(verification_questions, str):
questions_list = verification_questions.split(';')
self.add_item(discord.ui.InputText(label=question1, placeholder="Example: coolEp1cGamer69"))
self.add_item(discord.ui.InputText(label=question2))
self.add_item(discord.ui.InputText(label=question3))
self.add_item(discord.ui.InputText(label=question4))
async def callback(self, interaction: discord.Interaction):
print("works")
class MyView(discord.ui.View):
@discord.ui.button(label="Send Modal")
async def button_callback(self, button, interaction):
await interaction.response.send_modal(VerifyModal(title="Modal via Button"))
@bot.slash_command()
async def send_modal(ctx):
await ctx.respond(view=MyView())
As far as I know, 28 days are possible with a TImeout.
With this method, however, no more than 27 are possible. How do I fix this
time_val=27
elif unit == 'd':
return timedelta(days=time_val)```
im still getting the TypeError: VerifyModal.__init__() got an unexpected keyword argument 'title' error, but when a normal modal is provided there are no problems
probably because it is 28 when discord gets it because timedelta is weird
What should i use instead
__init__ acts pretty much like a normal function
you just need to have
def __init__(self, **kwargs):
super().__init__(timeout=None, **kwargs)
and than
VerifyModal(title="Modal via Button") later on
you can try 28-1 second/minute
also, are you using timeout or timeout_for
class MyView(discord.ui.View):
def __init__(self, **kwargs):
super().__init__(timeout=None, **kwargs)
@discord.ui.button(label="Send Modal")
async def button_callback(self, button, interaction):
await interaction.response.send_modal(VerifyModal(title="Modal via Button"))
Like this? When I tested it I got the same error so Im sure I didnt do it correctly
alright, so that solved the title problem, however, now interaction is the problem: TypeError: VerifyModal.__init__() missing 1 required positional argument: 'interaction'
I tried adding interaction: discord.Interaction to the init but that didnt do anything
that error means it is in the init but you are not passing it in VerifyModal
you probably do not need interaction so you can remove it from the modals init
okay, how do I pass it into the VerifiyModal
just like a normal function
rembed it has to go before the title= as that is a keyword argument and positional arguments always go first
timeout
how
await interaction.response.send_modal(VerifyModal(interaction, title="Modal via Button"))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: VerifyModal.__init__() takes 1 positional argument but 2 were given
😭
try timeout_for
can you show your init again
for myview or verifymodal
the modal
def __init__(self, **kwargs):
super().__init__(timeout=None, **kwargs)
Why?
read my message and find out
you need to have interaction in the init.
I recommend you take some time to learn the basics of python as it will make the bot creation process easier.
.tag lp
Resources For Learning Python
- Official Beginner's Guide
- Shortcut to guide for people new to programming and people with experience programming
- Official Tutorial
Other Resources To Learn Python
- Automate The Boring Stuff for complete beginners to programming
- Learn X In Y Minutes for people with experience programming
- Swaroopch is a useful book
- Code Abbey has practice for beginners
- W3Schools is a good resource for general use
But its the same or?
almost
xd
Has someone codet a activity here already
not in pycord, cuz pycord cant support activities
Yes i know
yes
How was it
it was fine
can i dm you?
sure
haha sorry mate, but get something like vsc or pycharm, much better
AttributeError: 'FFmpegPCMAudio' object has no attribute '_process'
@commands.command()
async def play(self, ctx: commands.Context, *, query: str):
"""Plays a file from the local filesystem"""
source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(query))
ctx.voice_client.play(
source, after=lambda e: print(f"Player error: {e}") if e else None
)
await ctx.send(f"Now playing: {query}")
can anyone help please ?
Me too haha
Have you installed ffmpeg to your server / pc
is this a module ?
when I try to pip install it, I have no results
Thanks, is it possible to use it on a pterodactyl panel ?
also did you install py-cord[voice]?
Yes I did
ig just install it with apt get
how to do it?
thanks
why this doesn't work? am i passing the datetime object in a wrong way? I want it execute for e.g at 6 pm everyday
@tasks.loop(time=datetime.time(hour=16, minute=35))
async def open_channel(self):
channel = await self.bot.fetch_channel(MOD_CHANNEL)
await channel.send("Everything's ready to go")
do the docs say it takes a datetime.time object?
well yes, if i change the time attribute to seconds=10 it executes
try seconds = 0
or just work with this lol
time continues to plague developers around the world :>
well it'd be certainly better to just leave it to execute at the concrete hour of the day, it's a pain in the ass if I would had to adjust those seconds or hours based on time bot boots up
my guess is the timezone info is wrong
I think it uses a default timezone, you should either convert your time to UTC or specify your local timezone
(Assuming you have not waited a full 24 hours while testing)
the bot is local , and I don't know if datetime.time object gives me a possibility of specyfying the timezone whatsoever
It's so confusing
print a dummy time object and find out
but generally timezones are always assumed to be UTC unless specified otherwise
just wondering what your goal is that you need to convert it to a specific time zone?
read up
You can add this as a kwarg with your time zone
tzinfo=datetime.timezone.utc
ok
Does autocomplete work on mobile at all? It appears to just load forever even with 1 option
You are probably not responding correctly
To autocomplete?
Works here, but not one via my code, however my code does work with PC just not mobile
Hmm. Can you show your autocomplete function
it should work
how many str do you have at the autocomplete?
If you are constantly typing it will not load
That might take longer than 3 seconds, I suggest caching the API request response
ah so gotta get it within 3 seconds
Yes, that includes latency so latency from discord on your PC might be faster than on your phone so that might be the issue
API request in autocomplete is usually kinda hard yea
especially since you make an API call every single time the user times a letter
so if they type extremely fast you are absolutely spamming that api
You should look into a TTL cache.
Time to live. Essentially is a cache that will delete the cached item after x amount of time. So for example the autocomplete would see nothing in cache (be slow and not respond for 3 seconds) but than cache the results so for the next x amount of time no slow API calls are made.

Hi, I forgot how to edit a ctx.respond message I remember something like edit_original_message but that was for interactions can someone guide me rq
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...
ctx.edit or ctx.interaction.edit_original_message
edit original response*
aight thanks a ton
both should work
edit original message is sync for some reason
okay nope, the docs just lied
thank you!
await ctx.respond("Processing...")
await ctx.interaction.edit_original_message
Doesnt do anything for som ereason
Tried doing var = await ctx.respond...
var.edit but doesnt work either
show the actual code in your ide
async def crop_media(ctx: discord.ApplicationContext, attachment: discord.Attachment):
await ctx.respond("Processing...")
media_bytes = await attachment.read()
media_filename = attachment.filename.lower()
if media_filename.endswith((".png", ".jpg", ".jpeg")):
await ctx.interaction.edit_original_message(content="Image detected, cropping...")
cropped_bytes = crop_image(media_bytes)
elif media_filename.endswith((".mp4", ".mov", ".avi")):
await ctx.interaction.edit_original_message(content="Video detected, cropping...")
cropped_bytes = crop_video(media_bytes)
elif media_filename.endswith(".gif"):
await ctx.interaction.edit_original_message(content="GIF detected, cropping...")
cropped_bytes = crop_gif(media_bytes)
else:
await ctx.interaction.edit_original_message(content="Unsupported file format for cropping.")
return
await ctx.interaction.edit_original_message(content="Processing done. Uploading cropped media...")
await ctx.send(f"<@{ctx.user.id}>", file=discord.File(cropped_bytes, filename=f"cropped_media.{media_filename}"))
#await ctx.interaction.response.delete()
try _response
ctx_response?
edit_original_response
wow
mhm, what is with that? {ctx.mention} instead of <@{ctx.user.id}>
yea _message is deprecated
so prolly kinda broken
why tf does it work differently tho?
it's quite literally just an alias
ye
can you validate input with regex in interaction before starting it? or only after it?
Wdym before starting it
if you mean string input in a slash command no it will only be a string, you cant give regex to discord to validate before the user sends
i have a website where a user can submit data, that data should get posted to the discord bot which then creates a new channel and posts the data in it. is there an easy way to go from submitting the data and posting it directly to the bot or do i need to upload it to a db and have the bot watching for changes in the db?
i mean, that isn't really pycord specific
i mean, that isnt really helpful. idk if discord api/pycord provides support for posting data directly to the bot
Yea it isn't helpful, because you are asking a question that is out of the scope of a discord bot library
we can't help you connect your frontend to your backend
Not directly, but if you wanted to be super-extra, you could set up fastapi on your bot and post directly to it (be mindful of security)
did u start it ?
with open_channel.start()
I feel like this is a really dumb question but I cannot find anything online (incl. the docs) so here I am:
I have an /invite command: ```py
@bot.command(name='invite', description='Invite a user to tobezdev Studios')
@commands.is_owner()
async def _invite(ctx, user: discord.User):
try:
await user.send(embed=discord.Embed(
title="tobezdev Studios - Invite",
description=f"""
Hey, {user.mention}!
You've been gifted an invite to tobezdev Studios by {ctx.author.name}.
You can join the studios using [this link](definitely a discord invite link), it expires in approximately 7 days.
Please note that you may be asked to verify in this server. Please DM tobezdev for a verification bypass when you join if you cannot verify successfully.
"""
))
return await ctx.respond(embed=discord.Embed(
title="Invite sent!",
description=f"Successfully invited {user.mention}.",
color=discord.Color.green()
))
except discord.Forbidden:
return await ctx.respond(embed=discord.Embed(
title="Invite Failed",
description="Failed to invite the specified user: Bot doesn't have permission to send messages to the user.",
color=discord.Color.red()
))```
My error is the default "A specified user ID was not valid" error produced by Discord - screenshot attached. The command works fine when mentioning a user inside of the current server, but raises the above mentioned error when someone outside of the server is mentioned, specifically using the <@xxxxxxxxxxxxxx> method.
My bot does not even receive the interaction and so I have narrowed it down to be an error specifically do so with the actual command, rather than the processing of it. Does anyone have any pointers? Thanks!
that's a prefix command or
Is there a way to check if a server has premium
It's an interaction command.
Then 1. you need discord.Member, and 2. why _invite?
Just cause if I use help then it shadows the original help and my IDE errors out - just like to keep to the theme I guess 🤷
I'll try the discord.Member and let ya know
Still this error, with discord.Member instead of discord.User
...wait
you cant put a user in there that doesnt share a server with the bot
that doesnt work
It's a command to invite people to the server-
I'm not going to be inviting people who are already in the server.
does the bot share any servers with the invited people?
Yes, I could send them a link but it's my (soon-to-be) professional space and I want it to look good.
No, the bot is only in the 1 server where the commands are present.
Then you cant do that
bots cant dm people they dont share a server with for all i know
But then surely it'd raise a forbidden error rather than an invalid user id error?
Discord is stopping you before the command is sent to the bot
because that ID cannot be valid for that bot because its not sharing any servers with the bot
That's so stupid
does py-cord support polls ?
not yet on stable
I have no idea tbh
Could there be a workaround maybe using the Discord API to get a user and then sending it like that?
cool thanks.
i highly doubt it
it would be quite invasive to let bots dm literally anyone
for good reason
You might have a legit reason for it
But what about the 10 others that scrape user IDs and spam the everliving fuck out of everyones dms? while not sharing a server?
Yeah I guess that is true
Time to do something wild and find a workaround for it
Thanks for the help :)
My workaround is to make a new (public) server and invite people to that, and then keep the official one invite-only.
Probably a stupid idea but my brain is rotting slowly
are you sharing classified documents in that server or what
why this way of inviting even
No it's my (soon-to-be) professional space and I want the invites to actually look decent rather than just DMing people a plain link. Also keeps my DMs clean.
So it turns out this is still giving me an issue. Console says token must be type str, not NoneType
Also not professional.
But spam DMing everyone is?
please use an IDE
and use [], not ()
it's a dict
nevermind. fixed it myself by reducing the name of the .env file to only be the extension
ah
also on what line?
os.getenv
but i think i was mixing it up with another method of using dotevn then
Exactly what I am trying to avoid, by sending professional-looking invite embeds to users. It keeps track of who has been invited and blocks sending if they already have an invite.
invites via bot DMs are the least professional thing i can think of
its just annoying and unsolicited
Maybe, but we all have our ways of doing things. Thanks anyways :)
you should ask some people then
i cant think of anyone that would not find that annoying
if you want anyone to actually join
Because with invites, your opinion of the method doesnt matter
The opinion of your target group does
I have asked 3 communities (most of which would like to join the server when it's finishes) to which the majority said bot embeds looked more professional, compared to a user DMing a plain link.
I did do my research beforehand.
alrighty
Probably not worth having an argument about, though.
is this the correct appearance for python?
wdym appearance lol
I loaded it in visual studio code, but I've never messed with python before
usually they color code the stuff, so I wanna make sure its the right setting for python
Not that it makes a huge difference anyways
if you only do python id recomend pycharm
but yea i mean its highlighting the keywords correctly lol
I do c# and java too so I'd rather just use VS:C
jetbrains has you covered for all of those ;) but yea
the students i talk with all use vsc for other langauges but pycharm for python. buuut, yeah, to each their own i guess 🙂
Why not use vsc for python though?
think of it like this
A specialised IDE is near perfect at its perfection
VSC sucks at everything equally
:>
ah
no but seriously, vsc is really annoying to make word good for one language
it can do everything a little but nothing great, except js which is i think like the "main" language that has full built in support
what about c#?
is that not VS' territory?
idk, didnt use them yet.
anyway #general :3
well, I guess there's no reason not to use pycharm
bt2
yea
@slash_command()
async def serverinfo(self, ctx):
""" Get the current server's info """
guild = ctx.guild
owner = await discord.utils.get_or_fetch(guild, 'member', guild.owner_id)
embed = discord.Embed(color=discord.Color.random(), title=guild.name)
embed.description = f"""
**Owner:** {owner.mention}
**Members:** {guild.member_count}
**Roles:** {len(guild.roles)}
**Verification:** {str(guild.verification_level).title()}
**Channels:** {len(guild.text_channels)} Text, {len(guild.voice_channels)} Voice
**Created:** <t:{round(guild.created_at.timestamp())}:R>
**Emojis:** {len(guild.emojis)}
**Stickers:** {len(guild.stickers)}
"""
embed.set_thumbnail(url=guild.icon.url)
embed.set_footer(text=f"ID: {guild.id}")
if guild.banner:
embed.set_image(url=guild.banner.url)
features = ", ".join(guild.features).replace("_", " ").title()
embed.add_field(name="Features", value=features)
await ctx.respond(embed=embed)
thanks
fancy enough? :)
funny how different u can use the embed features
wym
also yes, the lack of indentation in the description is on purpose
do not indent it
** @slash_command(name="help", description="When you know, you know (WIP)")
async def help(self, ctx, command: Option(str, "The command you want to see the help for") = None):
embed = discord.Embed(title="Help Menu", color=discord.Color(config()["color"]))
casual_names = self.get_commands()[0]
casual_name_and_desc = self.get_commands()[1]
sub_names_and_desc = self.get_commands()[2]
sub_names = self.get_commands()[3]
subs = self.get_commands()[4]
casus = self.get_commands()[5]
sub_cmd_list_names = [item.name for subs in [i.subcommands for i in subs] for item in subs]
sub_cmd_list = [item for subs in [i.subcommands for i in subs] for item in subs]
sub_cmd_names_and_desc = [f"{item.mention} - {item.description}" for subs in [i.subcommands for i in subs] for
item in subs]
if command in sub_names:
value = ""
for i in subs[sub_names.index(command)].subcommands:
value += f"{i.mention} - {i.description}\n"
embed.add_field(name=f"Subcommands of {command}", value=value)
embed.set_footer(text=random.choice(self.choices))
elif command in casual_names:
if casus[casual_names.index(command)].options:
embed.add_field(name=f"Command:", value=casual_name_and_desc[casual_names.index(command)], inline=False)
option_value = ""
for i in casus[casual_names.index(command)].options:
option_value += f"``{i.name}`` - {i.description}\n"
embed.add_field(name="Values", value=option_value, inline=False)
else:
embed.add_field(name="Command:", value=casual_name_and_desc[casual_names.index(command)], inline=False)
embed.set_footer(text=random.choice(self.choices))
elif command in sub_cmd_list_names:
if sub_cmd_list[sub_cmd_list_names.index(command)].options:
embed.add_field(name=f"Command:", value=sub_cmd_names_and_desc[sub_cmd_list_names.index(command)],
inline=False)
option_value = ""
for i in sub_cmd_list[sub_cmd_list_names.index(command)].options:
option_value += f"``{i.name}`` - {i.description}\n"
embed.add_field(name="Values", value=option_value, inline=False)
else:
embed.add_field(name="Command:",
value=sub_cmd_names_and_desc[sub_cmd_list_names.index(command)],
inline=False)
embed.set_footer(text=random.choice(self.choices))
elif command:
embed.add_field(name="404", value=f"Command ***{command}*** not found - Try again", inline=False)
embed.add_field(name="Advise", value="/help doesn't need the group name for subcommands, \n"
"just try the name of the command.\n", inline=True)
embed.add_field(name="Example", value="``/help ping`` instead of \n"
"``/help general ping``", inline=True)
embed.set_footer(text=random.choice(self.choices))
else:
if sub_names_and_desc:
embed.add_field(name="Command Groups:", value=' '.join(sub_names_and_desc), inline=False)
if casual_names:
embed.add_field(name="General Commands:", value=' '.join(casual_name_and_desc), inline=False)
embed.set_footer(text="If you need help with a command, use /help <command/group>")
embed.set_thumbnail(url=self.bot.user.avatar)
await ctx.respond(embed=embed```
my prototype of my help menu command, vs how u build embeds
holy mother of code
but whats the difference lmao
(im a bit stupid today)
i would embed.Embed(title=, description=, stuff=) while u use embed.description=
oh, yea
line length and readability :3
still can read it Xd
fair
but jesus i lost my notes, need to get new objects
lala deleted my notes in her server -.-
oh okay
yeah i use config files if i dont wanna have it mutiple times in the code
global changes and stuff
config() is just a function that puts a json in the RAM
@lru_cache()
def config():
if os.path.isfile("config.json"):
with open("config.json", encoding="utf-8") as fp:
data = json.load(fp)
else:
with open("app/config.json", encoding="utf-8") as fp:
data = json.load(fp)
return data

Is there a way to check if a server has premium
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 ...
Guild yes?
guild yes?
thats what i linked i think yes
So, I run this code and my bot activates, and it does print that it initiallized, but when I actually say !hello in my server that the bot is in, it doesn't do anything
thats a slash command lol
discord.Bot is converting bot.command to a slash command and not a prefix one
so it has to be a slash command?
it is already a slash command
and you can remove the command_prefix from discord.Bot because discord.Bot is slash-only
OH. It actually just worked for the first time when I put /hello
if you want to have a prefix command you have to use commands.Bot and ctx.send instead of ctx.respond
so command_prefix isn't doing anything?
ye
not now, no
so if I just remove that and leave intents=intents, nothing should change?
alright it works
I don't understand what @default_permissions() does. What is a default permission? Is that like the everyone permissions?
default permissions the command gets set up with in the server
so if I want to restrict a command for use by only people with a certain permission, would I use has_permissions()?
ohhhh. is has_permissions() channel specific?
No, that makes it permanent and unchangeable
default permissions can be changed by the server owner
huh. so default permissions are the permissions that i can give to people through roles and stuff?
has_permission will only allow people with the ban permission to use it for example.
default permissions will only let users with the ban permission use it unless the server managers go into integration settings and set roles and users that should be allowed to use the command.
Oh I think I understand now. So default_permissions will also take into account access given by integration settings
yea no reason not to in my case
so you dont take control away from the server owner
conveniently I'm only making a bot for uses on my own server, so there's a lot of considerations that I don't exactly have to keep in mind. It doesn't make too much of a difference for me. That being said, I should get used to using the better option for most cases
also, has_permissions doesn't hide the command from people who cant access it i'm 90% sure, because those permission restrictions are never shared with discord i think
Hello I am getting a TypeError: Invalid usage of typing.Union when trying to use bridge.Context as a type hint. PyPy 3.10.
show your code
part that's erroring
@bridge.bridge_command(guild_ids=[config.MAIN_SERVER])
@bridge.guild_only()
async def import_instance(
self, ctx: bridge.Context, guild_id: int, file: Attachment
):
which pycord version and which python version
Latest dev version of pycord from https://github.com/Pycord-Development/pycord. PyPy running Python 3.10.
if you have no reason not to, update to 3.12
as for using the dev version, well, you should always expect there to be bugs in that
Oh
pypy is a different version of python basically?
well, thats likely why then
because that error shouldn't be happening really
try normal python
Is there a function that I could use for my bot to just send a message in a specific channel when triggered? I want the bot to send a message in a channel as part of its startup process
@bot.event
async def on_ready():
with sql.session_scope("save") as db_session:
pass
print('--------------------------------------')
print('Bot is ready.')
print('Eingeloggt als')
print(bot.user.name)
print(bot.user.id)
print('--------------------------------------')
await bot.change_presence(
activity=discord.Activity(name=f'/help | {bot.user.name}', type=discord.ActivityType.playing))```
smth like that but just with channel.send
I found the error. bridge.Context is deprecated, had to use bridge.BridgeExtContext instead. Should really add a deprecation error instead of a semi-unrelated error.
the hell is a bridge command?
bridgeextcontext is wrong tho (?)
bridgeextcontext is what gets passed when its used as prefix cmd, and bridgeapplicationcontext is passed when used as slash
or where did you see its deprecated
prefix and slash in one
Ah
Ah. I actually have a rather simple version of that. Out of curiosity, what does with sql.session(“save”) as db_session do?
i use sqlalchemy for sql stuff.
so i made some things for it to run it more smoother
db_session handling and stuff
oh ok so that’s for working with something else
def init_db(uri):
engine = create_engine(uri, pool_recycle=3600, pool_pre_ping=True, pool_use_lifo=True)
db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False,
bind=engine))
Base.metadata.create_all(bind=engine)
return db_session
@contextmanager
def session_scope(action):
data = config()["sql"]
try:
session = init_db(f'mysql+pymysql://{data["user"]}:{data["password"]}@localhost/{data["database"]}')
except Exception as e:
print(e)
session = init_db(f'mysql+pymysql://{data["user"]}:{data["password"]}@10.0.0.2/{data["database"]}')
if action != "request":
try:
yield session
session.commit()
except:
session.rollback()
raise
else:
yield session
session.close()```
this is what im using
so what id be looking for is channel.send? Does that require me to import something other than just discord?
never used yield myself ngl
no
just try it lol
yield is fun as hell if u know how
why tf do you have yield in a def?
return ends the def, yield returns and continues the def
or maybe im stupid
Switching to bridge.BridgeContext worked???
and I still use pymongo with NOSQL
u use yield to return loop stuff lol
lol
like when u use stuff like with:
so I define the channel I want it to send to as channel = client.get_channel(id) then do await channel.send(“text here”)?
yep
also is there a difference between using ‘ and “?
Because if I remember correctly, it does make a difference in C++
it does, because you can use ' in " and " in '
what about quotes inside of quotes? What is the bypass sequence?
and dont forget """"
again, use ' if in " and " if in '
or just \"
ah so it is the same as c++ there
I’ve got myself into a really strange area where I went halfway with Java, switched the C++ and went halfway
\ is universal really
Now im starting python
so im mediocre with two other languages learning a third one lol
good luck, be careful when u start system programming with bash or powershell
commandline is mighty as fuck
you can just destroy stuff can’t you?
yeah thats just stupid
import os as cache
cache.remove()
yea. my brother was reformatting a usb on my computer; really worried me since he wasn’t really sure which drive he was on after he started the reformat process.
wtf
And I’m guessing if he reformatted my actual drive it would just delete everything
thats what reformatting does
that reminds me of the Steam accident 
all because he wanted a window boot usb and didn’t want to wait for me to do it myself. Luckily he did select the right drive
wuhahahaahahahaha
A deeper look into a steam-for-linux GitHub issue (https://github.com/valvesoftware/steam-for-linux/issues/3671) investigating how a steam script was able to delete the entire contents of someone's root directory. While the direct cause of the rm -rf is fairly obvious, how it was triggered in the original bug report is not, and may forever remai...
no way, how did u know?
Immer diese duitser hier
lol
last time i used diskpart at work i killed my windows server installation stick
#general
I'm getting weird fluctuations in my message sending?
Here is code
@bridge.bridge_command(aliases=["ms"])
async def ping(self, ctx: bridge.BridgeContext):
"""Gets the current ping between the bot and discord"""
start = time.time()
await ctx.respond(f"🏓 Pong! {round(max(time.time() - ctx.message.created_at.timestamp(), self.bot.latency)*1000)}ms")
print(f"Ping took {time.time() - start} seconds to send")
It's not a personal ping issue, I've already tested that. This is just so weird to me?
When I do client.get_channel, client is an unrecognized reference
sh
ah*
hold on, subbing with bot variable
works now. recognized bot.get_channel and I forgot to put await before channel.send
why does it have to await anyways? Is that basically like 'wait for this to happen on the other client before moving on'?
yes and no

its giving control back to the main thread until the to-be-awaited thing is done
that way that line of code doesnt block the rest of your bot
but no, thats not how programming works
a line is fully executed before moving on to the next
ah
thats also why using aiohttp is a must to make API requests, else your bot freezes for the duration of a requests api call
if u capeable of multithreading aiohttp is just nice to use.
but async is recommended at least
Also I force my bot offline by terminating the program through command prompt, but is there a way to kill the bot with a command from discord?
Has anyone been having issues with on_guild_join() not being triggered on the dev master branch?
how can i use smth like that in a bridge command:
member: typing.Union[str, int]```
not a thing
restart discord
like close and reopen discord on my computer?
I get this as an error
well close it
if you opened those
if not, 
i think you should be able to do exit()
but that exits the entire program
so you need to print before that
show your pip list
lol i often forget that I have a ultrawide screen
yea thats what exit does
ohh, I see. The command itself says that the bot didn't respond, but it did execute and end the program
so I'll just throw in a ctx.respond
now if I'm running the bot and I do just close the window running it, there's no way to have it deal with that is there?
because that would be instant termination of the program
therefore it couldn't say 'bot has been closed' or whatever, right?
well usually you wouldnt ru nthe bot on your pc unless for testing lol
and yea if you close the cmd it stops
well I'm only using it for a specific niche purpose
so I'll only ever run it off my pc
there are tutorials on how to open cmds like that minimized / in the background
I'm guessing I could actually set it up so that it could run on startup, couldn't I?
yea
i got it! Task scheduler is really convenient
so I want to use a bot to give temporary access to a channel. Do I have to use roles to do that, or can I actually just give access directly to the user?
because in channel settings, I can see that you can assign permissions to individual users
well my original idea was to create a role for each of the restricted channels that I wanted to control specific access to, and then use the bot to add and remove those roles from individuals to allow/deny them access
but I was wondering if using roles for that would even be necessary
Well..
This is overkill
It's for a roleplay server. I am going to password-lock access to certain channels. you unlock them by using an access command with the correct password
hence the strange method
so I could instead change the member restrictions?
that'd be a lot easier than having a convoluted list of roles for accessing every locked channel
I mean yea
Anyone know if there’s any functions that exist that deal with changing member restrictions in pycord?
I can’t find any related documentation
Member restrictions?
Yes channel permissions for individual 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 ...
Ah thank you
Why would I used BridgeOption instead of Option ? It says in the doc that bridge is for both a Slash Command and a Prefixed Command. I don't want that, I only want slash command. But now it is saying that "Option is deprecated since version 2.5, consider using BridgeOption instead"
because you're importing something bridge
What would function would I use to read for a response after the command is triggered?
wdym
I want the bot to give a prompt, read the user’s next message, then do an action based on the response
I just don’t know how step 2 works
I think you can use bot.wait_for for that
look it up on the docs
or wait
.rtfm wait_for
yea
So that will collect the next message?
You can make it do that yes
I think it's also described in the guide, as a way to wait for a reaction for example
Anywhere you want
it's python after all
Wdym? I want to have to unban members via name and id
You can't pass IDs as int
Try it, discord will stop you
You can only do that via a string option
Discord IDs are too long for the length of int discord allows
And even if that wasn't the case, options can only have one input type afaik
yeah, if for some reason you really, really need that id and can not use some user object for it you have to length check, use isdigit, try to get or even fetch this user and keep in mind a baned member is discord.User not discord.Member.
and I'd never use names. at a certain size you'll run into cases where the name doesn't exsist
Yea but it might still be nice to have, you won't necessarily always have someone's ID
even tho you should be able to get that 98% of the time
yeah, and it's so reliable when you want to unban your former member: ツァイ
😂 Okay okay, it can be nice to have it as an option, but it's drawn to errors on both sides and you have to try/except everything.
pomelo usernames are ascii
i just don't like relying on names
yea ik
Even if you use names it is possible to accidently ban the wrong person by accidently using display name instead of username
this is about unbanning
same applies (but is less importent i guess)
How do I edit the role hierarchy? Using role.edit(position=num) doesnt change the position at all but throws no errors
did you try hardcoding a few positions to make sure the num variable isn't the problem
also, is the bots highest role above where you're trying to move that role?
how i can get the category name by his id?
like a channel
no the category name like this category name is HELP AND SUPPORT
yes, you get that like a channel
Toothy means you can use get/fetch_channel discord treats categories similar to channels
oh ok
but how i can get the one that i need by his id
nvm
What would be the correct way to edit an message that has been sent to an moderation channel through modal callback? I'm sending and embed with 2 buttons but when interacting with it I want it to also edit the current message attached to the button. I've tried this but im sure its something im doing wrong regarding the message edit
class AcceptRejectView(discord.ui.View):
def __init__(self, application_id):
super().__init__(timeout=None)
self.application_id = application_id
async def disable_buttons(self):
for item in self.children:
item.disable = True
self.stop()
@discord.ui.button(label="Accept", style=discord.ButtonStyle.green, custom_id="accept_application")
async def accept_button(self, interaction: discord.Interaction, button: discord.ui.Button):
# Fetch and update message using the stored message_id from the database
async with aiosqlite.connect('mybot.db') as db:
cursor = await db.execute('SELECT message_id, channel_id FROM applications WHERE application_id = ?', (self.application_id,))
data = await cursor.fetchone()
if data:
message_id, channel_id = data
channel = interaction.guild.fetch_channel(channel_id)
message = await channel.fetch_message(message_id)
await message.edit(content="Application approved.", view=None)
await db.execute('UPDATE applications SET status = ? WHERE application_id = ?', ('approved', self.application_id))
await db.commit()
@discord.ui.button(label="Reject", style=discord.ButtonStyle.red, custom_id="reject_application")
async def reject_button(self, interaction: discord.Interaction, button: discord.ui.Button):
async with aiosqlite.connect('mybot.db') as db:
# Fetching user_id and message_id for the application from the database
cursor = await db.execute('SELECT user_id, message_id FROM applications WHERE application_id = ?', (self.application_id,))
data = await cursor.fetchone()
if data:
user_id, message_id = data
# Updating application status in the database
await db.execute('UPDATE applications SET status = ? WHERE application_id = ?', ('rejected', self.application_id))
await db.commit()
message_channel = interaction.message.channel
message = await message_channel.fetch_message(message_id)
await self.disable_buttons()
await message.edit(content="Application rejected.", view=None)
# Send DM to the user about the rejection
member = interaction.guild.get_member(user_id)
if member:
await member.send("Your application has been rejected.")
And the the callback from modal if it helps:
if moderation_channel:
message = await moderation_channel.send(embed=embed)
# Save application data including the message_id and channel_id to the database
async with aiosqlite.connect('mybot.db') as db:
await db.execute('''
INSERT INTO applications (unique_id, user_id, channel_id, message_id, ceo_name, airline_name, star_level, route_count, chosen_option, status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (unique_id, interaction.user.id, moderation_channel_id, message.id, ceo_name, airline_name, star_level, route_count, chosen_option, 'pending'))
await db.commit()
#Fetch app ID
cursor = await db.execute('SELECT last_insert_rowid()')
application_id = await cursor.fetchone()
if application_id:
view = AcceptRejectView(application_id[0])
await message.edit(view=view)
Instead of fetching the channel and message you can use the built in
View.message in your case self.message attribute.
your current code should have worked though. did you get any errors?
yeah hardcoding again doesnt throw any errors but doesnt change the role position. And the bots role is at the very top
show your code
I keep getting errors regarding editing message like 'Button' object has no attribute 'guild'
async def callback(self, interaction: discord.Interaction):
guild = interaction.guild
username = interaction.user.id
member = discord.utils.get(guild.members, id=username)
usercolor = self.children[0].value.replace("#","")
color = int(usercolor, 16)
color_role = discord.utils.get(guild.roles, name=color)
if color_role is None:
try:
color_role = await guild.create_role(name=usercolor, reason="Creating color role", color=color)
except discord.Forbidden:
await interaction.response.send_message("I don't have permission to create roles.", ephemeral=True)
return
except discord.HTTPException:
await interaction.response.send_message("Failed to create the role.", ephemeral=True)
return
try:
await member.add_roles(color_role)
await color_role.edit(position=3)
is that the button of a view or
This is a modal, takes the input of the hex color and assigns it to a role
did you try printing to see whether it even reaches that position, and which value the color_role variable has?
when ive tried to troubleshoot, it always says: "moved role to position". Let me do some tests in another file rq
also.... does it actually even assign the role?
I dont know if you just cut it off in the above code but the try at the bottom needs a matching except
so what was the fix
can we have this type of form with pycord ?

