#Basic Pycord Help
1 messages · Page 25 of 1
if someone knows really well the slash commands, can you ping me i might have some question about that ;)
how do i add reaction to interaction message
I'm trying to split my commands into groups, but I get this:
TypeError: The provided command is a sub-command of group
My code:
bot = discord.Bot(intents=discord.Intents.all())
giveaways = discord.SlashCommandGroup("giveaway")
@bot.command(name="giveaway", parent=giveaways)
async def giveaway(ctx):
pass
bot.run("token")
look at the second line
it should be
giveaways = discord.SlashCommandGroup("giveaways")
with the s
and i think you can also do @giveaways.command
doesnt help
try this
bot = discord.Bot(intents=discord.Intents.all())
giveaways = discord.SlashCommandGroup("giveaways")
@giveaways.command(name="giveaway")
async def giveaway(ctx):
pass
bot.run("token")
There are no errors, but the command is not registered.
Do I have to add a subgroup to the bot somehow?
did u try this ?
yes
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - Pycord-Development/pycord
look at those exemple
should help you
But this code doesn't use subcommands, does it?
You probably meant that
https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_groups.py
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - Pycord-Development/pycord
yes, now it works
ty
import discord
from discord.ext import commands
class JoinLogger(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def on_member_join(self, member: discord.Member):
join_log = member.guild.get_channel(1109924971951685682)
print('Testing Event')
await join_log.send(embed=log_embed(member))
def log_embed(member):
embed = discord.Embed(
title=f"{member.name}",
description='Joined the Server',
color=discord.Color.from_rgb(10, 10, 10)
)
return embed
def setup(bot):
bot.add_cog(JoinLogger(bot))
How would I tell the script now that on_member_join is supposed to be an event? Since @bot.event dont work now
nvm @commands.Cog.listener() works
@commands.Cog.listener
Is there a function I can override to do something upon shutdown? before the event loop is closed.
Specifically, I want to sync an empty command list so all my application commands are cleaned up.
why?
because there are two versions of my bot, a production one and a development one. Both use the same commands so having them show up in the slash autocomplete is confusing for users.
why do you have your dev bot anywhere near where your users are
you could gate it into specific channels with permissions
i dont really understand what u trying to do but you can created command and limit to some guild
Development, in this case, is one specific server where I noodle around with stuff people have requested running out of a pycharm window.. production is the exact same server plus about five others.
I mean, I could just make a command and run it by hand, but if there was some way to automatically do something on shutdown...
#dev-bot channel, and gate all commands to that channel only
What I'm getting from this is that the answer to my original question is there isn't one.
Either way, I appreciate the effort, just not down for the re-architecting that would require right now.
well, i've never synced commands manually, so i for one cant help with that
just giving you the most simple and quick idea i could think of
This is a little niche, but you can try de-abstract run and run your own logic instead
There's on_disconnect but it can run multiple times because of how gateway works so it won't be reliable
Really, it depends on how you do the shutdown
Like if you somehow force killed the bot's Python process then any automated shutdown stuff would be bypassed
Ooh, that's a neat idea. And yeah, it would only work for graceful shutdowns. In PyCharm's case, it would be a keyboard interrupt exception.
@sacred burrow Note that there is a limit of registering 200 commands a day. So if you remove and re-add that would count. So that could add up quickly if you are doing a lot of testing.
true
you could test the slash command as a prefix command and change is later to a prefix command
if its basic stuff
why is this returning all permissions as None
because it doesnt have any channel overrides
maybe youre in the wrong channel
not surei f oyu need any intents
are you sure the default_role parameter is correct?
it does have override. default_role is correct I print and check its returing @ everyone
is there any way to identify whether the fetched discord.User/discord.Member object is a deleted user or not?
im using discord.Bot.get_or_fetch_user() to do this
the discrim will be 0000 i think
u sure?
They return all zero now for everything other than bot accounts.
well, what is the pomelo name of a deleted acc
before when i used to do discord.Bot.fetch_user() id only sometimes get discord.errors.NotFound error
but it isnt consistent
itd sometimes return the member object the other times
Someone tried to use a slash command for my bot and got a "The application did not respond" timeout.
Not only does it work fine for me, but I have listeners for on_application_command, on_application_command_error, and on_error, each of which writes to a logging logger. I tried using the command both before and after he tried, and I can see my commands in the log. There's nothing in the log at all for his attempt.
If I got the request, but I just didn't execute it quickly enough, I would have thought I'd at least see the on_application_command log entry, but I just don't see any evidence that I ever got his request at all.
My gut feeling is that his internet just crapped out and the request never made it to me before the end of the timeout window, but before I ask him to try again, is there anything else I should double-check?
Defer the interaction, if it still fails it means it's an internet issue
to defer it, await discord.ApplicationContext.defer()
ctx is just a conventional parameter name, he could even name it as context
yea, but your code makes no sense
discord.ApplicationContext is what ctx actually holds
no
it holds an object of that class
you cant just call the class' function and expect something to happen
That's what I'm telling
no
you are telling them to call the bare function of the class, not of the actually passed object
Instance I meant
Well I just said that so it's easier to look from the docs
then link the docs :)
Cuz that's how the docs documents it
I'm lazy
😞 just stop it. It's okay to be wrong sometimes and be corrected.
For what it's worth, I was initially confused, since the way it was phrased made it seem like some kind of module-level singleton or something like that.
But after I figured out what he meant, spelling out the full class name did make it a lot easier to find in the documentation.
(I mean I know what a context is, I'm just talking about making sure I'm looking at the right class for defer)
i mean you should always have the ApplicationContext docs open when programming
thats what i do lol
always need something from it
yeah, refering to it is a good thing
i just guess attribute names and i usually get them right
or i'll tab complete until i find what i want
Trying to convert code between dpy and pycord, whats the difference between pycords user command decorator and dpys normal commands
has no breaking changes
gets errors becausediscord.Embed.Emptydoesn't work anymore
how would i check if a message was a reply-ping? (aka the user didnt turn off the ping when replying to the bot)
Hi all, my bot can't see message content when I'm trying to:
async def on_message(self, message)
What could be wrong?
check if the intents message is enabled
That was it. Thanks 🙂 Fixed it 
pleasure
Hello, with prefix commands, is that possible to create a command name with a space, for exemple +backup list, and not backup_list ?
Any idea why my bot takes forever to startup and get to the on_ready() function? I also get this message when it's starting before it hits on_ready():
WARNING:discord.gateway:WebSocket in shard ID 0 is ratelimited, waiting 58.00 seconds
like a sub commands?
with prefix comand so not / but yes
do you use shard for your bot ?
Yes. Should I not?
no you should use it
do you use the autoshardedbot ?
Yes
so try to check if you doesnt have fonction that can send a lot of request at the beginning
as far as I know command names in discord.py must be a single word without spaces. So, no 🙂
i think they might be a possibilty, with the bridge command, you can also use command with a space so maybe. But thanks
What would an example of this be?
a fonction at the startup that create a invite in each guild, or fetch everymember
for example
async def backup(ctx, *, args):
args = args.split()
subcommand = args[0]
subargs = args[1:]
if subcommand == "list":
await backup_list(ctx, *subargs)
elif subcommand == "create":
await backup_create(ctx, *subargs)
else:
await ctx.send("Invalid subcommand!")
something like that?
I only have some initial setup like connecting to the SQLite db, starting an AsyncIOScheduler, declaring some authentication variables, and cog extension management commands
i can, but with command with a 1000 lines is more complicated, but i think i will switch to /, more easir
i can really help you with that but you can try to remove a function to see if that solve, if not you put it back and remove another etc
just to find from where it can be
absolutely, I can't see a reason to not use the slash commands
prefix are faster
and not everyone is a big fan of /
well, good luck mate 😄
thanks you man
Oh, wow I ran the code on my testing bot that's in only a few servers and it got to the on_ready() instantly. So for some reason it's because of how many guilds my bot is in...?
of course more there are member more it will take time
but you can handle that to handle the rate limit
but for example event like on_presence that give role are not the best if you try to add role or else
With the actual bot it runs through the whole main.py script then gets to the bot.run(token) and takes forever to get to the on_ready() after that. So it's just sitting there starting the bot up the whole time and has nothing to do with my code then
the fact that is take time is normal
because of the number of guild
but the rate liimit can be handle
You're saying to not use certain event listeners?
no but to be careful with it
on_presence, on_message are event trigger really often
Oh, I can add a check at the beginning of them to not do anything if the bot isn't ready
so if you do an action for each one, you can be rate limit
Can I load a cog with the rest of the event listeners aside from on_ready() after the bot is ready?
you can but why would you do that
it will not solve the rate limit
Oh, so my issue is too many event listeners?
Can I give only some event listeners to one shard and the rest to another shard and that would help?
its not like to many listener, it depend what you do in those listener
to be honest im pretty bad with rate limited, i think you should open a post in #969574202413838426 to get better advice
I just added a check at the beginning of each of the event listeners I have that returns right away at the beginning of the listener if the bot isn't ready. Yet I'm still getting ratelimited
hi guys, in my slash command im responding with ctx.respond()
but my bot has to connect to a different api, get data, process it and then respond
it is taking it longer i think 6 seconds to do all that work
is there a way i can increase the amount of time my bot takes to respond? right now it is erroring out
how do you do that?
how am i connecting to the api?
nah i am using https://cocpy.readthedocs.io/en/latest/
they have their own python package, im using that
it is also async
ok its using asyncio
yeah
if it takes more than 3 seconds you have to defer the slash command with await ctx.defer()
oh
so can i just do ```py
@bot.slash_command(name='war_plan', description='generate the war plan for current war')
async def warplan(ctx):
from game import war_plan
plan = await war_plan()
await ctx.defer()
await ctx.respond(plan)```
okay
just put the defer under the (ctx):
i think i should defer before calling the slow funciton lol
ye
thanks!
mhm
can you link to this part?
Thank you, ill read up on it
Is there any example for usage in a cog somewhere?
I've built my own thing for this case now. However, if someone finds or has an example how to do it with built in stuff for a cog, please do ping me.
Hey @fleet cedar, do you know if the once decorator can be used in cogs? Looking at the code it doesn’t seem like it’s exposed in the same way as commands.Cog.listener
(Tagging since you wrote it ❤️)
That was my first approache. was confused it couldn't be used there 🙂
@commands.Cog.listener(once=True)
async def on_ready(self):
print('ready!')
have you tried that?
That is not gonna work
no, that's working. as stated above, this was my first approache
yeah, wont work in the cog
@commands.Cog.listener()
async def on_ready(self):
print("ready..")
@commands.Cog.listener("on_ready")
async def once(self):
print("printed once when the cog is ready")
workaround? @grizzled loom
I solved by assigning another attribute, boolean and True, to the class and turning it false after on_ready was executed.
guys why arent my commands appearing when restarting the bot
show a command of yours in your code
Restart your client
and that
hm
from discord.option import Option, OptionChoice?
...what?
if you wanna use the decorator. import discord.option
why did you import Option two times?
actually i think its the same thing because of how its set up
but, yea, dont import the same thign twice
Okay, why are you importing it three times
do it once
and ideally, dont do multiple imports on one line, for readability
not to speak of most your imports being unused from what i can see
and please dont duplicate "import discord" 50 times just for importing different things under shorter names
Is there no listener for when commands.Cog is loaded? on_ready only works when the bot is running.
in the init ig?
i want use await but await allowed only within async function can i resolve it?
no idea if you can make an init async, i doubt it
You can. Its kinda weird, but you can
There are examples in this channel
idk what to import so the problem will be fixed, sorry
dont import option 3 times
so just from discord import Option, OptionChoice
yes
or just import discord normally and do discord.Option
import discord
from discord import Option, OptionChoice
from discord.ext import commands
from transmitter.embedmitter import InputMitter
from embed.embedmodal import Embed_Maker
class Fun(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.slash_command(description="Erstelle ein eigenes Embed", name="embed")
@commands.has_permissions(administrator=True)
async def embed(self, ctx, title: Option(str, required=True), color: Option(str, choices=colors, required=True)):
if color == "Ge":
col = discord.Color.yellow()
elif color == "Or":
col = discord.Color.orange()
elif color == "Re":
col = discord.Color.red()
elif color == "Li":
col = discord.Color.purple()
elif color == "Gr":
col = discord.Color.green()
elif color == "Bl":
col = discord.Color.blue()
InputMitter().cmdinput(title, col)
await ctx.send_modal(Embed_Maker())
def setup(bot):
bot.add_cog(Fun(bot))
looks like that now, option is still underlined
and what does it say when you hover over it?
mean that?
how can i fix?
what will @app_commands.describe(command="describe") in pycord
never seen that before
no clue, think you cant
@sage tendon ??
what
@sage tendon ..
are you blind or smth
app command?
sorry but i have no idea about py-cord
yeap
eh
great, but i still said ive never seen that before lol
that is the old discord.py stuff
no slash command describe
do you want to use py-cord?
i am using
do pip list in a cmd window and show us the output
pls do pip list
brh
ok
and I already see discord
yea that looks like discord.py is installed
``pip3 list
Package Version
aiohttp 3.9.3
aiosignal 1.3.1
attrs 23.2.0
Brotli 1.1.0
frozenlist 1.4.1
idna 3.6
msgspec 0.18.6
multidict 6.0.5
pip 24.0
py-cord 2.5.0
yarl 1.9.4`
hm
do you have other version installed?
no
or a venv?
show us the code of the command please
venv
and did you run pip list in the venv?
i think there's something called BridgeOption that you need to use to put a description then
ok
give me example
plz
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...
never used bridgeoption before so i cant help you more than the docs do
ok brother
but you need to typehint the parameter in your function definition as a bridgeoption
Traceback (most recent call last):
File "d:\MOON NIGHT\bot.py", line 5, in <module>
from command import *
File "d:\MOON NIGHT\command.py", line 10, in <module>
@bridge.BridgeOption(
^^^^^^^^^^^^^^^^^^^^
TypeError: 'BridgeOption' object is not callable
`import discord
from discord.ext import bridge
Define clear command
@bridge.bridge_command(
name='clear',
description='Clear messages from the channel',
aliases=['clr',"cm"],
)
@bridge.BridgeOption(
description="Enter Amount"
)
async def clear(ctx, amount = str):
if amount == "all":
amount = None
try:
await ctx.channel.purge(limit=amount + 1)
await ctx.send(f"Cleared {amount or 'all'} messages.", delete_after=5)
except discord.Forbidden:
await ctx.send("I don't have permission to delete messages.")
except discord.HTTPException:
await ctx.send("Failed to delete messages.")
`
.
can i find example?
Use something called the search bar
Very popular around Discord
Try it and see
@stuck oar can u help me bro or sis ? chat in dm
bruh
actually the docs apparently also just use the normal option decorator for bridge commands too
so use that
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - Pycord-Development/pycord
weird
it was another topic bro
then DM them directly or ask your question directly
app.py:22: RuntimeWarning: coroutine 'Suggestion.__new__' was never awaited
continue
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
what is this error?
class Suggestion(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def __new__(cls, *args, **kwargs):
suggestion_embed = discord.Embed(
color = 0x7469B6,
title = "💬 건의사항",
description = "이 채널에 건의 내용을 **구체적으로** 작성해주세요.\n- 건의 내용이 구체적이지 않거나 적합하지 않다면 **거부**될 수 있습니다.\n- 작성해주신 건의사항이 승인되면 #1218583527604490343 채널에 메시지가 올라옵니다."
).set_footer(text="🌱 Copyright 2024. Lucy Studio all rights reserved.")
SUGGESTION_CHANNEL_ID = 1218582335180505161
SUGGESTION_MESSAGE_ID = 1218582404457828392
suggestion_channel = cls.bot.get_channel(SUGGESTION_CHANNEL_ID)
suggestion_message = await suggestion_channel.fetch_message(SUGGESTION_MESSAGE_ID)
await suggestion_message.edit("", embed=suggestion_embed)
obj = super().__new__(cls)
await obj.__init__(*args, **kwargs)
return obj
await the get_channel
suggestion_channel = await cls.bot.get_channel(SUGGESTION_CHANNEL_ID)
or wait
right?
app.py:22: RuntimeWarning: coroutine 'Suggestion.__new__' was never awaited
continue
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
same error
oh
well
beacuse its async, you need to await the creation of the suggestion object now
mb
damnnn, ah and why isnt the command appearing for me even after restart of bot?
restart your discord
File "d:\MOON NIGHT\command\clear.py", line 34, in <module>
@clear.command(
^^^^^^^^^^^^^^
File "D:\MOON NIGHT\venv\Lib\site-packages\discord\ext\bridge\core.py", line 396, in wrap
slash = self.slash_variant.command(
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\MOON NIGHT\venv\Lib\site-packages\discord\commands\core.py", line 1258, in wrap
command = cls(func, parent=self, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\MOON NIGHT\venv\Lib\site-packages\discord\ext\bridge\core.py", line 83, in __init__
super().__init__(func, **kwargs)
File "D:\MOON NIGHT\venv\Lib\site-packages\discord\commands\core.py", line 694, in __init__
self._validate_parameters()
File "D:\MOON NIGHT\venv\Lib\site-packages\discord\commands\core.py", line 712, in _validate_parameters
self.options = self._parse_options(params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\MOON NIGHT\venv\Lib\site-packages\discord\commands\core.py", line 770, in _parse_options
option = Option(option)
^^^^^^^^^^^^^^
File "D:\MOON NIGHT\venv\Lib\site-packages\discord\commands\options.py", line 232, in __init__
raise exc
File "D:\MOON NIGHT\venv\Lib\site-packages\discord\commands\options.py", line 227, in __init__
self.input_type = SlashCommandOptionType.from_datatype(input_type)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\MOON NIGHT\venv\Lib\site-packages\discord\enums.py", line 834, in from_datatype
if isinstance(datatype, str) or issubclass(datatype, str):
^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: issubclass() arg 1 must be a class```
@sage tendon
@celest atlas
@lapis dock
anybody
Do NOT override __new__ in a cog
is this a bridge command
yeap bridge command group
map_to
uhhhhh
@bridge.map_to(
name="all",
description="Delete All The Msg Of This Channel"
)
async def clear(ctx : bridge.BridgeContext):
await ctx.channel.purge()
await ctx.reply(f"Cleared all messages.", delete_after=5)
@clear.command(
name="bot",
description="Delete All The Bot Msg Of This Channel"
)
async def bot(ctx : bridge.BridgeContext):
def is_bot(message):
return message.author == bot.user
deleted = await ctx.channel.purge(check=is_bot)
await ctx.reply(f"Deleted {len(deleted)} bot messages.", delete_after=5)
@clear.command(
name="amount",
description="Clear Messages From The Channel"
)
async def amount(ctx : bridge.BridgeContext,amount:int):
await ctx.channel.purge(limit = amount +1)
await ctx.reply(f"Cleared {amount} messages.", delete_after=5)
@clear.command(
name="user",
description="Delete all msg of specific user"
)
async def user(ctx : bridge.BridgeContext,user: discord.user):
def is_user(m):
return m.author == user
deleted = await ctx.channel.purge(limit=100, check=is_user)
await ctx.send(f'Deleted {len(deleted)} messages from {user}')```
why are you not using the option decorator like i suggested
can you follow these instructions #1132206148309749830 message
its work before adding option user
Don't ping random helpers for help, be patient and if your question is not answered try rephrasing it or putting it in a forum channel
ok brother
(that answer meant "go away, I always do it like this and i wont stop doing it")
bro my problem fix i dont cap -> u in user: discord.user and than making problem
If you program like you speak english then i know why that is
yeap
discord.user should be uppercase discord.User
i am not good in langauge
Extension 'cogs.ticket' raised an error: RecursionError: maximum recursion depth exceeded while calling a Python object whats that
Bump (just in case)
you seem to have recursion in your code, find it and fix it
do you know what recursion is?
no
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 think this should work
if you have a function that keeps calling itself in its body, thats recursion
oh damn, how can i find it
read your code
damn it
if you're lazy then give it to chatgpt and ask it to find it
sure
Have already tried, seems to work only when mentioning the bot with @ and not reply-pinging
https://docs.pycord.dev/en/stable/api/data_classes.html#discord.MessageFlags.suppress_notifications i'm not sure if this just means the @silent thing
but you can try it out
im p sure it would just trigger for @silent but i cant find anything else that would make reply pings detectable
think fixed it but now i get: Extension 'cogs.ticket' raised an error: AttributeError: 'TicketDB' object has no attribute 'setup'
well, read the error lol
why do you have a cog in your main file
what
why are you loading a cog like that
im so confused
i have so many questions
then why are you redefining your bot?
and why is your class definition under all the code?
wait why do you have 2 ticket classes
oh
like 1 is for all the functions you know
i had that error before Extension 'cogs.ticket' raised an error: TypeError: TicketDB.__init__() missing 1 required positional argument: 'bot'
I meant this
and thats why you dont mix your util classes into your cogs
i know
how to fix?
well
if you only need the functions in the db class for your cog, just put them in the cog lol
just dont do it the second way?
i dont really see the issue lol
ping is the command, ! is the prefix
and yes, you can override it
if im wrong correct me everyone but i think you can just copy the help command class from the lib and change the stuff you wanna change
Heya all, I am trying to escape this ^ character from my discord file return. For some reason either it does not send and throws an error or it returns without the ^
Name I want - mp_m_freemode_01^jbib_diff_001_a_uni
await ctx.respond("Uniform Created")
filename = f"sent/mp_{sex}_freemode_01^^{type}_diff_{number}_{letter}_uni.ytd"
await ctx.send(file=discord.File(filename))
or dont
there's nothing special about ^
that's what the Attachment option type is for
Thanks for giving me the founding brick to my goal 
Is there already a way to change the bot av via code
yes
Can u send?
There always was.
?tag gif_avatar
How to upload an animated avatar for your bot
To use and upload an animated avatar you can run the following snippet as standalone script:
import discord
# Create a Discord client instance
client = discord.Client(intents=intents)
# Event to handle bot's initialization
@client.event
async def on_ready():
print('Logged in as {0.user}'.format(client))
# Upload animated avatar
try:
with open('yourpicture.gif', 'rb') as avatar:
await client.user.edit(avatar=avatar.read())
print('Animated avatar uploaded successfully!')
except Exception as e:
print('Failed to upload animated avatar:', e)
# Run the bot
client.run("YOUR_TOKEN")
That should be all, have fun!
Nope
No what?
That's how you do it.
You get the ClientUser object with discord.Bot.user
As an AI language model, I have no idea what you mean by that /j
There is no way to change banner
you said avatar
You change the banner through the dev portal...
Oops sorry
No its bugged
idk what you mean @timid shuttle has it
zoom it out /s
And how?
What type of banner are you trying to upload
which aspect ratio, more importantly
png
69:420 /s
Hey, is there a way to have more emojis in one choice of select menu?
having emojis directly in the text for example
discord seems to not allow this
Honestly I don’t remember anymore 😅
I’ll check and let you know
its just unicode characters, so, why not
Hmm okay
So await operations can't be performed when Cog is loaded?
Why do you need an async init?
I would like to send a message when Cogs loads. (specified channel)
Add a cog listener to the on_ready event and send the message there.
Cogs on pycord aren't loaded at runtime, they're loaded before.
That way, messages will only be sent the first time the bot is run. I would like to have it transmitted even when unload and load (reload) cogs. Is this not possible?
Traceback (most recent call last):
File "D:\MOON NIGHT\venv\Lib\site-packages\discord\client.py", line 400, in _run_event
await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
TypeError: on_ready() missing 1 required positional argument: 'bot'
could we see some code here
import os
import discord
from discord.ext import bridge
from button import *
from command.clean import clean
from dotenv import load_dotenv
from events import on_ready, on_voice_state_update
load_dotenv()
TARGET_VOICE_CHANNEL_ID = int(os.getenv("TARGET_VOICE_CHANNEL_ID"))
CATEGORY_ID = int(os.getenv("CATEGORY_ID"))
TOKEN = os.getenv("TOKEN")
intents = discord.Intents.all()
intents.voice_states = True
custom_activity = discord.CustomActivity(name="𝓔𝓵𝓲𝓽𝓮𝓹𝓻𝓮𝓹 🚀")
bot = bridge.Bot(command_prefix='!', intents=intents, activity=custom_activity, status=discord.Status.dnd)
bot.add_bridge_command(clean)
bot.add_listener(on_ready)
bot.add_listener(on_voice_state_update)
bot.run(TOKEN)
``` main.py
event.py - ```
async def on_ready(bot):
print(f'Logged in as {bot.user}')
async def on_voice_state_update(member, before, after, bot):
if before.channel != after.channel:
if after.channel and after.channel.id == bot.TARGET_VOICE_CHANNEL_ID:
category = member.guild.get_channel(bot.CATEGORY_ID)
new_vc = await category.create_voice_channel(f"{member.name}'s Channel")
await member.move_to(new_vc)
if before.channel and before.channel.id != bot.TARGET_VOICE_CHANNEL_ID and len(before.channel.members) == 0:
await before.channel.delete()
so here's the thing, on_ready doesn't take any args.
this might be better put inside a cog instead of a seperate file
There comes a point in your bot’s development when you want to organize a collection of commands, listeners, and some state into one class. Cogs allow you to do just that. The gist: Each cog is a P...
Thanks Bro Now Working
great
but i do suggest trying to use a cog for future use. you might run into issues in the future if bot can't be referenced
oo
File "d:\MOON NIGHT\main.py", line 8, in <module>
from command.vc import test_buttons
File "d:\MOON NIGHT\command\vc.py", line 4, in <module>
from discord.ui import ButtonStyle
ImportError: cannot import name 'ButtonStyle' from 'discord.ui' (D:\MOON NIGHT\venv\Lib\site-packages\discord\ui\__init__.py)```
really have no idea how
so to await something you need to add an await before ;)
for file in os.listdir(r"cogs"):
if file.endswith(".py"):
extension = file.replace(".py", "")
try:
bot.load_extension(f"cogs.{extension}")
except Exception as error:
print(error)
here is the right spot
this is not where your error happen
because that's where your print is
damn
the problem might be that he is trying to create a new task instead of using the bots already existing loop to call .setup
server_id INTEGER PRIMARY KEY, <- this is gonna be a problem
primary key has to be unique
you have a primary key set for a guild id
you can not make a second entry with the same id
make it a combination of two things. first part of your primary key can be guild.id.
the second part of your primary key must be something that only appears once in combination with this guild id
so if you store several rows for this server
and several rows for each category
category can not be the second part of your key
also any part of your primary key should not have DEFAULT 0, cause it can run into the same problem. in has to have NOT NULL instead, so its sth. you have to pass when creating a db entry
*pass meaning "pass along" not "pass" in the python sense of the word
Does this make sense to you FantasyOnFire?
furthermore
pretty complicated actually haha
what is
self.db = None
for? it's not used anywhere
in simpler terms
a primary key is there to identify one specific row.
therefore under no circumstances two identical primary keys can exist in any database
row one, column 1, guild_id = 1234
now you can not make any more entries with guild_id = 1234 in the entire table
better?
yes
good
here is the problem?
the problem is how your table layout is made when it's created.
ofc everthing else that tries to use this table will fail eventually
as lont as this isnt changed working on other parts doesnt make much sense
*long
and you have to delete the table with the wrong layout/design so it makes a new one ofc
so just recreate the table like that?
no, that's your code. its from the txt file you sent in here a few minutes earlier
yep
i just used it to highlite the problem, so you know what part to work on 🙃
also server_id should be BIGINT and not INT
depends
because guild can be higher than the int limit
i use mysql
what Luma said then, for mysql he's perfectly right
😅 I just assumed it would be sqlite when I saw the int
so what should i change to what?
in your table int to bigiunt
i already dropped the tabled
I don't think so
How many commands does your cog have that you'd need multiple files
https://github.com/Dorukyum/pycord-multicog made by a pycord dev but not offical supported
hey guys is it possible to send 2 modals in a row?
i have amodal where i need to put 5 inputs haha, so its too big apparently
so i wanted to send a second modal after for that but im not sure its possible
5 should work fine
5 is the limit for a modal
to answer your original question no, you would have to have the modal respond with a button that responds with another modal
Okay thanks
Ohhh i didnt know that, thought it was 4, lesgooo !
Is there a way to change bot's banner? (I mean can the bot change it)
At the website you can do it but I dont know if they already added it to pycord
Ik that I can do it on developers portal
But my banner includes stats so bot should update it by itself
They added it https://github.com/Pycord-Development/pycord/commit/530f3d45956e037d3d5bea0a02153887abfafe2f
Signed-off-by: Brandon <[email protected]>
Signed-off-by: plun1331 <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.no...
Hi, so basically i made a function that sends an embed with 2 button, how could i return a value to a variable whatever a button has been pressed when calling that function
only in the master branch
ik
use the button callback
do you have an example?
just handle the stuff you wanna do in the function of the button you defined i nyour view class
i dont wanna do that tho
bruh
Or just read the docs about the button
if you dont wanna do whats required to solve your problem then what exactly do you want
I dont think you understand what im trying to achive
i absolutely do
yea you said that
you cant return a value from the callback
but thats not really how buttons / views work
Then how could i apporach this then
also just use f strings for this, simple tip
yes it was just for testing
Yes you can
How?
Because i cant just put return value in the callback
the function just returns the message sent before and not the button pressed
Define a variable on the callback self.my_value = "hello" and you also add self.stop()
view = MyView()
view.wait()
print(view.my_value)
lemme try
like this?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'startSetup' object has no attribute 'my_value'
startSetup is the file
a wait
i had to await it
Thank you
ah yes, sorry
No worries
Consider adding a check for if the view times out
View.wait returns True or False depending if it timed out or if it was manually stopped
.rtfm ui.View.wait
thanks
hm, never did that actually
ctx.command.name gives you the name of the command :3
ctx.command returns the command
yes, when stringified, it returns the name
Is there any option for slash command that you can only enter a user?
yes
when i try to put 5, i get this error
modal.add_item(inputText)
File "C:\Users\billy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\modal.py", line 206, in add_item
self._weights.add_item(item)
File "C:\Users\billy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\modal.py", line 289, in add_item
total = self.weights[item.row] + item.width
IndexError: list index out of range
when i try to put something on row 5
got it
i should start with row 0 then?
i was always starting with row 1 hahaa
oh gosh same for buttons and all, i never knew that 😭
i know that very good haha
but i didnt know the rows system had to start at 0
thought it was made so it starts at 1
Why cant I put any gif in the developer portal for a banner or pf for an bot ? only accept jpeg or png
they're planning on updating it to support gifs
for now, you can set a gif avatar via bot.user.edit; banner support was just added on master, but not a formal release
I see thank you !
what kind of error am i looking at?
something dns related maybe. definitely network
i assumed as much but I just have a hard time believing it's a dns issue considering that im able to open and operate discord.
can you curl or ping anything?
what about not on the local machine
everything else is working
the 3 other residents in the building also aren't making any complaints
amazing, I kid you not it's working now
I'm going to assume my isp was being fuckity and somewhat got their shit together
Is it possible to respond to multiple interactions with the same response? If so, how can it be done?
no
to give a role to a member I need to give the role's ID?
it's on the on_member_join event
then, yes
Hi so I'm trying to make a command like the example below but I'm not sure what object/class (?) I need to use in order to make it work. I would like it to auto complete or suggest values for the state
async def change_state(ctx: discord.ApplicationContext, search: str, state:...):
so when I type /chnage_state search: "some text" state: I get options of different states to pick (start, stop, restart).
I'm probarbly not explaining it very well
do you have a set amount of choices or is it just supposed to suggest a few words
the former, the choices will always be start, stop, restart
then make a discord.Option() with the choices=[] parameter
though
do you have the search option already handled via the @option decorator?
nope, but I'll hopefully be able to figure it out
i would always suggest using the @option decorator
else your function header can get very long
example
okay thank you for the example, using the decerator does make sense
so somehting a little like this
@commands.option(name="state", description="The state to change the container to.", type=3, choices=[discord.ApplicationCommandOptionChoice(name="start", value="start"), discord.ApplicationCommandOptionChoice(name="stop", value="stop"), discord.ApplicationCommandOptionChoice(name="restart", value="restart")])
i am pretty sure you can just do choices=["string", "string2"]
but lemme check
yea you can do it like this if your names and values dont differ
okay great. saves on a whole bumch of lines lol
since I know how to use a decorator to "autocreate" a slash command I dont use options anymore like that x3
then how
also, you can just use discord.option or just import option directly btw
Is there a way to get the guild count from other bpts
action = discord.AutoModAction(action_type=discord.AutoModActionType.block_message,
metadata=trigger_metadata)````
For what do i need metadata in here
docs will tell you
I dunt understand it
Docs are bad when i talk about automod
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 ...
action = discord.AutoModAction(action_type=discord.AutoModActionType.block_message, metadata=)```thats my code
If i put custom_message in i get an error
just make a AutoModActionMetaData object
metadata=discord.AutoModActionMetadata(custom_message="You have one or more words in your message that are forbidden on this server.")
This should be correct?
@sage tendon^^
try it and see
It doesnt work
It says
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: AutoModActionMetadata.__init__() got an unexpected keyword argument 'custom_message'```
Bro its copyed from docs tf
What is the problem?
literally wtf
maybe pass it positionally?
wdym
dont pass it as keyword
and?
wait which am I supposed to import to use the @option decorator? the commands.option or discord.option?
its teh same, but discord.option
um okay
management-bot | Traceback (most recent call last):
management-bot | File "/app/main.py", line 69, in <module>
management-bot | @option(name="state", description="The state to change the container to.", type=3, choices=["start", "stop", "restart"])
management-bot | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
management-bot | File "/usr/local/lib/python3.12/site-packages/discord/commands/options.py", line 416, in decorator
management-bot | func.__annotations__[name] = Option(type, **kwargs)
management-bot | ^^^^^^^^^^^^^^^^^^^^^^
management-bot | File "/usr/local/lib/python3.12/site-packages/discord/commands/options.py", line 227, in __init__
management-bot | self.input_type = SlashCommandOptionType.from_datatype(input_type)
management-bot | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
management-bot | File "/usr/local/lib/python3.12/site-packages/discord/enums.py", line 812, in from_datatype
management-bot | datatype_name = datatype.__name__
management-bot | ^^^^^^^^^^^^^^^^^
management-bot | AttributeError: 'int' object has no attribute '__name__'. Did you mean: '__ne__'?
@dockercmdgroup.command()
@option(name="search", description="The container to change the state of.", type=3)
@option(name="state", description="The state to change the container to.", type=3, choices=["start", "stop", "restart"])
async def change_state(ctx: ApplicationContext, search: str, state: str):
embed: discord.Embed = container_change_state(dockerclient=dockerclient, containersearch=search, state=state)
await ctx.respond(embed=embed)
3 is not a type
do I need to tell it which type to use or will it just do it?
what do you want to do wit hthat
pass it as the first positional argument
thats how i do it
I see there's 4 types in the docs
yea, you just type the name
i always pass the name and type as positional arguments, in that order
because they're kinda obvious to read in the code
so this?
@option(3, name="state", description="The state to change the container to.", type=3, choices=["start", "stop", "restart"])
how do I find the name? is it just SlashCommandOptionType? I read the docs as there being 4 types and that each type was a list of sub types (making SlashCommandOptionType the sub type)
ohh
management-bot | Traceback (most recent call last):
management-bot | File "/app/main.py", line 69, in <module>
management-bot | @option(str, name="state", description="The state to change the container to.", choices=["start", "stop", "restart"])
management-bot | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
management-bot | TypeError: option() got multiple values for argument 'name'
```I'm really not sure what it's saying here because only one name is defined
@option("state", str, description="The state to change the container to.", choices=["start", "stop", "restart"])
oh, well that's confusing
would this be valid? type=str, name="search directory", I like to be explicit where possible
.tias
of course
but as i said, i always pass them positionally because i like my lines not 1000 chars long
okay thanks again for the help
np
Let's say I deferred the response to an interaction, but then an exception occurs afterwards.
In order to keep the interaction from waiting forever with a "[my bot] is thinking..." spinner, is the best practice here to listen for on_application_command_error, and context.respond the context provided as a parameter to that event, with some kind of "Some kind of error occurred" message?
(I mean I know I can do that, I'm just asking whether that's the normal/advised practice.)
seems fine to me
What
Can someone tell me how I make a user command
like the right click commands?
Nope. Since yesterday users can add apps to themselves
You know what i mean?
not possible in pycord yet
but fwiw, there's nothing much to change - when it's available, they'll be easy to implement within discord's limitations
Shouldn't pycord have been notified by Discord that they had this on time?
lala and doruk were already working on it since last year
that doesn't mean it can be released instantly
Since last year? What
for some features lib devs might have info on it early
This function has been planned for so long?
...internally, 7 years ago (this is kinda getting off track, if you wanna read some of lala's insights it's from #general message)
A friend send me, that u have to put 2 words and 4 numbers in the commands. That can’t be take that long
then go patch it in yourself idk man
Okay
sure we *could* just release that but it needs to be properly implemented to the API spec
Btw https://discord.com/channels/881207955029110855/1219383639553474640 is a bug or?
no, it was implemented on 2.5
if you tried to use it on 2.4 then of course it'd error
Can i add a custom message and timeout
The docs state that it has been available since 2.0
that's for AutoModActionMetadata, not custom_message
(arguably that should have a separate version number but i probably forgot)
Do you know when a bot get the Automod badge
👍
You may have noticed a new badge floating around on various bot profile pages. Here is some info about the AutoMod badge and how to obtain it for your application:
💡 If your app has at least 100 ru...
They have to stay
probably?
how to make discord Modal pycord
discord.ui.Modal
discord.ui.Modal.add_item
discord.ui.Modal.callback
discord.ui.Modal.children
discord.ui.Modal.custom_id
discord.ui.Modal.on_error
discord.ui.Modal.on_timeout
discord.ui.Modal.remove_item
discord.ui.Modal.stop
discord.ui.Modal.title
discord.ui.Modal.wait
discord.ui.modal.Modal
discord.Guild.fetch_auto_moderation_rule
discord.Guild.fetch_auto_moderation_rules
discord.Guild.create_auto_moderation_rule
@keen relic
thx
how to write server name in message?
thx
View does not work in forum channels.
class BuyButton(discord.ui.View): # <------ HERE
@discord.ui.button(label="구매하기", style=discord.ButtonStyle.green, emoji="💵")
async def button_callback(self, button: discord.ui.Button, interaction: discord.Interaction):
print("asdf")
# await interaction.response.send_message(f"{name}, {price}, {description}")
await interaction.response.send_message("test")
class ShopManager(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name="제품생성")
@commands.is_owner()
async def shop_create(self, ctx, id:int=None, name=None, price:int=None, *, description=None):
if id == None or name == None or price == None:
error_embed = discord.Embed(
color = discord.Color.red(),
title = "❎ 오류 발생",
description = "`!제품생성 [상점ID] [제품명] [가격] [제품설명]` 으로 사용해주세요."
).set_footer(text="이 메시지는 5초 후 삭제됩니다.")
await ctx.reply(embed=error_embed, delete_after=5)
return
# sql = f"INSERT INTO products_{id}(product_name, product_description, product_price) VALUES (?, ?, ?)"
# sql_data = (name, description, price,)
# cur.execute(sql, sql_data)
# conn.commit()
category = discord.utils.get(ctx.guild.categories, id=id)
channel = discord.utils.get(category.channels, name="⛄│제품목록")
embed = discord.Embed(
color = 0xF6F7C4,
title = f"💵 {name} 구매하기",
description = f"> {name}을(를) 구매하려면 [ 💵 구매하기 ] 버튼을 클릭하세요.\n{description}"
).add_field(name="제품 가격", value=f"{price}원").add_field(name="판매자", value=ctx.author.mention)
await channel.create_thread(name="test", content="", embed=embed, view=BuyButton(timeout=None)) # <-------- HERE
await ctx.message.add_reaction("⛄")
If I call that view from a regular message it works fine, but it doesn't work for messages in a forum channel.
Slash command sub-commands
Like /set [add|sub|set] user int
How do I add sub commands? I forgot
@bridge.map_to(
name="all",
description="Delete All The Msg Of This Channel"
)
async def clean(ctx: bridge.BridgeContext):
await ctx.channel.purge()
embed_message = EmbedMessage(ctx)
await embed_message.send_embed("Cleared all messages.")
@clean.command(
name="bot",
description="Delete All The Bot Msg Of This Channel"
)
async def bot(ctx: bridge.BridgeContext):
def is_bot(message):
return message.author == ctx.bot.user
deleted = await ctx.channel.purge(check=is_bot)
embed_message = EmbedMessage(ctx)
await embed_message.send_embed(f"Deleted {len(deleted)} bot messages.")
@clean.command(
name="amount",
description="Clear Messages From The Channel"
)
async def amount(ctx: bridge.BridgeContext, amount: int):
await ctx.channel.purge(limit=amount + 1)
embed_message = EmbedMessage(ctx)
await embed_message.send_embed(f"Cleared {amount} messages.")
@clean.command(
name="user",
description="Delete all messages of specific user"
)
async def user(ctx: bridge.BridgeContext, member: discord.Member):
def is_user(m):
return m.author == member
deleted = await ctx.channel.purge(limit=None, check=is_user)
embed_message = EmbedMessage(ctx)
await embed_message.send_embed(f"Deleted {len(deleted)} messages from {member}", hex_color="#42f5f2")
Take a look at this
Here's the slash cog groups example.
how to create a role?
check the docs for "guild"
thx
@sage tendon like I said its an application bot. Someone answers questions in a DM, then the bot posts those responses along with accept/deny buttons in a thread for admins to review
as for the views, can you show the code that handles creating them, and the view itself
older thread buttons die once it posts a new appliation thread
are you making a new view object every time or reusing the old one?
yea that's what popped in my head just now too
and you probably want to look at persistent views
im going to get evicerated on my code 💀
Here's the persistent example.
if you're even just an average coder, half of all people are worse
Is there a way to refresh the slashcommands? I've got to the point with my bot where I will fire it back up in debug to see if a slashcommand works, and the old slashcommand remains and the new one doesn't exist (and or the changed option isn't updated and still has the old one)
restart your discord
How to set permissions correctly when creating a role? (I need an example)
Read the doc
make sure you're waiting 2 minutes between restarts, you could be rate limited when registering commands
restarting your bot* discord ofc doesn't matter
Yeah heard - both god sends. Thank You
these are the approvalRoles buttons that break once a new thread is made
ok first question why are you iterating over a list
why aren't you doing it like, on-demand as the users request it or whatever your setup is
I cant remember precisely, I made this about 6 months back and now im trying to fix some things. If I remember its because I didnt know how to keep context for sending the right questions to each of the DM sessions with the bot so I used an array
yea the code confuses me a lot lol
Its actually written really well
this is really where my python knowledge ends but I think it MIGHT be because you keep using the same variable and it keeps being overwritten? so the old view goes out of scope?
I already saw so messy codes at this server here 
correct me pretty please I'm tired
so im probably overwriting the view with each application thread that is made huh?
where does server_id come from
I was thinking that, but I genuinely don't know how this stuff works in python
in java it'd be clear
I think persistent views will fix it
well you'd be letting the view go out of context basically, and so it gets deleted from ram
maybe lol
yea you need this anyway I think
all of the variables are just globals uptop until I eventually make a config file
all?
all.
all the statics are up there like the role ids and such yeah
the only globals are role ids, server id, and the application question strings
is having those static id numbers up top while im still just developing and testing it that bad?
i understand moving them to a config file to make changes easier eventually
globals in python were a mistake
>>> x=[1,2,3]
>>> for i in x:
... x.remove(i)
...
>>> x
[2]
🙃
I have @discord.default_permissions(manage_messages=True) on 3 commands. Everyday users can still use the command. Why is that
check the actual permissions in the server settings
you / someone might have overridden them
Imma tell the owner that then
I thought python wouldn't let you
oh it would
and i think its good
programming languages should not set any hard limits unless absolutely necessary
because even if most cases end in shit like this, it still has uses
oh and you probably want a break after you remove the member @safe obsidian
unless you expect them to be in the list twice
so I should restructure the removal to snag the index, break, then remove after?
yeah
Personally I think a dictionary would be a better choice instead of a nested list
how to send message to a specific channel?
it's just channel.send once you have the channel object
fast question, does message.reply have some option to reply without pinging?
yes, I believe it's mention=False 
yeah, but why it isn't said in docs
i mean optional parameters
am i dumb? why does this not edit the response?
it's mention_author
https://docs.pycord.dev/en/stable/api/abcs.html#discord.abc.Messageable.send
?
the response sends just fine
but i wanna edit it
it keeps getting stuck there without an error
it should also work with ctx.interaction.edit_original....
Command?
Do await ctx.edit
how to make a message that will only be visible to one person. example:
interation ephemeral
thx
That was for master killer, not you
oh
Does it work
how to made cooldown for a command?
You can start here
Here's the cooldown example.
eh cba to try around more, just did defer now
Okay
ctx.edit
so i can do
ctx.respond()
and then
ctx.edit()?
It's property because it's a copy of interaction.edit, poor formatting from our autodoc
And yes
how can i edit an embed twice while interacting with it? apparently i cant prompt a modal, then edit the same message after modal has been fulfilled. it gives:
this message already has been edited.
error or something like that
Pycord Guide is a complete guide for Pycord. Learn how to create Discord Bots today!
Can you show your code
i changed it but it was something like this
it would say, interaction message has already been edited before
Why don't you just create the role on the modal callback?...
because i need it later on
What im trying to do it to setup a ticket category with the correct permissions ect
why dont you use a dropdown to select an existant role ?
thats what the second button is supposed do
basically what im trying to achive is to ask the user for information, and create a ticket system based of those information
also i am creating the role in the callback, im just returning it as a value later on
If I'm using the required=False attribute in the decorator then I don't need to use search:str = None, right?
@option(name="search", type=str, description="Search for specific containers.", required=False)
async def list(ctx: ApplicationContext, search: str = None) -> None:
p sure itll be none regardless
is there a way I could make a slash command accept the same input multiple times. I have a search argument and I'd like users to be able to input multiple searches. Would I need to add multiple search arguments like search_1, search_2 or could I use *args or somehting
Discord requires you to specifically define them. So have a search_1, search_2, etc
Another way would just be to tell the user to split searches with , or somthing.
yeah that makes sense and lines up with what I thought
I'm trying to make buttons wider for my paginator using something similar to: #998272089343668364 message
(just adding spaces to the label)
But it isn't changing the width. Any ideas?
buttons = [ButtonClass("prev", label=" < ", custom_id="paginator1" + str(nameId), style=discord.ButtonStyle.green),
ButtonClass("page_indicator", custom_id="paginator2" + str(nameId), style=discord.ButtonStyle.gray,
disabled=True),
ButtonClass("next", label=" > ", custom_id="paginator3" + str(nameId), style=discord.ButtonStyle.green)]
I suspect it could have something to do with my custom ButtonClass that I'm using to make the paginators persistent:
class ButtonClass(PaginatorButton):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
async def callback(self, interaction: discord.Interaction):
test = interaction.message.components[0].children[1].label
teststring = str(test)
testsplit = teststring.partition("/")
selectsplit = int(testsplit[0])
self.paginator.message = interaction.message
self.paginator.current_page = selectsplit - 1
await super().callback(interaction)```
I'm sure discord stips the spaces
You should use an invisible character instead
The user of the thread you mentioned uses invisible characters, not spaces
Aha this is what I was missing thanks
how to log any command/event etc? there's something to log every update?
(i want to log in a discord channel)
is there a way to detect if a user is talking? or how can i use start_recording as long the user is talking? Currenlty im using
await asyncio.sleep(2)
but it will only record for the given seconds and then continue.
Anyone has a clue?
I want to make prefix commands that only I have access to.
So Is it possible to make prefix commands that only work within a DMChannel of a specific user?
And should something other than wait_for be used for a function like this?
The docs has all possible events you can listen to. Read them.
There's a is_owner decorator for that.
Only the owner of the bot would be able to run that command.
Thanks Dark!
So if it's a slash command it wouldn't be visible to others?
No, if it is a slash command it'd still be visible
The decorator is just an internal check.
The only way to "hide" a slash command is only registering it in a private guild of yours.
Dang thanks good to know!
That's a smart workaround.
I'll make it a prefix command instead then since those have no visibility
can you already use user apps with the master branch or is this feature not yet implemented?
Does pycord supports rate limits of top level resources in a bucket ?
is it possible to sync slash commands in pycord since my command isnt appearing after restart
not yet
did you override on_connect
elaborate
on_connect?
if you didn't that's fine
i mean i could have, but im not sure where it is
if you did then it'd be in your main bot file
that's where the command sync happens, normally you wouldn't need to do anything special - it's always meant to sync on startup
dont think i override it
okay thx, do you know when this feature will be implemented?
don't have an ETA but lala and doruk have already been working on it for a while
if you're desparate for user apps you could try look at the changelog and implement it yourself since at the baseline you only need minor changes
but for a proper pycord release they have to be more thorough
Okay thank you, its not that desparate. I'll stick around and look at the git commits if there are any for user apps.
fair enough
(if you do want to prod around, for commands you mainly need to implement the integration_types and contexts attributes as per https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-structure)
Yeah I've seen that already, maybe i'll try it later idk yet
As per the discord docs, the same route can have different rate limits based on its bucket and top level parameters
The library dynamically handles ratelimits based on any 429 response, which if it receives it will attempt to retry automatically
So in general, you don't need to worry about them so long as you aren't pushing it too much
So if you are been rate limited, it will wait for the time mentionne by discord for all requests?
The rest of the bot will continue to run
It'll wait for the specific ratelimited request to be available again before retrying
(Also note, you need minimum loglevel of WARNING to see ratelimits in console https://docs.pycord.dev/en/stable/logging.html)
In my case I do a add/remove a role to all member of a server. But if for one server only I get rate limited as guild_id is top level parameters, it will block all add/remove roles for all the other guilds ?
No
If you want you can test it yourself with an example command
The ratelimit for changing a channel name is twice every 10 minutes - set your loglevel with the instructions I linked above, then make a command that changes the current channel's name
Try running it a few times and see the results for yourself
I see I will try ! Thank you
I'd move text += chunk.text at the top of the condition
So you only have one
Otherwise, uh, looks fine ig I don't think you can get it any shorter
true
Hello, i would like to know if its possible to have multiple sub command in the same class ?
for exemple :
group moderation
1 file with ban
1 file with lock
etc etc
i dont see why not
but i dont know if its possible to do it
cos it will need to use the same cog in mutiple file (i thjink)
what
if i want to create subcommand in different file
i will need to have the same cog in different file no ?
i dont know
your question said "same class" lol
the class is a cog
and i dont think multicog are supported
yea and you said "same class" which would mean same file
i will open a help thread i think to explain better
Hey guys, how to make that users can't iteract with my bot through DM's with it?
Like this for example:
if isinstance(ctx.channel, discord.DMChannel):
return
yeah
In a big picture:
@bot.slash_command(
name="ping",
description="Check the bot's latency"
)
async def ping(ctx):
# Check if the command is used in a DM
if isinstance(ctx.channel, discord.DMChannel):
return
```
if you want to add a check to every command, you can use a decorator or add it to on_interaction
i think there are a decorator no_dm
Is there? Could u refer me to the api docs? Thank you in advance
or @discord.guild_only
whichever one you prefer
you didn't clarify if you were using slash commands or text-based
so I was vague with my answer
looking at his code, its slash
I didn't know that on first interaction
and they proposed an equally correct solution
There was nothing wrong with it
If a user has a server nickname set, do i have to do member.user.display_name to get their non-server display name?
nevermind, it's member.global_name
I like str(Member), but that depends on your use case.
oh hell no 
🤷♂️ I use that for moderation reports since A) Discord doesn't always resolve user tags, and B) if I'm reporting on a name, seeing what it was at the time is important.
If that works for you, go for it. I'm simply providing an alternate viewpoint. I don't know if you know this, but not everything people say is an adversarial attack on you.
I think str(member) was more useful pre-pomelo because username#0000 was very widely used, but it's still nice after migration for showing both names as discord would when you resolve a member (obviously we can't just switch to @username)
How can i set the bot status to dnd with custom status
doesnt work
that is literally exactly how you do it
idk what to tell you lmao
(discord.Status.dnd obviously btw, i just imported status specifically)
Yeah i know its like that but it doesnt work
On custom status
works for me just fine
Getting an error like this AttributeError: module 'discord' has no attribute 'Bot'
do pip list in a cmd window and show us the output
correct! You seem to have both installed. Because both our package and discord.py use the discord namespace, you need to make sure only py-cord or discord.py is installed at a time
what command did you run to uninstall discord.py?
Can u send cde to me?
python3 -m pip uninstall discord.py
No
But i also tried the custom activities (as in, bot status) a few days ago, and it worked flawlessly
so
what even is the problem btw
discord.py is gone from my list as well
show us your pip list again? It looks like you have discord and discord.py there
run the same for discord
then run pip install py-cord
make sure both are gone
got it
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.custom, status=discord.Status.do_not_disturb, state="💩 "))
That doesnt work
This is my list now ans still same issue...
just do it in your bot definition
and the status isnt part of the activity for al i know
now reinstall py-cord
uninstall then reinstall
Wdym?
