#Basic Pycord Help (Quick Questions Only)
1 messages · Page 56 of 1
I dont think they wrote there own code. :/
Okay it seems to be a problem with the DB somehow. I exported the DB from the server and hosted it locally on my computer and then I get the same error. If I use the old local DB then it works on the computer, will load this times on the server and test.
or just use epoch
Okay for those who are interested in the solution. There was an identical entry in the list that caused the error. A lake was entered twice in the list and thus the error occurs.
Fortunately I have now searched so many hours because of such a trifle 😄
how do i add an image to a buttonb
Is there a way to detect when a user joins a voice channel?
image to a button? you cant. you can set an emoji tho
yes
the voice_state_update event
.rtfm voice_state_update event
Ok thanks! Will try!
oh and you need the intent for it
👍
ya i figured
how do i delete an embed when a buytton is clicked tho
edit the message and pass embeds=[]
where is the embed located? same message as that of the button?
As a sanity check, is it expected that I cannot include the whole server in a Thread by using @everyone? Roles seem to work, so was sorta hoping default_role would work even better.
(This is for legitimate server-wide notifications)
Unrelated, how can I get whether a higher role has access to a channel?
Say I have a couple of roles:
- Core
- Verified
I have a specific channel that Verified has explicit access to, which would give implicit access to Core (who is presumably also Verified)
When I ask
target_channel.permissions_for(<Role Core>).view_channel
I get false, even though someone with the Role definitely has access to the channel.
Is there some other way I can calculate this?
Is there a way to check if a message had a slash command attached to it?
.rtfm message.interaction
?tag replit
Installing Pycord with Replit (only use replit as a last resort) - pycord-replit-install.md
Is there a way to get all active cooldowns?
You would pass a member object. That factors in multiple roles
Hm. But then that would require comparing all users individually, which sounds inefficient.
The idea is to infer whether members in the current channel can see messages in a target channel based on each channel’s allowed Roles.
For instance, a channel that only allows the “Core” Role should be able to see messages sourced in a channel that has a base allow of “Verified”, but not vice-versa.
For now, I just made an explicit override in the target channel so that permissions_for works, but I wish there was a better way of rolling up permissions.
Hello everyone. I wanted to know. Who can throw off the code for the discord cogs. And approximately how it should look in the files.
PS. I already tried to make cogs on PYCord ,but every time I run the program code, only one file with commands out of 3 is launched.
I will be glad if you write in a personal chat. Thank you in advance.
check out the guide on how cogs are to be done
.guide
embed.set_footer(icon_url=guild.icon.url)
await ctx.respond(embed=embed)```
embed.set_footer(icon_url=guild.icon.url)
AttributeError: 'NoneType' object has no attribute 'url'

anyway to get the bot to not use footer if guild has no icon
no i know i cant find this anywhere
Ok so stop acting smart bc that shows nothing of what I want so i think you should read again
use "if" "else"
The docs tell you everything you need to know
And if you can't use simple if statements, you shouldn't be making a bot yet
The problem is that is not all people with core have verified it would not know what to do.
How many buttons can i have in pycord?
25 per message
The same as any other library. Max 5 action rows, and max 5 buttons per row
But that is a discord limitation not a pycord limitation
If you mean just in general, trillions, idk. How ever many you can keep in your ram
hmmm ok so there is a problem on my side.
i have 4 rows with 2 buttons each. and one is not showing
Show your code and which button isn't showing
omg. i found it. i called the function in the button the same as another button 😄
2 days for this 😄
oof
Hey guys just a quick question:
Is there any preferred way to store data when developping discord bots ?
I was thinking to use either sqlite (I never used it before) or PostgreSQL (which I already used) but I think sqlite is more adapted as I don't need crazy functionnalities
use a db which supports asyncio
There isn't a preferred way as it all depends on what data you're storing and what you're comfortable using. If you're good at sqlite, there's no reason to use postgres unless you actually need to.
You don't really need to worry about what database to use as long as you know how to use it. Unless you have an ungodly amount of data that needs to be handled in a specific way, then it might be worth looking at which engine works best for you.
If you're comfortable with psql, use psql.
Ok thanks to both of you (I'll probably go for sqlite then 😄)
python already have one
You should probably use aiosqlite over the one that comes with python though.
^
I mean 99% of your queries probably finish in a matter of milliseconds, but it's still good practice to use async wherever you can in an async environment.
Thanks I'll look into it (+ I'm not really comfortable with async yet so it'll probably help me learn a little more ^^)
Knowing how to work with async/await is mandatory for making a Discord bot, so learning more sounds like a good idea.
Can I use instead of
await interaction.response.send_modal```
```py
await interaction.channel.send_modal```?
With slash commands, can everyone see the response or are they private?
?tag ephemeral
An 'ephemeral' message is one that's only visible to the person who invoked a command. If you ever got a command error with a blue background, this is an example of one.
To do this, set ephemeral=True when you first use an ApplicationContext. (This includes .defer()ing it; the choice of whether a message is ephemeral or not must be made up front. If you .respond() to a deferred message, setting the ephemeral flag at that time will have no effect.)
This is the equivalent of hidden=True if you're coming from interactions.py
Ahh, that is why "The Application didn't response" and the correct response are different colours
Thank you!
yw
Woop, I got it 😄 That makes this much easier
How can you reply to a interaction response message? When i try and use ctx.message.reply or ctx.interaction.message.reply, the message object is always None
what?
interaction.response.send_message
i thought i tried doing that, hold on a sec
yeah thats not what im trying to do
nope. modals can only be sent as a response to interactions. you can however send a message in the channel with a button that responds with the modal
wait im stupid, ctx.respond has WebhookMessage as a return type
i can just reply from that
ye
got it thanks 
Any ideas why this:
def get_oauth_tokens(code):
url = 'https://discord.com/api/v10/oauth2/token'
params = {
"client_id": BOT_ID,
"client_secret": BOT_KEY,
"grant_type": 'authorization_code',
"code": code,
"redirect_uri": REDIRECT_URL,
"scope", "identify",
}
response = requests.post(url, data=json.dumps(params), headers={'Content-Type': 'application/x-www-form-urlencoded'})
return response.json()
Is returning this:
{'error': 'unsupported_grant_type'}
I also tried doing json=params, as well as using path queries
Do you even know, what you are doing?
try it
do you have something like this active?
Hmmm ... I don't know.
because it's urlencoded you can't use data or json; i think it has to be as a url query instead?
it errors for the first condition it's checking for (grant_type) since it can't read the data at all
iirc in requests you can use the params kwarg to transform a dict into a query
https://requests.readthedocs.io/en/latest/user/quickstart/#passing-parameters-in-urls
...ironic that your variable is called params lol
n=int(input("Enter number:"))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")
could someone explain me this code?
it's a program to check whether a number entered by the user is a palindrome or not
101 when reversed gives us 101, since 101 = 101 hence it is a palindrome whereas 102 when reversed gives us 201 which isnt equal to 102 hence it isnt
basically this is what a palindrome is
just need help w the code
im new to python so please explain it in simple terms
this sounds suspiciously like homework... so i won't explain it fully
% (mod) gets the remainder from a division
// (div) is the opposite; it gets the result without the remainder
e.g. 10%3 = 1, 10//3 = 3
n or temp is whatever number you input
then it's doing some fun loops with rev; i recommend printing the results of each variable to see how the program progresses.
Isn't there an easier way of doing this
if i had to guess, someone gave them that code to analyze
it's a decent demonstration at a low level at least
if you wanted a better method idk convert to string and iterate through to see if i matches length - i
If you google how to reverse an int this code shows up
yea it is, i tried converting it into a string and do it but i dont get the desired output
so i googled the question and found this code
this is what i have done
ill be sendin the whole code, im just stuck at the palindrome part
#Record Q-6
#Write a Python program to perform the following task according to user’s choice using menu:
#Accept a number and check whether the number is odd or even.
#Accept a number and check whether the number is a palindrome or not.
#Accept a number and check whether the number is an Armstrong numberor not
#Showing the user the options
print("|No.| |-----------------------Choices----------------------------------------|")
print("|-1--| |-Check whether the number entered is odd or even-------|")
print("|-2--| |-Check the number entered is a palindrome of not---------|")
print("|-3--| | Check the number is an armstrong number or not---------|")
print("0 or any other number beside the choices to exit")
#Obtaining the user's choice
user_ch=int(input("enter your choice"))
#code to check if it's odd or even
if user_ch==1:
n=int(input("enter a number")) #obtaining the number
if n%2==0: #code to check it's even
print("it is an even number")
else:
print("it is an odd number")
#code to check the number is entered is a palindrome or not
if user_ch==2:
n=int(input("enter a number"))
n_str = str(n)[ : :-1]
if n_str == n:
print("it is a pal")
else:
print("its not")```
Great code, "```py"
hey guys, do you know why await interaction.response.defer() isnt working?
I'm sure it works
it's still incomplete bc im stuck at the second part
.idw
Saying it doesn't work or asking what's wrong with this code is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
Yeah my bad, i accidently entered while typing
you're comparing a string and an integer, so they'll never be equal
hm
i see
i can't really think of any other way other than the code i sent earlier
do you have one in mind?
well.. you could just not convert the type on a certain line
but again as per #help-rules we aren't gonna provide extensive help for hw/exams; the solution here should be straightforward enough to figure out on your own or with a bit of research
it's not exactly a homework
but okay lol
I'd just convert it to a str and reverse it lol
thats what i did
You were comparing a str to an int
hm
wdym?
How does localization work in teams?
i am trying to defer response because my view is have so many buttons (19)
my code is
@discord.ui.button(label='users', style=discord.ButtonStyle.primary, emoji='🪪')
async def users_callback(self, button, interaction):
await interaction.response.defer()
users = [await self.bot.fetch_user(i[1]) for i in self.get_users()]
embed = discord.Embed(
title='users',
description='select user',
color=discord.Colour.blue()
)
...
but... discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
please help
Providing 1/4 of your code isn't helpful
Ahhh help me out!!
No
my code have 1421 lines...
You should be able to figure out what's wrong with the reverse string function
If not, learn python basics
.paste
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
That's what i am doing right now, we just recently started learning python
it have russian language
and we didnt even learn reversed() function
ok?
i decided to learn it early because i found the topic interesting
and this was one of the questions from the topic
Is that for school?
Yes
How does localization work in commands?
fwiw py users = [await self.bot.fetch_user(i[1]) for i in self.get_users()]is a HORRIBLE idea
that aside the defer looks like it'd be fine, if i had to guess you're erroring somewhere else in the button.
this button is just showing all users in database
could you help me out with it?
it can still error further down in the function
and giving me permissions to do something with selected user
ok, i will send my full code
but it have russian language
well it doesn't have to be the entire file, for now just do the button
and the language is fine regardless
oh, good
my code: https://pastebin.com/mez2j7qB
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
password: somepassword
Why doesn't the second cog work?
after using defer, you should use interaction.edit_original_response instead
also... did you really need to use exec
@cyan quail help me after ?🫠
that looks incredibly painful
and access it in view
that code should just be a separate file which you import, or make it a real class above the view
what pycord version are you on
and do you load the cogs before using bot.run
Yes
Last
like can you show it in pip list
also unrelated... but visual studio is an interesting choice for python
hmm ok
and you're 100% sure the cog is loaded during runtime? i.e. it's present when you print bot.cogs
yes
I think she is the best
ouuu
I tried
hey, sorry, but how to use this function? its just edit message
replace interaction.response.edit_message with interaction.edit_original_response, since defer is the original response.
well as long as it works ig?
@cyan quail This is weird.
?
ok
It turns out the method from the guide does not work 🤔🤔🤔
im pretty sure looping to load extensions has always worked
idk what the issue is in your scenario
In my?
yes
not worked:
Ignoring exception in view <SecretView timeout=None children=8> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='Пользователи' emoji=<PartialEmoji animated=False name='\U0001faaa' id=None> row=None>:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/ui/view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "/home/container/cogs/secret.py", line 1054, in users_callback
self.MyView = MyView''')
File "/home/container/.local/lib/python3.10/site-packages/discord/interactions.py", line 961, in edit_message
await self._locked_response(
File "/home/container/.local/lib/python3.10/site-packages/discord/interactions.py", line 1090, in _locked_response
await coro
File "/home/container/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 215, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
from what i can tell, it's erroring somewhere in your exec so we can't do much about it unless it's restructured
but this exec works fine before i add so much buttons
and coincidentally, it broke after you added stuff
yes
then
i will just delete this
i have 9 more commands based on this
and all of them is works good
thx
Show how you defined block
Target not found, try again and make sure to check your spelling.
.rtfm SlashCommandGroup
discord.SlashCommandGroup
discord.SlashCommandGroup.add_command
discord.SlashCommandGroup.after_invoke
discord.SlashCommandGroup.before_invoke
discord.SlashCommandGroup.call_after_hooks
discord.SlashCommandGroup.call_before_hooks
discord.SlashCommandGroup.callback
discord.SlashCommandGroup.can_run
discord.SlashCommandGroup.cog
discord.SlashCommandGroup.command
discord.SlashCommandGroup.cooldown
discord.SlashCommandGroup.copy
discord.SlashCommandGroup.create_subgroup
discord.SlashCommandGroup.dispatch_error
discord.SlashCommandGroup.error
discord.SlashCommandGroup.full_parent_name
discord.SlashCommandGroup.get_cooldown_retry_after
discord.SlashCommandGroup.has_error_handler
discord.SlashCommandGroup.invoke
discord.SlashCommandGroup.invoke_autocomplete_callback
class BLOCK(commands.Cog):
def __init__(self, bot):
self.bot = bot
block = SlashCommandGroup("block", "Various greeting from cogs!")
@block.command(name='user', description="Close a participant's voice channel.")
@commands.cooldown(1,30, commands.BucketType.user)
@commands.guild_only()
@commands.has_permissions(manage_channels=True)
async def block(self, ctx: discord.ApplicationContext, member:discord.Member):
voice = ctx.author.voice
if voice is not None:
channel = ctx.author.voice.channel
overwrite = channel.overwrites_for(member)
overwrite.connect = False
await channel.set_permissions(member, overwrite=overwrite)
await ctx.respond(f"
ame}.",ephemeral=True)
else:
await ctx.respond("Sign in to a channel to change its rights.",ephemeral=True)
@block.command(name='role', description='Close the voice channel for a role.')
@commands.cooldown(1,30, commands.BucketType.user)
@commands.guild_only()
@commands.has_permissions(manage_channels=True)
async def lock(self, ctx: discord.ApplicationContext,role:discord.Role=None):
if role == None:
role = ctx.guild.default_role
voice = ctx.author.voice
if voice is not None:
channel = ctx.author.voice.channel
overwrite = channel.overwrites_for(role)
overwrite.connect = False
await channel.set_permissions(role, overwrite=overwrite)
await ctx.respond(f"Channel {ctx.author.voice.channel.mention} has been closed for role {role.name}.",ephemeral=True)
else:
await ctx.respond("ights.",ephemeral=True)
def setup(bot):
bot.add_cog(BLOCK(bot))
You have a function called block
Which overwrites your block group
Just name it anything else
Ok
why is there a space after bot. ?
lol
Hey! I feel like I should be able to find this in the documentation, but I just can't find it anywhere: how do I add descriptions to various slash command arguments? If the slash command is /hello [playername], how would I add a description to playername? Thank you!
Here's the slash options example.
@long zealot ig you might want to be pinged
Where?
Check the Screenshot
Hmmmm
How would i go about finding the uptime of my bot?? Is that a possibility?
(Of the bot, not the machine)
Just create a variable that stores the current timestamp when your bot starts. The uptime will be current time - start time.
ok
How do I check if a message had a command invoked on it?
I previously used to check this using ctx.valid but currently it doesn't seem to work.
.rtfm discord.Message.interaction
Traceback (most recent call last):
File "C:\Users\tearx\PycharmProjects\Rosalina\bot.py", line 6, in <module>
bot = discord.Bot()
AttributeError: module 'discord' has no attribute 'Bot'```
Show your pip list
What IDE are you using?
Did you install pycord with the pycharm package manager?
yes
And the correct environment is selected?
Are you using conda?
Are you usng virtualenv?
yes
Better give it a search on google
alright 2 secs
Try opening a command prompt and activating the environment with source %venv%/bin/activate (linux) or ./venv/Scripts/activate.exe (windows)
Then, find the python file and run it with python3 %file%
What OS?
interesting
windows
Impressive
is it still discord.Bot()
Yeah
Pretty sure both commands.Bot, discord.Bot and discord.ext.commands.Bot supports slashcommands
Depends on what you want to use. For slash commands discord.Bot is fine
Sure that works
Epic
If you want BOTH slash and prefix commands, however, you should look into the bridge bot
Is there a way to detect if a user is a self bot?
Nope, sadly
Am I right i think ive used it before it's just @bridge.command right?
in a cog
it's discord though lol
I've actually never used it, but you can find an example on the GH. That, however, seems correct
The only reliable way to see if a user is a self bot would be to see if a normal user sends an embed, because only bots can do that
well I say "reliable", it's a way at least
They wouldnt be allowed to?
People have found ways to work around it, I've seen normal users send embeds
That would be to send a link to something, which Discord then embeds
nope, you can fake that you're a bot via webhooks but when u click the profile it doens't load
I guess with links, you can check with https check thing
Iiii, dont think thats what were meant
I'm pretty sure an embedded link is different from a bot embed
reply to this if the link you send as it becomes embedded
They have fewer fields, but are built the same way
it can be either a normal command or a bridge command
Oh i might be wrong here, sorry
Just read up on it
However its dumb discord hasnt fixed it...
Well you can't really check if a message was invoked by a prefix command unless you make the bot reply to the message that invoked it.
And then check the message for replies
i have bridge commands setup how to check for a specific error in an error
@bridge.Cog.listener()
async def on_application_command_error(self, ctx, error):
if isinstance(error, commands.UserNotFound):
embed = discord.Embed(description=f"Invalid User Silly", colour=col)
await ctx.respond(embed=embed, mention_author=False)
Currently I have this but it's not working
That listener should be in your main file.
And on_application_command_error only triggers for slash commands
yeah its in the same file
oh i read that wrong
whats the one that triggers for bridge
I do not believe there is a collective listener for that
is there one for a command in particular?
https://docs.pycord.dev/en/stable/ext/bridge/api.html#discord.ext.bridge.BridgeCommand.error
You can set this decorator in your cog to define an error handler for one specific command
So if you have a command called my_command you can do @my_command.error as a decorator
and for the function?
i got it to work
Thanks for the help 🙏 you were correct as always
it could be a nice addition. what do you think?
Yeah, that seems handy tbh
If it doesn't already exist, I haven't used bridge commands personally so not too educated on them
hello everyone, why is my /help command is not showing in slash commands menu?
@commands.slash_command(name='help', description='Команда помощи')
@commands.guild_only()
async def help(self, ctx):
if self.check_commands(ctx.author) == True:
embed = discord.Embed(
title='Ошибка',
description=':red_negative_cross_mark: Владелец данного бота ограничил вам использование слэш-команд',
color=discord.Colour.red()
)
await ctx.respond(embed=embed, ephemeral=True)
else:
embed = discord.Embed(
title='Помощь',
description='Выберите категорию',
color=discord.Colour.blue()
)
await ctx.respond(embed=embed, view=HelpView())
did you remove the help command?
for what is the self check?
can you remove it and try it without it?
ok, i will try
also sometimes it takes some time to see slash commands
not working
i will wait ~10 mins
you also could add to the bot "help_command=None" so you dont have to use a new line
or use ;
stuff like this also works
print("Hello"); print("World")
Thanks! So I can’t incorporate it into the normal slash command format, this one? bot.slash_command(guild_ids=[], description="Change the bot's status.") async def playingstatus (ctx, status:str):
It would not go in the decorater but it works if you type hint the arguments of the command
async def hi(ctx, user: Option(discord.User, description="The user to say hi to"))
Reply with ping when 
@long zealot
.slashnoshow
Checklist for Application Commands Not Showing Up:
• Does your bot have the application.commands scope?
• Are you loading cogs before on_ready and on_connect?
• Is on_connect not overridden?
• Did you update to the newest version of py-cord (tag: install)?
• Is User Settings > Accessibility > Chat Input > Use legacy chat input turned off?
• Did you share your code and errors?
• Do you still have libraries that conflict with the discord namespace (e.g. discord.py)?
How can I send a message to a particular channel?
get the channel and send the message?
yes but how do I get the channel?
ok wait wtf
nvm got it didnt think it'd be so simple
Awesome, thank you!
Ooh, with the option tag is it possible to narrow down what the bot will accept? Let’s say you had a /ping command - is it possible to only accept valid user roles?
Love pycord 😂
How would I get emoji to use them on buttons? The normal Discord emoji, not custom ones.
Type an emoji with a \ in front of it and you'll get the unicode version of it.
Than copy paste it into the emoji field of the button.
Limit to
Str (min char max char too), Int (min max), user, individual channel types, roles
.rtfm options
discord.ApplicationContext.selected_options
discord.ApplicationContext.unselected_options
discord.AutocompleteContext.options
discord.ext.pages.PaginatorMenu.options
discord.SelectMenu.options
discord.ext.bridge.BridgeApplicationContext.selected_options
discord.ext.bridge.BridgeApplicationContext.unselected_options
discord.ui.Select.options
Thanks.
IN Api Ref. subtracted about the localization of the commands.
Please give a guide to it, as very little is written in the API.
Localizations are a way to make your bot more accessible to your users. Learn all about localizations now!
@silver moat thx
@bot.event
async def on_ready():
await webhook.send(status_text, username='Foo')
async def foo():
async with aiohttp.ClientSession() as session:
webhook = Webhook.from_url(status, session=session)
await webhook.send(status_text, username='Foo')
why is it not defined
How can i add multiple buttons to a single message?
create a class and send it
Hi everybody, i have a question, how to create a command that works through a profile?
like this
Thanks in advance for your reply.
Appreciate it!11
if i have a user's id, how do i turn that into a mention?
im trying f'@{ctx.author.id}' but not working
Anyone?
U need <@>
After the @ is where u add the ctx author thing
okay
did you mean like this <@>{ctx.author.id}?
Yeh but with the other stuff
oh
f'<@{ctx.author.id}>'
This
worked thanks!
Do u know the fix to my webhook problem
This
not sure mate
Alr
not defined means it can't see where webhook was first initialized, but ofc you already know that
Yeh but I defined it already
is there a way to post in chat who´s pressing a discord button?
interaction.user
The async def foo part
And when I add await webhook send
It just says not defined
Forgot to reply
Need to keep track of a variable between functions? No problem!
⚠️ Careful what you name it though, else you might overwrite something ⚠️
Just add it to your commands.Bot or discord.Client instance like so:
bot = commands.Bot(...)
bot.my_variable = 0
async def foo():
bot.my_variable += 1
# In a cog
@commands.command()
async def counter(self,ctx):
await ctx.send("Current Counter is at {}".format(ctx.bot.my_variable))
This also allows you to access this from other cogs/extensions/functions. Anywhere you have access to the bot instance
So doing this will fix
pretty sure
depends on where foo is
if foo is run before bot is ready, it will work. else it wont
you might want to look into asyncio.Event if you want to synchronise stuff
isnt it non pythonic (and usually problematic) if you are using global variables
Could you pass the variables as parameters to make it more modular
yea thats why no global variables. always use bot vars
thats still sharing variable between different functions tho
Becouse that is a different function. Variables in one function can't be used in another.
yea this is better. but not always possible
true
Oop, did not see they were getting help
using botvars along with asyncio.Event makes it usable
thx, got it 🙂
the on_ready webhook isn't defined
So can I just have to define it again without the function
If you don't know how variable scoping works, you should not be making a bot. You need to learn basic Python
is there a way to check for permissions for a button like in commands? @has_permissions or is_owner?
i am using @discord.ui.button()
so im trying to edit an embed on button click but im not sure how to pass my message id or class or whatever to my class to be able to edit it is this possible?
view = RockPaperScissors(ctx.user, user)
await ctx.respond(embed=no_turn_embed, view=view)
```
where is the embed? same message as button? you can use interaction.response.edit_message
also, view.message should have the message object if you want the embed
this is in slash command wont interaction.response.edit message only edit the response from pushing button?
wont interaction.response.edit message only edit the response from pushing button
well if you havent sent a message as a response, then the original message is edited
Can you change the color of a dropdown menu when you have selected something?
no
so i was trying to make so it just dont respond when you cloick button according to docs from what i could tell you do self.stop() but i did that and it still responds... do i do self.disableallitems
You need to edit the message with your view after you disable the items to update the buttons
can i just make it not listen to them
ok
Is it possible to disable buttons after a specific time? Like its working for the first 5 minutes the message was sent and then greys out automatically?
.rtfm view.disable_on_timeout
Target not found, try again and make sure to check your spelling.
.rtfm view.dis
Just override the on_timeout function and edit the message with the updated view
Thanks!
What is the best way to make message templates when sending a response. With slash commands I subclassed get_application_context so I could do ctx.prespond.success(message) and it would return an embed that was created to look like a success message. However there is no such thing as get_interaction_context so how would I add these functions to interaction s well?
since you cant have custom methods on interactions, you would have to go a little different way
you will need to use function programming
is this in a view?
if so, you can have a method that accepts an interaction (or even the button/select menu), and does the stuff you want
or you can even have this function outside the view in the global scope that does the same
What does this mean?
What is "internal message cache", if I may ask?
pycord has a message cache that stores messages the bot receives. it has a size limit of 2000 messages by default. pycord has various such caches, like member cache, role cache etc.
often it happens that an older message was edited and it wasnt present in the cache. events with raw are called regardless of whether the object is in cache or not
Ohhhh- I did not know that, tysm :)
Is there a way to separate a command group into multiple cogs? I'm looking to try and organize files a little better.
Can confirm. Works wonderfully
How many times will Python execute the code inside the following while loop?
i = 1
while i < 10000 and i > 0 and 1:
print “ Hello ...”
i = 2 * i
Answer:
14.```
why is it 14? i don't understand
i've tried the code and yes it did print it 14 times
code:
i = 1
while i < 10000 and i > 0 and 1:
print ("Hello ...")
i = 2 * i
Output:
Hello ...
Hello ...
Hello ...
Hello ...
Hello ...
Hello ...
Hello ...
Hello ...
Hello ...
Hello ...
Hello ...
Hello ...
Hello ...
Hello ... ```
Print i and you'll see
alright
code:
i = 1
while i < 10000 and i > 0 and 1:
print ("Hello ...")
i = 2 * i
print (i)
Output:
Hello ...
2
Hello ...
4
Hello ...
8
Hello ...
16
Hello ...
32
Hello ...
64
Hello ...
128
Hello ...
256
Hello ...
512
Hello ...
1024
Hello ...
2048
Hello ...
4096
Hello ...
8192
Hello ...
16384
i do understand it doubles itself everytime, but im confused why is it restricted to 14times?
Because 16384 is > than 10000
but the code here is "while i < 10000", so shouldn't it not print 16384?
You're printing i after the change
When the loop starts again and checks, it stops
Because i is not smaller than 10000
hm alright i see thanks
What is the and 1 there at the end? It literally does nothing
Hi, is it possible to make a search option for a Select menu on mobile? Because it is not possible to search through members in a select menu on mobile
You can't just make a mobile feature work on your bot. That's through the Discord client, if it doesn't work, it doesn't work.
just found out lol
mistakes are part of the process
im a beginner so yeah
While we do appreciate your enthusiasm, I think the Python Discord server would explain these topics much better
.gg/Python

How to check if a snowflake ID is a user id, role id, or channel id?
How can i access the context received in a slash command in a button callback method?
The button is part of a view shown with the slash command response
Pass the ctx to the view init and store it as a self var
Oh
Do you have a mention string or only the snowflake id?
I was actually struggling with the init of view
Not sure if i gotta do something to super()
Yeah you need to
First line in your init should be a call to super init
Like this super().__init__(...)
Okay
And then you would set the ctx to a variable
Okay makes sense. Thank you
only snowflake id (im trying to make a command that fetches id information)
Then you don't have a choice other than using get_member get_role and get_channel to find if anything returns a value
Anybody know how I can make a help command using Slash Commands? There isn't anythign on the guide, sadly.
How can i use disable_all_items() in a button callback command?
view.disable_all_items() ?
yeah
That was your answer 
lol nah wait pls
so i have a class that inheits from discord.ui.View
and i've got two button callbacks in this class
Anybody know?
is it possible to do something like self.disable_all_items()?
Oh yea ofc
You have to edit the msg too
could that be causing a conflict?
Yeah set view=self that's all
Well it's not that easy
I've been using slash commands for quite a while now and have been registering them one by one, which is I believe normal, however, I've been wondering if I could "bulk register" all slash commands at once. (I haven't been able to do so, so far which is why I'm asking)
Pycord is able to handle registration for you. Can you show how you are registering them?
the way I'm registering them is different than what I want ( which is bulk register ), but sure:
@client.slash_command(
name="ping",
description="Bot latency"
)```
(*it works! but that's not how I want it to be*)
I was thinking of something maybe as following:
commands = {
"ping": "bot latency",
...
}```
You could do this
https://docs.pycord.dev/en/master/api/clients.html#discord.Bot.add_application_command
Bots: Attributes activity, allowed_mentions, application_flags, application_id, auto_sync_commands, cached_messages, cogs, debug_guilds, description, emojis, extensions, get_command, guilds, intent...
I think you would have to use docstrings for the description though.
oh, didn't notice that my bad, yeah that's fine, tho what I'm worried is the choices since I usually use
@discord.commands.option(name="name", description="description", required=True)```
Please tell me. What will the best team look like to clear the chat.
use type hint options instead of decorators. It makes more sense
alright, thanks
I already have one, but it can sometimes freeze.
Please tell me. What will the best command look like to clear the chat.
.rtfm purge
Or if it is the whole channel. Just duplicate the channel and delete the old one.
What is the code. Somewhere you are passing username instead of user id
Im not sure if you really can use discord.User
fetch_user takes the user ID you are giving it the member object.
Oups thanks
@errant crane is down... oof
Likely the sticker bug
👍
so this should work fine
So I have a situation where if I announce updates, the message would be sent in every server that has configured the Bot in a logging channel, is it needed await asyncio.sleep(0.05) when sending the message to those channels to prevent my bot from being put in the spam list?
you might not need it as ratelimits are per-route, but having a sleep is sensible anyway to avoid global ratelimit
though regardless, the library already handles ratelimits for you so there isn't much risk
also you should probably encourage users to follow an announcement channel instead
One message removed from a suspended account.
it's not built in no
I recommended it, but incase they ignore, that they'll know about it so it's not excluded
fwiw you could build a command that follows the channel for them
just have them enter their destination channel, then on your end use channel.follow(destination)
bot will need decent permissions though
One message removed from a suspended account.
again, it's not built in; you'd need to create your own system
One message removed from a suspended account.
if your button's custom ID is unique enough, you could easily set up a dict that maps the custom ID to the last timestamp it was pressed at
I presume that it won't carry the @everyone ping over?
yes
(typically) webhooks can't mention
(and tbh, using an @everyone mention in every guild your bot's in may be seen as abuse)
hi, how can i get the modal title in the callback from the modal?
If I have lets say 1000 people clicking a button at one time, I am needing to defer these interaction responses, and hititng the rate limit quickly. Is there any way for me to throttle these calls to make them not hit the rate limit?
I would think asyncio might have something to help?
interactions have their own ratelimit which you typically don't have to worry about
but hm
the library already handles ratelimits for you by queuing stuff when necessary
Weird because it gets rate limited quickly
is it specifically defer that gets ratelimited?
what is in your callback
or somewhere else in your code
replit?
run
The interaction.followup.send() call is returning a 429 error saying its being rate limited
But even before being rate limited, it was getting a 404 unknown interaction on the interaction.response.defer() call
(Not using replit)
Using a Vultr VPS to host
That's the callback for the button
should probably defer before the DB call, beyond that the best you could do is create your own queue system with task loops which handles followup.send
though odd that ratelimit handling isn't applied here...
Yeah that was what is weird, that it is not automatically handling the ratelimit
I know the issue that started this more was the fact that the generate_watermark_image() function is a compute heavy function, so with more than 100 calls at a time, it can take a few seconds to complete, but this should be solved by the defer() calls, no?
strictly speaking yes, the main issue is that defer is being ratelimited then you're doomed
ugh
but i don't think it should
the first error started coming when it was giving me this error when trying to call defer
perhaps paste/screenshot the error?
that's a completely different button
wrong error hold on
that's the correct buttoin
Should i get rid of the button being part of this view?
I cannot see any message you send
because it's impossible to do anything else if you can't defer
at the interaction
The line await interaction.followup.send(file=discord.File(img_path), ephemeral=True) is the response to the interaction
it is just sending an image in an ephemeral message
you need something like interaction.response.send_message or edit_message
well I had the interaction.response.send_message, but then i saw i needed to defer the calls because the computation was longer than the 3 second timeout
import discord
from discord.ext import commands
import os
intents = discord.Intents.all()
bot = commands.Bot(command_prefix=">", intents=intents, case_insensitive=True)
bot.remove_command("help")
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
bot.load_extension(f'cogs.{filename[:-3]}')
bot.run("...")```
This says command not found. I have a command in the cog
what am i doing wrong here
and the command?
is it worth opening a bigger issue for this? It's kind of killing my bot's use case by not being able to defer...
import discord
from discord.ext import commands
class InfoCommands(commands.Cog):
def __init__(self, bot):
self.bot = bot
#----------------------OWNER------------------------
@commands.command()
async def hi(self, ctx):
await ctx.send("hello")
def setup(bot):
bot.add_cog(InfoCommands(bot))```
@young bone ^
well that's not what we can handle; if you get ratelimited on defer of all things the 3 seconds will be up without a response
thus you'd actually have to go to discord for an increased ratelimit
(i think that's how it works?)
but indeed, we could do with a github issue on ratelimits not being handled on every function
so there's no way for me to just throttle the calls? I thought that discord.py was supposed to handle the rate limit...
the problem is you physically can't throttle in this scenario
you cannot delay a defer
or rather, you can't extend that 3 seconds without a response
using typehint options ruins ide autocomplete because you dont have those str int or discord.Member things anymore 
wondering if this can be improved
What if we respond with a "incoming message" and then send the "actual" message when the computation is complete?
if discord themselves is preventing the response you need to continue then it's out of our hands
would that get around the rate limit?
you can try, but i don't know if response.send_message and response.defer have different ratelimits
I was just doing the response.send_message before and it was just running out of time and not finding the interaction, but not getting rate limited per se, so I will try something like that
nvm i figured it out
if you respond immediately before doing anything else then maybe it'll be viable
interaction responses dont have ratelimits tho. and defer is a valid response. the followups have ratelimits
yeah but observing the error here #998272089343668364 message, it couldn't make it to defer
Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.
so is there any way around doing the followup?
do they actually have 0 rate limits or reduced rate limits
hmm. what about moving the defer up to the first line of the callback?
not really. i made a bot wide producer consumer based coroutine queue for the followups that sleeps around 0.3 seconds before sending the next followup. if a followup still failed due to a ratelimit, then sleep for the time specified in retry_after and retry the followup again. I havent faced issues after that
last time i asked in ddevs server, they said 0
interesting
so how can I implement this for my use case?
and isnt the rate limit like a 15 minute cooldown, or is it just until you aren't makeing more than 50 calls per second
uh i gtg now sry. ill help when im back
ok
I think you can do this.
async def hello(self, ctx, number: int =Option(description="") might be wrong though.
nope. Option must be a typehint
well you are being ratelimited on defer, rather than followup
did you try this?
Yeah i did and this starts popping
im confused on how it can't find the interaction even though its the first thing in the callback...
where are you hosting your bot?
also share pip list and python version
on a Vultr VPS
can you check if the same happens on your local pc
could be a network issue on the vps
I just did it on my local PC and the same issue
oh
do you have any cpu intensive or event loop blocking work going on somewhere else in the code?
not anywhere else, just the generate_watermark_image function in the callback
Its generating images
should I be like threading this work out?
probably yes. use asyncio.to_thread
Okay let me try to implement this
it worked for like the first 10-15 clicks then still getting the too many requests on the followup
so it looks like the defer call isnt getting screwed up now
aah
thats nice
so does this look like something you need?
I am thinking probably yes... btw i appreciate all the help
.rtfm Interaction
discord.Interaction
discord.Interaction.app_permissions
discord.Interaction.application_id
discord.Interaction.channel
discord.Interaction.channel_id
discord.Interaction.client
discord.Interaction.custom_id
discord.Interaction.data
discord.Interaction.delete_original_message
discord.Interaction.delete_original_response
discord.Interaction.edit_original_message
discord.Interaction.edit_original_response
discord.Interaction.followup
discord.Interaction.guild
discord.Interaction.guild_id
discord.Interaction.guild_locale
discord.Interaction.id
discord.Interaction.is_command
discord.Interaction.is_component
discord.Interaction.locale
#883236900171816970 please
Np lol
So you want some example code?
That would be extremely helpful... I understand the concept of producer/consumer just not as it applies in this case
ok so this is just some rough stuff i will type out right in the chat input
bot.followup_queue = asyncio.Queue() # This is a queue of coros that we will run sequentially rather than asynchronously
@bot.event
async def on_ready():
# Don't use on_ready as this can fire multiple times. Just using for an example
while True:
coro = await bot.followup_queue.get()
try:
await asyncio.sleep(0.5) # sleep for a while. this blocks the loop from going to the next coro in the queue
await coro
except discord.HTTPException as e:
await asyncio.sleep(e.response.headers.get("Retry-After", 20)) # Get retry after seconds and sleep for it
await coro # Retry
# Somewhere else
coro = interaction.followup.send(...) # Notice how we dont await
interaction.client.followup_queue.put_nowait(coro)
Okay for the most part this makes sense. I am going to try and implement something this afternoon
I really appreciate the help!
cool (i myself thought of that and used it just a month ago. couldn’t find a better approach)
np 🙃
where did you run the consumer routine? I am just having trouble figuring where it would be good to go... don't want to need to start it by running a slash command
well i just ended up keeping it in on_ready cuz i forgot 💀
my plan was to put it in a function and call bot.loop.create_task(my_func())
haha okay, thank you!
😀
I have included the 'WetterView' above.
I call the view 'WetterView' via the button. After I click a button in WetterView I want the 'OptionalView' to be called again and the button to be displayed disabled.
How can I get this to work?
Because to include the views on the other side does not work as far as I know or?
from tageszeiten import WetterView
class OptionalView(discord.ui.View):
def __init__(self, bot: discord.Bot, spotdaten):
self.bot = bot
self.spotdaten = spotdaten
super().__init__(timeout=None)
@discord.ui.button(label='Wetter', custom_id="Wetter_Button", style=discord.ButtonStyle.primary, disabled=True)
async def wetter_button(self, button: discord.ui.Button, interaction: discord.Interaction):
attach_message = self.spotdaten[1]['messageid9']
await attach_message.delete()
await interaction.channel.send(view=await WetterView(self.bot, self.spotdaten))
await interaction.response.defer()
General python question... any OOP gurus about? I want to set up and reference configurations for a single common service (API) but with different configs/base urls. There will be a dozen of them or so. Much (if not all) of the same class logic itself would apply, it's just various addresses that might change.
Can't determine whether I should have a Singleton that contains all of the configs, or use individual instances with some sort of collection class
How do you prevent the bot from running any command until the bot is ready
I have database commands but people tend to use them more often. When the bot is restarting, it takes some time to load the database. Up until then, any database command used will cause error
There is await self.bot.wait_until_ready(). I can put this in every command function but that would be redundant?
I am sure there must be another way to stop commands from running until the bot is fully loaded
You can use the on_command and on_application_command listeners
prefetched_commands = await self._bot.http.get_guild_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\يولين\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\http.py", line 360, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
Show pip list
It seems like on_command runs after the command is processed. This always results in ong printed after the results of command.
wym by pip list. for what?
the pip list
all ofit?
Because it's a listener. You'd need to override the methods
yes
Yeah that makes sense
can you do a better screenshot pls
also do you have intents?
Deleted.
yea yea all. (also i added and checked application.command)
website and code?
intents = discord.Intents.default()
intents.message_content = True
yea.
My slash commands won't register
They take time?
Waiting for 12 hours
without code and other stuff we cannot help you
can you show how you define the bot and intents?
from discord.ext import commands
import discord, asyncio, os
TOKEN = ""
intents = discord.Intents.default()
bot = commands.Bot(intents=intents)
@bot.event
async def on_connect():
print(f"Logged in as: {bot.user}")
print(f"Loaded {len(bot.guilds)} guilds")
await bot.register_commands()
cogs = [
"cogs.generate",
"cogs.invite",
"cogs.vote",
"cogs.help",
"cogs.status",
]
for cog in cogs:
try:
x = bot.load_extension(cog)
print(f"Loaded extension {x[0]}")
except:
print(f"Failed to load extension {cog}.")
while True:
await bot.change_presence(
status=discord.Status.dnd,
activity=discord.Activity(
type=discord.ActivityType.watching,
name=f"{len(bot.guilds)} servers"
)
)
await asyncio.sleep(25)
bot.run(TOKEN)
This is my code
i mean thats not how the errors presets. im sure.
you load the cogs at "on_connect"?
same thing...
dont load the cogs at on_ready or on_connect
Ignoring exception in on_connect
Traceback (most recent call last):
File "C:\Users\يولين\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 377, in _run_event
await coro(*args, **kwargs)
File "C:\Users\يولين\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 1164, in on_connect
await self.sync_commands()
File "C:\Users\يولين\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 738, in sync_commands
app_cmds = await self.register_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\يولين\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 531, in register_commands
prefetched_commands = await self._bot.http.get_guild_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\يولين\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\http.py", line 360, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
Logged in as Hound#5599 (ID: 1070369109704982538)
full error
do you use anything like debug_guilds?
It's working now Thanks
no.
and what is with both message intents?
enabled all intents..
Now i am getting broken pipe errors
File "/opt/homebrew/lib/python3.10/site-packages/discord/ui/view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "/Users/jeffrey/Desktop/pepperai_dev/cogs/generate.py", line 79, in select
await msg.edit_original_response(embed=embed, view=View(self.prompt, images), file=discord.File(f"images/{image_uuid}.png"))
File "/opt/homebrew/lib/python3.10/site-packages/discord/interactions.py", line 428, in edit_original_response
data = await adapter.edit_original_interaction_response(
File "/opt/homebrew/lib/python3.10/site-packages/discord/webhook/async_.py", line 157, in request
async with session.request(
File "/opt/homebrew/lib/python3.10/site-packages/aiohttp/client.py", line 1141, in __aenter__
self._resp = await self._coro
File "/opt/homebrew/lib/python3.10/site-packages/aiohttp/client.py", line 560, in _request
await resp.start(conn)
File "/opt/homebrew/lib/python3.10/site-packages/aiohttp/client_reqrep.py", line 899, in start
message, payload = await protocol.read() # type: ignore[union-attr]
File "/opt/homebrew/lib/python3.10/site-packages/aiohttp/streams.py", line 616, in read
await self._waiter
aiohttp.client_exceptions.ClientOSError: [Errno 32] Broken pipe
how can i fix this
is there a way to check if this is set? I typed in Rule Screen in the docs hoping to get keywords, but all I got was the welcome screen
EDIT: Found the Solution, had to find screening itself and dig around the docs
can you show the pip list pls
its running trough docker the packages are
py-cord
requests
pillow
is that anything?
yes
After running a new slash command a few times, it gets... unregistered
And I have to restart the bot for the command to work again
I got guildIDS set to the right server too
Do you have multiple instances of the bot running?
Lol 👍
Sorry to resurrect this conversation. Formatting wise would it be discord.roles, just roles…?
You can see exactly how it works in the docs and examples
This is more of a design question: when should I name a file in its plural state (e.g. enums.py as opposed to location.py)?
This is a comment from the Java reddit, but I think it makes sense in any environment:
As always, it's up to your discretion and what makes sense in your environment, but I tend to name them singular when the classes in the package are classification and plural when they are implementations. For example, I would put Sheep, Goat, and Pig inside of com.example.animals and I would define it as com.example.animal in the case that it contained infrastructure, utility, or other similar classes such as Pet, WildAnimal, Feeder, AbstractAnimal, CommunicationInterface, etc.
It doesn't look like there are any conventions for it, so yeah, pretty much up to you whatever you think makes the most sense.
Alright, thanks!
How to get a list (data type) of banned users in a guild?
.rtfm guild.bans
The docs quite literally gives you the code you need for that
Hmmm ChatGPT I already did. But I need help with the code. How will he respond?
what?
I have included the 'WetterView' above.
I call the view 'WetterView' via the button. After I click a button in WetterView I want the 'OptionalView' to be called again and the button to be displayed disabled.
How can I get this to work?
Because to include the views on the other side does not work as far as I know or?
from tageszeiten import WetterView
class OptionalView(discord.ui.View):
def __init__(self, bot: discord.Bot, spotdaten):
self.bot = bot
self.spotdaten = spotdaten
super().__init__(timeout=None)
@discord.ui.button(label='Wetter', custom_id="Wetter_Button", style=discord.ButtonStyle.primary, disabled=True)
async def wetter_button(self, button: discord.ui.Button, interaction: discord.Interaction):
attach_message = self.spotdaten[1]['messageid9']
await attach_message.delete()
await interaction.channel.send(view=await WetterView(self.bot, self.spotdaten))
await interaction.response.defer()
What? What isn't working? You're just sending code
If I put this in my tageszeiten .py to then call the OptionalView again. My bot always crashes. I think because I import the two files each other and thus have an infinite cycle or?
from submit_spot import OptionalView
await interaction.channel.send(view=await OptionalView(self.bot, self.spotdaten))```
I don't understand what you're trying to do. Why are you importing OptionalView?
And why are you awaiting OptionalView?
I have a file submit_spot.py where the OptionalView is inside.
Here I call the WetterView from the file tageszeiten.py via a button.
In the WetterView is also a button. If I click this I would like to call again the OptionalView with the button which should be however deactivated.
So why don't you just edit OptionalView and disable the button in your button callback?
Because when I press the button in OptionalView, the button should be deleted and then be under the WetterView again.
So that OptionalView is always the last message.
I want to jump to another file via the button click, execute something there and then jump back to the insert_spot.py file to display the view again.
Why can't you just import both views into one file and use both of them? Your file structure makes no sense
Okay my problem is more complex after all, I have to think again, thanks anyway 🙂
How can I access the contents of the dict "spotdata" here outside of init and without a function?
class OptionalView(discord.ui.View):
def __init__(self, bot: discord.Bot, spotdaten):
self.bot = bot
self.spotdaten = spotdaten
super().__init__(timeout=None)
data = self.spotdaten[1]
I want to check with an If query if the variable 'check' is set to True. If it is set to True the button disabled should be displayed, if it is set to False the button enabled should be displayed.
Had thought so
if self.spotdaten[1]['check'] == True:
@discord.ui.button(label='Wetter', custom_id="Wetter_Button", style=discord.ButtonStyle.primary, disabled=True)
async def wetter_button(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.defer()
else:
@discord.ui.button(label='Wetter', custom_id="Wetter_Button", style=discord.ButtonStyle.primary)
async def wetter_button(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.defer()
I have no idea what you are talking about. Why do you need to make a variable called data outside of your functions??
how to let buttons access value?
?tag codeblock
Please put your code in a code block:
```py
Here is your Code
```
That makes reading code in Discord a lot easier:
print("This is an example.")
class Event(View):
@button(label="1:Apex", style=discord.ButtonStyle.blurple)
async def callback1(self, button, interaction):
data=data+str(interaction.user)
await interaction.response.edit_message(content=f"List:\n{data}\nPlease select ", view=self)
Where is data defined?
user id
what?
save user id
where is data defined???
gobal variable
.botvar
Need to keep track of a variable between functions? No problem!
⚠️ Careful what you name it though, else you might overwrite something ⚠️
Just add it to your commands.Bot or discord.Client instance like so:
bot = commands.Bot(...)
bot.my_variable = 0
async def foo():
bot.my_variable += 1
# In a cog
@commands.command()
async def counter(self,ctx):
await ctx.send("Current Counter is at {}".format(ctx.bot.my_variable))
This also allows you to access this from other cogs/extensions/functions. Anywhere you have access to the bot instance
use that instead of global vars
global data
data=""
class Event(View):
@button(label="1:Apex", style=discord.ButtonStyle.blurple)
async def callback1(self, button, interaction):
data=data+str(interaction.user)
await interaction.response.edit_message(content=f"List:\n{data}\nPlease select ", view=self)
not work
Saying it doesn't work or asking what's wrong with this code is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
File "c:\Users\user\Desktop\emotion_eng_chatbot\Youth_Discord_Chatbot\try.py", line 13, in callback1
data=data+str(interaction.user)
UnboundLocalError: local variable 'data' referenced before assignment
Use this
Don't use global variables when you don't need them
I see thanks
And in the future, provide code and errors. It's a waste of time having to ask multiple questions just to see what's wrong
got it
Is it possible to use hyperlinks([]() method) in embed titles?
no
it's probably faster to just try it instead of asking here tbh
Just wanted to make sure it's not my code
I'll try experimenting with the description ig
embeds already have a url attribute
that's what makes the title a link
if you meant field titles then no
I meant embed titles, and the url attribute works, thanks! Sorry if this was a xy problem
Any ideas on how i'd go about making a ticket transcript that is html instead of just txt files
can i remove an option from a select menu
wdym ideas? Just make it html instead of txt
just don't implement it?
?
what did you want to do? remove option in code or remove after callback?
remove after callback
like after i click a button
.rtfm View.remove_item
^
that remove the entire select menu doesnt it
i want to remove an option from the select menu
You probably need to query https://docs.pycord.dev/en/stable/api/ui_kit.html#discord.ui.Select.options and remove it from the list
and initialize a new select menu with different options?
you can just edit the current select menu with different options
how do i do that specifically
original_options = select.options
# remove your option here
new_options = ...
select.options = new_options
and edit_message(view=self) in the callback right
iff select is a child of view.
hmm...
so i want to edit the select menu after clicking the button
and theres a button callback function taking a View, a Button and an Interaction object
do i do this?
View.children[0].options = new_options
and await Interaction.response.edit_message(view=View)?
What does your button callback look like?
async def button_callback(View, Button, Interaction):
Is this in a view subclass?
other than the casing, everything looks fine.
thanks for helping
careful. if you have imports like this from discord.ui import View, then it can get messy
local variables shouldn't have any uppercase letters anyways if you want to follow the normal conventions (which you should)
and renaming self seems useless to me
Sorry I should've expanded my original message. Was wanting it to run onto a website so people could see it but I've seen people say things like django wasn't so good
Why wouldn't django be good?
🤷♂️ I wasn't the one saying it isn't good
And what's stopping you from using your own brain? Instead of a stranger that tells you it's bad and doesn't give a reason.
Either way you'll have to deal with things like proper authentication to view transcript etc.
Sup everybody, can anybody help me?
AttributeError: 'Guild' object has no attribute '_member_count'
I'm getting this error while this code
@tasks.loop(seconds=8)
async def change_banner():
guild = await bot.fetch_guild(guild_id)
print(guild)
members = guild.member_count
Where is guild_id defined? And why are you fetching the guild on every loop?
Oh, it's global variable upper which contains guild id , i'll fix this fetch, but i have no idea why isn't it working
oh, i've replaced it with members = len(guild.members) and it works
Issue with django is that its blocking and not async. That's why running it on the same thread as your bot is difficult
It wouldn't be that hard to just run django on it's own and use a shared database though
If you only need a web framework then you might be better off using fastapi or quart
Yeah, if you only want to display HTML pages with no auth stuff or anything django is going to be overkill.
But Django does come with a pretty good built-in ORM and Authentication system
what is with Flask?
Flask should work with it
But tbh if you want to build an actual web application, I'd look at a fully fledged JS/TS frameworks instead. Like Angular or SvelteKit
is there a way to make a forced set of options in a slash command? like if I want the user to input a weekday, it can only be Monday, Tuesday, etc.
I've tried autocomplete but the user can still input something else, it's more of a suggestion
yes, but only up to 25 choices
Here's the slash options example.
cool thanks!
It's a Discord limitation, if you need more than 25 options you have to use autocomplete and make your command respond with something like "Invalid value for option 'weekday' " if they input something else.
Can I remove a button from an edited message?
yes
How? I dont really have an idea
.rtfm view.remove

it works, thx!
Which program do you think is the best for coding Discord bots in Python?
There isn't a "best". It's whatever you prefer.
I'm always hesitating between vs Code and PyCharm 
Why?
vim, duh
Every editor has pros and cons. We can't pick for you because we don't know what you want in an editor.
I think both are great, only PyCharm sometimes uses too much ram for me
Then your only options are getting more ram or using a different editor 
hmm, yes, I see. Everything's ok
or switching to a unix distro
because iirc only windows has an issue with ram for intellij based IDEs
Probably, Windows has RAM issues with a lot of things
Just dual boot and use Linux whenever you're developing, ez
mac
Google Chrome 
chrome's just a ram hog in general. Firefox all the way.
I think I'll prefer Visual Studio Code then.
Chrome uses a lot of RAM no matter what OS you're on
I would use pycharm if you mainly use python and VScode if you use multiple different languages.
I use IntelliJ for everything 💀
Just do JavaScript and Python Discord Bots
Quick question how to use emoji with name from particular server and can we use animated emojis from a server with the bot?
Type a \ before the emoji and you will see what to use in your bot
E.g
= !pycord
And yes, you can use animated emojis
As long as the bot has permission to use external emojis in the server
Traceback (most recent call last):
File "E:\Ganger\Raid-Protect-Discord-Bot\main.py", line 23, in <module>
bot.load_extension(f"Cogs.{filename[:-3]}")
File "C:\Users\يولين\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\cog.py", line 910, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\يولين\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\cog.py", line 791, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'Cogs.changePrefix' raised an error: ClientException: Cog named 'ChangePrefixCog' already loaded
help.
if name == 'main':
for filename in os.listdir("Cogs"):
if filename.endswith(".py"):
bot.load_extension(f"Cogs.{filename[:-3]}")
Read the error, and use code blocks when asking for help
yea ofcourse i read? and it said its already loaded yea how to fix it? how uh make it pass if its loaded? tf... it crashes the whole bot.
Don't load it multiple times
And if you're making a bot you should be at the level of Python competence where you know how to catch errors
can you stop being wierd? LOL as if i dont know python, secoundly smartie im already just doing it once.
Evidently not, the error doesn't lie
And if you do know Python, you should also know how to catch an error and prevent crashes
ok ill just do for i in range the number of cogs?
what?
it sounds like your the one who is replying by just saying the error and not completely knowing how to fix it and still making wierd sterotyping about me.
Oh I know how to fix it, but we don't spoonfeed here. You're probably loading your cogs in the wrong place
Nope. see your wrong.
?
cogs are in there correct location.
ik dumb question but docs always confuse me. how do i add a dropdown menu to a message?
So where are they then?
they are in cogs file. in the same directory
I'm not talking about the cog files, I'm talking about your code that loads the cogs
Where is that code?
NEXT TO COGS.
bot\ main.py cogs
i see theres a busy argument so i will ask later
I don't care where in the folder the code is, I'm asking where you're loading the cogs. Is it in on_ready, is it in on_connect, is it before you run .start????
where in the file
oh yea not on ready. just if name = main,
if name == 'main':
for filename in os.listdir("Cogs"):
if filename.endswith(".py"):
for i in range(21):
bot.load_extension(f"Cogs.{filename[:-3]}")
?tag codeblock
Please put your code in a code block:
```py
Here is your Code
```
That makes reading code in Discord a lot easier:
print("This is an example.")
I've already told them that before as well
if __name__ == '__main__':
for filename in os.listdir("Cogs"):
if filename.endswith(".py"):
for i in range(21):
bot.load_extension(f"Cogs.{filename[:-3]}")
```
if the file name ends with .py itll load it as a cog?
oh that
huh?
You should rather use bot.load_extentions notice the s at the end
And pass the Cogs folder to it. The library will automatically load all files and files inside subfolders from it
.rtfm load_extentions
Target not found, try again and make sure to check your spelling.
discord.Bot.load_extension
discord.Bot.load_extensions
discord.ext.bridge.Bot.load_extension
discord.ext.bridge.Bot.load_extensions
discord.ext.bridge.AutoShardedBot.load_extension
discord.ext.bridge.AutoShardedBot.load_extensions
discord.AutoShardedBot.load_extension
discord.AutoShardedBot.load_extensions
discord.ext.commands.Bot.load_extension
discord.ext.commands.Bot.load_extensions
discord.ext.commands.AutoShardedBot.load_extension
discord.ext.commands.AutoShardedBot.load_extensions
extensions* 
Here's the dropdown example.
