#Basic Pycord Help
1 messages · Page 28 of 1
you can also ctx.respond to the same slash command several times. may differ when you defer, not sure about this part.
how do i keep a button alive
persistent views
@discord.ui.button(label="Delete User", style=ButtonStyle.red, custom_id="adminpanel_deleteuser_button")
async def cancel_button_callback(self, button: Button, interaction: Interaction):
if interaction.user.id in adminids:
modal = UserDeletionModal(title="SECRETZ User Deletion")
await interaction.response.send_modal(modal)
else:
await interaction.response.send_message(content=f"<@{interaction.user.id}> You dont have admin!")
adminids = ["835431172942856232"]
why isnt this working thats my id and it get the @
because IDs are supposed to be an int, not a string
oh tru 💀 im a bit sped
man change your name please
nah i like it
user = await discord.get_user(SPECIAL_NUMBER_USER_ID)
dm_message = f"This special number ({number}) was used by {ctx.author.name}."
await user.send(dm_message)
return```
i want it to the bot to dm the bot owner that this special number is used and idk how to do that can someone help?
The hell is discord.get_user
even idk ig i found it on stackoverflow prolly
We have something called docs and support server
i just want the bot to dm that message to the owner thats it
discord.utils.get_or_fetch
discord.ext.bridge.AutoShardedBot.get_or_fetch_user
discord.Client.get_or_fetch_user
discord.ext.commands.Bot.get_or_fetch_user
discord.Bot.get_or_fetch_user
discord.ext.commands.AutoShardedBot.get_or_fetch_user
discord.AutoShardedBot.get_or_fetch_user
discord.AutoShardedClient.get_or_fetch_user
discord.ext.bridge.Bot.get_or_fetch_user
Bots: Attributes activity, allowed_mentions, application_flags, application_id, auto_sync_commands, cached_messages, cogs, debug_guilds, description, emojis, extensions, get_command, guilds, intent...
It's a method of your bot instance
tysmm
fixed
class Search(commands.Cog):
def __init__(self, bot):
self.bot = bot
@discord.slash_command(name="search", description="Search information about a Pakistani number or CNIC")
@option("number", description="Enter the Number or CNIC you want to search")
async def _search(
ctx: discord.ApplicationContext,
number: str
):```
it doesnt shows the options 🤦♂️
Never used decorators for options, but pretty sure the gotta go above the slash command decorator
But that’s just how I remember seeing them, just guessing here
Did u restart ur discord between change ?
Is there a rate limit for sending mass direct messages to users, such that you can't send 100 DMs in 1 second?
Is there a rate limit for sending mass messages to channels as well?
btw 1 single message to 1 user
yes there will
and only your bot will get flag and will not be abble to send message to user again
nope
what are you even trying to do
why is your number a string?
and did you restart discord after adding the option?
No, pycord handles rate limits
with expereience, i can say that with pycord and a for member in ctx.guild.members await member.send, my bot got flag
maybe it has changed since, but my bot get flag after 50 members
Can I use paginator.edit for ephemeral message?
sending embed message to users
yea but for what purpose do you need to mass message people
@sage tendon
like this
it's working for all users but i wanna know about rate limit:)
i did some optimization and it's sending 70dms in 1 sec ig 😗
but what about rate limiting 🙂💔
as I said, pycord should handle ratelimits, but you should just not send 70 messages per second
yeap it's handling rate limit ig
if you bot open discussion with a lot of member in a short time
he will get flag
I've implemented a system where I load all the bot.fetch_user() objects into a global dictionary. This way, I avoid the need to fetch the same user multiple times. Once a user is fetched, their information is stored in the global dictionary, eliminating the need to fetch them again
async def CacheUser(UserID):
global UserCache
try:
UserCache[str(UserID)] = await bot.fetch_user(UserID)
return UserCache[str(UserID)]
except Exception as e:
return False
async def ReturnCache(UserID):
global UserCache
if str(UserID) in UserCache:
return UserCache[str(UserID)]
else:
return await CacheUser(UserID)
it's already open ig
if its the same member its ok, but if it open with new member, you have a chance to get flag
also use await bot.get_or_fetch it will first check the cache to make less requets
what about the rate limit of .send() function ?
you will not likely be abble to hit her
like you will need to send more than 50 messages per seconds
did you disable cache?
they say they send 70+ per second..
for one user ?
no
then why would you need to fetch any user?
just because if i use the int for the number people sometimes feed the number including spaces and the + accoding to the country code so i have to manage that aswell, yes i treid restarting my discord it shows me this but not the option
did you restart your bot :)
yes i did that
also why is your function name _search?
i was getting a error that search command already exists i was frustrated i just changed that
yea I mean that could be the issue lol
just because i was using discord.py before and im trying to switch to pycord
make sure you don't have it duplicated anywhere
that's not the case rn i've just 3 commands as cogs
import discord
from discord.ext import commands
from bs4 import BeautifulSoup
import requests
import datetime
from discord.commands import option
```here are the imports
import option from discord directly
and maybe change it to option("number", str, ....)
Also just a heads up, don't use requests, use aiohttp
And you will most likely need to defer the interaction if you rely on API requests because they take more than 3s to complete usually
wait, you arent passing self, thats the problem
its passing self to the ctx parameter and ctx to the number parameter so it breaks
oh yea, the self is missing
already said that :)
Is it possible to run two instances of a bot for failover/redundancy?
you mean you start the bot two times?
Yes. Although I don’t think that’s the right way to do it. Maybe having HA in a cluster would be better…
sure, if you shard it and run each shard on seperate servers
but that will still make half your servers be offline when one server goes down
Using a slash command and an option that uses a custom function for the autocomplete, is there any way to stop someone typing in the field and hitting enter and instead having to wait to choose something from the autocorrect? People getting non-responding to commands because they aren't waiting for the autocompleted and choosing something.
just use choices, not autocorrect
Autocomplete can't be enforced, no
If the results are static then use choices (up to 25), otherwise you have to verify the value inside the command
Hi guys. Sooo I've probably spent 10+ hours trying to figure out how to add modals to the quickstart template. I know sooome python but not nearly enough to actually understand everything from the docs. I've watched 3+ tutorials and all of them seem to be outdated because when I copy their files 1:1 there's always something that goes wrong. So is there anyone who could just give me a quick explanation about modals? I'm even willing to pay for this 😭
open your own thread. This probably isn't a quick question
ight, sorry about that
this might be more of a general python question but im making api calls for some information, im using asyncio ofc to not block up the bot, and the returned json is massive, how can i speed up the api calls and the json parsing
how are you parsing it?
by doing it normally? im not sure if i misunderstood your question, i just do var["key"]["key2"]
well, then i don't think there's much you can do with parsing.
Can you be more specific about how you are accessing the API?
async with aiohttp.ClientSession(trust_env=True) as session:
async with session.get(f"http://{host}/v1/profile/{uuid}/{self.profile}?key={sky_api}") as response:
response_text = await response.text()
try:
data = orjson.loads(response_text)
return data["data"]
except Exception as e:
print(f"This is our exception: {e}")
print(f"This is our uuid: {uuid}")
return None```
just using aiohttp
are you facing any significant performance issues?
well, it takes an incredibly long time to get all the data and put into the embed like i want, like upwards of 45 seconds
id like it to be faster
do you know how long it takes for the request to process?
is it the "translating to embed" that uses a significant amount of time?
well no, i print out when data is finished parsing so the embeds are nearly instant but it does take quite a while for it to grab and parse the data, afaik the get request is basically instant but the actual parsing is what takes time
what is the api response format?
so you should just use await response.json()?
i do
this says text
oh yeah ignore that one it was something i was testing
i forgot i sent the wrong one my fault
but i do use await response.json everywhere
yeah will do, thanks for your help regardless
do you think multithreading the json calls may help? i switched to ujson and it is faster compared to before but its still pretty slow
is the data big?
yeah 55k lines of json
is there no way to use loop.run_until_complete alongside pycord for my method calls?
it speeds it up by a lot but since pycord doesnt like that a whole lot, i cant really use it
asyncio.run(coro) ?
oh yep im an idiot, do u think this will actually work in speeding this up or na lol
¯_(ツ)_/¯
import discord
from discord.ext import commands
class SERVER_MEMBERS_ACTIVITY(commands.Cog):
def __init__(self, bot):
self.bot = bot
@discord.slash_command(name='server-members_activity', description='Check activity of individual member')
async def _server_members_activity(
self,
ctx: discord.ApplicationContext,
member: discord.Option(discord.Member)
):
guild = ctx.guild
embed = discord.Embed(
title=f'{ctx.author.display_name}\'s Server Member Activity Check',
color=0xFFA500,
)
total_messages = 0
for channel in guild.text_channels:
async for message in channel.history(limit=200):
if message.author == member:
total_messages += 1
embed.add_field(name=member, value=f'Total Messages: {total_messages}', inline=False)
await ctx.respond(embed=embed)
def setup(bot):
bot.add_cog(SERVER_MEMBERS_ACTIVITY(bot))
In this code i am getting unknown interaction error in terminal
i don't know why
Also in discord.Option i always got this warning
'Call expression not allowed in type expression'
@errant trout Please help
Bridge?
No only slash
You don't use bridge.Bot at all in your main file?
yeah i never
Can you paste the full traceback
import os
import sys
import discord
from dotenv import load_dotenv
load_dotenv()
bot = discord.Bot()
# Append the parent directory to the sys.path to access modules in the parent directory
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
@bot.event
async def on_ready():
print(f"{bot.user} is ready and online!")
bot.load_extension('commands.roles')
bot.load_extension('commands.channels')
bot.load_extension('commands.integrations')
bot.load_extension('commands.members')
bot.load_extension('commands.activity')
bot.run(os.getenv('BOT_TOKEN'))
this is my main.py file
Oh also you can just ignore the warning
You should defer at the start of your command
Fetching history for every channel will take time
oh then how?
Just await ctx.defer()
can you give me some peice of code or hint
Invalid interaction application command
is that an error on the bot or red text
nothing in console...?
console is fine
ok
Now it shows application did not respond
raise ApplicationCommandInvokeError(exc) from exc discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
and this error in console
the defer should be the first line of your slash command
@discord.slash_command(name='server-members_activity', description='Check activity of individual member')
async def _server_members_activity(
self,
ctx: discord.ApplicationContext,
member: discord.Option(discord.Member)
):
guild = ctx.guild
total_messages = 0
for channel in guild.text_channels:
async for message in channel.history(limit=200):
if message.author == member:
total_messages += 1
await ctx.defer(f'{total_messages}')
like how
@discord.slash_command(name='server-members_activity', description='Check activity of individual member')
async def _server_members_activity(
self,
ctx: discord.ApplicationContext,
member: discord.Option(discord.Member)
):
await ctx.defer()
guild = ctx.guild
total_messages = 0
for channel in guild.text_channels:
async for message in channel.history(limit=200):
if message.author == member:
total_messages += 1
await ctx.respond(f'{total_messages}')
or this?
the latter
Sometimes my / commandes just broke, (choice doesnt appear as choice menu but as just input box, description doesnt appear. This happen only for the choice menu. Is that a bug reported ?
also non required option become requiered, is like the decorator just doesnt register the option
here some example
or
(i precised that the member is required here while it shouldn’t
it sometime works correctly and sometime its broken
Why do you have the name and description like that?
Because its from an yaml file
I also use a yaml file for it but I dont have to add the name and other stuff to it
Yes but i have it to be customizable by the other, however that doesnt cos the issue
Its more like the option is not register at all using the decorator
Yes
guys, how could i fix that?
I might be misunderstanding something here.
why can't I throw .__dict__ at member.guild_permissions?
simpel, you are above the character limits. hang on a minute, ill provide you some details
thanks!
"Zeichen" means characters.
yes im from germany too haha
alright. have fun building 🙂
thanks!
LOL
why lol, he is perfectly correct with this path
Does someone know how to create sides like if u fetch warns and they are to many, that you can press a button to go on the next side
Yes I didn’t know that
you mean an embed with several pages?
Yes
you need to make the creation of each side yourself and can use paginator to send this collection of pages as one embed then.
usually it uses buttons, allowing the user to switch between pages.
there certainly is a way to make it switch pages on its own through updating the embeds current page and sleep.
you gotta build it yourself though, i think
But how do I create them
like you create any embed
you just build a logic that builds a page and stops + starts building another page once it reaches a certain amount of characters.
then you bundle all those pages in a list or tuple or such and hand it over to paginator
not sure what datatype it expects exactly, details should be availible in the docs for ext.pages somewhere
did this answer your question?
(by page i mean embed)
Ja und Nein:
Ich entwickele seit einer Weile als Hobby. Offiziel werde ich ab 17.06. zum Fachinformatiker für Anwendungsentwicklung mit Schwerpunkt auf Java ausgebildet.
Hast du verifizierte Bots wenn ich fragen darf
Verifiziert und öffentlich nur einen. Der überwacht inzwischen 1.4 mio Member. An dem arbeite ich auch gerade 🙂
Wie siehts bei dir aus?
maybe we should take this to #international-chat
Ok
I have a problem with geting a guild/member.
when I do it like this:
def search_recommendations(self):
for t in db.get_all_teams():
guild = self.bot.get_guild(1083719609997332530)
owner = guild.get_member(t[5])
I get this error:
discord.errors.ExtensionFailed: Extension 'cogs.teams' raised an error: AttributeError: 'NoneType' object has no attribute 'get_member'
but when I implement like this:
async def search_recommendations(self):
for t in db.get_all_teams():
guild = await self.bot.fetch_guild(1083719609997332530)
owner = await guild.fetch_member(t[5])
I get this error message and the cog don't load:
TypeError: 'coroutine' object is not iterable
I'm using the function here:
def __init__(self, client):
self.bot: commands.Bot = client
self.searchteam.options[0].choices = self.search_recommendations()
what am I doing wrong?
and how can I fix this problem?
because you can't use async functions in init
do you not have the guilds intent?
In the Discord Dev Portal?
no
have you set any intents
in your code
oh i see now
if it's in your cog init, you're trying to use get_guild before the bot's started
so no guilds exist
you should create an on_ready listener in your cog and use await self.bot.wait_until_ready()
then after that use the code from your first version
mainly just need to account for race conditions; make sure values are set before trying to use them
you need to take into account that any guild as well as member can be None.
So you need to check if it is None or if it is type discord.Guild/discord.Member
and when its not what you wanted it to be
(careful with the member, might be discord.User, you dont want to work with that within context of a discord.Guild even though it has some similar attributes)
Also you need to run those things when your cache was loaded as Nelo said, with an is_ready check (there is several ways)
lastly, when get_something leads to None try fetch, but only after cache was loaded (meaning ready is true), cause fetch causes an API request and you dont want to hammer them when you dont need to.
like this:
@commands.Cog.listener()
async def on_ready(self):
await self.bot.wait_until_ready()
self.searchteam.options[0].choices = self.search_recommendations()
```?
getting stuff is a bitch, but they made a good job going easy on the api with cache 🙂
yeah that seems about right
so I should use get_member instead of fetch_member?
get_member and get_guild are more ideal yes
Careful!
This would run every single time your bot has its cache loaded. this can happen several times for a load of reasons!
oh thats new to me, what should I change then?
yes, you always try get first.
if get returns None, you fetch
just check if self.searchteam.options[0].choices has been set before
in the on_ready listener?
well, yeah
with something like self.searchteam.options[0].choices = None?
if the value has already been set then you don't need to run it again
uhhh it might be a list
I solved just this very thing a few days ago. let me give you an example how I solved it.
yea that would be nice, thanks
class Ready(commands.Cog):
def __init__(self, has_run: bool):
# other stuff
self.has_run = False
# on_ready event listener here
# code that executes on ready
# at the end:
self.has_run = True
thanks, the self.has_run = False is in the init, the on_ready not and at the end of the on_ready you set the has_run to True?
if you want to use it elsewhere you can always:
bot.is_ready() # to get true/false for loaded cache
to get True/False for cache being loaded
yes.
Of course there is also an:
if has_run:
return
at the very beginning of the code under 'on_ready:'
like this:
def __init__(self, client, has_run: bool):
self.bot: commands.Bot = client
self.has_run = False
@commands.Cog.listener()
async def on_ready(self):
if self.has_run:
return
await self.bot.wait_until_ready()
self.searchteam.options[0].choices = self.search_recommendations()
self.has_run = True```
but I don't understand what the reason of the has_run: bool in the init parameter is for
so it's an attribute for this class.
A normal variable would reset when the event is triggered again.
A global variable would work, but global variables is asking for messy code.
makes sense?
yes, thank you for helping me
but where do I need to put the argument to stop this error: discord.errors.ExtensionFailed: Extension 'cogs.teams' raised an error: TypeError: Create_team.__init__() missing 1 required positional argument: 'has_run'
thanks that worked
I have a embed whose description always expands automatically when someone is warned, but since embed have a max length, i dont know how i can do this in the future now
learn python before building bots
?tag learnpython
To be clear:
When we tell you to learn Python before asking questions here, it is not meant in a derogatory way, we are not calling your dumb or incompetent. We are simply stating the fact that usage of PyCord requires a fair bit of knowledge with using OOP, Async/Await etc. in Python. If you are not comfortable with these concepts, chances are you will not understand the answers given to you in this channel.
We understand that everyone learns at a different pace, and your current knowledge with Python may have been enough so far. When we say "you need to learn Python", it is most likely a sign that we have given you an explanation that you could not understand and there is no way for us continue to help you without spoonfeeding.
thanks for the help mate
?tag lp
Resources For Learning Python
- Official Beginner's Guide
- Shortcut to guide for people new to programming and people with experience programming
- Official Tutorial
Other Resources To Learn Python
- Automate The Boring Stuff for complete beginners to programming
- Learn X In Y Minutes for people with experience programming
- Swaroopch is a useful book
- Code Abbey has practice for beginners
- W3Schools is a good resource for general use
@sly ember
eh, their question wasn't particularly bad... all the while you were giving someone a step by step tutorial
check the len of each things
and then you only take the number of character needed
basically just make sure you're within the limits (512 for fields, 4096 for description) and if not add a new field or make a new embed
1024
for fields
ohok
all text content in a single message's embeds is limited to 6000 characters, so if you surpass that you have to send another
I didn't think it was a bad question and when you scroll up a bit, i also provided some more details about the character limitations for each field in an embed to the person.
My thought was:
"If he doesn't know len is a thing it might be best to refer him to some sources that cover or brush up on the basics, it'll make live a lot easier along the way"
So I wanted to be helpful
Hey, if this came across the wrong way, I meant well.
Please don't feel brushed off and don't hesitate to ask things in the future
Wie kann ich aus einem Select menü das angewählte nehmen und für jeder Auswahl einen anderen Output ausgeven
no no, its okay i mean i knew i could use embed fields but since the bot automatically adds a new line when someone gets a warning, the emebd description expands itself, i just wanted to know if i somehow could fix it without fields, since im not sure if the bot can automatically add a new field when someone was warned, you know? But its okay, i know im not the best in coding and i appreciate your help, thanks!
match case statement
Häh
hahah du bist ja deutsch
leider
Yeah, I understand.
You need to build your own sorting logic to tell the bot when to start a new embed or field and how. Thought it's best when you learn about things like len or more complex logic first, cause building those things can be a little painful at times, especially without them
Warum leider? 
Ich weiß nicht wie ich rauskriegen das er von Nur dem einem Select menü die Auswahl kriege und wie finde ich raus was er ausgewählt hat was muss ich abfragen?
HAAHAHAHAH du auch
Perfect, i will, thanks mate!
many here are
habe oft das Gefühl dass in jedem Support Server der welt deutsche nicht gerade überdurchschnittlich sind
aus Erfahrung
Ich kann ja mit If und els usw umgehen
Zeig den Code für dein select
Kann ich Später Grade net
😄
Ist äh etwas Schwierig wenn einem der Linux Boot Zerschossen ist
match case:
Sehr viele sogar
Wenn die Installation läuft schick ich den Code
Kinda
yo, i have something this simple:
class BuyPremium(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(
label="Purchase Premium",
style=discord.ButtonStyle.url,
url="https://whop.com/checkout//",
)
async def purchase_premium(
self,
button: discord.ui.Button,
interaction: discord.Interaction,
):
pass```
but for some reason it keeps saying button() got an unexpected key argument 'url'
is that not how you do button links?
Here's the link example.
THANK YOU
@errant trout can i talk you about a bug or should i open a issue on the github rn ?
An issue would work better
i will first open an help here to be sure that its not a simple thing and then open an issue
asks
proceeds to do the opposite
he answered too late
everything was already prepared
Is there a way to disable all existing buttons created from the same class view 'MyView' with a slash command instead of disabling them one by one?
On a single message?
all messages that has the buttons
You'd have to loop and edit every message
a single one message this has been solved thank to you
ah okay so there isn't an easier way to do it
thanks
Mhm
no
you can do it an easier way, if you centrally store all view objects and then call a disable-all function inside them
centrally store? you mean like a database?
...regardless you have to edit every message
no
You literally do
Go on then
I'm all ears 😄
okay i might have forgotten that i edit the message but i outsourced that line of code
i should sleep.. im too tired to concentrate
sorry
why only autocomplete offers you option of passing the whole function with conditionals to return specified options depending on what you selected before
can't do the same with choices
choices are static, autocomplete is dynamic
ask discord
hm so is there a way to do the same thing here, but with hard-coded options that you can only select? without letting user type additional input
well, i don't know if it's a great idea especially when I got 17 possible options lol
but if it's the only way
i guess i'll try that
hello how do i take a file input from the user to process it later ?
discord.Attachment
are you looking for this?
they basically want choices depending on an input
ye so how would i accept it in a command
bridge or slash commands
slash
then discord.Interaction isn't right anyway
it's discord.ApplicationContext
and the var for it should be named ctx
do you use discord.Option or @option for command options
@fresh sierra just found this, might help you with your issue / problem
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
and how would i save the file to my local
Answer my question
i dont know
i m making this after a long time i never worked with files
its no different from any other command option
this is the issue
on my side I also have a question I have created a command to edit a button, I successfully managed to change label and disable/enable it
I also like to change the button style but I'm stuck on that part, how can I call ButtonStyle function based on view?
Thanks
or do you never explicitly make them options and just put parameters into your function header
ah
what
again, parameter_name breaks the typehint (if you don't pass type separately) because of an oversight
well yeah they were using parameter_name from the beginning

when you have a view, you can use view.get_item(...) to get it by custom ID
then change button.style to the new style
or if you're using .children then whatever the index is
well you arent using any explicit way of creating the option
does the file option show up as an attachment picker in discord?
yeah it has to be Attachment, not File
you don't have to use Option, but it's needed if you want any customizations on it
yea i was confused because i remember it as attachment too, but in the doc search i only find discord.File
file is an object we use for conversion on send, but otherwise everything recieved from discord is an Attachment or Asset
like what customisation
descriptions, special input parameters, etc
description, choices, autocomplete, default, etc
also unrelated but why do you sync your commands?
oh i got caught lol
ok thanks but once I use view.get_item what's the exact syntax to change the button style?
no i dont want any i just want it to simply accept a targert string and a file from user
i mean, nothing against them, but we can't help with that lib
💀
idk if they actually use File or Attachment, it may well be different to us
am i stupid or why cant i find discord.Attachment in the docs?
i mean i had pycord installed and used pycord only
but that code is dpy...
also nelo, what made you able to tell its dpy
Models -> Message
we don't use tree

yea thats only really why i noticed that line of code too lol
just search attachment, nothing else
(on further inspection there's other stuff but that's the easiest thing to spot)
this has to be a search oversight
ye i have it rn too and the above code is just copy pasted lol
why do i not find it by exact name
probably, but there's no reason to specify discord
i always do lmao
because everything on docs is under discord
idk why
in that case you need to rewrite your code to be more pycord focused by comparing on docs; we can't convert everything for you
it probably wouldn't run using pycord tho
(or alternatively switch back, idk ultimately your choice)
ok ok
also when will more data be added in the style thats available on pycord.dev
wdym
can't tell about that exactly, but just having a look at the github channel here, the devs as well as some others hand in sh constantly. sometimes at insane rates 😄
also, dev branch was deleted i think? lemme check
#library-updates second last post
what do they even mean by "data"
wdym by "more data", the docs has everything available in the library
if you mean new features you can install master or specific unmerged PRs, but all of that stuff is beta and subject to change
true, the docs are really good.
when i dont find something in there its either cause it does not exist or I am doing sth. wrong.
yea i mean the docs are completely fine
they arent missign anything (major), not that i noticed anyway
but in that case one can always bother toothy 😜
No you're not! stop saying that, i need advise for the weirdes edge cases and ideas past 12 pm 😄
:>

glad
Do I have to set the presence intents for this in the code?
for what?
That the bot starts faster
yea you would have to run the bot with that intent

Okay and that how long it takes to start
im slow but i usually end up getting it right :>
?
what are you saying lmao
Im dumb i say it in German bc i know you are German
Wie viel schneller ist das dann ungefähr
Das sagst du mir wenn du es jetzt ausprobierst
Habe ich jetzt nicht vor deshalb frag ich
Kommt stark drauf an wie viele server und member 
how do i make no slash commands initialise in my bot
870k member 5160 server
damn
so you don't want slash commands?
yeah
Oops wrong
tf?
Tf
whats going on
@limber terrace
i honestly dont remember how to make a purely prefix bot in discord lmao
its definitely your bot definition that has to change
Bro what is wrong with you
Yes
yall
@hasty prism @loud kayak
oh, just pass guild_ids=xxxx in the slash command decorator
if you want to apply that to every command then do debug_guild_ids in the Bot constructor
@slash_command(guild_ids=[id1])
I say bye bye to you
oh, how can i do it in the bot constructor
mods pls
i have never in my time on discord seen such entirely unwarranted and pointless anger, even by such a kid
damn automod slacking 
Haha
I hope you get banned from discord
oh nvm automod working overtime
Is he just trolling or what is the problem from him
oh i forgot i can delete messages
they have logs, im just using report feature
i reported several messages to discord already
wow how cool
i know its going straight into the garbage @ discord, but oh well
gooby

oh nice thanks
yes pls
they're gone already lmao
Is he gone?
yes
Banned?
maybe purge too
Hey muffin
Who dare to ping while i took a shower
Sorry for Ping. Someone escalated here
Discord Mod Permissions revoked
anyway #general
Aha
guys, im running 2 bots on one token, one that has slash commands and one doesnt, but the one that doesnt keeps deleting all other slash commands, any way to fix?
...is there a particular reason you're running them separately?
yeah ones discord.js lol
...why?
bruh
certain elements of my code only work in python
to disable it in pycord you set auto_sync_commands=False in Bot
then rewrite those parts in js, or rewrite the rest of your bot in python lol
why my commands arent shown when i press / in my server
restart your discord
also I'm p sure required is true by default
also, you need to pass type=discord.Attachment to the option
else it'll default to string
is markdown possible for button labels?
Pretty sure no
is there anyway to deselect a users dropdown selection or effectively reset the selection
nop
they have to either restart the client, or you update the view
since updating it forces it to reset
ugh how annoying, thank you for the info
speaks for itself, really
that object doesn't have that attribute
you're probably looking for ctx.message.attachments
tried that too
didnt work same error
show your code and what you do in chat
if self.values[0] == '2':
self.disabled = True
# do some other logic
await interaction.respond(embed=e)
self.disabled = False```
this is for dropdown and im trying to disable the dropdown until the logic is done but it doesnt get disabled
Because you are supposed to edit the message with the new view
That’s kind of you but we already figure it out, I was using it but with the parameter name we can use the input type, we have to use type only
Is there a way to turn of slash commands for the DM channel completely without checking the context in every single command (I have a lot of them). I discovered that ALL users (also non-Admins and non-Mods) are able to use all slash commands in the DM channel because there, the server side settings in discord which commands are usable for which role are completely ignored. (Thats some major security issue). I thought maybe there is a global boolean or something to tell pycord to block the DM channel for commands generally
@outer trout
Just wondering what intents are required for the bot to use self._bot.http.get_guild_commands because it keeps returning discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access. I'm assuming its not anything to do with guilds because that is already enabled as shown below: py bot = discord.Bot(intents=discord.Intents( messages=True, message_content=True, guilds=True, invites=True ))
Thanks!
portal intents are on right?
& it'd be helpful to see some code related to the command you're talking about
and a stack trace
Required intents are toggled on the developer portal & It's not a command, it's the on_connect event and that's the only trace back I get.
I believe I get that too
it doesn't break anything though right?
I'll go run the bot again and copy the whole trace back.
alr
None of my commands are registering :/
Ignoring exception in on_connect
Traceback (most recent call last):
File "C:\Users\julia\PycharmProjects\Nestling Bot\.idea\Lib\site-packages\discord\client.py", line 400, in _run_event
await coro(*args, **kwargs)
File "C:\Users\julia\PycharmProjects\Nestling Bot\.idea\Lib\site-packages\discord\bot.py", line 1178, in on_connect
await self.sync_commands()
File "C:\Users\julia\PycharmProjects\Nestling Bot\.idea\Lib\site-packages\discord\bot.py", line 754, in sync_commands
app_cmds = await self.register_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\julia\PycharmProjects\Nestling Bot\.idea\Lib\site-packages\discord\bot.py", line 531, in register_commands
prefetched_commands = await self._bot.http.get_guild_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\julia\PycharmProjects\Nestling Bot\.idea\Lib\site-packages\discord\http.py", line 367, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
is what I get
on every startup
oooh shoot
are they slash commands?
I only have the /help and /ping commands with the raw @bot.command decorator. The ones under @config and @flags(.command) aren't appearing at all. Thy are created with bot.create_group()
Yessss
hmmmmmmmm
On pc now, bear with.
ok so I believe this is a problem with on_connect itself
async def on_connect(self):
if self.auto_sync_commands:
await self.sync_commands()
^ Is within the BotBase
so if you overwrite it
it's not syncing commands
@bot.listen()
async def on_connect():
will not overwrite
All my events work (decorated with @bot.event)
All the raw commands work (decorated with @bot.command where bot = discord.Bot() with intents passed
I have 2 groups: flags, config which are created with bot.create_group()
No commands from either groups will register, when the raw commands do.
@bot.event for on_connect will overwrite the sync
Example group: py config = bot.create_group( name="configuration", description="All the internal bot configuration commands.", guild_ids=[ 1224207263162695792, # msa official 1211037017853665360 # testing server ], )
Example command: py @config.command(name='set', description='Set a config value.') async def set(ctx, key: str, value: str): try: Config.set(key, value) await ctx.respond(f"Successfully set {key} to {value}.", ephemeral=True) except OperationalError: print(f.LIGHTMAGENTA_EX + f"Failed to set config key: {key} to {value}. Originated from Discord with the interaction above." + f.RESET) return ctx.respond(f"Failed to set {key} to {value}.", ephemeral=True)
Do you have on_connect?
Only have on_message, on_message_edit & on_interaction.
oooh ok
I'm starting to think maybe this isnt a 'quick question' and I should make a thread for it ;-;
idk
I'll put the traceback in the thread, want me to ping you?
sure!
Is there a way to have 2 source codes running and one with slash commands and the other without?
Is it possible? Yes.
Should you do it? Definetly not.
Why not
Wdym
Events would get called on both instances for example
Why dont you just use a bridge bot?
Using the slash command subgroups, is there anyway I can limit just the subgroup itself to a specific role type instead of specifying it for each command?
also could I set "hidden=True" for the subgroup itself and hide everything within that subgroup without again explicitly doing it for each command?
where can i see if the user of a slash command is on mobile or pc?
ctx.author returns the user which was running the command ;3
Discord side, perms are already forced on the entire group
If you mean internal checks, you can pass a list of checks through
mobile_status seems to have it, but only for Member, not User
How can i dont let the bot delete the slash commands registered by the other code?
I tried ctx.author.mobile_status, but this always returns offline, even when i turn off the app and run the command via my phone.
Ask again but now in English
Wait
I have 2 bots running. How can I make sure that the 2nd script does not cancel / overwrite the slash commands of the first one?
by having them in different environments
if you're on pycharm you dont even need to do much for it.
each time you make a new project it gets its own .env automatically
and the projects live in their own subfolder as well, so you don't need to worry about your cogs being loaded into the wrong bot.
Can i define that in the code?
set auto_sync_commands=False in Bot
thx
how to disable the !help command?
Hi, I need help. I have a while loop in one of my button callback. The problem: When I press the button nobody other can use this button. how can I fix this?
Why do you need a while loop?
I need to execute a function when the unix time hit a specific timestamp, but only when 2 users used the button otherwise I need to run anohter function
help_command = None in the commands.Bot()
can I do it with: asyncio.create_task(self.start_game_timer(game))
Yes indeed, I was about to mention you need a separate task
thanks
when I do it like I said other users still can't use the button
i'd use a task loop, but it depends on how precise and how far out it is
you could also use await bot.wait_for("interaction") with a check that validates the timestamp and button presses... a lot of different approaches to consider
thanks that helped
hello how can i make it so that if the user has the role with role id 123 then he can access the bot cmd else he would get a message that you dont have the id
role= discord.utils.get(ctx.author.guild.roles , id =123)
if role not in ctx.author.get_roles :
ctx.respond("you dont have access)
its like this ?
ctx.author.roles
toothy my frenn u there
rest is correct right?
Wait no
Why u don’t do ctx.guild.get_role?
allowed = False
for role in ctx.author.roles:
if role.id == custom_role_id:
allowed = True
break
if not allowed:
return await ctx.respond("Nuh uh", ephemeral=True)
that's how i'd do it
bit clunky but im tired
you could also create a check function and pass that to the slash command decorator via the checks= parameter
Hello! How to do slash cmnds in DM?
nothing to do, they already work in DMs
they isnt in select
?
they are not in the selection in DM
do you mean in the DMs with the bot, or with other users
show your slash command code
@commands.dm_only()
async def submitclue(ctx):
await ctx.send("Submit your answer")
message = await secret.wait_for('message')
print(f"{message.author} is an author of the message.")
if message.content == "twopeople":
await ctx.send("Answer correct.")
else:
await ctx.send("Answer wrong")
what is secret
is name of bot
that's usually discord.slash_command..
did you just import discord as the name of your bot?
no
from discord.ext import commands
from discord.ui import Button, View
secret = commands.Bot(command_prefix='.', intents=discord.Intents.all())
token = 'token'
@secret.command(name='clear')
async def clear_chat(ctx):
channel = ctx.channel
if isinstance(channel, discord.TextChannel):
await channel.clear_messages(limit=100)
await ctx.send(f"Cleared {len(channel.history)} messages in {channel.mention}")
else:
await ctx.send("This command can only be used in text channels.")
@secret.slash_command(name='submitclue')
@commands.dm_only()
async def submitclue(ctx):
await ctx.send("Submit your answer")
message = await secret.wait_for('message')
print(f"{message.author} is an author of the message.")
if message.content == "twopeople":
await ctx.send("Answer correct.")
else:
await ctx.send("Answer wrong")
def run(bot, token: str):
bot.run(token)
run(secret, token=token)```
that will 2+ bots
ok
also, do not request all intents
request default, and if you need members intents, add that manually
,rtfm intents
i forgot the prefix
but just do
intents = discord.Intents.default()
# and if you need members
intents.members = True
requesting all intents is unnecessary and will break stuff if you didn't also enable all intents in the dev portal
also, for slash commands, you need to use ctx.respond
then why do you put it in your code?
dont ask fucking chatgpt for code, especially not gpt3.5
thx
also, change your bot definition to discord.Bot
im p sure commands.Bot is only for prefix commands
ok
and logically also remove the command prefix parameter then
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)
i stand corrected
but usually discord.Bot is what you need unless you really want prefix commands
if you do only event and slash it would be discord.Bot yea
but i would not trust chatgpt with that, so, just dont do prefix commands
(or learn to code without chatgpt)
Here's the slash options example.
thank you toothy love u sm 🤗 ♥️
how to do clear cmnd
@option(
"amount",
min_value=1,
max_value=None,
default=20,
# Passing the default value makes an argument optional.
# You also can create optional arguments using:
#
)
async def clear(ctx, amount: int = None): # По умолчанию будет удалять последние 5 сообщений
if amount is None:
await ctx.channel.purge() # Удалить весь чат, если параметр amount не указан
else:
await ctx.channel.purge(limit=amount+1)```
here`s my code.
i can`t to delete all mesages in dm
You can't delete other's DMs
my dm
No
not other
my dm with bot
what would you even need that for
it can`t to delete my messages
If you mean the slash commands in the bot's dms, the bot has to delete those, because those are his messages according to how discord works
but i dont know how to do that, i never do anything with DMs
How can I get the user that uses a command so I can ping them?
ctx.author(.mention)
How do I put the value in a respond context? I tried this
user = ctx.author(.mention)
await ctx.(f"Message... {user}")
and
await ctx.(f"Message... {ctx.user(.mention)}")
without the brackets lol, that was just because you get the user with ctx.author, and adding .mention mentions them directly
if custom_role in [role.id for role in ctx.author.roles]

I keep getting a syntax error when using the dot.
Sorry if I'm missing something obvious.
I want to send a message that pings/mentions a user. Am I going about this the wrong way?
that's what I meant mb
well, show your code
What can it break ‘
it can just make your bot not work
and you also enabled them all in the dev portal
Yes
yea, most people dont
Oo I see
But without it kind difficult to do most of the thing
Can’t see message, presence or even kick or ban member
message_content is rarely needed with slash commands
I doing
await ctx.(f"Message... {ctx.author(.mention)}")
but I feel like that is not the way I'm meant to be doing it.
again, without the brackets
.
and it's still ctx.author, not user
ctx.user ? It’s not author ?
Heyy I'm getting TypeError("Invalid usage of typing.Union") here, any idea?
@level.command(name="réponse", description="Ajouter une réponse à un niveau")
@commands.has_permissions(administrator=True)
async def answer(self, ctx: bridge.Context, réponse: str, level: int): ...
I doing
await ctx.(f"Message... {ctx.author.mention}")
but I feel like that is not the way I'm meant to be doing it.
can you please just screenshot your code @queen iron
Why are u adding some other things
show the stacktrace
Connected to pydev debugger (build 233.14475.56)
WARNING: PyNaCl is not installed, voice will NOT be supported (client.py:256)
Traceback (most recent call last):
File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "C:\Users\jerem\D\05. Discord\Dystopia\modules\__init__.py", line 2, in <module>
from .admin import Admin
File "C:\Users\jerem\D\05. Discord\Dystopia\modules\admin.py", line 39, in <module>
class Admin(commands.Cog):
File "C:\Users\jerem\D\05. Discord\Dystopia\modules\admin.py", line 53, in Admin
async def answer(self, ctx: bridge.Context, réponse: str, level: int):
File "C:\Users\jerem\D\05. Discord\Dystopia\.venv\lib\site-packages\discord\ext\bridge\core.py", line 396, in wrap
slash = self.slash_variant.command(
File "C:\Users\jerem\D\05. Discord\Dystopia\.venv\lib\site-packages\discord\commands\core.py", line 1258, in wrap
command = cls(func, parent=self, **kwargs)
File "C:\Users\jerem\D\05. Discord\Dystopia\.venv\lib\site-packages\discord\ext\bridge\core.py", line 83, in __init__
super().__init__(func, **kwargs)
File "C:\Users\jerem\D\05. Discord\Dystopia\.venv\lib\site-packages\discord\commands\core.py", line 694, in __init__
self._validate_parameters()
File "C:\Users\jerem\D\05. Discord\Dystopia\.venv\lib\site-packages\discord\commands\core.py", line 712, in _validate_parameters
self.options = self._parse_options(params)
File "C:\Users\jerem\D\05. Discord\Dystopia\.venv\lib\site-packages\discord\commands\core.py", line 760, in _parse_options
option = Option(option.__args__)
File "C:\Users\jerem\D\05. Discord\Dystopia\.venv\lib\site-packages\discord\commands\options.py", line 232, in __init__
raise exc
File "C:\Users\jerem\D\05. Discord\Dystopia\.venv\lib\site-packages\discord\commands\options.py", line 227, in __init__
self.input_type = SlashCommandOptionType.from_datatype(input_type)
File "C:\Users\jerem\D\05. Discord\Dystopia\.venv\lib\site-packages\discord\enums.py", line 798, in from_datatype
raise TypeError("Invalid usage of typing.Union")
TypeError: Invalid usage of typing.Union
python-BaseException
Seems like an internal error
I got this after upgrading to v2.5, iut works just fine with v2.4.1
await ctx.respond(f"{ctx.author.mention}")
never use time.sleep
oh without the () not brackets. I feel silly.
also, you cant respond after more than 15 minutes, thats the max interaction time limit
@little cobalt does responding twice do a followup automatically by now btw?
What should I use? I'm trying to setup a pomodoro timer bot. Is there a better way to be doing this?
asyncio.sleep()
^
thanks
and change the respond after the sleep to await ctx.channel.send
with await in the front
because the response will not work after 15m
you do probably want to ping the user in that case then
It was always working after 30 minutes for me x3
but I send a instand respond and a other later
isn't the time limit for interactions 15m? views, responses, everything?
ah, maybe its different for followups then
^^
according to zervy you can ignore this @queen iron
Is there any way to do this then? If 15 is the limit?
just send a respond after the execution and one later
wait does discord.Option take positionals in the order type, name?
or why does it work that they pass it in that order
becuase i'm p sure discord.option, the decorator, needs name,type
.... i just realised discord.Option doesn't have a name
well it does but only as kwarg and optional
Thanks for you help <3
np
has anyone an idea? The update seems to also have messed up a lot of other bridge-related stuff...
I know that bridge had some breaking changes with 2.5
did it? i didnt see anything breaking in the change log
and it was a minor update
so shouldn't be
ye
now you have to use BridgeOption
and discord.option is not working anymore
i think that was listed as a fix
which makes it not a breaking but a correcting change
Also in a bridge command does name need to be a kwarg or an arg or can it be both
eh kind of up to interpretation
At least my dependencies where pinned
by default it takes the function name
if you havent set a name, the name will be the one at your code
Yeah I know that, it's just that I did set name= and it broke
saying I set name twice which was not the case
Oh fair enough idk why it worked previously maybe they removed it, or there was a catch-all kwargs
why this error is it because i didnt respond within 3 sec ? but i used .defer and the followup send
just put it here
ah its a bit priv
so are my DM settings
😢 pls toothy
no

you can DM it to me
also, you do not send a followup to a defer
then what do i do to increase the resp time ?
and how did you know that lol
i didnt even share anything
no, you can only respond a defer with a followup
..no?
ctx.respond just handles that for you
yea duh
but we are talking about the user facing side of the library, not the inner workings
a defered interaction can also come in a form of a button, which cannot just be simply responded to
yes, but we are talking about a normal message interaction
a message interaction is different from a slash command
sigh
you know what i mean
there are multiple things you can mean by that. I do not know which one.
Okay
But you are also not the one asking for help rn
this is simply incorrect
@errant river is the first line of your slash command a defer?
In the library, its... command.id
For the current command its ctx.command, otherwise you want bot.get_application_command (which takes the command name)
you can also just use command.mention for the string
can you also by any chance prefill that mention with arguments
used to, removed because abuse
no
then change it so that it is
can u dms
yes
How can i create a cluster with Py-cord?
do you mean shard your bot?
i mean yyeag
or run it on several servers?
Well, I mean stop that you have one bot but different instances like with the big bots
On a single physical server or multiple ones?
both
one
how many guilds does your bot have?
250+
less than 1000?
yeah
is this a discord featrues or oly pycord
Discord
and host one bot of multipl servers
i mean thats just somethging you can do, its not really a feature of anything
pycord just allows you to set specific shards on specific devices so you can run half of them on server A and half on server B
ah okay thx
Hello, i have been receiving Missing Access error (error code: 50001) only after loading cogs. it works perfectly fine with normal slash commands in the main file.
I have already taken the following steps to address the issue:
- Enabled the necessary
botandapplications.commandsscopes. - Reinvited the bot to the server after updating permissions to ensure they take effect. (It is a brand new bot in only one server)
Despite these efforts, the issue still persists. any idea on how to fix it?
?tag missing_access
If you get a Missing Access (50001) error, you probably forgot to add the applications.commands scope.
To fix that, just re-invite your bot to the guilds you specified guild_ids or debug_guilds for.
can you paste/show a screenshot of the full traceback
(strictly speaking there's no minimum, it's just rather pointless that early)
hey all, lets say i have a command which takes in arg1 and arg2, is there a way for arg2s choices to be set based on what arg1 is?
Use an autocomplete
.rtfm AutocompleteContext.options
To get the option selected in arg1
Task exception was never retrieved
future: <Task finished name='Task-103' coro=<ApplicationCommandMixin.on_application_command_auto_complete.<locals>.callback() done, defined at C:\Users\thund\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py:869> exception=NotFound('404 Not Found (error code: 10062): Unknown interaction')>
Traceback (most recent call last):
File "C:\Users\thund\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 872, in callback
return await command.invoke_autocomplete_callback(ctx)
File "C:\Users\thund\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 1042, in invoke_autocomplete_callback
return await ctx.interaction.response.send_autocomplete_result(
File "C:\Users\thund\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 1139, in send_autocomplete_result
await self._locked_response(
File "C:\Users\thund\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 1243, in _locked_response
await coro
File "C:\Users\thund\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 220, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```
what in the world does this mean?
or can i like defer the autocomplete
im basically using arg and running it thru an api and i kind of need it but the autocomplete times out i guess
no
probably don't do that then
i cant just not do that, is there no workaround?
can you be more specific for what you are doing?
yep, so basically the user enters an ign, i then throw it into an api to get all the "profiles" this ign has and the 2nd arg returns all the profiles as autocompletions, the issue is the api throws out massive json and i need to parse thru it to get the profiles which is most likely why it times out
how many "profiles" are there
Is there any way to quickly check whether a role is assignable to a member? e.g. a bot-role, or @here/@everyone can't be assigned to a user, though these are selectable with a slash-command with option discord.Role.
you could just make an exception for @here and @everyone
cause the other roles would just be if the bot's role is higher than that role & or it has certain perms
I'm not sure if there's a helper function though
maybe that'd be a useful PR...
How to mention user in bot description
<@id>
read something the other day that you could only do so via an API request.
There was a code example how you can do it too, but i don't recall who sent it or in which channel.
It's in here "somewhere" 🙃
@pale scroll
?tag gif_avatar
?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!
?tag gif_banner
No tag gif_banner found.
maybe if you simply exchange
... .edit(avatar= ...
with
... .edit(banner= ...
?
idk though, never tried it. just a thought.
fair enough
Use the full name, e.g group subgroup subcommand
just config display
but the command works with /config display, right?
oh..
slash command have no .id attribute
or, well, application commands
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
use qualified_id
specifically, subgroups/subcommands don't have IDs
only the root group has an ID, which is why qualified_id is used to get their parent ID
wait so you cant ping a subcommand like /config display?
oh
This is strange. Randomly, my bot is exhibiting issues changing its presence.
await self.bot.change_presence(activity=discord.CustomActivity(...))
File "/home/.../.local/lib/python3.10/site-packages/discord/client.py", line 1386, in change_presence
await self.ws.change_presence(activity=activity, status=status_str)
AttributeError: 'NoneType' object has no attribute 'change_presence'
(I'm on the newest version of py-cord)
Okay, nm. I had to wait_until_ready()
Yo, guys I am quite new to the Pycord, but my slash commands dont seem to update when I rerun the code. Meaning some deleted functions are still present. Is it something on discords side or is there a way to properly sync them?
restart your discord
haha, thank you <3
Ignoring exception in on_interaction
Traceback (most recent call last):
File "/usr/local/lib/python3.10/site-packages/discord/client.py", line 400, in _run_event
await coro(*args, **kwargs)
File "/data/cogs/commands.py", line 520, in on_interaction
if interaction.message.author == self.bot.user:
AttributeError: 'NoneType' object has no attribute 'author'```
How do I get rid of this error?
Code:
```py
@commands.Cog.listener()
async def on_interaction(self, interaction: discord.Interaction):
if interaction.message.author == self.bot.user:```
interaction.user is the user who triggered the interaction
interaction.message is the message that contains the component that was clicked (if that's the type of interaction)
its an event for buttons
So i want to fetch the button clicks
Ik the method i use is not the best
then filter the interaction type
also
interaction.message.author will never not be the bot user
unless you used a webhook
Dumb question:
If i have a bot with the button id "custom_id"
Is it possible, that a other bot react on that too?
no
So i can remove that right?
yeah
Because if interaction.message.author == self.bot.user: checks if its the bot?
yes
Okay thank you
Ill try it
Other question
self.shard_status = {}
@commands.Cog.listener()
async def on_shard_connect(self, shard_id):
self.shard_status[shard_id] = "Connecting"
@commands.Cog.listener()
async def on_shard_ready(self, shard_id):
self.shard_status[shard_id] = "Online"
@commands.Cog.listener()
async def on_shard_disconnect(self, shard_id):
self.shard_status[shard_id] = "Offline"
@commands.Cog.listener()
async def on_shard_resumed(self, shard_id):
self.shard_status[shard_id] = "Online"```
Sometimes it doesnt trigger the events or they stay offline
But the shard is on
@edgy nestdo you have a idea...
nope
Hi, I want to make a slash command that is only able to be invoked by an admin. It seems like default_member_permissions is the relevant attribute but I'm confused on how Permissions objects work. First question is am I on the right track here, and if so, can someone give me an example of how I need to instantiate the Permissions object?
administrator=True
ohhh, that makes sense.. So perm = Permissions(administrator=True) and then @bot.slash_command(..., default_member_permissions=perm) would make it so only those with the administrator discord permission can use the command?
so that makes it so the command can only be used by those with the "ban members" perm?
yes
can that be applied to a slash command? like you'd stack that decorator on top of the slash command decorator?
below
i see
gotttt it, ok, interesting
have you defined your own slash_command so you don't have to always pass in the guild ids and stuff? and perhaps any other args?
no, its just empty
I created my own command "builder" so I dont have to add the option stuff every time
wouldn't it not register the command with discord/the guild then?
if its empty it will be a global command
none of my slash commands have anything in the slash command decorator
huh, interesting. so does that mean the default behavior is that it registers the slash command with every guild it connects to?
yes
i see
thats usually what you want from a bot lol
mine looks like this: @bot.slash_command(guild_ids=[GUILD_ID])
