#Basic Pycord Help (Quick Questions Only)
1 messages ยท Page 81 of 1
tyty
dms are open for help :)
is there a way to use on_interaction to get the options of a select menu?
how would i go about updating giveaways message in a task loop so i dont get rate limited say there's 400 giveaways going on at the time and i need to update each of those embeds
Is there a discord.Permissions object for "send voice messages"? Not sure if that's something that has to be updated in Pycord or if it just naturally extends as discord adds new permissions?
You shouldn't be using on_interaction to respond to views or do stuff with views
I'm doing it anyways it was the only way
Probably on the new version
Update when they finish or?
yeah basically
without really getting rate limited
it is unlikely i guess so im fine
Rare that many giveaways end at the same time tbh
yeah i suppose so
The library does handle ratelimits for you. There will be a warning in the logs, but the request will go through when the ratelimit is over
oh that is perfect then
Is there an event for someone using a slash command - I want to log command uses but i'd rather not add a function to every command
guild = bot.get_guild(GUILD_ID)
await guild.leave()
I think that's right, i havent tested it
cool
on_application_command(context)
thanks
this is cool to know. Been thinking about more tracking features lately to help clients understand how user activity relates to bot usage + just basic anlaytics for myself to see what people like
How can I disable the default help command? (prefix commands)
help_command=None where you define the bot
Thanks
Can you show the pip list pls
It means you don't have git installed or added to path
Thanks ill check it out when im on later
nice code
NameError: name 'bot' is not defined
My Code
import discord
import logging
logger = logging.getLogger('discord')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)
@bot.event
async def on_ready():
print(f"We have logged in as {bot.user}")
@bot.slash_command(guild_ids=[1114355858919407676])
async def hello(ctx):
await ctx.respond("Hello!")
bot.run("MY TOKEN")
Docs Page Im Following
https://docs.pycord.dev/en/stable/logging.html
Terminal Error
Traceback (most recent call last):
File "/home/admin/Wumpus/bot.py", line 10, in <module>
@bot.event
NameError: name 'bot' is not defined
where is your bot defined?
How come on my guild where i was previously debugging the bot is there now 2 of each command after i removed the debug_guilds. But on any other server there is only 1 of each command.

i dont know how i got this error i used the docs example but it didnt say where to define the bot
Because it's just a guide to setup logging?
It won't tell you the obvious thing to define a bot
Pls learn Python basic's first
ask chatgpt
no
i dont understand how my bot is not working after i added logging please can i have real answers not trolling answers
I gave you a real answer
Plus the error is obvious
You never defined a bot variable
the turioral never mentioned anything about defining a bot varible
Because the guide you linked is just how logging should be setup
what steps must i take to define my bot varible
The tutorial assumes you have defines a bot and the commands and stuff
Read the guide and docs.
i used the / command example and it worked but than it showed up a wierd error after i added logging
Do you know python basics?
Because you seem lost by simple examples and you don't even know what your code does
import logging
logger = logging.getLogger('discord')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)
bot = discord.Bot(debug_guilds=[1114355858919407676])
@bot.event
async def on_ready():
print(f"We have logged in as {bot.user}")
@bot.slash_command(guild_ids=[1114355858919407676])
async def hello(ctx):
await ctx.respond("Hello!")```
I imported bot = discord.Bot(debug_guilds=[1114355858919407676]) im really new to coding especially discord bots
im currently learning python along with pycord
im confused i was able to re register the / command and my discord.log text file got updated?
?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.
yeah but im looking to learn pycord and im explainging my question as best as i can
you can't learn pycord with python. It's like trying to learn rocket science without knowing algebra
im confused i dont understand whats wrong with my question i showed my code and terminal, while i understand that learning python basics is important im currently trying to learn discord bot development at the moment
You didn't get squid's point.
You're trying to run without even knowing how to stand up.
If you want to learn how to develop a Discord Bot with Python and Pycord, you cannot without knowing the basic understanding of Python. You cannot decide to skip critical fundamental principles and go into the deep end.
i used bot = discord.Bot(debug_guilds=[1114355858919407676]) and its working so far for me?
But you don't know why.
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.
Because you don't understand your code.
Just blinding copying and pasting code doesn't make you learn anything
im reading the docs to try and understand it and i will be going back over the python basics
copying and pasting works better for me personally since im a slow typer because i have dyspraxsia
so far im not getting any errors registering my / commands after adding the bot varible
And still not getting the point.
The docs are written in a way that it should be digestible to any intermediate/advanced python programmer. While it is possible you may understand the documentation, you will not understand how to apply it.
You are also making it sound like "the python basics" is some simple and trivial topic. It isn't.
sir people here dont even know that (a+b)(aa+bb) = (aaaa-bbbb)/(a-b) and you are trying to talk about something complicated
is the support server for professionals? because i dont quite understand what i did wrong i asked a question and i implimented the right varible and now its working
mabey i need to open up a ticket i dont want to get banned or anything im just confused
Add me to that list cause I dunno either 
pycord isn't a framework for beginners. It is for those with a solid understanding of fundamentals. While we do appreciate your enthusiasm, you โ to put it bluntly โ do not know enough, yet.
i understand i dont know the basics but im still confused what rule i broke?
You didn't break any rules.
do such a recommendation again and you'll be gone faster than you can look
I wanted to make persistent select menus but the way I was making them was kinda hard to use the normal way of making them persistent in this case ur was the only way
Which onesss? Am I one of the ones you likeee? :0
Whaaa wut does that mean- plus answerrr
ok so.
numbers = [int(num) for num in all_datas]
view = discord.ui.View()
for i in range(1, 26):
if i in numbers:
label = "โจ"
else:
label = "๐ฃ"
button = discord.ui.Button(label=label, disabled=True)
view.grid().add_item(button)
await ctx.send("Here is the grid:", view=view)
i dont know at all what is wrong (in buttons) / couldnt find any help on how to do it the way i want in docs. if you just mind 1m if your time telling me how to fix this you would be a amazing person โค๏ธ
@fervent cradle discord buttons are limited to 25 button on 5 rows each row has 5 buttons
uh
well
if i am starting from 1, 26
shouldnt i have 25 ?
or should i start from 0,24
- the entire thing is giving a error
for thing in range(24) -> will start counting from 0 to 24 means that the index max is 25
so why not to send the Traceback
sure
Traceback (most recent call last):
File "C:\Users\ููููู\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\ููููู\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 375, in invoke
await injected(ctx)
File "C:\Users\ููููู\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'View' object has no attribute 'grid'
i meantioned you #international-chat
discord.Bot not discord.bot
discord.errors.Forbidden means that your bot have no access to that thing you trina do
- make sure you enable all of the intents for the dev
it has admin perms
also pass the intents parameter into the discord.Bot like discord.intents.all()
i mean on the https://discord.com/developers
discord dev portal?
ye
yes all of them
and thats it?
..
ignore that you just enable the intetns
and make sure to add these to your code instead of the old one
bot = discord.Bot(intents=discord.Intents.all())
ye this is the bot variable
or instance wutever
replace this with it
that's it
you got this err after invoking a command?
yes
bot = discord.Bot(command_prefix="?", activity=activity, status=discord.Status.online)
should that still be there
or replaced?
i mean if you are importing something called bot just delete that import
yo
you are importing everything from discord ๐
use import discord instead of filling out the IDE with discord classes
you actually must to import the used stuff only
and not all of the lib
so what should i remove out of that?
that's my not just make every thing looks messed up but will fuck up the ide later on
clear all that then start importing what is needed
and also i want info about this
i dont know what is needed lol
๐ฆ
if you mean a VC, so i have no issue but i have no mic lol
nw
Why?
Nvm found a fix
I was using on_slash_command_error
instead of on_application_command_error
Yo im tryna import pycord but it just says No module named 'discord'.
Ive tried everything to fix this like uninstalling discord.py and that stuff reinstalling it but it still doesnt recognise the module.
Every other library I installed works fine apart from this one.
Can you show the pip list?
pycord is in there with version 0.1.1
Should be py-cord not pycord
is there a way to change the bots presence in the commands.Bot instead of doing it in the on_ready even as that event calls multiple times upon startup adding additional requests to discord
huh. so how do i install py-cord then
i know theres activity, but i need presence or is that the same thing?
Uninstall any other libraries which are imported as discord, and install py-cord
Pass activity=PresenceClass to bot
mind showing an example? i dont quite know what you mean
thanks
to get the value, however, i need the bot object:
class Presence():
def __init__(self):
maintenance = bot.checkMaintenance()
startup_activity = Activity(type=ActivityType.playing, name="in maintenance mode", status=Status.do_not_disturb)
if not maintenance: startup_activity = Activity(name="for /help", type=ActivityType.watching, status=Status.online)
uh no?
pass the activity classes
like
.rtfm discord.Game
or discord.Streaming or discord.CustomActivity
yeah but i stil need to get the maintenance with the bot object
you can create the activity object in the same file
you dont need to make your own class
okay but i need to get the maintenance value from the bot object that im trying to set it to
maintenance = bot.checkMaintenance() returns true or false
eh you have a non-ideal scenario....
bot depends on the activity, but the activity depends on the bot
yk
yeah i know but moving it to a different file would actually defeat the purpose of having a subclassed bot
hmm can i also ask what bot.checkMaintenance() is
reads a value from a json file, if its 1 means maintenance mode is on it returns true
oh you can actually do stuff in the init
of your subclass
class MyBot(...):
def __init__(...):
maint = self.checkMaintenance()
if maint:
act = ...
else:
act = ...
super().__init__(..., activity=act)
yk
so i cant set the activity from the main file then or what uve lost me lmao
you are setting the activity in your subclass
any reason to do it only in the main file? i dont see why you cant do it in the file with your subclass
oh, so i do like
maintenance = self.checkMaintenance()
startup_activity = Activity(type=ActivityType.playing, name="in maintenance mode", status=Status.do_not_disturb)
if not maintenance: startup_activity = Activity(name="for /help", type=ActivityType.watching, status=Status.online)
super().__init__(*args, **kwargs, activity=startup_activity)``` so something like this, if my understanding is correct
lets see
one more thing, how do i close the bot?
@bot.event()
async def on_disconnect():
await bot.close()``` or is it no on_disconnect?
oh so no need to do that on_disconnect, okay
why isn't .dark_theme() embed colour invinsible in discord dark theme?
Does anyone know if there's a way to send out Stuff from a Announcement Channel via Bot? I havenet found anything yet
message.publish?
oh damn..thanks ๐ i've just looked at the channel Section ๐
Just use aiohttp
genuine question why is it so bad to use on_interaction?
i found a use for it that i genuinely dont know if theres another way i could do it-
Hello, I wounded if thereโs a way to handle multiples user at the same time without the bot stop โworkingโ (like stop doing what he is supposed to do), for example Im making a command that when you use it create a channel and add the author then start making question with bot_wait for they, when all question are done, remove the user and send and embed with buttons etc, is there a way that the bot can handle more than 3-5 users without stop sending questions?
the bot by nature is async. meaning that multiple commands can run simultaneously without blocking each other.
but they will block each other if a command has some blocking code in it
Ye ye ik, but somehow is just stopping sending question without showing any errors, all others parts works except for that.
Not getting an error, but definitely should be?
Do you also have an on_command_error set up?
Please make sure to look at, and implement,** the 3 or so lines starting with 'else'** in the example below. Without this code or similar, your error handler is eating all unhandled errors. As you can imagine, this is bad when you get an unexpected error.
https://gist.github.com/EvieePy/7822af90858ef65012ea500bcecf1612
Do you also use asyncio.run and/or bot.start?
Please make sure logging is setup correctly.
https://docs.pycord.dev/en/stable/logging.html
Ty Iโll check it
^^
missing access to add cmds to the server
yeah just re-invite the bot with these scopes. no need to kick it
a slash option that not written manually by the user, what type of slash option is that? idk the name
autocomplete?
this is part of community onboarding, can't be set via api
(ok it is on API but not implemented yet)
ok thank you !
Is it normal that message.publish() doesnt publish the Mention, when someone is mentioned?
You could blame discord for that
Is it against Discord's ToS to do this?py BotInviteLinks = [f"https://discord.com/api/oauth2/authorize?client_id={member.id}&permissions={member.guild_permissions.value}&scope=bot%20applications.commands" for member in ctx.guild.members if member.bot]I'm currently trying to make a Discord backup bot, and I wanted to get invite links of other discord bots that are in the Discord server.
As far as I know
It's definitely not against TOS, as long as you don't use self-bot to auto-invite bots
I don't see anything criminal in creating links so that user can easily get back bots
But yeah, it will be really sad to lose bot settings, because I don't know a lot of bots that support transferring settings from guild to another guild
Great! Thanks for the info ๐
it's a webhook, and iirc they can't mention users
aah okay^^ so then i just have to add the ID as a String^^ Thanks ๐
sup, how do i properly make my slash commands "fancy"? I thought about using Groups as a first step, is there anything else?
what's your definition of fancy?
It's more of a question what is possible
If i got i right, Groups and Subgroups are the "only" thing i can do
Adding some description in it afterwards
personally I think components like buttons and select menus are under/over utilized
and also context menu commands whenever possible
alright, will have a look on them =)
Is it possible to send a modal object twice?
Like
modal = MyCustomModal
await send_modal(modal)
await modal.wait()
# somewhere else (the modal object got passed along)
await send_modal(modal)
||(I don't respond to the same interaction twice. I pass the modal along to a button and that button sends the modal upon being pressed)||
The goal is to send the modal with the same values that the user filled in earlier. (Without creating the same modal again but with the values from earlier)
So, yeah it is possible, but is it a common use case or can it break things?
Like (ikd if it's related to this or something else) when I send it the second time the modal.wait() doesn't work anymore.
You can't respond to interactions twice
I know and I don't (although the code might suggest that, yes) and that wasn't my question.
to be safe, i would just create a new modal with values set from the old modal's text inputs
but im not sure about the actual answer. you might need to dig through source
Do you know if I could just copy the children?
Based on the weird behavior of modal.wait() the second time I'd say that it's not intended but that could be a boug or so...
Oh yeah modal.wait will only work once
You can actually make it work again by modal._stopped = modal.loop.create_future() I just found out xD
Hmm the modal might get removed from the internal cache after that tho
NGL making a fresh modal will be better
probably. Even with making wait() work again the values still don't get passed at the second attempt...
This might be possible
Hm. Actually.
new_modal = MyModal()
new_modal.children = old_modal.children
send_modal(new_modal)
Doesn't work either. So I suppose it has something to do with the InputText Objects...
I just found a refresh_state method in the Inputs, trying that rn
That's for the interaction iirc
?
Just simply
for i in old.children:
n = discord.InputText(sytle = i.style, value = i.value, ...)
new.add_item(n)
Iirc, refresh_state is called by the library when the user sends the modal
You can even have a method in your subclass that returns a new modal
like a copy() ?
And do this
I did this now after looking a bit through the source:
for child in self.modal.children:
child.value = child.value # sets the recieved value as default value
self.modal._stopped = self.modal.loop.create_future() # for wait()
works like a charm. At least for now xD
Took me long enough to figure it out tho...
Btw: Has it always been possible to edit ephemeral messages?
yes
Fix it, i just merge the buttons inside the command and smh now woks
tysm
You could also just import the buttons/views?
i had it
Im working on a bot to schedule events for me, im using guild.create_scheduled_event(options...). Its working great, however it seems to not properly represent the time i give it in discord. I'm giving it an ISO8601 time using datetime and when the event is created the time is roughly 5 hours behind.
start = dateparser.parse(each['start_time'], settings={'PREFER_DATES_FROM': 'future', 'TIMEZONE': 'EST'})
end = start + datetime.timedelta(hours=2)
guild.create_scheduled_event(name=each['name'], description=each['description'], location=each['location'], start_time=start, end_time=end)
the time difference gets to a point where sometimes it will throw 400 bad req errors due too trying to schedule an event in the past. I cant really find much of information to why online. Any help is appreciated, Thanks.
convert it to UTC
thats what Im doing now, i made a test event and printed its start time, to find out its +00:00 
not sure if I understand this correctly. So is it working or not?
running a test rn
yeap its workin
i can finally go to bed
yay
Am I wrong or is there a typo in the docs?
When you right-click a message, you may see an option called "Apps". Hover over it, and you can see commands a bot can run with that message. These are called message commands.
When you right-click a user in the user list, you can once again see an option called "Apps". Hover over it, and you can see commands a bot can run with that message. These are called user commands.
Shouldn't the second sentence end with something like ... you can see commands a bot can run with that user ...
Oh yea
What exactly do you mean by this? ^^'
Youscrolled up so farto find that-
how should i get the owner id of a threat if it is created by a bot using a command like a ticket system or something
Store the ID in a database?
or do threats have descriptions like channels? im not sure i could have their id there
Not even far if you know that this message is there and have 27โ 1440p monitor
dam XD
do you means threads?
They dont
ah that sucks then
@bot.event
async def on_member_join(member):
role_id = 1073702911852433408 #Gives the "Nouveau membre" role
role = member.guild.get_role(role_id)
await member.add_roles(role)
print(f"{member} a rejoint le serveur.")
##########################################################################################
#On leave
##########################################################################################
@bot.event
async def on_member_remove(member):
del db['used_mails'][db['users'][f"{member.id}"]['mail']]
del db['users'][f"{member.id}"]
print(f"{member} a quittรฉ le serveur.")
why doesn't it works as expected
?tag 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.
When someone joins nothing happens
what intents do you have
intents = discord.Intents.default()
intents.message_content = True
bot = discord.Bot(intents=intents)
yeah you also need members intent for these events
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
bot = discord.Bot(intents=intents)```
still not working
(I don't have any error)
could you put a print or something to see if it is even ran?
when i start my bot i get this
Ignoring exception in on_connect
Traceback (most recent call last):
File "/opt/homebrew/lib/python3.11/site-packages/discord/client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "/opt/homebrew/lib/python3.11/site-packages/discord/bot.py", line 1164, in on_connect
await self.sync_commands()
File "/opt/homebrew/lib/python3.11/site-packages/discord/bot.py", line 738, in sync_commands
app_cmds = await self.register_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/lib/python3.11/site-packages/discord/bot.py", line 531, in register_commands
prefetched_commands = await self._bot.http.get_guild_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/lib/python3.11/site-packages/discord/http.py", line 365, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
Bot doesn't have permissions to add application commands.
Re-invite it with the correct scopes.
How can I manage to make slash subcommands inside of sub-groups recognize arguments? I am running py-cord 2.4.1
Here is a snippet of my code:
# Create /config Slash Command group with bot.create_group
config = bot.create_group("config", "Configure all of features...")
# Create the "/config admin" subgroup within the "/config" group
admin = config.create_subgroup("admin", "Manage admin roles")
# Define "/config admin add" and "/config admin reset" subcommands within the "/config admin" subcommand
@admin.command()
@commands.has_permissions(administrator=True)
async def add(ctx, role: discord.Role):
async with aiosqlite.connect('spellguardian.db') as db:
await db.execute('INSERT INTO admin_roles (guild_id, role_id) VALUES (?, ?)', (ctx.guild.id, role.id))
await db.commit()
await ctx.respond(f'Successfully added {role.mention} to admin roles.', ephemeral=True)
When I try to run "/config admin add", the command seems to not expect any kind of arguments.
it can- i think this is being caused by me having a guild specific command
you can try removing/commenting out the command, run the bot, add the command back, run the bot, and restart your discord. Your discord client's command cache could be out of sync
Is there a way to reference the bot object in a modal callback without passing the bot object to the modal during init?
Like through the interaction or smth
interaction.client ?
The docstring says this: Returns the client that sent the interaction.
Does the bot send the interaction?
yes
Ah ok, I though the user that clicked a button or so, is sending the interaction. Thanks ๐
client is always the bot
Just tried that, it's still not expecting any argument ๐ฆ
I even tried on an alt account
alright, thanks
try using the @discord.option decorator
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/slash_options.py at master ยท Pycord-Development/pycord
I tried using it, as the following snippet shows:
# Define "/config admin add" and "/config admin reset" subcommands within the "/config admin" subcommand
@admin.command()
@option("role", discord.Role, description="Role that will be added as admin for the bot")
@commands.has_permissions(administrator=True)
async def add(ctx, role: discord.Role):
async with aiosqlite.connect('spellguardian.db') as db:
await db.execute('INSERT INTO admin_roles (guild_id, role_id) VALUES (?, ?)', (ctx.guild.id, role.id))
await db.commit()
await ctx.respond(f'Successfully added {role.mention} to admin roles.', ephemeral=True)
But the command still shows no argument. It's not even showing the description.
I have also tried stopping the script, letting the bot go offline, and then ran it again. The command seems to not be updating ๐ฆ
do you have multiple instances running?
Nope, I am only running one instance and have only added it to one server, which is my testing server
How does Pycord handle the new username system?
If I use msg.author / ctx.author for a person with "TestName" as a display name and "@testuser" as the username, will i receive "TestName", "testuser" or "testuser#0"?
what
string would return testuser#0
display_name would return TestName
discriminator would return 0
name would return testname
get_x methods come from cache right? I remember hearing that somewhere, but I don't know if it's true, or where to find that information. Is it documented anywhere?
yes
Ok thanks, is it documented anywhere?
not directly I think
Ok thanks!
awesome, thanks for explaining all of that! Is it possible to get the "global / default display name" instead of the one from the server?
display_name for user is the global name
Could you paste the pip error in a code block
the error
I'm not doing that. However, https://stackoverflow.com/questions/65670259/every-python-related-executable-broken-fatal-python-error-init-import-size-f
The post may help
if you have a file called os.py or stat.py that you created, it may be creating the error
do you have a site.py file?
oh alright. thanks!
deso pycord support message reaction? if so waht format are the emojis supposed to be in. im trying to get 1๏ธโฃ to 9๏ธโฃ to auto react to a msg the bot sends but its throwing me 400 bad req Unknown emoji errors
see unicodes
where specifically
ive looked for it before but what it gave me didnt work
use normal emojis (unicodes) instead
i know its going to be unicode, however when i tried to put in a unicode value it didnt work
bruh
do you have a site you go for unicodes?
hold on
yea im still waiting for that one to finish loading all of the emojis
why not just to use emoji
import it and start
lemme give that a shot
Good
im still getting unknown emoji errors
What's the error?
1๏ธโฃ
1๏ธโฃ
what the actual hell, why does that work
It's unicode
whats the difference between that and U+ codes
use win+period
That's what discord uses to show emojis in discord
unicode is well unicode
win+period returns the unicode form
Welcome!
send code
?
I mean a code block
with the import statement
or whatever made the error
Oh do you mean within replit's importing?
another question, im currently trying to work on adding an image option to my guild.create_scheduled_event(). discord documentation says it likes it in data URI scheme. However when i create the URI and send it with the "image=" option, it complains and gives me this error: Any clues to how i could fix this, or am i misunderstanding what its asking for.
Ohhh you're sending bytes
that's why
do you have the code?
yea lemme drop it, i assumed it was in string form
image (Optional[bytes]) โ The cover image of the scheduled event
So the image is supposed to be in bytes
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
which is weird because when i do sent bytes it doesnt like that either
What does it say?
How are you converting to bytes
base64_data = base64.b64encode(image_data)
what is image_data
try this:
with io.BytesIO() as output:
image_data.save(base64_data, format="PNG")
base64_data.seek(0)
oh nvm
i was overthinking it
What was the problem?
i was too focused on the URI aspect, when all i had to do is send the raw image bytes without b64 encoding
oh lol
sorry if I confused you even more
all good, asking questions is half the battle go figuring out that the right solution was alot easier than what i was doing.
Is there a way to make the bot not reply to itself when doing ephemeral=True? I tried python @bot.event async def on_message(message): if message.author == bot.user: return if message.author.bot: return But I believe it works for regular messages and not ephemerals.
I don't believe that is possible outside of commands
https://pycord--2096.org.readthedocs.build/en/2096/api/abcs.html#discord.abc.Messageable.send
An abstract base class(also known as an abc) is a class that models can inherit to get their behaviour. Abstract base classes should not be instantiated. They are mainly there for usage with isinst...
there is no ephemeral parameter in ^
So no matter what, it will still reply to itself in ephemerals unless i turn it into a non ephemeral?
*whoops this is a pull req docs link, but it should be the same
I don't think it sends if you put that parameter
Ok, thanks!
Ephemeral is only for interactions
anyway to limit a dropdown so only the user that started the command could use the dropdown or select menu? It would be in a channel, so Ephemeral wont work.
Pass the ctx author to your view
Override interaction_check and check if interaction.user equals your ctx author
Return True or false accordingly
er well i cannot get ctx. forgot to mention its a persistent view
so like basically i have a persistent view that gets posted to a channel. the thing is, anybody can use the same box.
Ok now.im confused
Why everyone can see the select menu but you only want one person to handle it
Ok I kinda get the point
You could store their ID somewhere, and then get such id
Why the second dropdown can't be ephemeral?
because its in a channel
If it's directed to a single user who select a category from the above
i didnt think you could send ephemeral in a channel
Does the second dropdown come up if the user selects a category from above?
Is that what it does?
correct
Then you can make it ephemeral
you're kidding.
channel.send doesnt support ephemeral i didnt think? maybe i misread the docs on that one
Ok no it doesn't
Why are you using channel.send?
If it's from an interaction
You have interaction.response.send_message
hmm i see
I'm gonna assume you're using it to send the first embed
Just send it altogther
It's unnecessary to add a second message with the dropdown jus to "whst item would you like to purchsde?" The select typeint is already doing that
Ignore my messed typing. I'm on mobile
oh no ,
so the flow is
the channel has a store that you can select "weapons cars or drinks etc"
the first dropdown tells lets you pick weapons lets say
i pull all the weapons, send the list of weapons from the store, then the second dropdown lets you pick which weapon you want.
does that make sense lol
but i think this gave me an idea. thanks!
do slash commands have an object of the message theyre being replied to?
liek can i reply to a message and invoke a slash command on that and it will have an object fo rthe message i replied to
reply when answer ty
Nope
Try replying to a msg and invoke a Slash cmd
The reply won't go through
Discord limitation
You might rather be interested in message commands
just gona use a normal command then ty
These are found by long pressing on a message
Like so
Hey
@bot.command(description="Afficher les infos d'un compte donnรฉ.")
async def profil(ctx, member: discord.Member = None):
if member is None:
member = ctx.author
color = get_dominant_color(member.avatar.url)
color_int = int(color, 16)
color_discord = discord.Colour(color_int)
info = db['users'].get(str(member.id), {})
clubs = ',\n - '.join(list(info.get('profile', {}).get('clubs', [])))
embed = discord.Embed(
title=f"Profil de {member.name}",
description=f"""
__Utilisateur__ : {member.mention}
__Nom__ : {info.get('mail', '').split('@')[0].split('.')[0].capitalize()}
__Prรฉnom__ : {info.get('mail', '').split('@')[0].split('.')[1].capitalize()}
__Adresse mail__ : `{info.get('mail', '')}`
__Vรฉrification__ : {info.get('profile', {}).get('verif', '')}
__Infractions__ : {info.get('infractions', '')}
__Clubs__ : - {clubs}
""",
color=color_discord
)
embed.set_thumbnail(url=member.avatar.url)
embed.set_footer(text=text.footer+f" | Commande utilisรฉe par {ctx.author.mention}")
await ctx.send(embed=embed)
Does not work when i replace send by respond
(ping me if you have an answer please)
what doesn't work
it gives unknown interaction error
when i replace send by respond
otherwise it works properly
you need to defer first
it's probably taking too long, so at the start of the command add await ctx.defer()
received answer but still thinking
did you change send to respond
No, thank you for your help it's fixed now!
Why do I always get "Message not found" and cannot delete the message?
What am I doing wrong?
view = ConfirmButton()
message = await interaction.response.send_message(embed=embed, view=view, ephemeral=True)
view.message = message
class ConfirmButton(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.message = None
@discord.ui.button(label='Confirm', custom_id="confirm_button", style=discord.ButtonStyle.grey)
async def confirm_button(self, button: discord.ui.Button, interaction: discord.Interaction):
try:
await self.message.delete()
except:
print("Message not found")```
What about interaction.message
I send the message after the modal and then want to delete it via the button when I have confirmed the message:
class Select(discord.ui.Modal):
def __init__(self, channel):
super().__init__(
title = "XXX",
timeout=300,
)
self.channel = channel
self.user = discord.ui.InputText(
label="XXX",
min_length=1,
max_length=4,
required=True,
placeholder="XXX"
)
self.add_item(self.user)
async def callback(self, interaction: discord.Interaction) -> None:
embed = discord.Embed(
title=f"Details for XXX",
color=BOTCOLOR
)
view = ConfirmButton()
message = await interaction.response.send_message(embed=embed, view=view, ephemeral=True)
view.message = message
class ConfirmButton(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.message = None
@discord.ui.button(label='Confirm', custom_id="confirm_button", style=discord.ButtonStyle.grey)
async def confirm_button(self, button: discord.ui.Button, interaction: discord.Interaction):
try:
await self.message.delete_original_response()
except:
print("Message not found")```
response.send_message doesnt return the message object
It just returns the interaction
Naming it as message would be confusing (and will break on master branch)
Name it smth like parent_interaction
Master branch has view._parent that does the same
view.message is also set at many more places
well they are using delete_original_response in the new code, but yeah a different name would probably work
Okay so just like that then?
view = ConfirmButton()
parent_interaction = await interaction.response.send_message(embed=embed, view=view, ephemeral=True)
view._parent = parent_interaction```
Okay so just like that then?
view = ConfirmButton()
parent_interaction = await interaction.response.send_message(embed=embed, view=view, ephemeral=True)
view.interaction = parent_interaction
class ConfirmButton(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.interaction= None```
Just
view = ...
interaction.response.send_message(...)
view.interaction = interaction
is fine too
interaction.response.send_message just returns interaction back. No need to save it
Sort of a needless feature lol
Okay works. Thanks! ๐
How can I turn off the message about creating a thread?
how do i get ctx in on_member_join?
What do you need ctx for?
nvm im dum i got it ๐ญ
async def on_member_join(member):
...member.guild```
Have you used it?
Yis
What message?
For some reason ctx.send and ctx.respond differe when it comes to emojis
my variable for my emoji is set to self.tick = ""
if you are sending it with ctx.send, the bot needs the permissions to send external emojis in that channel/guild/category. The bot also needs to be in the server that the emoji is in
its in the same server and the bot has the required perms
this message was sent in a channel with the same perm levels with VARIABLE.send
confirm that the emoji is correct?
Hey guys, quick question: is there a way to use built-in Discord emoji in a SelectOption without copy-pasting it ?
Because i'm fetching cities (and their countries) from an API and I would like to have the country displayed as an emoji (so I have something like this:
emoji = f":flag_{country_code.lower()}:"
But it doesn't work.
I didn't find a way to convert the string version to emoji (idk if there's a way to make something like this:
get_emoji_from_str(":flag_fr:")
Which would output ๐ซ๐ท
so if the emoji is in server a, the bot is also in server a?
yeah
lmao emojis time it seems
top is with ctx.respond
bottom is with ctx.send
thats odd
same server, bot is allowed to use external emojis
send code?
or does it have to be the EXACT same and not a mutual?
i thought bots could pull emojis from other servers
bots need to be in the server to use that server's emojis
it is
respond works because technically it is a webhook which can use emojis from anywhere
oh i seee
what is bot.self.cross?
you can get a partial emoji from that
im guessing get_emoji()
could you check if the emoji is the bot's cache: bot.emojis?
what are your intents?
since its a comissioned bot, i put all
ok and I'm assuming that bot event loop thing doesn't cause any problems
nah, its just so if i want to run smth on the same event loop without creating a task with the bot
Ok thanks, weird design tho as we are force to iterate over the guild emojis even for basic emojis like flags (I tried using the emoji module but it doesn't work with flags I guess)
@midnight torrent could you try using bot.get_emoji(id) or await ctx.guild.fetch_emoji(id) and see if that yields a correct emoji?
yeah one sec
if you have the emoji string, you wouldn't need to do that
Idk how to get the emoji string as i'm determining them programatically
and it's flags
hmm
its in the same server as the emojis in
but im using it from another server
ok, but like is the ID and everything correct
yeah
emoji is in server a and bot is in server a but i want to use it in server b
with the bot
this is the emoji
waaaait whaaattt
the ID you have is incorrect
i swear i copied the id
copy ID copies the message ID
oh ffs
that gives the id?
that gives the emoji string
i thought that just turned the emoji into the unicode eqiv
just for normal emojis
what default tick
pretty sure you can just delete it
hold on
god, someone get me away from programming
it uhhh
the bots in the wrong server
BRUH
christ im sorry lmao
literally first thing I asked you
yeah, i know, i thought it was, i was so sure
but i guess, my brain skipped thinking to check
average human brain moment
k
Is there a way to update just one part of a view with interaction.message.edit or do you have to update the whole thing?
Trying to activate a "submit" button after required select menus are selected, but reseting the whole view with view=self obviously returns the default select menu options.
I don't think so.
As a workaround, you can always have pre-set select menu options with https://docs.pycord.dev/en/master/api/data_classes.html#discord.SelectOption.default
Some classes are just there to be data containers, this lists them. Unlike models you are allowed to create most of these yourself, even if they can also be used to hold attributes. Nearly all clas...
Hmm. Thanks for the response. Can you think of any way to turn button.disabled = true to button.disabled = false without resetting the whole view?
sorry, I don't think there is...
Ugh ok
hey, does anybody know how to kinda reset the selected options with a selection menu? like i want my users to be able to select something and after that it will reset the options they selected so they do not have to click something else to be able to click the first one again.
edit the message with something like await interaction.response.edit_response(view=self)
ah thank you !
why do i get a message object for print(interaction.message) but when i try to do await interaction.message.edit(view=self.view) i get 404 Not Found (error code: 10008): Unknown Message
i think i could use await interaction.response.edit_message(view=self.view), but i have to send a modal after that and it will not work because i responded before
interaction.response.edit_message()
and if i want to send a modal too?
Are discord.ui.Views only used by pycord internally to handle components or are they actual parts of the discord api?
Because I wondered why the discord.Message does not have a view attribute.
You would have to try a few things because I dont really know it
what could i try?
Is the modal at a view class?
how do you mean? its just ```py
class EditCategoryModal(Modal):
def init(self, *args, **kwargs) -> None:
super().init(*args, **kwargs)
with items and a callback
interaction.response.send_modal(the modal)?
yeah
simply my command works like that:
slash command --> select menu with options --> you choose one option and a modal pops up and the select menu resets itself
For it would be
interaction.response.edit_message(view=self)
interaction.response.send_modal()
but lol i removed ephemeral now from my slash command respond
and its now working
is await interaction.message.edit(view=self.view) not working with ephemeral messages?
but this would not work because you can only use response one time?
Message has the components attribute in the form of discord.Component objects, which is translated to a View via View.from_message
It's built like this to make sending components a bit easier on the user (e.g. not having to constantly worry about ActionRows)
what is key for?
member.id, member.name etc
all good, you'll probably be interested in reading the other docs for Member https://docs.pycord.dev/en/master/api/models.html#discord.Member
fairenough
I am trying to use pycord extensions, this is the code I am running in the extra file (very simple stuff)
from discord.ext import commands
@commands.command(name='hello', description='test command')
async def hello(ctx):
await ctx.respond(f'Hello {ctx.author.display_name}.')
def setup(bot):
print('โข Loading Discord Bot Code')
bot.add_command(hello)
def teardown(bot):
print('โข Unloading Discord Bot Code')
However I am getting this error when running the main code:
discord.errors.ExtensionFailed: Extension 'modules.discordbot' raised an error: AttributeError: 'Bot' object has no attribute 'add_command
It's pretty much the exact code stated in the docs so i'm a bit confused: https://docs.pycord.dev/en/stable/ext/commands/extensions.html
There comes a time in the bot development when you want to extend the bot functionality at run-time and quickly unload and reload code (also called hot-reloading). The command framework comes with ...
use cogs
There comes a point in your botโs development when you want to organize a collection of commands, listeners, and some state into one class. Cogs allow you to do just that. The gist: Each cog is a P...
Is there a way to hide a regular slash command from user? I have a owner-only command, which only I can execute. It's defined like so:
@discord.slash_command(description="...", hidden=True)
@commands.is_owner()
async def shutdown(self, ctx: discord.ApplicationContext):
await ctx.respond("Shutting down..")
# await ctx.send("Shutting down...")
Log.info(f"Manual shutdown initiated by {ctx.author.name}")
await self.bot.close()
Does hidden=true hide this command from users who cannot execute it?
nope, it only hides it in the help command
Any way of doing so then?
best I can think of is using guild_ids and then tweaking the integration permission system

Is there a way to put the cache on disk, or do a hybrid approch (somme in memory and some in disk) ?
wdym
the cache is save in RAM, is there a way to save it on disk or hybrid ?
for exemple in a database
not that i know of
you'd have to store relevant attributes and reconstruct it, but with how fast the api operates this isn't really worth it
I saw somewhere that you can modify how the cache save and get information, but I cant seem to find how to do it
i mean
"the cache" is basically just several fancy dictionaries mapping IDs to objects
yeah I am in more than a thousand
now I use 1,5 G of ram
surely you could upgrade the server
It is a free bot, I donโt want to pay for a better server ๐
trying to store objects on disk... sure it might have more space, but the loss of speed is very significant; RAM exists for a reason
the fact that you're running a bot with over 1000 servers on a free host is pretty impressive in itself, but realistically you should go for a paid option
chances are it isn't even that expensive
Yeah that is true
I am running it on a raspberry pi
oh wow
The thing is I donโt really need the cache often
Only at the start of the bot, or if the bot loses connection
you could just not use it/disable the intents and use fetches then
what specifically are you dealing with? members? guilds?
I am the guild and member intent yes
so like, what does your bot do?
it creates timed roles. For exemple you can get a server timed role. If a person get that role, it will only be for a limited period of time
I just need to check the cache when I lose connection/start because I miss some "on_member_update" events
so I need to iterate over all member to do that
Ooh so it will not work without the cache at all ?
pretty much yeah
it's possible to disable startup cache and let the cache fill with members naturally after that, but chances are you'll miss initial events
Soo I really need the cache ! But it gets very big pretty quickly!
Hybrid cache would be very nice 
hybrid as in half stale?
Not sure what stale mean, but with some in ram and some in disk
perhaps, but a full implementation of that is very out of the scope of the library
(though if your bot is just for timed roles, do you really need member cache?)
Like you said, I need it for the on_member_update
what are you checking for in member_update tho
for roles changes in members
for exemple user X get a timed role Y, I need to add it in the db
perhaps i don't understand the full scope of your features, but i would approach timed roles just with a task loop and save timestamps in the db to check when to remove a role
you can probably just use audit logs for that?
ahhhh audit log event is only on master but that could work
wait we still havenโt released that ๐
2.4.1 was in like march
that sound like a good idea yes !
we might have a 2.4.2 for pomelo?
no new features tho ig
So I will wait for the feature to be release in that case !
Do you know approximately when it will happen ?
if you want to give it a go:
- install the
masterbranch of py-cord (pip install git+https://github.com/Pycord-Development/pycord) - use the
on_audit_log_entryevent https://docs.pycord.dev/en/master/api/events.html#discord.on_audit_log_entry which gives you anAuditLogEntryobject https://docs.pycord.dev/en/master/api/audit_logs.html#discord.AuditLogEntry
though without the members intent, you might have to use the raw event instead
I see and is it possible to read logs I would have miss if my bot goes down for instance/lose connection
you can fetch existing logs with await guild.audit_logs
which also supports filtering
I see ! what will happen to all the server my bot is in tho ? Because it requires Intents.moderation. Will they all just stop working ?
I dont have that intent activated currently
https://docs.pycord.dev/en/master/api/models.html#discord.Guild.audit_logs
e.g. py async for entry in guild.audit_logs(action=discord.AuditLogAction.ban): print(f'{entry.user} banned {entry.target}')more examples on that doc page
hmm
and the view_audit_log permissions to
i mean, intents.moderation can be enabled freely
and if you can already manage roles, it wouldn't be too unreasonable for server owners to give the bot audit log perms
yes I agree ! But for servers with the bot already in it they wont know that
the bot will just stop working for them
perhaps include it in responses somehow and have a migration period?
yeah that is probably best !
assuming your bot has commands
you can have it check if it has the permission already, and if not add a little note
if you really want, you can iterate through all bot.guilds and check how many servers you'd have the right perms in
yeah and with the migration it would be good, but my bot is mostly you run the command once and never have to do it ever again ahaha
but thanks you so much for your help ! Oh and if you are curious about the bot, the code is even public on github
o cool
Oh and one last question ! How stable is the master branch ? Just to know If I can use it without to much problems
i don't think there are any major issues?
Perfect thank you !
Is it possible to dynamically enable or disable buttons based on the user's roles at the time the message is displayed, making it update dynamically to whoever is seeing the message? Example: the button shows as enabled for users with the "VIP" role but shows as disabled for users without it.
No, but I believe you can do that in code based on the roles of who pressed the button
Ohh, yes, I have been able to do that as response to an interaction.
Thank you for the answer!
Welcome!
Good luck, have a nice day
Thank you, I wish you the same ๐
How does one check if a member is a guild owner?
I'm trying to figure it out with https://docs.pycord.dev/en/stable/api/data_classes.html#discord.Permissions
Some classes are just there to be data containers, this lists them. Unlike models you are allowed to create most of these yourself, even if they can also be used to hold attributes. Nearly all clas...
But I can't find an owner attr
Thx
If I'm making a command to reset a server after it's been raided, is there a chance I'll get rate limited? The command deletes all the channels and roles, and makes general new ones.
I'm going to add a command cooldown per guild so it doesn't get abused, but I'll be testing this command a lot
ehh probably but the library handles most ratelimits
wdym
it'll warn me or something?
if you have WARNING logs in console it will warn you, and it'll queue whatever function that got ratelimited to run when the ratelimit expires
(that being said, chances are if you hit it too much you'll get a harder limit)
how do I get warning logs
Idea:
I use asyncio.sleep within my function to slowly complete tasks so I don't hit a rate limit
would that work, and would it work only for that function?
pycord already handles ratelimits for you
if you mean ratelimits for something else, I have no clue
I kinda don't want to hit the ratelimit at all and would be willing to slow down my code
I'm guessing asyncio.sleep would do the job
you will not get rate limit, only if you're spammer
It's 50 requests per second. If I have 100 members in a server and try to rerole all of them, I'll get rate limited
but if I do that over the course of a couple seconds, I should be fine
see tag 429
What about it? It's basic discord request info
whenever it becomes useful when someone begins reading
wdym
So I made a bot that is supposed to have a "fixed" panel (in the form of an embed) that has two buttons on a channel through the form of a message. At first, it seems like the fixed panel is working as intended, as it does show the first step and responds to the user interacting to the buttons.
However, after just a few minutes, and I really mean a few (less than 5), the bot seems to stop responding to the button interactions. There is no console error, it just shows the "โ This interaction failed " message after around 3 seconds a the user clicking on the button.
I am sending the embed through this simple helper function:
async def send_embed(channel, description, title, icon_url, view):
embed = discord.Embed(description=description, color=discord.Colour(0x313338))
embed.set_author(name=title, icon_url=icon_url)
embed.set_image(url=image_footer_gradient)
await channel.send(embed=embed, view=view)
Did you set the timeout to None?
I had completely forgotten about that, lol. Now I did it and it's working as I intended.
Thank you so much! 
I want the thread creation message not to appear. How can I receive a sent message or disable its appearance?
How do I access the headers in an api call such as TextChannel.edit()? I need the rate limit data
hello i have intresting question
Traceback (most recent call last):
File "C:\Users\misha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "C:\Users\misha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\bot.py", line 1164, in on_connect
await self.sync_commands()
File "C:\Users\misha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\bot.py", line 738, in sync_commands
app_cmds = await self.register_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\misha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\bot.py", line 531, in register_commands
prefetched_commands = await self._bot.http.get_guild_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\misha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\http.py", line 365, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
Mikis is ready and online!
how fix that error
Read the error
invite your bot with the app cmds scope
and re-check your guild ids
^^
hi, how do i get self.bot in a cog when i am not in my commands.Cog class? i am in a discord.ui.Select class
pass it to the class, think of it like it is a ball
srry 4 the explain that will drop ur balls
How can I get bot's permissions inside the code?
get the bot role via discord.Guild.me and see its permissions
.rtfm Guild.me
yeah did it now like that, thanks

interaction.client
use that. simple
if you're not in a callback, just pass it in
personally, I subclass all the ui components and pass it in to all of them and use my ui components instead
I'm using lazy loading and singleton patterns to handle bot and database objects. It's very convenient. For me, at least.
Quick question though.
How to create a prefix command using discord.Bot() and not discord.ext.commands.Bot()?
I don't want to use ext.bridge, because I only need a few prefixed commands. It's mostly slash-based bot.
you can't lol
you would need to use commands.Bot
This is really annoying. You can't hide slash commands and you can't mix them with prefixed
Do users see all slash commands, or only those, which they can use?
That depends on permissions you set
if they've been denied permissions by either default_permissions or Settings > Integrations then they won't see them.
how can i statically get the emoji object of an emoji
what does "statically" mean in this context?
all good, discord.PartialEmoji is what i was looking for
Does anyone have example code for a persistent paginator? I've read that each component needs a customID and that it can be called as a view but I can't find a working example anywhere.
can i possibly hide slash commands from users? like only if the user is the owner of guild or something then they see it
.
what are some breaking changes with the next 2.5 update
I think none
ok cool
okay but what about setting it like for owner of the bot then? what if i want to hide some commands only i can use?
your best bet is to register that command under specific guild(s)
alright, then ill just make one big subcommand and my raise my own error for them
uh there are a few
i made 2 myself ||unless bob decides to revert them ๐ ||
oh yeah client.once is gone (never existed for the stable version people
yea no there is a big breaking change for embeds
Embed.Empty is removed. None is now used
another small one is that view.message is not set when sending the msg using interaction.response.send_message, but rather when interaction is received for the components
have you guys added the global nicknames yet? or am i too late
Hello, I have a slash command with a button that makes a request to a minecraft server and edits the message when clicked.
When the button is clicked, the request is actually made and the message is edited, but after editing, a text appears that says this interaction failed, but the editing had no errors. Do you know why this error happens?
without code we cant do much
how are you editing the message?
@discord.ui.button(label="Ping again", style=discord.ButtonStyle.primary, emoji=":tasks:1234")
async def button_callback(self, button, interaction):
# ...
# ...
embed = discord.Embed(
title=":mc: Minecraft Java Server",
description="Minecraft Server",
color=0x8080ff)
embed.set_thumbnail(url="")
embed.set_footer(text=f"Requested by {interaction.user.name}", icon_url=interaction.user.avatar.url)
embed.timestamp = datetime.datetime.utcnow()
await interaction.message.edit(embed=embed)
yup use interaction.response.edit_response instead
AttributeError: 'InteractionResponse' object has no attribute 'edit_response'
I fixed it using interaction.response.edit_message, anyway thank you Silly Squid
if you were on the latest, pretty sure it is edit_response
glad I could help
nvm it's interaction.edit_original_response
how would i send an embed to someone's dm
if i try using user.send(embed = embed) is says coroutine.send() takes no keyword arguments
did you await it?
yep
user is a self.bot.fetch_user(id)
oh is fetch_user something you have to await
yes
ah my bad then
what's the difference?
if the user is cached it will not make an API call
ah ok
im going to assume it's also awaited because it may have to fetch, which is awaited
yes
works perfectly ๐
tyvm
async def RandomMemory(ctx: discord.ApplicationContext, tag: Option(
str, "Choose a tag", choices=[""]
)):
how do i make the tag optional
whys this not the standard then
like why have different commands for get or fetch if they yeild the same information
Required=False
They do not yield the same information
async def RandomMemory(ctx: discord.ApplicationContext, tag: Option(
str, "Choose a flair", choices=["test"], required=False)):
still doesnt work as optional
get_x methods come from the cache. This stuff is already in memory
fetch_x requests data from the api. This is a much slower process
The objects returned by get methods in many cases have more data (especially when related to guilds and members). This is due to the fact that guild cache is built from the websocket, and not the api
Using fetch methods very frequently can also get you ratelimited
for some reason channel = bot.get_channel(config["balance_channel"]) gives None back though config["Balance_channel"] gives back an integer i just copied from the channel id
is it an integer or a string? recheck that
I want to edit a message but it doesn't work, does anyone have an example code?
async def edit(self, ctx):
msg = await ctx.respond("Original message")
await asyncio.sleep(5)
await msg.edit(content="Edited message")
.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.
ctx.resppnd doesn't return a message object
You have to use ctx.edit
Which is a shortcut for ctx.interaction.original_response iirc
that explained what I want to do in a simple way... but okay
oki doki
yes
Oki doki is so Spanish

anyone got any idea?
Stick to one channel
its an integer
tried both and neither worked for me
its weird cuz with my other projects i do the same thing and works fine
but now suddenly it doesnt find the channel or something
The channel must not be in the cache. You will need to use fetch_channel if get_channel returns None. Note that you should always try get_channel first because it is faster and does not require an API call.
nah fixed it already
i was dumb enough to try and find the channel before bot was started
changed loop to start on bot ready and works
ahh, you still might encounter cache issues later on so keep it in mind :)
Hey there, when i should use defer()
Anytime that you think a command could take over 3 seconds to respond. Some common cases would be editing a image and sending it or accessing a database that might take a bit to return.
lets say you generate an image with some library like easy-pil or pillow then you use File to use the image. Then how can you use that image in an embed? Like set_image wont work because its not an url
?tag localfile
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)```
how can i like get or fetch a message sent by the bot it isnt an interaction and how can i edit it
fetch the message ;3
vague question. It depends on how you sent the message, under what circumstances are you trying to edit the message. We need more information
right so i send the message to a channel using channel.send and i have the messages id, guild id, and channel id
do i need to add file=f in ctx.respond when im sending the embed with image?
No
msg = channel.send() should work?
else you have to get the channel and fetch the message with the id
right, but its giveaways, there will be multiple i need to fetch it or something without having too many api calls so i dont get rate limited
do you need any data from the message object? or you only want to edit/delete the message?
if you dont want the data from it, you can use partial message
.rtfm channel.get_partial_message
if you want to go a step further and not rely on cache at all (not even for channel), see .tag partial
oh sick, so i can just do get_partial_message(id) and i dont need the guild id?
nice got it thanks
how can i check if they're meant to end then
@tasks.loop(minutes=1.0)
async def update_gaw_embed(self):
await self.bot.execute("DELETE FROM giveaways WHERE startTime + duration < (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') - INTERVAL '2 days';")
giveaways = await self.bot.fetch("SELECT channelID, customID, startTime, duration FROM giveaways")
for channel_id, custom_id, start_time, duration_str in giveaways:
channel = self.bot.get_channel(channel_id)
message = channel.get_partial_message(custom_id)
duration_seconds = duration_str.total_seconds()
end_time = start_time + timedelta(seconds=duration_seconds)
if datetime.utcnow() > end_time:
await message.edit(content="The giveaway has ended!")```
Hmm what is wrong with the code you sent?
Does it try to end all old gaws? If yes,
then either delete the gaws from the after they end
Or add an attribute to save whether the bot has ended the gaw or not
it doesn't edit the message, the giveaways are meant to delete automatically with the first query if they are older than 2 days just to be sure
hmm
.tag debug
Please don't post code like this and ask "what's wrong?"
@bot.event
async def on_message(message):
if x == y:
...
if a == b:
...
It can be difficult for us to determine this by just looking at the code, especially as it gets more complex. Are you even getting into this code? What are those values? It's very helpful for you to do some debugging first. Add some print statements to narrow down the problem. Or use your code editor's debugger if it has one.
- Are you even executing the code you think is the problem?
- Are you getting all the way through it? Maybe you're hitting an error you don't see. See
.tag noerrorfor reasons why you wouldn't see a thrown error. - Are the values you're comparing what you expect them to be? Maybe you're forking your code and not executing things because of if statements that don't behave like you assume they do.
Save us and yourself some time by doing some debugging ahead of time. It's much easier to have a discussion around a specific line of code not working as expected than trying to trace through logic (especially if it references variables passed in/out of scope).
I'm struggling to create a forum thread
channel = self.bot.get_channel(channel_id)
await channel.create_thread(name="Thread Name",auto_archive_duration=60)
but its throwing me an exception 400 Bad Request (error code: 50006): Cannot send an empty message
I tried passing in a message parameter but then it says that create_thread() got an unexpected keyword argument 'message'
you know get_channel can be None?
not the issue here
you would need to pass content or embed iirc
.rtfm fourmchannel.create_thread
Target not found, try again and make sure to check your spelling.
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
fourm
aight lemme read the docs real quick
I couldn't find much on forum threads for some reason
sending the embed inside the create_thread worked
now I gotta figure out how to send a message to that newly created thread
applying the same philosophy as a normal message, you would need at least one of content, embed, file or view
not sure if threads are treated any different
create_thread would return the thread object
you can just use the send method on it
r u 100% sure i can edit messages with get partial message?
it will raise an error if message is not found. just like when fetching the message
then i have absolutely no clue, i printed all the values they all returned what they should
i get absolutely no error
hm
end time is correct start time, everything is as it should
does it work with fetch_message + edit ?
i havent tried yet. let me see
nvm ill take a look at it tomorrow, but i dont think it will work since it doesnt work with get partial message
How did you edit it?
What does await ctx.defer() do?
.tias
Its for a slash command if you cannot respond in 3 seconds
Alright
Does Pycord have any support for the new usernames that Discord has rolled out already?
on master? yeah, we're planning for a stable release soon, too.
yea it's looking like user.display_name is showing username over display_name atm
Does user.discriminator return #1234 or 1234?
.tias
and the latter
what is the select parameter type should to be 
discord.ui.Select
what if the view class have more then one select row
bruh, nvm

how to get the member object from selecttype user :>
you don't :)
why ._.
if discord doesn't give us that info
but wut about slash command member option
discord returns the id and the lib returns the obj
get it yourself then
ono
