#Basic Pycord Help (Quick Questions Only)

1 messages ยท Page 81 of 1

normal tusk
#

oki

hushed cargo
#

tyty

normal tusk
hushed cargo
#

is there a way to use on_interaction to get the options of a select menu?

fervent cradle
#

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

vapid pumice
#

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?

full basin
hushed cargo
#

I'm doing it anyways it was the only way

full basin
#

It's not?

#

Subclassing Views exist

fervent cradle
#

yeah basically

#

without really getting rate limited

#

it is unlikely i guess so im fine

full basin
#

Rare that many giveaways end at the same time tbh

fervent cradle
#

yeah i suppose so

proud mason
#

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

fervent cradle
#

oh that is perfect then

grizzled sun
#

how to i get the bot to leave a server?

#

with a command

lethal nexus
#

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

lethal nexus
#

I think that's right, i havent tested it

grizzled sun
#

cool

silver moat
lethal nexus
vapid pumice
# silver moat on_application_command(context)

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

violet silo
#

How can I disable the default help command? (prefix commands)

young bone
violet silo
#

Thanks

fervent cradle
#

what does that mean

young bone
#

Can you show the pip list pls

somber pelican
young bone
#

?

fervent cradle
rare ice
#

nice code

echo oxide
#

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

young bone
#

where is your bot defined?

echo needle
#

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.

full basin
echo oxide
full basin
#

Because it's just a guide to setup logging?

#

It won't tell you the obvious thing to define a bot

young bone
young bone
echo needle
#

lol

#

it will probably get it right

echo oxide
#

i dont understand how my bot is not working after i added logging please can i have real answers not trolling answers

full basin
#

I gave you a real answer

#

Plus the error is obvious

#

You never defined a bot variable

echo oxide
#

the turioral never mentioned anything about defining a bot varible

full basin
#

Because the guide you linked is just how logging should be setup

echo oxide
#

what steps must i take to define my bot varible

full basin
#

The tutorial assumes you have defines a bot and the commands and stuff

#

Read the guide and docs.

echo oxide
#

i used the / command example and it worked but than it showed up a wierd error after i added logging

full basin
#

Do you know python basics?

#

Because you seem lost by simple examples and you don't even know what your code does

echo oxide
#
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

full basin
#

You don't do that.

#

#help-rules

echo oxide
#

im confused i was able to re register the / command and my discord.log text file got updated?

silver moat
#

?tag learnpython

obtuse juncoBOT
#

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.

echo oxide
#

yeah but im looking to learn pycord and im explainging my question as best as i can

silver moat
#

you can't learn pycord with python. It's like trying to learn rocket science without knowing algebra

echo oxide
#

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

full basin
#

You didn't get squid's point.

#

You're trying to run without even knowing how to stand up.

silver moat
#

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.

echo oxide
#

i used bot = discord.Bot(debug_guilds=[1114355858919407676]) and its working so far for me?

full basin
#

But you don't know why.

silver moat
full basin
#

Because you don't understand your code.

silver moat
#

Just blinding copying and pasting code doesn't make you learn anything

echo oxide
#

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

full basin
#

And still not getting the point.

silver moat
silver moat
echo oxide
#

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

full basin
silver moat
echo oxide
silver moat
waxen whale
hushed cargo
# full basin Subclassing Views exist

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

hushed cargo
#

Which onesss? Am I one of the ones you likeee? :0

#

Whaaa wut does that mean- plus answerrr

fervent cradle
#

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 โค๏ธ

normal tusk
#

@fervent cradle discord buttons are limited to 25 button on 5 rows each row has 5 buttons

#

uh

fervent cradle
#

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
normal tusk
normal tusk
fervent cradle
# normal tusk 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'

fervent cradle
#

anyone know?

normal tusk
fervent cradle
#

what is that?

normal tusk
# fervent cradle

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
normal tusk
#

also pass the intents parameter into the discord.Bot like discord.intents.all()

normal tusk
fervent cradle
#

discord dev portal?

normal tusk
fervent cradle
#

just those?

normal tusk
#

yes all of them

fervent cradle
#

and thats it?

fervent cradle
#

what number

normal tusk
#

and make sure to add these to your code instead of the old one


bot = discord.Bot(intents=discord.Intents.all())
fervent cradle
normal tusk
#

or instance wutever

fervent cradle
#

there are the files

normal tusk
fervent cradle
#

ok

#

so that?

normal tusk
#

that's it

fervent cradle
#

now this is the error

normal tusk
#

@fervent cradle this is a variable and its syntax meant to be a class like this

#

nvm

normal tusk
fervent cradle
#

yes

#

bot = discord.Bot(command_prefix="?", activity=activity, status=discord.Status.online)
should that still be there

#

or replaced?

normal tusk
fervent cradle
#

what

#

thats what i have

normal tusk
#

yo

#

you are importing everything from discord ๐Ÿ’€

#

use import discord instead of filling out the IDE with discord classes

fervent cradle
#

so what should i do

#

remove all of that?

normal tusk
#

and not all of the lib

fervent cradle
#

so what should i remove out of that?

normal tusk
normal tusk
normal tusk
fervent cradle
#

i dont know what is needed lol

normal tusk
fervent cradle
#

you able to call

#

and ill ss it

normal tusk
fervent cradle
#

nw

gray juniper
#

What's the error handling thing

#

Im kinda confused

young bone
gray juniper
#

Nvm found a fix

#

I was using on_slash_command_error

#

instead of on_application_command_error

echo needle
#

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.

echo needle
somber pelican
fervent cradle
#

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

echo needle
fervent cradle
somber pelican
#

Uninstall any other libraries which are imported as discord, and install py-cord

somber pelican
fervent cradle
fervent cradle
# somber pelican Pass activity=PresenceClass to bot

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)
proud mason
#

pass the activity classes

#

like

#

.rtfm discord.Game

proud mason
#

or discord.Streaming or discord.CustomActivity

fervent cradle
proud mason
#

you can create the activity object in the same file

#

you dont need to make your own class

fervent cradle
#

okay but i need to get the maintenance value from the bot object that im trying to set it to

proud mason
#

hm

#

and how is the maintenance var's value determined?

fervent cradle
#

maintenance = bot.checkMaintenance() returns true or false

proud mason
#

yk

fervent cradle
proud mason
#

did you add the bot with app cmds scope?

#

also, recheck your guild ids

proud mason
fervent cradle
#

reads a value from a json file, if its 1 means maintenance mode is on it returns true

proud mason
#

of your subclass

#
class MyBot(...):
  def __init__(...):
    maint = self.checkMaintenance()
    if maint:
      act = ...
    else:
      act = ...
    super().__init__(..., activity=act)
#

yk

fervent cradle
#

so i cant set the activity from the main file then or what uve lost me lmao

proud mason
#

any reason to do it only in the main file? i dont see why you cant do it in the file with your subclass

fervent cradle
#

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
fervent cradle
#

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?
proud mason
#

uh no

#

bot.close() is called automatically

#

no need to do it yourself

fervent cradle
#

oh so no need to do that on_disconnect, okay

fervent cradle
#

how do i get the error 50001 to go

dapper pasture
#

why isn't .dark_theme() embed colour invinsible in discord dark theme?

slow halo
#

Does anyone know if there's a way to send out Stuff from a Announcement Channel via Bot? I havenet found anything yet

slow halo
#

oh damn..thanks ๐Ÿ™‚ i've just looked at the channel Section ๐Ÿ˜„

young bone
#

Just use aiohttp

neon prairie
#

download httpx

hushed cargo
#

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-

weak violet
#

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?

proud mason
weak violet
proud mason
#

thats... weird

#

.tag noerror

winter condorBOT
#

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

weak violet
#

Ty Iโ€™ll check it

young bone
#

Did you read the error?

#

Yes

proud mason
#

missing access to add cmds to the server

#

yeah just re-invite the bot with these scopes. no need to kick it

tribal girder
#

a slash option that not written manually by the user, what type of slash option is that? idk the name

still helm
#

How to do this?

#

thats great!

cyan quail
#

(ok it is on API but not implemented yet)

still helm
#

ok thank you !

slow halo
#

Is it normal that message.publish() doesnt publish the Mention, when someone is mentioned?

full basin
#

You could blame discord for that

warm grotto
#

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.

spring hare
#

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

warm grotto
#

Great! Thanks for the info ๐Ÿ™‚

cyan quail
slow halo
fossil mulch
#

sup, how do i properly make my slash commands "fancy"? I thought about using Groups as a first step, is there anything else?

silver moat
#

what's your definition of fancy?

fossil mulch
#

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

silver moat
#

personally I think components like buttons and select menus are under/over utilized

#

and also context menu commands whenever possible

fossil mulch
#

alright, will have a look on them =)

wet coral
#

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.

full basin
#

You can't respond to interactions twice

wet coral
#

I know and I don't (although the code might suggest that, yes) and that wasn't my question.

proud mason
#

but im not sure about the actual answer. you might need to dig through source

wet coral
#

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...

proud mason
wet coral
#

You can actually make it work again by modal._stopped = modal.loop.create_future() I just found out xD

proud mason
#

Hmm the modal might get removed from the internal cache after that tho

#

NGL making a fresh modal will be better

wet coral
proud mason
wet coral
#

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...

proud mason
#

Hmm

#

You could recreate the input texts too

wet coral
#

I just found a refresh_state method in the Inputs, trying that rn

proud mason
#

That's for the interaction iirc

wet coral
#

?

proud mason
proud mason
# wet coral ?

Iirc, refresh_state is called by the library when the user sends the modal

proud mason
wet coral
#

like a copy() ?

proud mason
#

Yeah that works

#

You would need to override the copy method

wet coral
# proud mason 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...

wet coral
#

Btw: Has it always been possible to edit ephemeral messages?

silver moat
#

yes

weak violet
#

tysm

young bone
weak violet
lethal cosmos
#

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.

lethal cosmos
silver moat
lethal cosmos
#

yeap its workin

#

i can finally go to bed

silver moat
#

yay

fossil mulch
# silver moat and also context menu commands whenever possible

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 ...

proud mason
#

Oh yea

fossil mulch
hushed cargo
fervent cradle
#

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

fervent cradle
fossil mulch
fervent cradle
#

whoops

#

yes, that would be correct, autocorrect did me dirty

fervent cradle
#

ah that sucks then

granite stratus
#
@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

silver moat
#

?tag idw

obtuse juncoBOT
#

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.

granite stratus
#

When someone joins nothing happens

silver moat
#

what intents do you have

granite stratus
#

intents = discord.Intents.default()
intents.message_content = True
bot = discord.Bot(intents=intents)

silver moat
#

yeah you also need members intent for these events

granite stratus
#
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)

silver moat
#

could you put a print or something to see if it is even ran?

hushed cargo
#

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
full basin
#

Re-invite it with the correct scopes.

quaint coral
#

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.

hushed cargo
silver moat
wet coral
#

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

wet coral
#

The docstring says this: Returns the client that sent the interaction.
Does the bot send the interaction?

wet coral
#

Ah ok, I though the user that clicked a button or so, is sending the interaction. Thanks ๐Ÿ™‚

quaint coral
wet coral
silver moat
quaint coral
# silver moat try using the `@discord.option` decorator

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 ๐Ÿ˜ฆ

proud mason
quaint coral
errant pewter
#

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"?

silver moat
#

string would return testuser#0

#

display_name would return TestName

#

discriminator would return 0

#

name would return testname

zinc cloak
#

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?

zinc cloak
silver moat
zinc cloak
errant pewter
zinc cloak
#

Is it a pip import error?

#

What are you trying to do

silver moat
zinc cloak
#

Could you paste the pip error in a code block

#

the error

#

if you have a file called os.py or stat.py that you created, it may be creating the error

errant pewter
lethal cosmos
#

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

lethal cosmos
#

ive looked for it before but what it gave me didnt work

normal tusk
zinc cloak
#

Oh yeah, if you're using replit use their package installer

#

You have it open

lethal cosmos
lethal cosmos
normal tusk
lethal cosmos
normal tusk
#

import it and start

lethal cosmos
#

lemme give that a shot

zinc cloak
#

Good

lethal cosmos
zinc cloak
lethal cosmos
zinc cloak
#

Could you send some code

lethal cosmos
#

1๏ธโƒฃ

zinc cloak
#
1๏ธโƒฃ
lethal cosmos
lethal cosmos
zinc cloak
lethal cosmos
#

whats the difference between that and U+ codes

zinc cloak
#

use win+period

zinc cloak
#

win+period returns the unicode form

lethal cosmos
#

weird

#

makes my code look hella scuffed but we ball

#

thankyou

zinc cloak
zinc cloak
#

send code

#

?

#

I mean a code block

#

with the import statement

#

or whatever made the error

#

Oh do you mean within replit's importing?

lethal cosmos
#

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.

zinc cloak
#

that's why

#

do you have the code?

lethal cosmos
zinc cloak
# lethal cosmos
image (Optional[bytes]) โ€“ The cover image of the scheduled event
#

So the image is supposed to be in bytes

lethal cosmos
#

which is weird because when i do sent bytes it doesnt like that either

lethal cosmos
#

lemme try to recreate it

#

only sending the base64_data variable

zinc cloak
#

what's the image type?

lethal cosmos
#

its png

#

i also tried jpg

zinc cloak
#

How are you converting to bytes

lethal cosmos
#
 base64_data = base64.b64encode(image_data)

zinc cloak
#

what is image_data

lethal cosmos
#

just reading from an local image

#

got it

zinc cloak
# lethal cosmos

try this:

            with io.BytesIO() as output:
                image_data.save(base64_data, format="PNG")
                base64_data.seek(0)
#

oh nvm

lethal cosmos
#

i was overthinking it

zinc cloak
lethal cosmos
#

i was too focused on the URI aspect, when all i had to do is send the raw image bytes without b64 encoding

zinc cloak
#

sorry if I confused you even more

lethal cosmos
#

all good, asking questions is half the battle go figuring out that the right solution was alot easier than what i was doing.

cedar bluff
#

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.

zinc cloak
#

there is no ephemeral parameter in ^

cedar bluff
#

So no matter what, it will still reply to itself in ephemerals unless i turn it into a non ephemeral?

zinc cloak
zinc cloak
cedar bluff
#

Ok, thanks!

full basin
raven island
#

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.

full basin
#

Override interaction_check and check if interaction.user equals your ctx author

#

Return True or false accordingly

raven island
#

so like basically i have a persistent view that gets posted to a channel. the thing is, anybody can use the same box.

full basin
#

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?

raven island
#

because its in a channel

full basin
#

If it's directed to a single user who select a category from the above

raven island
#

i didnt think you could send ephemeral in a channel

full basin
#

Does the second dropdown come up if the user selects a category from above?

#

Is that what it does?

raven island
#

correct

full basin
#

Then you can make it ephemeral

raven island
#

you're kidding.

full basin
#

When sending the second select menu

#

Why wouldn't you be ablento?

raven island
#

channel.send doesnt support ephemeral i didnt think? maybe i misread the docs on that one

full basin
#

Why are you using channel.send?

#

If it's from an interaction

#

You have interaction.response.send_message

raven island
#

hmm i see

full basin
#

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

raven island
#

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!

earnest widget
#

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

proud mason
#

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

earnest widget
#

just gona use a normal command then ty

proud mason
granite stratus
#

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)

cyan quail
granite stratus
#

it gives unknown interaction error

#

when i replace send by respond

#

otherwise it works properly

cyan quail
#

you need to defer first

#

it's probably taking too long, so at the start of the command add await ctx.defer()

granite stratus
#

received answer but still thinking

cyan quail
granite stratus
#

No, thank you for your help it's fixed now!

green hinge
#

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")```
green hinge
# cyan quail 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")```
proud mason
#

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

cyan quail
#

well they are using delete_original_response in the new code, but yeah a different name would probably work

green hinge
#

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```
cyan quail
#

no use anything but _parent

#

like idk just call it interaction

green hinge
#

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```
proud mason
#

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

green hinge
#

Okay works. Thanks! ๐Ÿ™‚

candid coral
#

How can I turn off the message about creating a thread?

hushed cargo
#

how do i get ctx in on_member_join?

candid coral
hushed cargo
#

nvm im dum i got it ๐Ÿ˜ญ

candid coral
hushed cargo
#

Yis

proud mason
midnight torrent
#

For some reason ctx.send and ctx.respond differe when it comes to emojis

#

my variable for my emoji is set to self.tick = "![tick](https://cdn.discordapp.com/emojis/1074481381297631262.webp?size=128 "tick")"

silver moat
midnight torrent
#

this message was sent in a channel with the same perm levels with VARIABLE.send

silver moat
#

confirm that the emoji is correct?

midnight torrent
#

i have

#

works with my other emoji

mossy holly
#

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 ๐Ÿ‡ซ๐Ÿ‡ท

silver moat
#

so if the emoji is in server a, the bot is also in server a?

midnight torrent
#

yeah

mossy holly
#

lmao emojis time it seems

midnight torrent
#

top is with ctx.respond
bottom is with ctx.send

#

thats odd

#

same server, bot is allowed to use external emojis

silver moat
#

send code?

midnight torrent
#

or does it have to be the EXACT same and not a mutual?

#

i thought bots could pull emojis from other servers

silver moat
silver moat
midnight torrent
#

it is

silver moat
#

respond works because technically it is a webhook which can use emojis from anywhere

midnight torrent
silver moat
#

what is bot.self.cross?

midnight torrent
#

i can get an Emoji object via the id right?

silver moat
#

you can get a partial emoji from that

midnight torrent
#

im guessing get_emoji()

silver moat
#

could you check if the emoji is the bot's cache: bot.emojis?

midnight torrent
#

yeah one sec

#

there is nothing in the cache

silver moat
#

what are your intents?

midnight torrent
#

since its a comissioned bot, i put all

silver moat
#

ok and I'm assuming that bot event loop thing doesn't cause any problems

midnight torrent
#

nah, its just so if i want to run smth on the same event loop without creating a task with the bot

mossy holly
silver moat
#

@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?

midnight torrent
#

yeah one sec

silver moat
mossy holly
#

and it's flags

midnight torrent
#

its in the same server as the emojis in

#

but im using it from another server

silver moat
#

ok, but like is the ID and everything correct

midnight torrent
#

yeah

#

emoji is in server a and bot is in server a but i want to use it in server b

#

with the bot

#

tick this is the emoji

silver moat
#

!tick this is the emoji

midnight torrent
#

waaaait whaaattt

silver moat
#

the ID you have is incorrect

midnight torrent
#

i swear i copied the id

silver moat
#

copy ID copies the message ID

midnight torrent
#

oh ffs

silver moat
#

you should do \:emoji:

#

instead

midnight torrent
#

that gives the id?

silver moat
#

that gives the emoji string

midnight torrent
#

i thought that just turned the emoji into the unicode eqiv

silver moat
#

for example doggokek

midnight torrent
#

oh shit

silver moat
midnight torrent
#

oh wait no

#

the id is right

#

its not the default tick

silver moat
#

what default tick

midnight torrent
#

โœ…

#

oh that isnt even called tick

candid coral
silver moat
midnight torrent
#

hold on

#

god, someone get me away from programming

#

it uhhh

#

the bots in the wrong server

#

BRUH

#

christ im sorry lmao

silver moat
#

literally first thing I asked you

midnight torrent
#

but i guess, my brain skipped thinking to check

silver moat
#

average human brain moment

midnight torrent
#

im gonna go cry

#

thanks for taking the time to help my dumb ass

silver moat
#

k

pseudo surge
#

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.

silver moat
pseudo surge
silver moat
pseudo surge
#

Ugh ok

fervent cradle
#

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.

silver moat
fervent cradle
#

ah thank you !

chrome skiff
#

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

young bone
#

interaction.response.edit_message()

chrome skiff
wet coral
#

Are discord.ui.Views only used by pycord internally to handle components or are they actual parts of the discord api?

young bone
#

Pycord

#

Why do you ask?

wet coral
#

Because I wondered why the discord.Message does not have a view attribute.

young bone
chrome skiff
young bone
#

Is the modal at a view class?

chrome skiff
young bone
#

interaction.response.send_modal(the modal)?

chrome skiff
#

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

young bone
#

For it would be
interaction.response.edit_message(view=self)
interaction.response.send_modal()

chrome skiff
#

and its now working

#

is await interaction.message.edit(view=self.view) not working with ephemeral messages?

chrome skiff
young bone
#

Remove the .view

#

Just do self

cyan quail
wet coral
#

what is key for?

cyan quail
#

member.id, member.name etc

#

fairenough

lethal nexus
#

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
full basin
#

use cogs

tropic pecan
#

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?

silver moat
tropic pecan
#

Any way of doing so then?

silver moat
tropic pecan
undone falcon
#

Is there a way to put the cache on disk, or do a hybrid approch (somme in memory and some in disk) ?

undone falcon
# cyan quail wdym

the cache is save in RAM, is there a way to save it on disk or hybrid ?

#

for exemple in a database

cyan quail
#

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

undone falcon
#

I saw somewhere that you can modify how the cache save and get information, but I cant seem to find how to do it

cyan quail
#

i mean

#

"the cache" is basically just several fancy dictionaries mapping IDs to objects

undone falcon
#

yeah I know, it just takes to much memory

#

I have very limited ram

cyan quail
#

...it can't be that bad?

#

unless you're in like hundreds of servers

undone falcon
#

now I use 1,5 G of ram

cyan quail
#

surely you could upgrade the server

undone falcon
#

It is a free bot, I donโ€™t want to pay for a better server ๐Ÿ˜‚

cyan quail
#

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

undone falcon
#

I am running it on a raspberry pi

cyan quail
#

oh wow

undone falcon
#

The thing is I donโ€™t really need the cache often

#

Only at the start of the bot, or if the bot loses connection

cyan quail
#

you could just not use it/disable the intents and use fetches then

#

what specifically are you dealing with? members? guilds?

undone falcon
#

I am the guild and member intent yes

cyan quail
#

so like, what does your bot do?

undone falcon
#

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

cyan quail
#

hmm so one problem

#

on_member_update is already cache reliant

undone falcon
#

Ooh so it will not work without the cache at all ?

cyan quail
#

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

undone falcon
#

Soo I really need the cache ! But it gets very big pretty quickly!

#

Hybrid cache would be very nice 02meh

silver moat
undone falcon
cyan quail
#

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?)

undone falcon
#

Like you said, I need it for the on_member_update

cyan quail
#

what are you checking for in member_update tho

undone falcon
#

for roles changes in members

#

for exemple user X get a timed role Y, I need to add it in the db

cyan quail
#

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

silver moat
#

you can probably just use audit logs for that?

cyan quail
#

ahhhh audit log event is only on master but that could work

silver moat
cyan quail
#

2.4.1 was in like march

undone falcon
cyan quail
#

we might have a 2.4.2 for pomelo?

silver moat
undone falcon
#

So I will wait for the feature to be release in that case !

#

Do you know approximately when it will happen ?

cyan quail
#

though without the members intent, you might have to use the raw event instead

undone falcon
cyan quail
#

you can fetch existing logs with await guild.audit_logs

#

which also supports filtering

undone falcon
#

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

cyan quail
#

hmm

undone falcon
#

and the view_audit_log permissions to

cyan quail
#

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

undone falcon
#

the bot will just stop working for them

cyan quail
#

perhaps include it in responses somehow and have a migration period?

undone falcon
#

yeah that is probably best !

cyan quail
#

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

undone falcon
#

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

cyan quail
#

o cool

undone falcon
#

Oh and one last question ! How stable is the master branch ? Just to know If I can use it without to much problems

cyan quail
#

i don't think there are any major issues?

undone falcon
#

Perfect thank you !

quaint coral
#

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.

zinc cloak
quaint coral
zinc cloak
#

Good luck, have a nice day

quaint coral
zinc cloak
#

But I can't find an owner attr

zinc cloak
#

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

cyan quail
#

ehh probably but the library handles most ratelimits

zinc cloak
#

it'll warn me or something?

cyan quail
#

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)

zinc cloak
#

how do I get warning logs

zinc cloak
#

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?

silver moat
#

pycord already handles ratelimits for you

#

if you mean ratelimits for something else, I have no clue

zinc cloak
#

I'm guessing asyncio.sleep would do the job

normal tusk
zinc cloak
#

but if I do that over the course of a couple seconds, I should be fine

zinc cloak
normal tusk
quaint coral
#

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)
young bone
quaint coral
candid coral
#

I want the thread creation message not to appear. How can I receive a sent message or disable its appearance?

mortal cairn
#

How do I access the headers in an api call such as TextChannel.edit()? I need the rate limit data

novel yacht
#

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

proud mason
#

and re-check your guild ids

novel yacht
#

etc

proud mason
wind jay
#

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

normal tusk
#

srry 4 the explain that will drop ur balls

tropic pecan
#

How can I get bot's permissions inside the code?

normal tusk
winter condorBOT
wind jay
normal tusk
proud mason
#

use that. simple

silver moat
#

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

tropic pecan
#

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.

silver moat
#

you would need to use commands.Bot

tropic pecan
#

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?

full basin
#

That depends on permissions you set

cyan quail
tropic pecan
#

Interesting.. I'll read the docs about it

#

Thanks ๐Ÿ‘

fervent cradle
#

how can i statically get the emoji object of an emoji

silver moat
fervent cradle
#

all good, discord.PartialEmoji is what i was looking for

pseudo surge
#

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.

fervent cradle
#

can i possibly hide slash commands from users? like only if the user is the owner of guild or something then they see it

zinc cloak
#

what are some breaking changes with the next 2.5 update

silver moat
zinc cloak
#

ok cool

fervent cradle
# silver moat .

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?

silver moat
fervent cradle
#

alright, then ill just make one big subcommand and my raise my own error for them

proud mason
#

i made 2 myself ||unless bob decides to revert them ๐Ÿ’€ ||

silver moat
proud mason
#

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

fervent cradle
#

have you guys added the global nicknames yet? or am i too late

copper pine
#

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?

fervent cradle
#

without code we cant do much

silver moat
copper pine
#
@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)

silver moat
copper pine
#

I fixed it using interaction.response.edit_message, anyway thank you Silly Squid

silver moat
#

glad I could help

#

nvm it's interaction.edit_original_response

elfin dagger
#

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

silver moat
#

did you await it?

elfin dagger
#

yep

silver moat
#

what is user?

#

how is it defined

elfin dagger
#

user is a self.bot.fetch_user(id)

silver moat
#

and that's not awaited

#

await it

elfin dagger
#

oh is fetch_user something you have to await

silver moat
#

yes

elfin dagger
#

ah my bad then

silver moat
#

yay

#

also consider using bot.get_or_fetch_user

elfin dagger
#

what's the difference?

silver moat
#

if the user is cached it will not make an API call

elfin dagger
#

ah ok

#

im going to assume it's also awaited because it may have to fetch, which is awaited

elfin dagger
#

works perfectly ๐Ÿ‘
tyvm

earnest widget
#

async def RandomMemory(ctx: discord.ApplicationContext, tag: Option(
str, "Choose a tag", choices=[""]
)):

how do i make the tag optional

earnest widget
proud mason
earnest widget
# versed fern Required=False

async def RandomMemory(ctx: discord.ApplicationContext, tag: Option(
str, "Choose a flair", choices=["test"], required=False)):

still doesnt work as optional

proud mason
#

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

fervent cradle
#

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

proud mason
#

is it an integer or a string? recheck that

true pewter
#

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")
proud mason
#

.idw

winter condorBOT
#

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.

full basin
#

ctx.resppnd doesn't return a message object

#

You have to use ctx.edit

#

Which is a shortcut for ctx.interaction.original_response iirc

true pewter
full basin
#

Oh yes lmao

true pewter
full basin
#

Oki doki is so Spanish

true pewter
full basin
#

Stick to one channel

fervent cradle
#

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

grizzled sentinel
fervent cradle
#

i was dumb enough to try and find the channel before bot was started

#

changed loop to start on bot ready and works

grizzled sentinel
#

ahh, you still might encounter cache issues later on so keep it in mind :)

coarse cargo
#

Hey there, when i should use defer()

grizzled sentinel
#

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.

signal topaz
#

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

silver moat
#

?tag localfile

obtuse juncoBOT
#
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)```
fervent cradle
#

how can i like get or fetch a message sent by the bot it isnt an interaction and how can i edit it

silver moat
fervent cradle
#

right so i send the message to a channel using channel.send and i have the messages id, guild id, and channel id

signal topaz
full basin
#

No

young bone
#

else you have to get the channel and fetch the message with the id

fervent cradle
#

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

proud mason
#

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

proud mason
#

if you want to go a step further and not rely on cache at all (not even for channel), see .tag partial

fervent cradle
#

oh sick, so i can just do get_partial_message(id) and i dont need the guild id?

#

nice got it thanks

coarse cargo
#

There are some examples of how to use paginator?

#

Nvm on the docs there is one

fervent cradle
# proud mason if you want to go a step further and not rely on cache at all (not even for chan...

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!")```
proud mason
#

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

fervent cradle
winter condorBOT
#

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.

  1. Are you even executing the code you think is the problem?
  2. Are you getting all the way through it? Maybe you're hitting an error you don't see. See .tag noerror for reasons why you wouldn't see a thrown error.
  3. 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).

halcyon gorge
#

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'

young bone
#

you know get_channel can be None?

proud mason
#

not the issue here

proud mason
#

.rtfm fourmchannel.create_thread

winter condorBOT
#

Target not found, try again and make sure to check your spelling.

silver moat
#

fourm

halcyon gorge
#

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

proud mason
#

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

proud mason
#

you can just use the send method on it

halcyon gorge
#

ty

#

was doing await thread = create_thread and not thread = await create_thread

silver moat
#

lmao what

#

glad it works now

fervent cradle
proud mason
#

yep

#

.rtfm partialmessage.edit

winter condorBOT
proud mason
#

it will raise an error if message is not found. just like when fetching the message

fervent cradle
#

then i have absolutely no clue, i printed all the values they all returned what they should

#

i get absolutely no error

proud mason
#

hm

fervent cradle
#

end time is correct start time, everything is as it should

proud mason
#

does it work with fetch_message + edit ?

fervent cradle
#

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

livid wolf
#

What does await ctx.defer() do?

young bone
livid wolf
#

sigh

#

I am using it

young bone
#

Its for a slash command if you cannot respond in 3 seconds

livid wolf
#

Alright

halcyon gorge
#

Does Pycord have any support for the new usernames that Discord has rolled out already?

silver moat
halcyon gorge
#

yea it's looking like user.display_name is showing username over display_name atm

lethal nexus
#

Does user.discriminator return #1234 or 1234?

silver moat
#

and the latter

lethal nexus
#

thanks anyway <3

normal tusk
#

what is the select parameter type should to be mr7mbolh

normal tusk
#

bruh, nvm

#

how to get the member object from selecttype user :>

silver moat
normal tusk
silver moat
#

if discord doesn't give us that info

normal tusk
#

discord returns the id and the lib returns the obj

silver moat
#

get it yourself then

normal tusk
normal tusk