#Basic Pycord Help
1 messages · Page 50 of 1
ok ok
no?
ops
yes
you cant know what they're using based on that code
sorry
dw
if you're new to programing, i'd recommend pycord if you wanna use slash commands
discord.py is unnecessarily complicated and weird with slash commands
what can i use?
whatever you want, but i recommend pycord lol
ok thanks
why would this happen
if self.user is None
why would that happen
idk where do you set self.user
maybe you are setting it to none
you aren't giving enough context
Most importantly, what did you change since it last worked
thats code inside pycord..
the top of the stacktrace is what matters
the more you go down the more it gets into library code
How do I make a button that only works for the person who ran the command?
i just made it log memory usages of different events
put a check in the button callback
i can't read
can you show your code around where it happened
add the author do the class and check for it
it's literally bot.run(token) that causes it
show your code
resume?
are you by any chance running the bot again inside on_resume
im so dumb i didn't think of that 😅 thanks
add something like ctx to the class and check for it at the interaction
yeah it's working, ty
this is what happens in on_resumed
class DeleteButton(discord.ui.View):
def __init__(self, author):
super().__init__(timeout=None)
self.author = author # for outside classes
@discord.ui.button(label="Delete", custom_id="delete_button", style=discord.ButtonStyle.red)
async def delete_callback(self, button: discord.ui.Button, interaction: discord.Interaction):
if interaction.user.id != self.author.id:
await interaction.response.send_message("You do not have the permission to delete this message!", ephemeral=True)
return
await interaction.message.delete()
This button is supposed to be persistent, but it says Interaction Failed after the bot restarts. It doesn't even throw any exceptions
for information it does work before the bot restarts
You're supposed to add the view again on on_ready
.rtfm Bot.add_view
i am not
is there a way to tag everyone without actually showing @ everyone in the text message?
no
how can I hide it with a spoiler ||like this||? just with ||?
yea, but why lol
After my long mute of 1 minute, yes you can.
But I gotta DM you the text cause the stupid automod mutes me
well yea you can but the markdown spam trick doesn't work on mobile I think
and it just depends on a bug so meh
It does work on mobile lolz
dms open brother
kinda looks ugly with the @ everyone
guys
so I have a ton of commands for my bot
and all of them work as intended
except one of them
I just programmed in this new command
and it just won't run
I've tried try catch nothing shows up in console, keeps running as usual
and it just won't accept this one
command
and it's driving me nuts
cause I cant even get an error
Restart both discord and your bot first
task = asyncio.create_task(self.coro_listen_for_reaction(user, tester, activity_msg, ticket_channel, kit))
self.tasks.add(task)
task.add_done_callback(fn=self.tasks.discard(task))
The last line, Pylance is throwing: ```
Expected 1 more positional argument
can anybody help?
Try removing the fn=
When it expects more?
Is this solved or still a thing?
how can I use the emoji with discord.CustomActivity?
activity = discord.CustomActivity(emoji=discord.PartialEmoji.from_str(''), name=f"啟動中・啟動進度:{int((len(self.bot.users)/per)*100)}%")
print(activity)
await self.bot.change_presence(
status=discord.Status.online,
activity=activity
)
It’s possible
By doing a glitch
they were already told that yesterday
can you stop constantly replying to already-solved messages
it helps no one
is there a way to use pycord in a way that doesn't need a bot
i want to make a python script to search and fetch specific messages
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)
Not sure if .Client would suffice but you always need a bot user in the server
oh
I didn’t see
You should look at user app if they have access to message
Will be more efficient in ur case I think since it doesn’t need to have the bot inside the server
but you cant search messages and stuff then
the most you can do is use a message command on 1 message each
oh
whats the purpose anyway btw
they dont have access to channel history ?
ephemeral for slash command groups is not working
show what you mean and your code
i mean when i use a slash cmd group and use ephemeral it's ntow orking
great, show what you mean and show your code
@crypto.command(
name="sell",
description="Sell Crypto (Minecraft Economy)",
)
@option(
"symbol",
description="Crypto Symbol",
choices=["ETH-USD", "BTC-USD", "BNB-USD", "SOL-USD", "AVAX-USD"],
)
@option(
"quantity",
description="Quantity Of Crypto",
type=int,
)
async def sell(self, ctx, symbol: str, quantity: int):
await ctx.defer()
try:
quote = self.finnhub_client.quote(symbol=symbol)
if quote:
price = quote.get("c", 0)
total_price = price * quantity
cursor = self.conn.cursor()
cursor.execute(
f"""
SELECT {symbol} FROM stocks WHERE user_id = ?
""",
(str(ctx.author.id),),
)
row = cursor.fetchone()
if row:
crypto = row[0]
cursor.execute(
"""
SELECT * FROM user_data WHERE discord_user_id = ?
""",
(str(ctx.author.id),),
)
row = cursor.fetchone()
if row:
user = row[2]
if crypto >= quantity:
console_channel = self.bot.get_channel(self.console_channel_id)
await console_channel.send(f"eco give {user} {total_price}")
await ctx.respond(
"Sell Successful, Confirmation On Its Way!", ephemeral=True
)
self.symbol = symbol
self.buy_price = price
self.price = total_price
self.quantity = quantity
self.user_id = ctx.author.id
self.channel_id = ctx.channel.id
else:
await ctx.respond(
"You Don't Have Enough Crypto To Sell", ephemeral=True
)
else:
await ctx.respond(
"You Don't Have Enough Crypto To Sell", ephemeral=True
)
except Exception as e:
await ctx.respond(str(e), ephemeral=True)
traceback.print_exc()
what da ok then what to do
these work without the slash cmd grp though
does that will work await ctx.defer() -> await ctx.defer(ephemeral=True) since defer ephemeral does not exist with slash command ?
of course you can defer with ephemeral what do you mean
make the defer ephemeral lol
ok ok
i was thinking with slash command it does not change anything
or is it the invisible ?
cant really rn
it should be obvious
like as in await ctx.defer(ephemeral=True)
yes
kk
also you should do do a try except for each command you have an event name on_application_command_error for that
kk
ok so
i am getting 100 messages
and i want to get almost all the messages
an algorithm i thought of is get 100 messages before DATE then reverse the list to get the oldest message and then store the timestamp of the message in DATE and repeat
Is the DB even a asyncio one?
the problem is the date is a bit weird in discord
not really
i wanna convert datetime object for the first iteration to discord's own timestamp
then
i wanna get the oldest message(which is done by reversing the list) and get the timestamp via message["timestamp"] but then if i pass that timestamp it says its not a snowflake
int(message.created_at.timestamp()) -> if you want to save it in ur database else it will raise an error about unix thing
and you can just set the limit to None in channel.history
but you should still set a limit else you're never gonna get done
i filter the messages
yea but why
bc i need specific messages
well, do this
and done
but since pycord doesn't support the user stuff we mentioned earlier
i have to use the raw discord api
its not pycord but discord that doesnt support that stuff
if you mean selfbotting, obviously not, its agains the ToS
why cant you just add a bot to the server lol
well i want to filter specific embed messages sent from another bot that is another server
basically the same thing can be done as a user but its kinda teadious
thats why i wanted to automate a script to search for you and output a list
One question, can the input_type argument of an application command be of 2 types? I want the moderator to be able to enter a member or user ID
thats all encompassed by discord.Member
automatically
discord doesnt differentiate between that
which is usually more of a pain than a help
also to make your code a little shorter you can directly import slash_command from discord
Ok, thanks for the information 🙌
ok ok ty!
pass bot to the view constructor
or depending on your structure just self.bot if you have it passed to the cog already
gotcha thanx you
also for you know, in slash command discord.Member will also allow discord.User to be selected so you might add a check
interaction.client also works
thanx i think thats better
it isn't getting the guild
guild = interaction.client.get_guild(os.getenv("GUILD_ID"))
role = guild.get_role(int(os.getenv("LINKEDAC_ID")))
Error:
AttributeError: 'NoneType' object has no attribute 'get_role'
It was working fine when it was a command rather than a ui view
int() the guild_id
thanx i forget about that
I've started getting this error code today:
future: <Task finished name='Task-21' coro=<ApplicationCommandMixin.on_application_command_auto_complete.<locals>.callback() done, defined at C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\bot.py:876> exception=NotFound('404 Not Found (error code: 10062): Unknown interaction')>
Traceback (most recent call last):
File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\bot.py", line 879, in callback
return await command.invoke_autocomplete_callback(ctx)
File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\commands\core.py", line 1111, in invoke_autocomplete_callback
return await ctx.interaction.response.send_autocomplete_result(
File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\interactions.py", line 1178, in send_autocomplete_result
await self._locked_response(
File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\interactions.py", line 1288, in _locked_response
await coro
File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\webhook\async_.py", line 222, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```
It's a bit sporadic, but in response to a command which does use autocompletes.
show the command's code, and the autocomplete code
tbh not using an integer here should ValueError i will see if I can pr
Command is enormous, but starts with....
@bot.slash_command(description="For most types of rolls.",
integration_types={discord.IntegrationType.guild_install,discord.IntegrationType.user_install}
)
async def roll(
ctx,
description: Option(str, "You must explain in a few words what you are rolling."),
pool1: Option(str, autocomplete=discord.utils.basic_autocomplete(pool1_autocomplete), required=False),
pool2: Option(str, autocomplete=discord.utils.basic_autocomplete(pool2_autocomplete), required=False),
other: Option(int, "Add other modifiers to increase or decrease the final pool", max_value=15, required=False),
specialty: Option(str, "Add a die for a Specialty", autocomplete=discord.utils.basic_autocomplete(specialty_autocomplete), required=False),
):
# 200 Lines of dice rolling complexity
Pool 1 Autocomplete:
async def pool1_autocomplete(ctx: discord.AutocompleteContext):
statList = ["Strength", "Dexterity", "Stamina", "Charisma", "Manipulation", "Composure", "Intelligence", "Wits", "Resolve", "Glory", "Honor", "Wisdom", "Athletics", "Brawl", "Craft", "Driving", "Firearms", "Larceny", "Melee", "Stealth", "Survival", "Animal Ken", "Etiquette", "Insight", "Intimidation", "Leadership", "Performance", "Persuasion", "Streetwise", "Subterfuge", "Academics", "Awareness", "Finance", "Investigation", "Medicine", "Occult", "Politics", "Science", "Technology"]
return statList```
25 choices
Initially was happening during, but now seems to be after, and sometimes like... many seconds after the command has successfully resolved all its tasks.
if the command code takes more than 3 seconds you need to defer first
Command is basically instant. It's the error that seems to pop up way later.
is there a part of the traceback above this btw?
That's the whole thing
hm
can you show the other autocompletes too
async def pool2_autocomplete(ctx: discord.AutocompleteContext):
statList = ["Strength", "Dexterity", "Stamina", "Charisma", "Manipulation", "Composure", "Intelligence", "Wits", "Resolve", "Glory", "Honor", "Wisdom", "Athletics", "Brawl", "Craft", "Driving", "Firearms", "Larceny", "Melee", "Stealth", "Survival", "Animal Ken", "Etiquette", "Insight", "Intimidation", "Leadership", "Performance", "Persuasion", "Streetwise", "Subterfuge", "Academics", "Awareness", "Finance", "Investigation", "Medicine", "Occult", "Politics", "Science", "Technology"]
return statList```
```py
async def specialty_autocomplete(ctx: discord.AutocompleteContext):
with open('users.json','r')as f:
users = json.load(f)
target = str(ctx.interaction.user.id)
skills = ["Athletics", "Brawl", "Craft", "Driving", "Firearms", "Larceny", "Melee", "Stealth", "Survival", "Animal Ken", "Etiquette", "Insight", "Intimidation", "Leadership", "Performance", "Persuasion", "Streetwise", "Subterfuge", "Academics", "Awareness", "Finance", "Investigation", "Medicine", "Occult", "Politics", "Science", "Technology"]
specs = []
if ctx.options["pool1"] != None:
pool = ctx.options["pool1"]
if pool in skills:
if pool in users[target]['Specialties']:
specs.append(users[target]['Specialties'][pool])
if ctx.options["pool2"] != None:
pool = ctx.options["pool2"]
if pool in skills:
if pool in users[target]['Specialties']:
if pool not in specs:
specs.append(users[target]['Specialties'][pool])
if specs == []:
specs = ["No Specialties"]
return specs```
I haven't touched any of the autocompletes in several days.
i wouldn't recommend loading a file every single time, that will cause issues
load the file when the bot starts and save it in a variable somewhere
because every time you add a letter in the option it loads the file
and that isn't ideal
try changing it to load on bot start and see if you can still reproduce the issue
if no, you could make a task that loads the file every 10s or so and saves it back to a variable
users.json is being used as a database
Usage frequency would need it to load every second at minimum, but that really hasn't been an issue for any of the bots I've made with way sloppier json-loading.
Thousands of users all updating their (not-DnD) characters' stats whenever they feel like it.
Yeah I'll be migrating to something else before wide launch
how big is that file anyway
It's tiny right now because it's in testing - again this isn't the problem though.
i'd say it is because i have no other idea 
Or you could switch now and avoid a headache later tbh
Yeah but again that's not what I'm here for help with
i thought discord.utils.basic_autocomplete takes a list?
no, a function that returns a list
i think it handles the fuzzy-matching
I'm sending it lists
not quite no
maybe you're adding overhead to it so maybe just make it a list instead of a coro
you're passing functions that the basic_autocomplete calls
*coroutine
🤓
well fr now tho guys
in everything they sent i can only imagine the file loading somehow getting stuck because the OS blocks so many accesses or whatever, so one instance just gets stuck and only gets done a few seconds after
wdyt
i don't understand why discord.utils.basic_autocomplete is used here
specialty: Option(str, "Add a die for a Specialty", autocomplete=discord.utils.basic_autocomplete(specialty_autocomplete), required=False),
):
more than 25 options
aiofiles would definitely help
squid, it fuzzy matches
She can't use choices
that's not an issue
you can return infinite options
Specialties needs to check [pool1] and [pool2] to see if any of those are in the user's Specialties list
discord just uses 25
K let's just go ahead and remove all my autocompletes and see if that fixes it so we can get back ont rack.
Wait
So you need to return options based off past options?
this is the track
your autocompletes are the issue
nothing is off track here lol
They weren't for weeks
Can't we just try doing what toothy said
now they are
They have not been touched.
that wasn't even what he said, but ok
ok no i dont think that will change anything lmao
Isn't it
my entire point is that i think loading the file so frequently is the issue
so i just want them to try with a globally loaded file once to rule it out

Wouldn't it (assuming) raise an exception tho?
why would it
why?
we can sit here discussing all day but something needs to be tried
and since my best guess is the file, i want to rule that out first
if that isnt the issue we can see on
I'm brain storming ideas leave me alone 😭
Waiting for the command to update, sorry.
@slate idol can you profile your code by any chance?
Explain?
ok, nvm then
you're just changing the autocomplete, no need to wait
I'm removing all autocompletes to make sure that's actually the problem
Thanks!
i thought you read it lol
Why do you want a different function for your auto complete?
You can just do basic_autoconplete(my list)
pool1 and pool2 should be lists, but that's not the issue
K so I've commented out the stuff involving the json, and it freaked out on pool1 before even getting to specialties
They're more than 25 items.
the amount of items shouldn't matter
Otherwise I'd LOVE to make them lists, believe me.
Not in pool 1 and pool 2
It throws me an error.
It just triggered me
i'm 99% sure autocomplete can take lists >25 long
...
can you show your current code again
when you say it freaks out during pool1 what happens specifically
future: <Task finished name='Task-18' coro=<ApplicationCommandMixin.on_application_command_auto_complete.<locals>.callback() done, defined at C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\bot.py:876> exception=NotFound('404 Not Found (error code: 10062): Unknown interaction')>
Traceback (most recent call last):
File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\bot.py", line 879, in callback
return await command.invoke_autocomplete_callback(ctx)
File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\commands\core.py", line 1111, in invoke_autocomplete_callback
return await ctx.interaction.response.send_autocomplete_result(
File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\interactions.py", line 1178, in send_autocomplete_result
await self._locked_response(
File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\interactions.py", line 1288, in _locked_response
await coro
File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\webhook\async_.py", line 222, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```
show the code again that you have now
Followed up on other stuff: In 8.options.1.choices: Must be 25 or fewer in length. In 8.options.2.choices: Must be 25 or fewer in length.
So returning to autocompleting them.
yea we never said to try choices lol
K I misunderstood
Then my code is unchanged?
can you remove the option that uses the autocomplete with the file in it, just to make sure that one is or isnt the problem
just wanna make sure which of the 3 autocompletes is the issue
doesnt matter if the command itself errors
async def specialty_autocomplete(ctx: discord.AutocompleteContext):
skills = ["Athletics", "Brawl", "Craft", "Driving", "Firearms", "Larceny", "Melee", "Stealth", "Survival", "Animal Ken", "Etiquette", "Insight", "Intimidation", "Leadership", "Performance", "Persuasion", "Streetwise", "Subterfuge", "Academics", "Awareness", "Finance", "Investigation", "Medicine", "Occult", "Politics", "Science", "Technology"]
specs = []
if ctx.options["pool1"] != None:
pool = ctx.options["pool1"]
if pool in skills:
#with open('users.json','r')as f:
#users = json.load(f)
#target = str(ctx.interaction.user.id)
#if pool in users[target]['Specialties']:
#specs.append(users[target]['Specialties'][pool])
specs.append(pool)
if ctx.options["pool2"] != None:
pool = ctx.options["pool2"]
if pool in skills:
#with open('users.json','r')as f:
#users = json.load(f)
#target = str(ctx.interaction.user.id)
#if pool in users[target]['Specialties']:
#if pool not in specs:
#specs.append(users[target]['Specialties'][pool])
specs.append(pool)
if specs == []:
specs = ["No Specialties"]
return specs```
Commented that bit out, sorry, that has changed.
okay so none of your autocompletes load a file anymore?
Correct
Figured out what the other person meant, replacing Pool1 and Pool2 with a global variable which is a list.
Traceback (most recent call last):
File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\commands\core.py", line 138, in wrapped
ret = await coro(arg)
File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\commands\core.py", line 1082, in _invoke
await self.callback(ctx, **kwargs)
File "C:\Users\kazer\Documents\Programming\DiscordBot\W5\w5.py", line 2956, in roll
await end_roll(titlage, response, ctx, users, hex, rpool, pool, bruteskies)
File "C:\Users\kazer\Documents\Programming\DiscordBot\W5\w5.py", line 1821, in end_roll
await ctx.respond(embed=embedVar)
File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\interactions.py", line 616, in respond
return await self.response.send_message(*args, **kwargs)
File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\interactions.py", line 957, in send_message
await self._locked_response(
File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\interactions.py", line 1288, in _locked_response
await coro
File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\webhook\async_.py", line 222, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
The above exception was the direct cause of the following exception:
[part 2 coming:]
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\bot.py", line 1137, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\commands\core.py", line 435, in invoke
await injected(ctx)
File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\commands\core.py", line 146, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction```
now that just looks like the typical "taking more than 3s to respond" error to me
K, but the command fires perfectly, so is there something it's waiting for that I'm not giving it? Like a return or something?
?tag defer
No tag defer found.
If you responded twice the error would say so
Okay, so how do I send an embed for everyone to see AND an embed only the interacter can see?
yea thats hard
await ctx.send and await ctx.respond(ephemeral=True)
Send and respond, will try!
and tbh i have no idea how big bots do it that need tons of db requests before being able to figure out if its ephemeral
what
oh wait, and
i misread my bad
ignore what i said
obviously
if ((await ctx.send("hello") and (await ctx.respond(ephemeral=True)):
...
/s
i think it's also possible to respond twice, just the second time non-ephemerally
true
when would the if not return true
I'd commented out the second response, though. So while I do have code for that right now it's:
embedVar = discord.Embed(title=titlage, description=response, color=hex)
await ctx.send(embed=embedVar)
if bruteskies != True:
#await ctx.respond(view=RerollView(bot, rpool, pool), ephemeral=True)
print("this should be a reroll View")```
maybe if an error is raised
Frustrating thing is, it's all executing fine, it's just throwing errors.
then it's probably not fine?
can you just show your entire command code once
just send it doesnt matter if its long
great
there literally is
oh wait i think they changed the link the bot sends, it used to be normal pastebin
okay just out of curiosity, since you arent using cogs, how long is your main file
Too long. I've never taken a programming course so this is all a coblled together behemoth. It was under 800 lines before I got into trouble with Views... now it's 3500 lines
holy shit
I have no idea what I'm supposed to be looking at
please please please use cogs
no
Cogs, often known as modules or extensions, are used to organize commands into groups. This is useful
you're fired /j
that would require you to pay me /srs /j
what's the error again
lol
also yea, looking at your command now, you absolutely have to switch to a database before you release
the current solution is just asking for conflicts
based
#1132206148309749830 message i think
json's fine for beta tbh
thats why i said release
It was just supposed to be a die roller, then I learned too much.
"Oh I can store one thing... okay a few things... okay a whole dang character sheet.... move over DnD Beyond!"
FIXED
there's no way we don't have a tag for defer-ing
@sage tendon is the tag just called something else
Tag not found.
sure enough
i never use it because i find it pointless imo
but no, idk what its called
Thanks for all your help folks... and the many tangents ❤️
ok well what was the issue now
Honestly not sure.
It feels like it's disappeared as mysteriously as it appeared. I'll try putting in my terrible json loading again
defer definitely helps
@discord.Cogs.listener()
on_application_command(????)
await ctx.defer()
await self.bot.process_commands()
Like this right
what
joking lol
not one line of that makes sense 💀
cry about it
- @discord.Cogs.listener()
+ @discord.Cog.listener() # commands.Cog.listener() may work instead depending on the cog type
- on_application_command(????)
+ async def on_interaction(self, interaction):
- await ctx.defer()
+ await interaction.response.defer() # all responses are no longer ephemeral unless forced by discord
- await self.bot.process_commands()
+ await self.bot.process_application_commands(interaction)
okay nerd
and this is a listener which means it doesn't even override the current event
so it doesn't even work
Ummmm
..... I had two instances of the bot running. I was sitting here trying to figure out how a function I RENAMED was still firing.
amazing

bruhhhhh
i reset my bot's token every month (when I had a bot that was actually online)
why?
because security or something
whats gonna happen to your token if it only sits on your VPS
if its compromised changing it wont help
and nothing else can happen to your token really
well, it didn't
Hello!
I have a features.py file with the following function:
async def mass_ban_check(file_path, ctx, ban_amount: int, seconds_between_bans: int):
while True:
with open(f'{file_path}') as json_file:
data = json.load(json_file)
baninfo = data['fileinfo']['baninfo']
print(baninfo)
bans_within_timeframe = []
time_frame = timedelta(seconds=seconds_between_bans)
for i in baninfo:
current_time = datetime.datetime.now()
ban_time = baninfo[i]['data']['date']
print(ban_time)
if(current_time - ban_time <= time_frame):
bans_within_timeframe.append(baninfo)
if len(bans_within_timeframe) >= ban_amount:
print("Mass banning detected")
#take action here
await asyncio.sleep(1)
And then I have main.py where I try to call this function (I have already imported the function correctly):
@bot.command(description="Enable mass banning detection")
async def massbandetection(ctx, ban_amount: int, seconds_between_bans: int):
await mass_ban_check("data.json", ctx=ctx, ban_amount=ban_amount, seconds_between_bans=seconds_between_bans)
await ctx.respond("Successfully configured mass banning detection")
And it throws this error:
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: list indices must be integers or slices, not dict
I know that I am accessing the data.json file wrong, but I just can't seem to figure out how to access it right. Here is data.json:
{
"fileinfo": {
"baninfo": [
{
"data": {
"name": "GM peters#9338",
"server": "test",
"date": "2024-07-31 17:47:17.458763"
}
},
{
"data": {
"name": "GM peters#9338",
"server": "test",
"date": "2024-07-31 17:47:56.785292"
}
},
{
"data": {
"name": "GM peters#9338",
"server": "test",
"date": "2024-07-31 18:05:07.163366"
}
},
{
"data": {
"name": "GM peters#9338",
"server": "test",
"date": "2024-07-31 18:07:13.706827"
}
},
{
"data": {
"name": "GM peters#9338",
"server": "test",
"date": "2024-07-31 18:07:52.344879"
}
},
{
"data": {
"name": "GM peters#9338",
"server": "test",
"date": "2024-07-31 18:09:42.475643"
}
},
{
"data": {
"name": "GM peters#9338",
"server": "Zombs Combat Series [ZCS]",
"date": "2024-08-01 10:04:44.670617"
}
}
],
"unbaninfo": [
{
"data": {
"name": "GM peters#9338",
"server": "test",
"date": "2024-07-31 18:09:52.577499"
}
}
]
}
}
is the AutocompleteContext.options value for unrequired options the default value?
Why this returns true even if the person can't see the channel?
https://paste.pythondiscord.com/6BHQ
works fine for me
can you show me how do u get the member ?
this is the whole command:
https://paste.pythondiscord.com/ZOIQ
the issue is that channel isn’t a complete channel object
what do you mean
try fetching/getting it instead
i don’t see how mass_ban_check works. It seems like it’ll just keep running forever
getting it worked, im pretty sure it worked fine in the past why now it had to be updated?
sometimes discord just doesn’t give you the information
alright thank you very much
one last question what is the difference between fetching and getting a channel?
one is an api call, another is from cache, which may or may not exist
.tag get_x
Any function that starts with get_ in Py-cord is retrieving the related object from your bots cache. If the object is not in the bots cache the get_ method will return None. Because of this behavior you should check if the get_x method is None and if it is use the fetch_x method.
Why Is Using fetch_ Without Using get_ First Bad?
The fetch_ method makes a call to the discord API. This API call is unneeded if you already have the information. It will also make your command take longer because it will have to send and than wait for a response from the discord API. It will also contribute to the discord APIs global rate limit of 50 requests per second.
What Is Cache?
The cache is a temporary storage inside your bot. It holds many objects from members to messages. When you restart your bot the cache will be empty. When the cache is full it will delete older objects to make space for the new objects.
idk who did this one but its really good
so in my case it's probably better to use api calls as ticket channels probably dont always exist in cache
it’s generally good to first get from cache then if it doesn’t exist, then fetch
👍
yea
thats the point
it keeps running forever
and checks every second
for mass bans
Hi im getting this error
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
Could anyone help please?
I have MFA enabled on my acccount
The bot has Administrator priviliges
the bot has scope application.commands
Do you have guild_ids or debug_guilds anywhere in your code? If so, the bot isn't in one of those servers or the ID is not valid
I do have debug_guilds
The ID is correct
Wait
I feel so stupid I had it set in a config
But i hadnt actually added the lines to actually pull from the config
Thanks for that
Yall know how long was the @ everyone markdown bug around for?
The one that will tag everyone but you won't see the @ everyone in the text
like a year long or a few years long?
longer
das crazy
not really
I know so many bugs on discord
but even when you report them and they say they know about it they aren't fixed for years
(He's known for mimimi'ing everything about bugs)
tell us some that you think are pretty wild
im curious
I reported a bug with themes basically on their release day. They say they're aware. Nothing yet.
nothing, but I think I may have solved it
Hello. I need a bit of help with autocomplete in cogs. Right now this is my code (in a Cog class):
@embed_group.command(
description="Send an Embed from the defined Embed List (Check source code)"
)
@commands.has_permissions(administrator=True)
async def send(self, ctx: ApplicationContext, embed: discord.Option(str, autocomplete=discord.utils.basic_autocomplete(self.get_embed_names))) -> None: # type: ignore
for i in self.LIST:
if i["name"] != embed:
continue
# This is the embed we want to send
await ctx.channel.send(content=i["content"], embed=i["embed"], view=i["view"]) # type: ignore
await ctx.respond("Successfully sent embed to this channel", ephemeral=True)
async def get_embed_names(self, ctx: discord.AutocompleteContext):
output = []
for i in self.LIST:
output.append(i["name"])
return output
However, I get this error: ```
async def send(self, ctx: ApplicationContext, embed: discord.Option(str, autocomplete=discord.utils.basic_autocomplete(self.get_embed_names))) -> None: # type: ignore
^^^^
NameError: name 'self' is not defined
Can somebody tell me what I'm doing wrong?
is that all in a cog?
yep
This is the full file, in case it helps: https://paste.pythondiscord.com/KPHA
show the entire cog
nvm im blind sorry
yea you can't use self inside of the function header like that i'm p sure
thats not how OOP works in python
also why is your setup def not bot.add_cog(...) lol
lol
i prolly did it wrong
well, i get that now, but then how do you do typehinting?
what
I'd recommend putting that into a util class or somewhere
so like id have a util class w that as a function? Say the util class is called AutocompleteUtil or smth and the function is designed the same. Given that I've imported the class, how would I pass that into discord.Option?
AutocompleteUtil.get_embed_names lol
the problem is really just that you dont have access to self. inside of the function header
anything else works fine
ok bet
or import the function directly by name then its a little shorter
regardless of anything i still recommend using the @discord.option decorator over typehinting
but the issue remains that i'm using self.LIST in that function
Put that inside of the autocomplete util class
hmm, ok, thanks
What does this error mean and how to fix it? ```py
File "embed_helper.py", line 14, in <module>
"view": SetActivityView(),
RuntimeError: no running event loop
embed_helper.py ```py
from views.tester_activity_view import SetActivityView
from discord import Embed, EmbedField
import discord
LIST = [
{
"name": "set activity",
"content": "",
"embed": Embed(
title="Set Activity Status",
description="As part of our new testing system, use the 2 buttons below to get tickets to test.",
color=0x3333FF,
),
"view": SetActivityView(),
}
]
async def get_embed_names(ctx: discord.AutocompleteContext):
output = []
for i in LIST:
output.append(i["name"])
return output
can i remove the brackets (SetActivityView() -> SetActivityView) and then use it as:
ctx.respond(view=embed_helper.LIST[0]["view"]())
Put it into a class
wdym
this works
Why is my interaction failing with my view even though there is no error in console? (I'm for sure this is the only active token)
show the button callback
i will in a sec, but i'm finally getting an error out of this: ```py
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
ik to fix this in a command you do `await ctx.defer()`, but what to do in a button callback with only an `Interaction`?
@discord.ui.button(
label="I'm Online", style=discord.ButtonStyle.primary, emoji="✅"
)
async def active_callback(self, button, interaction: discord.Interaction):
# Check if a tester is active already
tester_info = firebase_helper.get_tester(interaction.user.id) # type: ignore incorrect null
if tester_info == None:
embed = discord.Embed(title="You're not a tester?!?", color=0xFF3333)
await interaction.response.send_message(embed=embed, ephemeral=True)
return
if tester_info["isActive"]:
embed = discord.Embed(title="You're already active!", color=0x33FF33)
await interaction.response.send_message(embed=embed, ephemeral=True)
return
# Give the tester the active role
active_role_id = config_helper.get_rank_role_id("online")
active_role = interaction.guild.get_role(active_role_id) # type: ignore it is NOT None
inactive_role_id = config_helper.get_rank_role_id("offline")
inactive_role = interaction.guild.get_role(inactive_role_id) # type: ignore
if active_role != None:
await interaction.user.add_roles(active_role, reason="online") # type: ignore
if inactive_role != None:
await interaction.user.remove_roles(inactive_role, reason="online") # type: ignore
# Create tickets for the tester
tickets: list[int] = await self.createTickets(
interaction, interaction.user, tester_info
)
# Update tester doc
firebase_helper.set_tester_active(interaction.user.id) # type: ignore
embed = discord.Embed(
title="You are now active.",
description="Check your channels, tickets should have automatically been made and assigned to you.",
color=0x33FF33,
)
await interaction.response.send_message(embed=embed, ephemeral=True)
404 typically means you take more than 3 seconds to respond
in which case you have to use await ctx.defer() as the first line in your callback
ik, but there's no ctx you see
ah yea interaction.response.defer
bet
now what does this error mean?
discord.errors.InteractionResponded: This interaction has already been responded to before
I think it's coming from this line: await interaction.response.send_message(embed=embed, ephemeral=True), but its definitely from this code block in the callback: ```py
tester_info = firebase_helper.get_tester(interaction.user.id) # type: ignore incorrect null
if tester_info == None:
embed = discord.Embed(title="You're not a tester?!?", color=0xFF3333)
await interaction.response.send_message(embed=embed, ephemeral=True)
return
if tester_info["isActive"]:
embed = discord.Embed(title="You're already active!", color=0x33FF33)
await interaction.response.send_message(embed=embed, ephemeral=True)
return
now though the error seems self explanatory, how could it be responded to before if i've never pressed the button before
maybe interaction defers have to be responded to in a different way, no idea
hmm
never do much with views, maybe someone else knows
hm, ok, thanks
also why do you have #type: ignore everywhere
pylance keeps thinking interaction.user is None
vsc?
yea
yea vsc is dumb
(it's technically correct for annoying reasons but just don't use a typechecker lol)
because its a union and MIGHT be null?
no, it's actually defined as None but doesn't know how to interpret the custom property decorator we use
ah
well, my issue is definitely with the line: ```py
await interaction.response.send_message(embed=embed, ephemeral=True)
discord.errors.InteractionResponded: This interaction has already been responded to before
1 sec
(if you defer then it's interaction.followup.send, so we added a generic respond function to streamline it)
got it, let me test interaction.respond rq
yep, back to ```py
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
you are still deferring right
no, cuz the nelo said you don't need to i think idk
ok i'm testing interaction.followup.send() + defer
respond will basically use interaction.response if the interaction hasn’t be responded else it will use interaction.followup
So if you use respond u don’t need to care about response or followup
sure
Dumb and very late questio but does 2.6 support user installs?
read #library-updates
yes
How can I specify which shard a bot connects to
shard_ids in your client object https://docs.pycord.dev/en/stable/api/clients.html#discord.AutoShardedClient.shard_ids
thanks I cant read
just to be clear, shard_count has to be the total shard count or the count of shards this instance connects to?
however many you're connecting to
yeah but like in total, or with that instance
uhhh
cuz I want to be able to split up the thing in multiple containers
idk
I have to check
but enough
And it's not like I want to now make it in multiple containers
I just want to prepare for doing it later
and also have high availability and stuff like that
the docs only really talk about sharding, beyond that if you're doing multiple instances then i'd presume shard_count is for each individual instance
(not much will happen if you get it wrong anyway)
ok that's also easier so better that
i guess i'll try and the worst is some downtime
how i can connect the bot to the channel i am in?
client = await voicechannel.connect()
or smth
this
yh but how i get my voice channel?
are you in a slash command?
.channel
yes
examples/basic_voice.py lines 63 to 70
@commands.command()
async def join(self, ctx: commands.Context, *, channel: discord.VoiceChannel):
"""Joins a voice channel"""
if ctx.voice_client is not None:
return await ctx.voice_client.move_to(channel)
await channel.connect()```
when can I add @rugged lodge 's rtfm to my user so i can use it in dms and wvweywee
code is right there
how hard is it to turn prefixed commands into slash commands?
Thanks
Pretty easy why?
just change ctx.send to ctx.respond
and ctx.message might not be reliable
that's about it
if the command takes more than 3 seconds for the first response, defer at the start
how so?
and what does this mean
means you should do
await ctx.defer()
at the top of your command's code if it takes long to process
interaction commands are a bit different, so it's best not to rely on it - you generally won't need it anyway, there are several shortcuts under ctx
when will self.bot.user.avatar be None in a Cog?
This is the code: ```py
embed = discord.Embed(
title="Server PvP Leaderboard",
footer=discord.EmbedFooter(
text="PvP Practice Bot", icon_url=self.bot.user.avatar.url # type: ignore
),
color=discord.Colour.from_rgb(50, 127, 168),
description="See the Top 10 Overall best PvPers below:",
image="attachment://image.png",
)
and the error: ```
text="PvP Practice Bot", icon_url=self.bot.user.avatar.url # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'url'
eh
use ctx.me instead
but also, display_avatar will guarantee an avatar is returned by using a default avatar if for some reason the user one doesn't exist
Hello,
What is the best practice to initialize aiosqlite database in discord bot ? I am actually using an asyncio.run() function but it seems to not be the right method because it breaks all tasks.loop() (I don't really know because I am not using loops but someone told me this)
use await bot.start()
so make an async def main function
in there you put
- Your database logic
- await bot.start()
then if __name__ == "__main__" you asyncio.run(main())
async def main():
bot.db, bot.cursor = await connect_database()
# Load cogs
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
bot.load_extension(f'cogs.{filename[:-3]}')
# Run the bot
bot.start(TOKEN)
if __name__ == '__main__':
asyncio.run(main())
you should put await before bot.start
other than that, yeah that should work I think
if I put the await on the bot.start, the bot is never ready
but if I don't put it, everything work lol
that is wierd
so this code is working?
weird, it does not work anymore.... I will troubleshoot from myself
Okay
not anymore, but the bot is never ready with the await too
what do you mean by never ready? do you have a print statement in your on_ready? Also, could you add some logging in your async def main funtion to see if the database connection does actually completes, etc.? Also enable logging if not done already
.tag logging
Pycord logs errors and debug information via the logging python module. It is strongly recommended that the logging module is configured, as no errors or warnings will be output if it is not set up...
normally, python should follow the order in main function and all cogs are loading, the database should be working so. And I have print in on_ready and in on_shard_ready. None of them are printing
yeah but if it dosen't work it means we aren't in a "normally" condition
my goal is to see if bot.start actually dosen't do anything, of it this:
bot.db, bot.cursor = await connect_database()
# Load cogs
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
bot.load_extension(f'cogs.{filename[:-3]}')
for some reason does not complete and blocks the start
furthermore, if you enable info logging like explained in the link above, you will clearly see if bot.start is being executed or not
and make sure to keep await on bot.start
yes I kept it. I have a meeting for my work and will get back ASAP
sure
the logging does not do anything more than printing the cogs prints, and the result of a print of bot.db and bot.cursor is <Connection(Thread-1, started 137563283130048)> <aiosqlite.cursor.Cursor object at 0x7d1cf3405010>. I have also added prints after cogs and it works, but it does not pass the start. I have added a print after too
async def main():
bot.db, bot.cursor = await connect_database()
print(bot.db, bot.cursor)
# Load cogs
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
bot.load_extension(f'cogs.{filename[:-3]}')
print('===== Cogs are loaded ! =====')
# Run the bot
await bot.start(TOKEN)
print('===== Bot is running ! =====')
yeah but if you enable the python logs, what do they say?
explained in
.tag logging
Pycord logs errors and debug information via the logging python module. It is strongly recommended that the logging module is configured, as no errors or warnings will be output if it is not set up...
import logging
logging.basicConfig(level=logging.INFO)
INFO:discord.client:logging in using static token
INFO:discord.gateway:Shard ID 0 has sent the IDENTIFY payload.
and I have a warning about PyNaCl for the voice but I personaly don't care
yeah that you can ignore
and this after 10secs :
WARNING:discord.gateway:Shard ID 0 heartbeat blocked for more than 10 seconds.
Loop thread traceback (most recent call last):
File "/app/main.py", line 199, in <module>
asyncio.run(main())
File "/usr/local/lib/python3.12/asyncio/runners.py", line 194, in run
return runner.run(main)
File "/usr/local/lib/python3.12/asyncio/runners.py", line 118, in run
return self._loop.run_until_complete(task)
File "/usr/local/lib/python3.12/asyncio/base_events.py", line 672, in run_until_complete
self.run_forever()
File "/usr/local/lib/python3.12/asyncio/base_events.py", line 639, in run_forever
self._run_once()
File "/usr/local/lib/python3.12/asyncio/base_events.py", line 1947, in _run_once
event_list = self._selector.select(timeout)
File "/usr/local/lib/python3.12/selectors.py", line 468, in select
fd_event_list = self._selector.poll(timeout, max_ev)
I had it 3 times
I don't have any loop
you said above that you had tasks
or I missunderstood?
wait no I missread mb
can you show me your on_ready and on_shard_ready then?
any any other listener that you might have (on_message, etc...)?
(I don't really know because I am not using loops but someone told me this)
I just wanted the best practice for initializing an aiosqlite db without breaking anything in case I need it in the future
basically this means that you are running somewhere a blocking code in an asyncronous environment
Yeah I have on_raw_reaction_add and on_message.
Here is my on_shard_connect :
# On shard connect
@bot.event
async def on_shard_connect(shard_id):
print(f"=== Shard {shard_id}/{bot.shard_count-1} is ready ! ===")
And my on_ready :
# On ready
@bot.event
async def on_ready():
await bot.cursor.execute("""
CREATE TABLE IF NOT EXISTS default_guild_language(
guild_id TEXT,
default_language TEXT,
reaction_activated TEXT
)
""")
await bot.cursor.execute("""
CREATE TABLE IF NOT EXISTS DMUser(
user_id TEXT,
yesno TEXT
)
""")
await bot.cursor.execute("""
CREATE TABLE IF NOT EXISTS reversed(
guild_id TEXT,
channel_id TEXT,
language_1 TEXT,
language_2 TEXT
)
""")
await bot.cursor.execute("""
CREATE TABLE IF NOT EXISTS channel_language(
guild_id TEXT,
channel_id TEXT,
language TEXT
)
""")
await bot.cursor.execute("""
CREATE TABLE IF NOT EXISTS force_reaction(
guild_id TEXT,
forced TEXT,
minimalist TEXT,
timeout TEXT
)
""")
await bot.cursor.execute("""
CREATE TABLE IF NOT EXISTS linkchannels(
guild_id TEXT,
channel_id_1 TEXT,
channel_id_2 TEXT,
language_1 TEXT,
language_2 TEXT
)
""")
await bot.cursor.execute("""
CREATE TABLE IF NOT EXISTS langinfo(
guild_id TEXT,
info TEXT
)
""")
print('===== Translator Bot is ready ! =====')
WARNING:discord.gateway:Shard ID 0 heartbeat blocked for more than 10 seconds.
for (dumb) example:
time.sleep(x)await asyncio.sleep(x)
.tag asynciodebug
Tag not found.
@flat wind can you set debug=True in your asyncio.run(main())
WARNING:asyncio:Executing <Task pending name='Task-1' coro=<main() running at /app/main.py:194> wait_for=<Future pending cb=[shield.<locals>._outer_done_callback() at /usr/local/lib/python3.12/asyncio/tasks.py:922, Task.task_wakeup()] created at /usr/local/lib/python3.12/asyncio/base_events.py:448> cb=[_run_until_complete_cb() at /usr/local/lib/python3.12/asyncio/base_events.py:181] created at /usr/local/lib/python3.12/asyncio/runners.py:100> took 1.141 seconds
that looks right tho
@flat wind What I think is that somewhere in your code, there is a piece of blocking code. Can you try adding one cog at a time and see when it stops working? Like you test with one, then two, etc... And also see if it works with no cogs.
Okay I will test with no cogs and see
or just read the code and find the blocking bit
without cogs it does not start either, this means the error is in the main file
could you send you main file entirely
I prefer in DMs if it does not bother you
np
sent ✅
1, because it is the "test version" of my real bot in around 13k servers
you should not use AutoShardedBot if the server count is that low
add a check to only use it in prod
always worked before the edits I have just made with you today
I know it is not the best practice, but this is only for a test
that's not the issue
ik I have other things I will tell you in dm
okay np, waiting your DM
is there a way to deal with slash command changes not showing up or do you just have to restart discord
restart
takes 3 seconds lol it's not a big deal
and you typically don't add commands every 2 minutes
i mean first of all, i actually am adding commands every 2 minutes
and even when i'm not, i'm probably changing them every 2 minutes
code changes don't count btw
they don't, but description, autocomplete, and stuff like that seems to
yea but I mean
again
typically you don't change that all that often
not in 2.6 yet, but it's in master im p sure
what pfp
yours
oh, lol
so, soon™️
you can use it now if you want to
not on master yet, if you REALLY want it there are instructions here #1132206148309749830 message
sometime
eventually™️
before gta6
cant make required option
@discord.option(
name="spam",
description="Mention spam?",
choices=["Yes", "No"],
default="Yes",
required=True
)
just shows up as 3 optional in slash command
I do
and make sure to put required options before optional ones
I restart the app and discord every time
and yes the rquired is before
show your code and what you see in discord
also, remove the default
that might be the issue
default what
the default kwarg
If it is required it cannot have a default. So that is most likly the issue.
How do i install pycord? Most of the guide is all over the place,and as a beginner,i feel overwhealmed
One question, what is the difference between View.parent.message and View.message?
Do they both allow me to access the View object's message?
pip install py-cord In the terminal
Looks like View.parent returns an interaction (which then you can get the message) and View.message is the message the View is attached to
I'd assume View.parent wouldn't work for normal messages
In the case of on_timeout() event, if I want to edit the message when the view times out, does it directly access View.message?
async def on_timeout(self):
await self.message.edit(view=self)
Yes. self is your view.
ok, thank you very much!
This is the documentation for Pycord, a library for Python to aid in creating applications that utilise the Discord API. Prerequisites: Pycord works with Python 3.8 or higher. Support for earlier v...
As toothy said, that's literally what the docs say at the beginning.
And so does the guide
https://guide.pycord.dev/installation#fresh-installation
Before you can start using Pycord, you need to install the library.
stupid question, has pycord made a way to handle/use application emojis?
ty!
hello, I have a interaction setup where after a user interacts with a button I have it defer on the first line and then later on I want to send a modal but because I have already deferred I'm not able to send the modal as it can't use followup.
Am I forced to just remove the earlier defer?
Yes.
hmm
You can't defer and send a modal. The modal must be the first response.
I just feel like that will cause people issues with slower internet
Because I have some processes before I have to use the modal
Do the processes outside the button.
How can I get all Messages from a Thread?
p sure you can just use .history just like for a channel
Oh right. Not sure how I missed this. Thank you
is this syntax correct?
https://mystb.in/d6d7a8f00fdc8bc393
if it's so little code you can just send it here
and no
name and type are positional, just do
discord.option("name", str, autocomplete=...
the second option is right but you can just use str instead of the slash command option type, it's shorter
oh and if you use the decorator, remove the Option typehint in the function header
it didn't feel like very little code
oh well
here, quite a big example from my bot
@discord.slash_command(name="image")
@discord.option(
"name",
str,
autocomplete=discord.utils.basic_autocomplete(single_image_name),
)
@discord.option(
"image",
str,
choices=["image", "thumbnail", "none"],
)
@discord.option(
"show", str, autocomplete=discord.utils.basic_autocomplete(single_image_show)
)
async def single_image(
self,
ctx: discord.ApplicationContext,
name: str = None,
image: str = "image",
show: str = None,
) -> None:
```so more like this?
yes
but you don't have to do = None, it'll be None by default
and if you want to you can leave the str away entirely in the decorator like I did, string is the default option type
alright
also, when i remove the = Nones, it complains about having non-default arguments after default arguments
ah
yea I never put defaults in the function header, I just use the decorator
also, how does the name work?
in discord.option
i guess this is more of a question of how @discord.option works
does name have to be the same as the argument name in the function
no
or is it just the first option coresponds to the first argument, second option - second argument, etc
if you set a name that's different from the parameter name, you can use parameter_name= to match it onto the parameter
aha, okay
no, it matches by name
Hi! I've discovered discord.Bot.slash_group decorator, but I'm having some issues with using it. Can someone please help me?
My code:
import discord
bot = discord.Bot()
@bot.slash_group()
async def hello(ctx):
await ctx.respond("Hello!")
DISCORD_TOKEN = ''
bot.run(DISCORD_TOKEN)
I'm getting:
Traceback (most recent call last):
File "C:\Users\Admin\PycharmProjects\discordBots\main.py", line 7, in <module>
async def hello(ctx):
File "C:\Users\Admin\PycharmProjects\discordBots\.venv\lib\site-packages\discord\bot.py", line 1038, in inner
group = cls(
TypeError: hello() got an unexpected keyword argument 'guild_ids'
just use the normal way of making slashcommand groups, never seen the decorator be used
That is what I am going to do if I'm unable to figure out what is wrong. I've been searching for someone having the same issue and I've discovered someone suggesting using it #977541067006152764 message
group = discord.SlashCommandGroup(...)
@group.command()
async def...
how to get roll id with role name?
well you could go through all the guild's roles and then search for the name
but again, role names aren't unique
class SelectMenu(view):
*options
member.addroles(select.values[0])
okay, then another question:
is there any way to have a slash group and a slash command named the same?
e.g.
/hello
/hello everyone
no
I thought it might be using that decorator since it is how prefixed command discord.ext.commands.Bot.group() decorator work
since it decorates some callback function
discord.Bot.is_owner
discord.raw_models.RawIntegrationDeleteEvent
discord.ext.commands.is_owner
discord.ext.commands.Bot.is_owner
discord.raw_models.RawReactionClearEmojiEvent
discord.raw_models.RawReactionClearEvent
discord.ApplicationCommand.get_cooldown_retry_after
discord.ext.commands.Group.get_cooldown_retry_after
discord.ext.commands.Command.get_cooldown_retry_after
discord.Interaction.authorizing_integration_owners
discord.InteractionMetadata.authorizing_integration_owners
you can use the docs search :>
is there a way to stop the advancing to the next parameter when selecting an option on a slash command?
then that option is required
i feel like you're misunderstanding what i mean by option
clicking on one of these makes the cursor go to the next parameter (if there is one)
blame discord
typically you put the least oftenly used options at the end so that isnt usually an issue

and it only happens with choices so 
imo its better to have this than not
would be annoying otherwise
i tried it on mobile and how it works there is especially annoying lmao
general rule on discord, dont use mobile
so true
how should i typehint that and what is wrong about the wrapper ?
Argument of type "(ctx: LumabotContext) -> bool" cannot be assigned to parameter "predicate" of type "Check" in function "check"
```
Callable[bool]
how can you typehint the callable's return type tho
context should probably be like [Union[ApplicationContext, commands.Context, bridge.Context]]
or like is it always the last parameter there
yeah it's always the last one
[[args], return_type]
I don't know what language I'm using anymore
that is what docs says check returns
well all of that is losing me
this happens after i unload a cog https://cdn.discordapp.com/attachments/1128743742686380032/1271192096685949001/Discord_giljOOKZJx.png?ex=66b67165&is=66b51fe5&hm=f3e5a89b457d2a03ec5c1f509e40c6acd36bfa337f45ad09a2eda2044010601a& how can i do a custom response instead.
what does an option with type discord.SlashCommandOptionType.channel give?
all channels i suppose
what does it give to the parameter
wdym
for red messages you can't give a custom error
damn
unknown integration means you need to restart discord i think
how can you check if the person using a command has a certain permission (like manage server)
.rtfm discord.default_permission
maybe this?
it allows the admins to change the permission needed easily to allow more flexibility
alright
yes, you should use that one
also, is there a type or something for all guild channels
type, not property or method
discord.abc.GuildChannel i think
guys, im trying to add role but writes error:
Ignoring exception in view <RoleChoice timeout=180.0 children=1> for item <Select type=<ComponentType.string_select: 3> placeholder='Какою роль выдаём' min_values=1 max_values=1 options=[<SelectOption label='Cha-Cha Bridge' value='Cha-Cha Bridge' description=None emoji=None default=False>, <SelectOption label='Breezily Bridge' value='Breezily Bridge' description=None emoji=None default=False>, <SelectOption label='FruitBerries Bridge' value='FruitBerries Bridge' description=None emoji=None default=False>, <SelectOption label='MoonWalk Bridge' value='MoonWalk Bridge' description=None emoji=None default=False>, <SelectOption label='God Bridge' value='God Bridge' description=None emoji=None default=False>, <SelectOption label='Dao Telly' value='Dao Telly' description=None emoji=None default=False>, <SelectOption label='Telly' value='Telly' description=None emoji=None default=False>, <SelectOption label='Dao Speed Telly' value='Dao Speed Telly' description=None emoji=None default=False>, <SelectOption label='Speed Telly' value='Speed Telly' description=None emoji=None default=False>] channel_types=[] disabled=False>:
Traceback (most recent call last):
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-packages\discord\ui\view.py", line 426, in _scheduled_task
await item.callback(interaction)
File "C:\Users\V\PycharmProjects\ilias_Projects\bots\FCB\main.py", line 78, in select_callback
await athr.add_roles(role)
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-packages\discord\member.py", line 1026, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-packages\discord\http.py", line 367, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
im trying fix this 2 hours but nothing
discord.abc.GuildChannel
discord.abc.GuildChannel.category
discord.abc.GuildChannel.changed_roles
discord.abc.GuildChannel.clone
discord.abc.GuildChannel.create_invite
discord.abc.GuildChannel.created_at
discord.abc.GuildChannel.delete
discord.abc.GuildChannel.guild
discord.abc.GuildChannel.invites
discord.abc.GuildChannel.jump_url
discord.abc.GuildChannel.mention
discord.abc.GuildChannel.move
discord.abc.GuildChannel.name
discord.abc.GuildChannel.overwrites
discord.abc.GuildChannel.overwrites_for
a list of that probably since it's all guild channels
your bot's highest role is probably lower than the role you're trying to add
rly
or the person that you're trying to to modify has higher privileges than your bot
can ctx.respond be used for ephemeral messages?
yes
do you just put ephemeral=True in it?
yes
okay
@frigid topaz you can have a maximum of 5 rows of components per message.
A select menu takes up and entire row. You can put 5 buttons in 1 row.
So maximum of 5 selects or 25 buttons or a combination
Also there are special select menu types for roles and channels. So you dont have to fill your own and be limited to 25 per select.
That might solve your issue
can a button callback "return" a value or something like that
no, but what are you trying to do
there's view.wait which waits for a view to stop - if you manipulate this correctly, it'd more or less get the result you desire
more or less, a function that creates a view, and if the user clicks button A, then X happens, but if the user clicks button B, then Y happens.
A and B would be the same, but X and Y differ depending on where it's called
so you don't want to use callbacks for the rest of the logic?
more so i don't know how i would use them
so there's a few relevant examples here
Here's the counter example.
this demonstrates using a View class with button decorators, logic in the callback
Here's the button roles example.
this is a bit more complex using Button subclassing
Here's the confirm example.
and this is the alternative solution, which uses view.wait to do all the logic in the original function
(if you're familiar with Bot.wait_for, it's similar)
huh
okay
I have a SlashCommandGroup with checks but for some reason they don't run for commands in that group
That is the SlashCommandGroup
mm = SlashCommandGroup(
name="modmail",
description="Commands related to ModMail",
checks=[commands.guild_only(), isStaff()],
)
And this the isStaff predicate
async def staffPredicate(ctx: commands.Context) -> bool:
try:
assert CONFIG.STAFF_ROLE_ID in [role.id for role in ctx.author.roles]
except AssertionError:
raise notStaffMember("You are not a staff")
return True
def isStaff() -> bool:
return commands.check(predicate=staffPredicate)
Does anyone know why it doesn't work?
does it work if you don't call them
The commands itself work. But the check isnt running
oh
forgot whether it's necessary
Throws this error when I dont have it as function
TypeError: guild_only() takes 0 positional arguments but 1 was given
the example shows commands.guild_only().predicate instead i guess...?
so perhaps it takes predicates directly
(also aside, you don't really need the guild_only check because you could set guild_only=True instead)
oh true. forgot about that
It fails when I dont have it as function. When I use the predicate directly for my custom one, then it needs the context as arg
alright, well, i did this, and the buttons work, but the interaction gives a This interaction failed
hm
is it possible to send a follow up message that has the [user] used [command] rather than being a reply to the previous message
no
what shows up to other users when the first message is ephemeral, while the follow up isn't?
followups to completed responses cannot be ephemeral
...what
what what?
that doesn't answer my question and i have little clue what "completed responses" means
do you know what a response to an interaction is?
maybe?
and i was able to send a follow up that is also ephemeral
what is View.to_components?
nah it can
if the initial response is ephemeral but the followup isn't, users will just see "Original message deleted"
it's only used in the http request for sending messages/responses, components is how discord interprets views
(or rather, View is Pycord's way of making components easier to manage)

is there a simple way to change the color of all the buttons when one of them is clicked?
alright, thanks
Can anyone help me with this problem?
I try to access the message containing the View and the message contains a single embed but it returns NoneType
Am I doing something wrong? Or should I access the embed another way?
Error:
Hora: 2024-08-08 20:49:34,416
Nivel: ERROR
Archivo: base_events.py
Función: default_exception_handler
Mensaje: Task exception was never retrieved
future: <Task finished name='discord-ui-view-timeout-30dc27a2a71415285a6923a7b5607e89' coro=<BotonesConfirmar.on_timeout() done, defined at C:\Users\Usuario\desktop\Bot de discord\Pruebas\components\juegos\botones_confirmar.py:46> exception=AttributeError("'NoneType' object has no attribute 'embeds'")>
Traceback (most recent call last):
File "C:\Users\Usuario\desktop\Bot de discord\Pruebas\components\juegos\botones_confirmar.py", line 51, in on_timeout
self.embed = self.message.embeds[0]
^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute
'embeds'
`
self.message can be None
So would I have to pass the embed directly to the class parameters? 🤔
you should check for it if its None or not
If there is none, is there another way to receive the embedded message?
Sorry, I'm not familiar with Views yet 🥲
Can you show the line where you originally send the embed/view?
Message should not be None if you are sending the message at the same time as the view
await ctx.respond(content=f"Hey! {user.mention}", embed=embed, view=buttons)
oh
Strange. I guess you can pass the emved to the view as a backup
As a parameter in the class?
I thought about that solution but wanted to know if there was a more direct way to fix it 😅
Im not sure why self.message is returning None. I thought it was that you were sending it as a separate message but that is not the case. It is late for me but I can look at it tomorrow morning to see if there is a better solution.
As a parameter in the class?
yes
Well, thanks, for now I'll pass the embedded message directly to the class 
is there a way to check if a response has already been sent
i get read the docs but i already checked like 3 different places where i would have expected to find something and didn't
Is there a way to have options only for a prefix command and not for the slash variant when using bridgecommands?
No there isn’t
The purpose of bridge is to make both thing
But you can still handle than in the command itself
With if ctx.is_app :
Yeah but that expects the Options then. My goal is to have a prefix command like
!tags add name content
and as slashcommand just /tags add
The SlashCommand should open a Modal which handles the input
yea that's not possible unless you separate the command into prefix and slash
I see. Is there a way to add Commands to the BridgeGroup?
Like
@bridge.bridge_group(guild_only=True)
async def tags(self, ctx: bridge.BridgeContext):
pass
@commands.slash_command()
async def slash_add(self, ctx: discord.ApplicationContext):
pass
@commands.command()
async def prefix_add(self, ctx: commands.Context):
pass
add = bridge.BridgeCommand(
name="add",
description="Adds a tag",
slash_variant=slash_add,
ext_variant=prefix_add,
)
tags.subcommands.append(add)
@tags.command()
Yeah but that adds it as BridgeCommand. I want to map it by myself. So that I can have one version with options and the other without
Well i want to have multiple subcommands in the group
Like
- Tags delete
- Tags list
And only 2 subcommands should be different
bridge is mainly just a wrapper for command compatibility across prefix and slash, if you're trying to customize each variant it isn't really designed for it
Fair tho
so it might be a little cumbersome, but for anything more complex you're better off not using it
how to ping role with bot?
which pycord version are you on
I swear this man gets the weirdest errors
is it alwas raised?
Can you please try two different bots? I wanna make something sure
2.6
what did you change since it last worked
idr
i think it was adding memory profiling for all my event handlers
i removed those
happened for the first time tdy
looks like a library bug
partial message should accept partial messageable
i see
if you wouldn't mind opening an issue for that
so someone can fix it
or fix it yourself and make a PR :3
lol idk how to fix it 😭
when using defer on a slash command, is the followup message forced to either be ephemeral or not based on what the defer is
yes
tragic
I can make a pr 🗣

?

