#Basic Pycord Help

1 messages · Page 16 of 1

frail basin
#

im not entirely sure why nothing before self.stop runs

vivid crag
shell radish
#

do you have an on_interaction event anywhere?

vivid crag
#

moved to #1180075454766522409

deft kestrel
#

Which one is better to use?
channel.edit(category=...)
or
channel.move(category=...)

i believe the ratelimit is 1 edit / 10 minutes, could channel.move go around that?

shell radish
#

iirc move is just a specific use case for edit

hushed rivet
#

is this a known issue, or am i doing smth wrong?

lofty parcel
shell radish
#

but messages is covered with default

shell radish
hushed rivet
#

wait so should i be using intents.messages?

shell radish
#

if you would like to not have a warning, you can use discord.Intents(…, message_content = true)

shell radish
hushed rivet
#

going well, havent had much time recently tho cause school exists

young skiff
#

How can I detect when a sent message is responding to a message sent by the bot?

lofty parcel
#

.rtfm Message.reference

shell radish
#

depending on the specifics, you may want on_message or wait_for

slender surge
#

so a user can add a specific time into a databse with a command, for example they input 2 days, how can i make it then send an alert when the 2 days have passed and it counts down?

lapis dock
#

Use tasks with the end time argument

harsh gust
#

i want to disable/enable buttons with conditions

#

how can i do that

lofty parcel
harsh gust
#

i want to make a view where it has 2 buttons. i have a secret number and i need to guess it. if my guess > secret number then i want to make the button 1 enabled and the button 2 disabled and vice versa

wooden yew
#
      aiohttp/_websocket.c(1475): warning C4996: 'Py_OptimizeFlag': deprecated in 3.12
      aiohttp/_websocket.c(3042): error C2039: 'ob_digit': is not a member of '_longobject'
      C:\Users\SkyMo\AppData\Local\Programs\Python\Python312\include\cpython/longintrepr.h(87): note: see declaration of '_longobject'
      aiohttp/_websocket.c(3097): error C2039: 'ob_digit': is not a member of '_longobject'
      C:\Users\SkyMo\AppData\Local\Programs\Python\Python312\include\cpython/longintrepr.h(87): note: see declaration of '_longobject'
      aiohttp/_websocket.c(3238): error C2039: 'ob_digit': is not a member of '_longobject'
      C:\Users\SkyMo\AppData\Local\Programs\Python\Python312\include\cpython/longintrepr.h(87): note: see declaration of '_longobject'
      aiohttp/_websocket.c(3293): error C2039: 'ob_digit': is not a member of '_longobject'
      C:\Users\SkyMo\AppData\Local\Programs\Python\Python312\include\cpython/longintrepr.h(87): note: see declaration of '_longobject'
      aiohttp/_websocket.c(3744): error C2039: 'ob_digit': is not a member of '_longobject'
      C:\Users\SkyMo\AppData\Local\Programs\Python\Python312\include\cpython/longintrepr.h(87): note: see declaration of '_longobject'
      error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Tools\\MSVC\\14.38.33130\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2
      [end of output]

Receiving this error for aiohttp when trying to install py-cord with pip install py-cord

little cobalt
wooden yew
#

its the version of aiohttp its trying to download

#

I just downloaded latest no issues.

#

Yeah the latest CPP buildtools does not support the methods the old version of aiohttp is using

glad garnet
lofty parcel
harsh gust
#

oh alr ty

minor meteor
#

await paginator.edit(ctx.message) does nothing

#

pls help

deft kestrel
minor meteor
deft kestrel
#

Why would that be obvious from 1 line?

shell radish
minor meteor
little cobalt
#

pls dont crosspost

round roost
round heart
round heart
# minor meteor and... how?

As long as you have access to the paginator view, the .update() method, passing in the current interaction from your callback.

That may mean your other UI classes, such as custom dropsdowns, need to be passed in your view in its constructor. Without code, nobody can help further, though.

minor meteor
round heart
#

Part of your issue will be your localized callbacks. I tried to do this at first, too... it just doesn't work very well. Save yourself some headache and pull them out to top-level methods.

#

Although/Alternatively, I'd highly recommend turning this whole thing into a series of classes. Like your dropdown would subclass discord.ui.Select and you'd send your parent view in the constructor, and can define your callback within it (where the callback would access self._view or whatever you've defined it as)

minor meteor
round heart
#

...oh. This goes beyond my ability to assist 😅
You have method definitions (e.g. weapon_part_inspection_callback) within your top-level invocation method (workshop). I had trouble using UI functionality with methods defined that way, and moved them to top-level (i.e. at the same 'indent level' as workshop)

minor meteor
round heart
#

I mean.. you can argue about it, or you can accept it. I chose to accept it. 🙂
(Although I moved my UI structures into classes, which helped for most of the internal stuff)

late slate
#

Anyone know why I might be getting this error on startup? On Windows 11 with Python 11.6

ERROR: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1006)')]
obsidian blaze
#

How would I add a reaction to a webhook that the bot sends?

await webhook.send(content=mention, embed=embed)

round heart
lofty parcel
#

Wait for the message back. With wait=True

obsidian blaze
young skiff
#

Is it possible to obtain the id of the user who invited the bot to a server?

hushed rivet
#

^ great question, idt its possible

#

ive wanted to know for a long time, but couldnt find any docs :(

cold wyvern
#

OK. Weird question. Is it possible to have a bot also open to HTTP requests similar to a flask server. I need it for interacting with an external OAuth2 service.

little cobalt
cold wyvern
#

Well yeah, but I don't think you can run a flask app concurrently with a pycord bot? Of am I wrong?

#

In the same script

little cobalt
#

flask support async

cold wyvern
#

Interestingly. I was under the impression that asyncio bot.run() blocked out anything else

little cobalt
#

or you start it at the on_ready event

cold wyvern
#

Interesting. Thanks.

shell radish
shell radish
#

or when your bot joins a new guild, check the audit log

minor meteor
hazy turret
#

Can I also embed a video from Youtube into my embed like Discord does automatically when I send a Youtube link into a channel?

swift gust
#

does the async def on_member_join apply for bots too? like if a bot joins?

swift gust
#

hm interesting

hazy turret
#

If you want to exclude bots, you have to check in the function whether the member is a bot or not and then say that nothing should happen with bots.

swift gust
#

no i need it to work with bots lmfao, im gonna open a thread

hazy turret
lofty parcel
#

You can't embed videos.

hazy turret
#

Okay so this is just an internal function of Discord itself?

lofty parcel
#

Mhm

hazy turret
# lofty parcel Mhm

Then I can only work with the thumbnail and put the link in the embed that takes you directly to the video, right?

cursive swallow
#

Yes

grizzled loom
#

Is it possible to make a slash command that is only availible to a specific server but have all other commands global?

cursive swallow
#

Yes, add guild_ids to the cımmand

autumn gust
#

hey, how do I install discord package again?

lofty parcel
#

pip install py-cord-dev

autumn gust
#

ty

#

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for multidict
Failed to build aiohttp frozenlist multidict
ERROR: Could not build wheels for aiohttp, frozenlist, multidict, which is required to install pyproject.toml-based projects
autumn gust
#

uhhh

#

I think so

#

latest, at least

#

or I think latest

lofty parcel
#

Aiohttp doesn't support python 3.12

autumn gust
#

ah

#

downgrade to 11?

lofty parcel
#

Indeed

autumn gust
#

11.6 is fine?

lofty parcel
#

Yes

grizzled loom
deft kestrel
#

i added this:

super().__init__(timeout=None)

and its still doesnt work after a restart

lofty parcel
#

Because you have to add the view again on on_ready

#

.rtfm Bot.add_view

deft kestrel
#

ok thanks

ivory meadow
#

How do I catch the event when the container stops in order to properly shut down the bot? Close all connections, unload all

sterile rampart
#

so everything works but

#

the buttons dont work after 180seconds

#

(timeout)

#

and i tried putting in "timeout=None"

#

but dont know where i have to put it exact´ly

little cobalt
sterile rampart
#

at

little cobalt
#

I see at the buttons

sterile rampart
#

async def Button(label,style)

sterile rampart
little cobalt
#

remove it x3

#

It has to be at the view class

sterile rampart
#

okay thanks

#

tried that but not like you did

little cobalt
#

I just did a screenshot from a example at github

sterile rampart
#

like this?

little cobalt
#

yus

sterile rampart
#

ty

lapis pollen
#

is anyone else experiencing rate limits? i cant even get my bot online

little cobalt
lapis pollen
little cobalt
shell radish
shell radish
# lapis pollen

it likely your host's issue. I recommend contacting their support for more information regarding ratelimits, or you can just wait it out since they usually last around an hour

pliant tusk
#

can I convert a discord.ext.commands.Context or a discord.commands.ApplicationContext into a bridge.Context without knowing which type it is?

pliant tusk
#

I want to resolve on_command_error and on_application_command_error with one function

little cobalt
#

Do you use bridge commands?

pliant tusk
#

yes

little cobalt
#

Do you have the version py-cord or py-cord-dev?

pliant tusk
#

anyways i fixed it by just using on_bridge_command_error instead

little cobalt
solid sapphire
#

Hi! How can I make VoiceChannel nsfw (age-restricted)?

glad spoke
#

await channel.edit(nsfw=True)

little cobalt
#

Keep in mind that you get really fast a ratelimit if you edit a channel

#

I think is only 1 or 2 every 10 Minutes

sour widget
#

I use bot.get_user(int(user_id)) to send message in DM, but got None. don't understand why. What should I do?

limber wagonBOT
#

Any function that starts with get_ in Py-cord is retrieving the related object from your bots cache. If the object is not in the bots cache the get_ method will return None. Because of this behavior you should check if the get_x method is None and if it is use the fetch_x method.

Why Is Using fetch_ Without Using get_ First Bad?
The fetch_ method makes a call to the discord API. This API call is unneeded if you already have the information. It will also make your command take longer because it will have to send and than wait for a response from the discord API. It will also contribute to the discord APIs global rate limit of 50 requests per second.

What Is Cache?
The cache is a temporary storage inside your bot. It holds many objects from members to messages. When you restart your bot the cache will be empty. When the cache is full it will delete older objects to make space for the new objects.

sour widget
#

thanks

burnt gorge
#

hey there, how do I get a list of all application commands? Apologies if it's been asked before

young skiff
#

the bot respond <discord.embeds.Embed object at 0x7f31f7869090>

little cobalt
#

or embed = response.get()

young skiff
#

thank you

young skiff
little cobalt
rugged lodgeBOT
shell radish
#

@burnt gorge ^

burnt gorge
burnt gorge
#

@shell radish apparently that method doesn't exist with AutoShardedBot?

pine yacht
#

How can I set a rate limit on a button in a view?

swift gust
#

im on a time schedule here,

what is the permission for managing members?

@command.has_permissions()

lofty parcel
#

managing members as in?

#

theres no specific "manage members" permission in discord

swift gust
#

oh LOL

#

so what would the ban permission be?

lofty parcel
#

ban_members

swift gust
#

cherrs

#

cheers

brave arch
#

is there a py-cord version that is compatible with aiohttp==3.9.0? pip complains that py-cord-dev==2.5.0rc5 requires version lower than 3.9.0, and i don't see any higher version for py-cord anywhere

#

i guess i could install from git commit, but i'd appreciate if there would be some other option

green kernel
#

How can I make a slash command available in DMs?

#

Ooh, I see.. The issue is that I have debug_guilds

bright cobalt
#

can you only assign one server to guild_ids?

shell radish
bright cobalt
#

oh nvm i accidently had an extra number

#

ty tho

#

oh another questions is there a way for that to not show up when u are using send and not respond

hollow dust
#

I'm getting this again and again

#

what do I do?

glad spoke
glad spoke
bright cobalt
glad spoke
bright cobalt
#

oh ic ty

hollow dust
#

found out it was of python version

low grail
#
from discord.ext import commands

bot=commands.Bot(command_prefix='.')

@bot.event
async def on_ready():
    print("BOT is ready")

@bot.command()
async def test(ctx):
    await ctx.send("Hello")

bot.run("")

idk why the command is not responding...

little cobalt
little cobalt
low grail
#

like how do I do that>

little cobalt
#

?tag intents

limber wagonBOT
#

Pycord Docs - Intents
Discord API Docs - Gateway Intents

import discord
from discord.ext import commands

# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True  # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content 
intents = discord.Intents.default()

# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True  # Required for prefix commands >= 2.0.0b5

# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()

# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
low grail
#

thanks I got it

deft kestrel
#

somebody can help me making invite tracker?

lapis dock
loud kayak
#

Is it possible to create sub group like you can with slash commands? So I can do something like !templates webhooks create?

#

Nvm docs says so

deft bronze
#

What's the documentation link for that sort of "form" a bot can give you?

rugged lodgeBOT
#

Here's the modal dialogs example.

autumn gust
#

any idea how to fix this?

little cobalt
autumn gust
little cobalt
#

uninstall pycord

autumn gust
little cobalt
#

install py-cord-dev

obsidian blaze
#
x = await ctx.respond(file=image_file, view=view)
print(x.id)```

This is how I would print the id of the message it sends correct?
deft bronze
shell radish
little cobalt
deft kestrel
#

hey im a little stupid can someone show me where my callback is at?

#
class Roles(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
    @discord.ui.button(label="RP Notified", custom_id="RP Notified", style=discord.ButtonStyle.secondary)
    async def button1(self, interaction: discord.Interaction, button: discord.ui.Button):
        role = 1183151145129095228
        user = interaction.user
        if role in [y.id for y in user.roles]:
            await user.remove_roles(user.guild.get_role(role))
            await interaction.respond.send_mesage("You have removed the role RP Notified", ephemeral=True)
        else: 
            await user.add_roles(user.guild.get_role(role))
            await interaction.response.send_message("You have added the role RP Notified", ephemeral=True)
#

someone said my callback arguments are swapped and I need to know where they are at to have them in the correct order

young skiff
#

i'm using ```py
await bot.change_presence(activity=discord.CustomActivity(name="status", emoji='📜'), status=discord.Status.online)

but the emoji is not showing in the status
shell radish
deft kestrel
shell radish
#

yes, button then interaction

deft kestrel
deft kestrel
shell radish
#

you forgot a comma

#

after Button and before interaction

deft kestrel
frail basin
#

i dont think python likes having both py-cord and py-cord-dev

azure sable
#

Is there a quick way to check if a bot is already in a vc and retrieve the vc object? I'm having some cases where my bot crashes and re-launches, but discord isn't kicking the bot from the VC

#

I'm in the process of making the crashes in question more graceful, but if there's a way to do this I'd be interested

autumn gust
#

sorry I got dragged away yesterday

#

I like that style

deft bronze
#

What's this lol

autumn gust
#

so, any idea how to fix this

#

I've installed it and it still says it's missing

deft bronze
#

You probably didn't

#

didn't correctly

autumn gust
#

apparently for C# rather than for C++

#

rn throwing shit at the wall and seeing what sticks

deft bronze
#

Then is not what you need

autumn gust
#

not this?

deft bronze
#

Idk, try

autumn gust
#

wait...

#

OH

#

I KNOW WHY

#

I FUCKING FORGOT TO DOWNGRADE PYTHON

#

RIGHT

#

I WAS GONNA DO THAT LIKE 2 WEEKS BACK BUT GOT DRAGGED AWAY

#

I feel dumb

deft bronze
#

You don't need to do that

autumn gust
#

I have 3.12

#

lol

deft bronze
#

but hope you fix it

#

oh maybe its that ye

#

3.12 buggy with libs

autumn gust
#

let me cook

#

how do you uhh uninstall python again

#

nvm

#

I assume 3.11.7 would be fine?

deft bronze
#

i use 3.11.4

autumn gust
#

maybe I need sleep

deft bronze
#

That's not the lib name

#
py-cord-dev
autumn gust
#

okay fixed it

autumn gust
#

I flipped cord and dev around

valid panther
#

in method, i can put multiple value in Option type?

role: Option(discord.Role, "Role to exempt", required=False, max_value=2)
valid panther
#

max_value is only for int and float

shell radish
#

Try using a role select menu

valid panther
# shell radish depends

the idea is to be able to have the user mention all the roles he wants, i.e. a list of discord.Role

valid panther
# shell radish Try using a role select menu

You are looking at doing it this way

    @option(name="channel", description="Channel to configure the auto mod", type=discord.TextChannel, required=True)
    @option(name="hours", description="Time to timeout the user (hours)", type=int, required=True)
    @discord.ui.role_select(
        placeholder="Choose the roles to exempt",
        min_values=1,
        max_values=10
    )
    async def auto_mod(self, ctx, channel: discord.TextChannel, hours : int, role: discord.Role):
little cobalt
valid panther
little cobalt
#

That is not how you use a select menu

deft kestrel
#

py-cord-dev has pycord voice too?

deft kestrel
#

thanks

hazy turret
#

Can I use an emoji that I have uploaded to server 1 with my bot and then find it in the bot and get it back correctly with the name and ID on another server 2 in a message so that it is displayed correctly there and not just the emoji name?

#

Ich hole mir das Emoji so von meinem Server 1

emoji = discord.utils.get(guild.emojis, name=emoji_str)```

And if I then send it to server 2 as a message, only the name of the emoji is displayed but not the emoji I fetched from server 1
#

Can't I just display this as a f string in an embed in a field?

f"{emoji}"```
Because when I add the emoji to a button, it doesn't work with my embed in the field
hazy turret
hazy turret
#

Oh nvm had set the authorization for the channel incorrectly🤦🏼‍♂️

agile oar
#

Is the cause of all the Unknown Interaction & Unknown Message errors within my views a result of me not responding fast enough?

frail basin
#

yes

#

iirc its 3 seconds

#

you could defer it tho and then just send a follow up later

agile oar
#

But im not sure if i instantly defer or do something in between. Need to check

deft kestrel
#

yo i have this error:

Exception has occurred: AttributeError
'Bot' object has no attribute 'remove_command'
  File "C:\Users\Assaf Cohen\Desktop\bot\python\bot.py", line 41, in <module>
    bot.remove_command('help')
AttributeError: 'Bot' object has no attribute 'remove_command'
soft hedge
#

my bot keeps going offline after running tasks.loop once and then is unresponsive to any other commands why does this happen

minor crescent
soft hedge
soft hedge
#

I'm currently on my phone and can't take my pc rn can I send it later?

minor crescent
#

is it possible to send a paginated embed in a DM without a ctx? I'm running a task loop and I'm trying to send a paginated embed

deft bronze
#

Im doing this and i want to get all the context after the command, how can i do a separator to include pages

lofty parcel
#

Just switch the arguments.

deft bronze
#

alr

civic plume
#

Why is my command name not updating?

@discord.slash_command(name = 'hastebin', description = 'Upload your text to Hastebin. Useful for sharing code.')
    async def modal_slash(self, ctx: discord.ApplicationContext):
        modal = hastebin_modal()
        await ctx.send_modal(modal)

In my test server it shows as modal_slash even after I gave it a name. What am I missing?

deft bronze
#

You didn't parse it in the function arguments

#

@civic plume

#

My embed is like "saving in cache" or something like that?

#

even trying to manually resetting it gives me the same embed

#

nvm

civic plume
heavy sky
civic plume
heavy sky
#

Ok, that's why probably why. You need to restart your discord client when you change the command name - as it has the old one in the cache already

#

It only updates it when restarted

civic plume
civic plume
#

Here is my full code:

import discord
from discord.ext import commands
from external.hastebin.api.endpoints.endpoints import create_hastebin

class hastebin_modal(discord.ui.Modal):
    def __init__(self, title = 'Message', *args, **kwargs) -> None:
        super().__init__(title = title, *args, **kwargs)

        self.add_item(discord.ui.InputText(label = 'Message', style = discord.InputTextStyle.long))

    async def callback(self, interaction: discord.Interaction):
        status_code, response = await create_hastebin(self.children[0].value)

        if status_code == 200:
            hastebin_url = response
            await interaction.response.send_message(f'{hastebin_url}')
        else:
            await interaction.response.send_message(f'Status code: {status_code} - Response: {response}')

class command_cog(commands.Cog):
    def __init__(self, sentinel):
        self.sentinel = sentinel

    @discord.slash_command(description = 'Upload your text to Hastebin. Useful for sharing code..')
    async def hastebin(self, ctx: discord.ApplicationContext):
        modal = hastebin_modal()
        await ctx.send_modal(modal)

def setup(sentinel):
    sentinel.add_cog(command_cog(sentinel))
keen loom
#

Does anyone know what the argument is to suppress embed when creating threads in channels?

await channel.create_thread(name=title, message=description, auto_archive_duration=60, type=discord.ChannelType.public_thread, reason=dynCode)

In the docs it says

suppress_embeds=True

That should work but doesnt. I get a unexpected argument error

swift gust
#

Is it possible to send an embed here?


chan = self.bot.get_channel(000)
await chan.send(-----)
shell radish
little cobalt
#

or the intents

swift gust
#

nevermind got it, i forgot to return my embed

#

thank youi

shell radish
#

intents determine what information you receive, not what you can send

red mist
#

Indeed, intents are there so people know what exactly your bot accesses before they add it to their server :P

jolly yarrow
#
@bot.slash_command(name = "kick", description = "Kicks member")
async def kick(ctx: ApplicationContext, member: Member, reason: Optional[str] = None):
    try:
        if ctx.author.guild_permissions.kick_members and member.top_role < ctx.author.top_role:
            await member.kick(reason)
    except Exception as e:
        await ctx.respond(f"{e}")

That gives Member.kick() takes 1 positional argument but 2 were given error message. What's your suggestion to solve the problem?

jolly yarrow
lofty parcel
opal hamlet
#

so theres obv. the possibility of sending an attachment to my bot, but what would be the best way to send multiple images at once? (working on an img/pdf converter bot, want to add support to send multiple images to be converted to pdf)

grizzled loom
#

hey guys, I need to set up my very first sql server. you got any recommendation what sqlversion/flavour to use for a bot? (async obviously)

preferably something where setting up the db server isnt too much struggle and the closer it is to sqlite3 the better.

so far i was written and working with sqlite3, but reached its limitations. at least as far as i can configure it.

kind grove
#

am i able to post via webhook in a thread?

lofty parcel
#

threads dont have webhooks

kind grove
lofty parcel
kind grove
#

sweet, thanks

kind grove
#

ty :]

rapid jackal
#

can I add a color as discord Slash Command option?

steep cliff
#

Hey, just wanted to make sure this is a discord sever error and not an issue caused by my code.

shell radish
steep cliff
#

Awesome thx

quick knot
#

anyone else had an issue with this r:

#

aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)')]

#

if so, go to discord and download the certificate

deft kestrel
#
@reset_pings.before_loop
async def before_reset_pings():
    await bot.wait_until_ready()

    current_datetime = datetime.now(GMT_3_TZ)
    time_until_midnight = current_datetime.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=1)

    print(f"Current Time: {current_datetime}")
    print(f"Midnight: {time_until_midnight}")

    await discord.utils.sleep_until(time_until_midnight)```

It works perfect for the first day, but then during the 2nd day, it's triggered an hour earlier than expected (11 PM GMT+3). And I have no idea why
jolly yarrow
#
@bot.slash_command(name = "ban", description = "Bans member")
async def ban(ctx: ApplicationContext, member: Member, delete_message_seconds: Optional[int] = None, delete_message_days: Optional[Literal[1, 2, 3, 4, 5, 6, 7]] = None, reason: Optional[str] = None):
    try:
        if ctx.author.guild_permissions.ban_members and member.top_role < ctx.author.top_role:
            await member.ban(delete_message_seconds = delete_message_seconds, delete_message_days = delete_message_days, reason = reason)
            await ctx.respond(f"{member.name}({member.id}) was kicked beacause of { reason if reason is not None else 'unspecifed reason'}")
    except Exception as ex:
        await ctx.respond(f"{ex}")

That gives TypeError: issubclass() arg 1 must be a class because of @bot.slash_command(name = "ban", description = "Bans member") line. I don't get it.

lofty parcel
lofty parcel
lofty parcel
jolly yarrow
#

thanks

agile cargo
#

Is there an alternative to ffmpeg that doesn't need to be added to the path

unkempt shuttle
#

why does 'pip index versions pycord' only show 0.1.0, 0.1.1, 0.0.1

limber wagonBOT
#

The official name of the library is py-cord. When installing the library use py-cord, pycord (without the hyphen) is a completely different package.

ivory beacon
#

How can I identify the user who initiated a slash command using the message ID or another method?

ivory beacon
hallow copper
#

wut why

ivory beacon
#

💀

pliant tusk
#

how can i trigger a command using a custom message

#

for example when a user sends =abcdef i want to trigger !s abcdef where s is a bridge command and ! is the prefix

pliant tusk
little cobalt
hallow copper
little cobalt
#

^^

fleet cedar
#

In case you want to do it using message id then you will need to either get or fetch the message then do the above

shell radish
stray pasture
#

Is it possible to have the cache fill up as get fails. For exemple when a get fail, it fetch the member/role and put it into cache ?

#

So the cache wont be fill with info that is never used

#

I know you can disable the automatic fill up of hte cache at start, but can you make it it fill as needed ?

quick knot
#
Traceback (most recent call last):
  File "C:\Users\Comet\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 399, in _run_event
    await coro(*args, **kwargs)
  File "e:\github\a\cogs\events.py", line 48, in on_guild_remove
    await cha2.send(embed=discord.Embed(title="Leave", description=f"Left: {guild.name}"))
AttributeError: 'NoneType' object has no attribute 'send'
``` not sure why it posts this and then works, also for some reason, the on join event doesnt work
quick knot
#

cha2 is cha2 = self.bot.get_channel(832008207316549673)

little cobalt
#

?tag get_x

limber wagonBOT
#

Any function that starts with get_ in Py-cord is retrieving the related object from your bots cache. If the object is not in the bots cache the get_ method will return None. Because of this behavior you should check if the get_x method is None and if it is use the fetch_x method.

Why Is Using fetch_ Without Using get_ First Bad?
The fetch_ method makes a call to the discord API. This API call is unneeded if you already have the information. It will also make your command take longer because it will have to send and than wait for a response from the discord API. It will also contribute to the discord APIs global rate limit of 50 requests per second.

What Is Cache?
The cache is a temporary storage inside your bot. It holds many objects from members to messages. When you restart your bot the cache will be empty. When the cache is full it will delete older objects to make space for the new objects.

quick knot
#

ic, cuz the bot isnt cached at the begining

#

should i fix this, and if so how would i?

#

use fetch?

#

but then it would be worse later

lofty parcel
#

If it returns None, fetch instead

quick knot
#

but, it works

#

as the error is thrown just seconds before the bot begins to cache

#

also, any way to cache faster?

lofty parcel
#

You will just fetch it one time

#

In case get returns none

#

You won't die because of 1 api call

quick knot
#

ok cool

#

ty

grave scaffold
#

issue with on_member_join function:
i have been trying to make this work but it seems to never work
things i have done.

  1. checked intents in bot, guilds, presence etc. set to on
  2. done scripting
@client.event
async def on_member_join(member):
    print("entered")

any help?

grave scaffold
#

i even tried bot.event just in case

grave scaffold
#
import discord
import os
from discord import client, message
from dotenv import load_dotenv

load_dotenv()
bot = discord.Bot()
intents = discord.Intents(members=True)
client = discord.Client(intents=intents)

this is the remainder

lofty parcel
#

Why you have two bots instances?...

grave scaffold
#

you meant the intents variable and client variable

lofty parcel
#

I said bots. You have bot and client.

grave scaffold
#

client was when i was testing client.event

lofty parcel
#

You either use discord.Bot OR discord.Client

#

And I don't think you're looking forward using discord.Client

grave scaffold
#

client was replace and can be ignored

lofty parcel
#

So you keep the discord.Bot and do the edits to your code.

lofty parcel
#

And run the bot

grave scaffold
#

so i NEED to use the client pass in the client.event

lofty parcel
#

No you don't

#

discord.Bot supports events.

#

You won't and will never use two instances of a bot.

grave scaffold
#

or can i just use @bot.event
for and on_member_join?

lofty parcel
#

?tag client

limber wagonBOT
#
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
grave scaffold
#

oh i see.

#

well this is the updated code:

#
load_dotenv()
bot = discord.Bot()
discord.Intents(members=True)


@bot.event
async def on_member_join(member):
    print("entered")
lofty parcel
#
  1. You're bot passing the intents to the bot
  2. You're not running the bot
grave scaffold
#

bot.run is later and exists

#

the issue is that its not picking up a user joining

lofty parcel
#

Then read 1.

grave scaffold
#

bot = discord.Bot(intents=discord.Intents.all())

is this correct?

shell radish
#

no because you should only request for intents that you need

grave scaffold
#

so members then

#

genuine life saver thanks so much 🙂

hasty kite
#

Can Somone Give me a sample slash command code

rugged lodgeBOT
#

Here's the slash basic example.

#

Here's the slash basic example.

hasty kite
#

How do i refresh the server to update the slash commands which are available

sterile bobcat
hasty kite
#

should i remove it later?

sterile bobcat
hasty kite
#

but my bot is just in 2 servers

#

but it takes 10 mins

#

i want it to load like within 2 min is it possible

sterile bobcat
#

Then just put IDs of the server in guild_ids. It'll work

hasty kite
little cobalt
#

It takes like 10 seconds to get the command global

sterile bobcat
#

I am trying to create a button that moves any user that clicks to the Speaker in the stage channel. The button is as follows:

class QuestionPost(discord.ui.View):

        def __init__ (self, question: JeopardyQuestion, voice):
            super().__init__(timeout=None)
            self.question = question
            self.voice = voice

   
        @discord.ui.button(label="Buzz In", style=discord.ButtonStyle.blurple)
        async def button_callback(self, button: discord.ui.Button, interaction: discord.Interaction):
            button.disabled = True
            user = interaction.user
            button.label = (f"{user.name} buzzed in!")         
            await interaction.response.edit_message(view=self)
            await user.move_to(self.voice)

It moves the User to the Listner's position, how can I make sure the user is moved into the Speaker position? Is it even possible?

coral lake
#

Can anyone point me in the appropriate direction for learning more about individual Rate Limits for actions such as:

  • Global Interaction Responses
  • Ephemeral Interaction Responses
  • Slash Command ctx responses

I've scanned the Dev Portal Documents, and I understand that they are sent in response headers, but those aren't accessible via Pycord IIRC.

lofty parcel
lofty parcel
coral lake
# lofty parcel You shouldn't need to worry about those limits.

When building apps for large numbers of users, the Rate Limits are super relevant to understanding how to parse the requests from the appropriate sources (in the design phase - i.e starting with a slash command over a global button press with an ephemeral response).

I ran into this problem with an RPG bot with a traversable map (via Button UI) that crashed disgustingly as ~1k users tried to press the Global "Enter" Button.

That example isn't entirely relevant to my existing needs, but it's a good reason to understand the rate limits that are in place and the best ways to navigate them.

deft kestrel
#

how i can mention somebody in embed but i have only the id of the user?

lofty parcel
deft kestrel
#

i did that but its just @tropic flint

lofty parcel
#

Wdym

#

You don't add the `

deft kestrel
lofty parcel
#

What is that? A field title?

deft kestrel
#

yes

#

oh i fixed it

lofty parcel
#

Field titles can't parse mentions.

deft kestrel
#

yh i can see now

solid sapphire
#

Is it possible to execute another bot's slash command using a bot?

red mist
#

I dont think so

solid sapphire
#

thanks

little cobalt
#

pls dont crosspost

compact sparrow
#

mbmb

stray pasture
#

Is it possible to access the AuditLog of a server but only for member roles updates and ignore all other actions

#

I only want that, but I am not sure how to only receives these event

compact sparrow
#
Traceback (most recent call last):
  File "C:\Users\jarex\Downloads\TOOLS\Jarexs Tools\HYDRA\hydrabot\bot.py", line 24, in <module>
    @bot.has_permissions(administrator=True)
AttributeError: 'Bot' object has no attribute 'has_permissions'
lofty parcel
stray pasture
lofty parcel
stray pasture
lofty parcel
#

No... the event fires for any audit log entry

#

You do the checks for whatever entry you need by yourself

#

Even if it was a built in thing, the library would do the same check that you can do by yourself.

stray pasture
lofty parcel
#

No, the gateway event fires for any audit log entry

#

It doesn't have an event for specific audit log entries

stray pasture
#

I see thank you !

#

Why is that method(on_audit_log_entry) is not in discord package ?

#

in the doct it says it is discord.on_audit_log_entry(entry)

fleet cedar
stray pasture
fleet cedar
stray pasture
#

ooh I see perfect !

young cove
#

I changed my bot's name last week on the developer portal, but it still hasn't updated. Its role is the new name and of course I can change its nickname in the channel, but can't figure out how to change its account name. What am I missing? I know this probably isn't the best place to ask

lofty parcel
young cove
compact sparrow
#

how would i make so if the user has a role they can use the command but if not then they cant

lofty parcel
#

.rtfm commands.has_role

sly karmaBOT
lofty parcel
#

@compact sparrow

compact sparrow
#

still havin strugles

#

can you give me like a code example

lofty parcel
#

Just like commands.has_permissions

compact sparrow
#
if ctx.author.has_role("Nitro Access"):

Like this?

#

nvm figured it out

stray pasture
#

Because I put the chunk_guilds_at_startup=False, I dont have any member in the members field in a Role object. Is it possible to fetch only the members for a role ?

stray pasture
#

Should I just do a guild.chunk() and after that manually removes the member not in the roles.members

jolly yarrow
#
@moderation_commands.command(name="ban", description="Bans member from server")
async def ban(context: ApplicationContext, member: Member, delete_message_seconds: Optional[int], delete_message_days: Optional[Option(input_type=int)] = None, reason: Optional[str] = None):
    try:
        if context.author.guild_permissions.ban_members:
            if context.author.top_role > member.top_role:
                if delete_message_seconds is not None and not (0 <= delete_message_seconds <= 604800):
                    await member.ban(delete_message_seconds=delete_message_seconds, delete_message_days=delete_message_days, reason=reason)
                    await context.respond(f"{member.name} was banned beacuse of {reason if reason is not None else 'unspecified reason'}.")
                    return
                raise Exception("\"delete_message_seconds\" must be between 0 and 604800.")
            raise Exception("Hierarchically higher members cannot be kicked by hierarchically lower member.")
        raise Exception("You don't have permission to kick members.")
    except Exception as exception:
        context.respond(exception)
jolly yarrow
young cove
#

Hey all, I'm deleting an ephemeral message view from a modal's interaction with delete_original_response(). Problem is that if two+ users are filling out my form system around the same time, the delete is happening for other users. Any thoughts on how to make it user specific?

loud kayak
#

Would you be able to please explain your use case and what you are doing so I can better help you?

young cove
# loud kayak Would you be able to please explain your use case and what you are doing so I ca...

Yeah absolutely, thanks so much for the response.

It's essentially a form system with multiple steps:

  1. Persistent (non-ephemeral) view with button that opens a modal. -- this might be the problem

  2. When the modal is submitted, an ephemeral view with several select menus is sent to the user with a button to submit. I'm passing the modal's interaction to the ephemeral view and calling delete_original_response using the modal's interaction here.

  3. Then I do the same thing (pass the interaction and delete) across several more ephemeral views.

loud kayak
#

.rtfm view.interaction_check

sly karmaBOT
young cove
loud kayak
loud kayak
young cove
loud kayak
#

The delete_original_response would delete the ephemeral message

#

Which is specific to the user who submitted the modal

#

Unless i'm misunderstanding something, it should only delete the user specific ephemeral message, and not others'.

young cove
#

Are modal interactions specific to users? Maybe not if they're being sent from the same button.

stray pasture
#

On RawAuditLogEntryEvent when a role is added or deleted, why is the new_value field a list ? If I check the documentation it should be only 1 Object

#

discord doc:

#

Am I missing someting, or is it really 1 object but pycord but it in a list

deft kestrel
#

pycord is working with fivem (gta)?

fickle salmon
deft kestrel
#

like doing that
but its connected somehow to the fivem server (fivem is a roleplay kind of mod to gta)
so i want to know if its possible to do it with pycord

fickle salmon
#

pycord can connect to anything, you just need to make an api call with aiohttp

compact sparrow
#

.rtfm bot.

compact sparrow
#

what are all the bot.(blablabla)

like

{Fore.RED}Logged in as : {bot.user}
#

.rtfm bot.user

little cobalt
#

#app-commands

#

;3

compact sparrow
#

mb but could you help me i cant really find anything docs

little cobalt
#

What do you need?

fickle salmon
compact sparrow
#

like this is what i mean all of these

fickle salmon
#

yep

compact sparrow
#

okie tyty

#

how can i make this so it says how many users it reads and not ever users info skul

fickle salmon
#

len()

compact sparrow
#

like this?

fickle salmon
#

yep

compact sparrow
#

okie ty

compact sparrow
#

docs confusing the shit outta me how do i make a input in my command 😭

#

like

@bot.slash_command(name="changestatus", description="Change The Status Of The Bot.",)
async def changestatus(ctx):
    await bot.change_presence(activity=discord.Game(name=text))
    embed = discord.Embed(
        title="**Changed Status!**",
        description=f"**Successfully Changed The Status To {text}! :white_check_mark:**",
        color=discord.Colour.green(),
    )
    await ctx.respond(embed=embed)
rugged lodgeBOT
#

Here's the slash options example.

compact sparrow
#

yeah nvm figured it

stray pasture
#

In on_raw_audit_log_entry() I am saving payload.id in the database to know what is the last entry processed. When I try to start the bot, I look for missing entries while the bot was offline. However it is giving me all audit of the servers, not the one the bot missed

for guild in self.guilds:
    async for entry in guild.audit_logs(limit=None, after=last_process_audit_log_id, oldest_first=True, action=discord.AuditLogAction.member_role_update):
        print(f'{entry.user} did {entry.action} to {entry.target}')
#

Here last_process_audit_log_id is a value that was fetch form the database

#

to save the last_process_audit_log_id I just do

await self.database.update_last_process_audit_log_id(payload.guild_id, payload.id)
#

I would want only the event after that one

edgy nest
#

i believe after takes a datetime

#

or an object

#

not an int

stray pasture
edgy nest
#

you're not giving it either, you're giving it an integer

stray pasture
#

how can I transform the entry id in a Snowflake ID in that case ?

#

because in the doc it says it is a Snowflake

#

but in the code it says SnowflakeTime:

#

also if I check the discord endpoint, it takes a Snowflake ID :

edgy nest
edgy nest
stray pasture
edgy nest
#

¯_(ツ)_/¯

#

make an issue

stray pasture
#

In the pycord code, it is assiging to a constant ...

#

instead of the value provided

#

and that constant is always 0

#

That is why if I print the after_strategy the id is always 0

#

but if I manually put the right value it works as expected

edgy nest
#

well you can pr a fix or make an issue and i or someone else will handle it tomorrow

stray pasture
#

but if the issue is fix in a PR, how much time will it take to make it to a release ?

#

because the fix is really easy, I believe you can just replace:

self.after = OLDEST_OBJECT

by

self.after = OLDEST_OBJECT if after is None else after
#

I have summited a issue in the git

karmic solar
#

how do I correctly indicate that the nsfw command?

karmic solar
#

when I tried to add @commands.is_nsfw(), even in nsfw channels in the console, this error:

#

discord.ext.commands.errors.NSFWChannelRequired: Channel '<discord.channel.PartialMessageable object at 0x0000023C71C68A60>' needs to be NSFW for this command to work.

compact sparrow
#

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'Guild' object has no attribute 'fetch_bans'

lofty parcel
brazen inlet
#

still no way to filter the role_select ?

lofty parcel
#

Blame discord

brazen inlet
#

what the best way to do a role selection menu dropdown now ?

lofty parcel
#

Use a string select and parse the options yourself.

tribal jasper
#

How do i get a list of slash commands? I run my bot and i get application name must be unique. but it doesnt tell me what names are conflicting

lofty parcel
tribal jasper
little cobalt
tribal jasper
little cobalt
#

uninstall py-cord and install py-cord-dev

tribal jasper
tribal jasper
#

2.5.orc5

tribal jasper
#

New question, How do i create command groups (Slash Commands) using cogs?

rugged lodgeBOT
#

Here's the slash cog groups example.

tribal jasper
#

New question, Is there a way to limit some commands to some roles?

#

They can be done from the server settings -> Apps -> Bot but how do i do it from the code?

#

Dyno and some other bots do it too

little cobalt
#

they have to do it

tribal jasper
little cobalt
#

do you mean hiding the commands?

#

or just a role command

tribal jasper
#

hide the commands if a user doesnt have X role

rugged lodgeBOT
#

Here's the slash perms example.

little cobalt
#

^ so that is for everyone who doesnt have the permission for it

tribal jasper
little cobalt
#

yea, that has to be done in the server settings

tribal jasper
#

if i cant then is it a limitation of discord API or pycord?

brazen inlet
#

In the callback of string_select I can print select.values, any way to have the labels too ? thanks

outer niche
#

Is there a way to print all the permissions a role (in this case my bot) has?

steep cliff
compact sparrow
#
@bot.slash_command(name="unban", description="Unban a user from the guild")
async def unban(ctx, user: Option(discord.Member, "User"), reason: Option(str, "Reason", required=False)):
    if ctx.author.guild_permissions.ban_members:
        banned_users = await ctx.guild.bans()
        banned_user_ids = [entry.user.id for entry in banned_users]

        if user.id in banned_user_ids:
            try:
                await ctx.guild.unban(user, reason=reason)
                unban_embed = discord.Embed(
                    title="**Successfully Unbanned User!**",
                    description=f"**User : {user} Unbanned{' for Reason: ' + reason if reason else ' without a reason.'}**",
                    color=discord.Colour.green(),
                    timestamp=discord.utils.utcnow()
                )
                await ctx.respond(embed=unban_embed)

ERROR :

Traceback (most recent call last):
  File "C:\Users\jarex\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1133, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\jarex\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 381, in invoke
    await injected(ctx)
  File "C:\Users\jarex\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 139, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: object BanIterator can't be used in 'await' expression
lofty parcel
#

If you want to use it as a list, you have to flatten it.

steep cliff
#

Not a PyCord, but a Python/PyCharm issue. Figured y'all are most likly to know the reason anyway, so here we are.

My Issues:

  • venvs I create are invalid interpreters, using the global version works fine
  • prob unrelated (started occurring 2 months ago): PyCharm auto-disabling windows defender stopped working
    Failed attempts to fix this issues:
  • reinstalled PyCharm
  • reinstalled Python versions 3.11.7 and 3.12.1
  • made sure Python saved as a PATH variable
  • restarted my PC
    Any ideas how to fix these issues?
    1. issue has priority
  • pls ping on reply

||Side Note: Wanted to create a thread, was blocked as I used header markup, but the cooldown applied to me anyways.||

compact sparrow
#
@bot.slash_command(name="authorise", description="Get The Customer Role Through Your Hydra Key")
async def auth(ctx, akey: Option(str, "Key To Authorise", required=True)):
    guild = ctx.guild
    customer_role = discord.utils.get(guild.roles, name="Customers <3")

    RSAPubKey = "auth"
    auth = "auth

    result = Key.activate(
        token=auth,
        rsa_pub_key=RSAPubKey,
        product_id=23107,
        key=akey,
        machine_code=Helpers.GetMachineCode(v=2)
    )

    if result[0] is None or not Helpers.IsOnRightMachine(result[0], v=2):
        error_reason = result[1] if result[1] else "Unknown error"
        print(f"Authentication failed: {error_reason}")
        
        embed_look_dm = discord.Embed(
            title="Look At Your DMs! :white_check_mark:",
            color=discord.Colour.green(),
            timestamp=discord.utils.utcnow()
        )
        await ctx.respond(embed=embed_look_dm, ephemeral=True)
        
        embed_invalid_key = discord.Embed(
            title="Invalid Key!",
            description=f"**The Key : `{akey}` is invalid.**\n\nReason: `{error_reason}`",
            color=discord.Colour.red(),
            timestamp=discord.utils.utcnow()
        )
        await ctx.author.send(embed=embed_invalid_key)
    else:
        if customer_role:
            embed_look_dm = discord.Embed(
                title="Look At Your DMs! :white_check_mark:",
                color=discord.Colour.green(),
                timestamp=discord.utils.utcnow()
            )
            await ctx.respond(embed=embed_look_dm, ephemeral=True)
            
            await ctx.author.add_roles(customer_role)
            embed_auth_success = discord.Embed(
                title="Authorization Successful!",
                description=f"You have been authorized with Key: `{akey}`",
                color=discord.Colour.green(),
                timestamp=discord.utils.utcnow()
            )
            await ctx.author.send(embed=embed_auth_success)
        else:
            print("Customer role not found")
            embed_look_dm = discord.Embed(
                title="Look At Your DMs! :white_check_mark:",
                color=discord.Colour.green(),
                timestamp=discord.utils.utcnow()
            )
            await ctx.respond(embed=embed_look_dm, ephemeral=True)
            
            embed_role_issue = discord.Embed(
                title="Role Assignment Issue",
                description="The required role was not found. Please contact support.",
                color=discord.Colour.red(),
                timestamp=discord.utils.utcnow()
            )
            await ctx.author.send(embed=embed_role_issue)

ERROR :

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\jarex\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1133, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\jarex\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 381, in invoke
    await injected(ctx)
  File "C:\Users\jarex\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 139, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
lofty parcel
compact sparrow
#

huh

compact sparrow
#

@lofty parcel

lofty parcel
lofty parcel
#

I literally told you what to do bruh

#

Add await ctx.defer(ephemeral=True) to the start of your function

compact sparrow
#

oh got it ❤️

#
channel_id2 = 1186810340235825152
    channelmc = bot.get_channel(channel_id2)

    if channelmc:
        guild = bot.get_guild(1180467100037423155)
        if guild:
            try:
                await channelmc.edit(name=f"members-{len(bot.users)}")
                print(f"{Fore.RED}Successfully Updated The Member Count Channel To {len(bot.users)} Members")
            except discord.Forbidden:
                print(f"{Fore.LIGHTGREEN_EX}Bot lacks permission to edit channel name")
        else:
            print(f"{Fore.LIGHTGREEN_EX}Guild not found")
    else:
        print(f"{Fore.LIGHTGREEN_EX}Channel not found")

Why does this shit take so long to initialize

grave scaffold
#

quick question what does this referance? id, mention, name?

#

edit(roles=roles)

#

based on

member.edit(roles=roles)

shell radish
grave scaffold
#

so it referances the name of the role?

shell radish
grave scaffold
#

so its just based on the base referance names thrown into an array

grave scaffold
#

ok, so im back. Im here for someone to tell me something obvious that was right in front of my face. But here we go. Right and simple slash command add role to member. no work help

@bot.slash_command(name="role_test", description="")
async def role_test(member2: discord.Member):
    await member2.edit(roles=[1182813829986521238])
    print("passed")
lofty parcel
#

You don't pass an int

grave scaffold
#

i tried that. unless i need to referance the role inside the discord.Object()

#

ie. bot.get_guild().get_role()

lofty parcel
#

The docs explicitly say you need a Role object OR, as squid said, a list of discord.Object(id) is enough

grave scaffold
#

so i need an instance of bot.get_guild().get_role() ?

lofty parcel
#

You just need a list of discord.Object(id)

grave scaffold
#

sorry c++ gave me brain damage. its been a while

lofty parcel
#

[discord.Object(whatever role ID here)]

#

That's what you pass

grave scaffold
#

and heres the error

line 103, in role_test
    await member2.edit(roles=[discord.Object(1182813829986521238)])
TypeError: Interaction.edit_original_response() got an unexpected keyword argument 'roles'

The above exception was the direct cause of the following exception:
#

i can paste the whole error if needed

little cobalt
#

?

#

that is a message stuff

grave scaffold
#

? the type error is the only one i see as important

#

its not like changing the nick breaks it, JUST roles

shell radish
#

there's no way you made member2 an ApplicationContext

grave scaffold
#

the script above is all there is. Theres no external referances classes etc. everything is scope correct so i dunno

shell radish
#

how did you define member2

grave scaffold
#

inside the role_test() coroutine

lofty parcel
lofty parcel
#

async def role_test(ctx: discord.ApplicationContext, member2: discord.Member)

grave scaffold
#

OH MY GAWD, im dumb

stray pasture
#

If I want to only chunk a list of guild but not the other, is there a more efficient way to do it than just calling await guild.chunk() on each guild ?

fresh totem
#

What's the command to change the bot's nickname in a given server?

lofty parcel
#

aiohttp does not support python 3.12

hazy turret
#

I am currently trying to use Discord Timestamps to display the correct time and date for the user.
Did I understand correctly that if I calculate and create the timestamp in UTC, each user should then get the correct time for their time zone, which the user has set on their system?

compact sparrow
#

Ew Python 3.12 vomit_ew

lofty parcel
#

older python version, 3.11

#

pycharm is an ide

hazy turret
lofty parcel
#

You need to change the interpreter in the settings

tepid coyote
#
logger = logging.getLogger("104th Datacore")
    # logging.basicConfig(
    #     level=logging.INFO,
    #     format='%(asctime)s - %(levelname)-8s - %(message)s',
    #     datefmt='%Y-%m-%d %H:%M:%S',
    #     filename=pathlib.Path("logs/104th Datacore.log").resolve(),
    #     )

    handler = StreamHandler()
    formatter = ColoredFormatter()
    handler.setFormatter(formatter)
    logger.addHandler(handler)

    # set success level
    logging.SUCCESS = 25  # between WARNING and INFO
    logging.addLevelName(logging.SUCCESS, 'SUCCESS')
    setattr(logger, 'success', lambda message, *args: logger._log(logging.SUCCESS, message, args))

any reason why commenting this out would let the bot work. when its not commented out the bot comes online then goes offline straight away

karmic solar
#

Can I hide some admin commands from users?

#

for example

lofty parcel
karmic solar
lofty parcel
#

You can't hide commands from specific users, programmatically or through discord.

karmic solar
#

So this won't work?
@bot.slash_command(name="grant", description="", permissions={"users": [619460266962452480]})
async def grant(ctx, member: discord.Member, duration: str = ''):

deft kestrel
karmic solar
#

for all others

lofty parcel
karmic solar
deft kestrel
#

You can just limit the command to your server and set its default permission to administrator

lofty parcel
#

You can just register the command in a private guild of yours

#

If its you who will only be able to use it

sour flint
#

Hello what can i use or do so that i can get the list of roles (role ids) a ctx.author

or like is the a decorator so that the command can only be runned if a user has of the roles needed

lofty parcel
sour flint
#

thank you ❤️

deft kestrel
#

how i can add name to a link like this in embed

shell radish
hazy turret
#

In Autocomplete you can't pass a name as a string and assign a value to it where you can then access it in the function of the slash command, can you?

deft kestrel
#

How can I make the bot send a message to a specific channel, but the code sending it to the channel is inside the button class, and it’s also a CG file, and the action also takes place in the user’s DM

tepid coyote
red mist
#

That's probably the most help you're going to get

deft kestrel
red mist
#

you should read trough cog examples in the guide

deft kestrel
little cobalt
#

interaction.client

red mist
#

theres also examples for view classes

tepid coyote
little cobalt
red mist
little cobalt
#

...

red mist
#

...

hasty moth
#

...

deft kestrel
#

I misunderstood the message, Google translator made a mistake

red mist
#

client is the bot if I am correct

#

oh

#

okay then.

little cobalt
red mist
# little cobalt yes

That's why I said ... as.. if its client and youre in the dms with a bot then... obviously??

outer niche
#

Is there a callback to detect view timeout?

little cobalt
#

do you use a view class?

#

@outer niche

#

you can use ```py
async def on_timeout()

outer niche
red mist
#

Can you please read the documentation.

#

.rtfm get_channel

red mist
#

bro

#

wait

#

you need to

#

do exactly as you said

#

where's your context?

#

no context here either

#

Can you please show me exactly what you did

#

Oh wiaiwait

#

am I stupid

#

hodl on

#

wait try without the context again

#

i might just be stupid

#

Am I blind or smth

#

I thought

#
@bot.command()
@option(name="stars", description="stars", choices=["⭐⭐⭐⭐⭐", "⭐⭐⭐⭐", "⭐⭐⭐", "⭐⭐", "⭐"], required=True)
async def vouch(ctx, comment: str, stars: str):
    channel_id = bot.get_channel(108021788007283528)
    embed = discord.Embed(title="**Review added**", description=f"{ctx.author.mention} has added a review", color=0x00ff)
    embed.add_field(name="Comment", value=comment, inline=False)
    embed.add_field(name="Stars", value=stars, inline=False)
    embed.add_field(name="User ID", value=ctx.author.id, inline=False)
    embed.set_thumbnail(url=ctx.author.display_avatar)
    await channel_id.send(embed=embed)
#

was initially correct

red mist
#

Is it possible that your channel id is incorrect

little cobalt
#

?tag get_x

limber wagonBOT
#

Any function that starts with get_ in Py-cord is retrieving the related object from your bots cache. If the object is not in the bots cache the get_ method will return None. Because of this behavior you should check if the get_x method is None and if it is use the fetch_x method.

Why Is Using fetch_ Without Using get_ First Bad?
The fetch_ method makes a call to the discord API. This API call is unneeded if you already have the information. It will also make your command take longer because it will have to send and than wait for a response from the discord API. It will also contribute to the discord APIs global rate limit of 50 requests per second.

What Is Cache?
The cache is a temporary storage inside your bot. It holds many objects from members to messages. When you restart your bot the cache will be empty. When the cache is full it will delete older objects to make space for the new objects.

red mist
#

Ohhh-

round heart
#

Didn't someone create an equivalent get_or_fetch for messages? Do I have to know (or be in) the channel id that the message is in?

#

I tried this...

await utils.get_or_fetch(ctx.channel, 'message', message_id)

... but it doesn't work because TextChannel has no get_message()

deft bronze
#

Can you make alias with bridgeCommands?

little cobalt
#

with avatar.url

delicate shell
#

if a slash command is called and I receive an ApplicationContext object ctx, does a method like ctx.guild.get_channel(...) involve a discord API call? or are the API-related methods all async?

shell radish
compact sparrow
#

how do i make like put a command in a embed

round heart
#

So a message with buttons has a components field, but of course I can't send a message with a components flag. These don't have to be interactions cuz they're just URL buttons, but I want to copy them to a new message.

Is there a relatively easy way to achieve this?

edgy nest
#

a view

round heart
#

Ooh. View.from_message does what I'm looking to do.

harsh gust
#

can i make a event listener to check for slash commands runs?

rugged lodgeBOT
harsh gust
#

alr thx

atomic fern
#

I'm passing 1 argument but? is this a bug from the library

    if len(selected_option) >= 2:
      response = await interaction.response.send_message("Processing..", ephemeral=True)
      message = ""
      # Berikan role
      for role_name in selected_option:
        role = discord.utils.get(interaction.guild.roles, name=role_name)
        
        if role in interaction.user.roles:
          await interaction.user.remove_roles(role)
          message += f"Removed {role}."
          
        else:
          await interaction.user.add_roles(role)
          message += f"Added {role}."
          
      print(message)
      await interaction.edit_original_response(message)
TypeError: Interaction.edit_original_response() takes 1 positional argument but 2 were given```
shell radish
# atomic fern I'm passing 1 argument but? is this a bug from the library ```py if len(sel...
    if len(selected_option) >= 2:
-     response = await interaction.response.send_message("Processing..", ephemeral=True)
+     response = await interaction.response.send_message(content = "Processing..", ephemeral=True)
      message = ""
      # Berikan role
      for role_name in selected_option:
        role = discord.utils.get(interaction.guild.roles, name=role_name)
        
        if role in interaction.user.roles:
          await interaction.user.remove_roles(role)
          message += f"Removed {role}."
          
        else:
          await interaction.user.add_roles(role)
          message += f"Added {role}."
          
      print(message)
      await interaction.edit_original_response(message)
#

similarly, with edit_original_response

harsh gust
#
import discord
from discord.commands import slash_command
from discord.ext import commands
from discord.commands import option

# Some functions here

BASE = [f'base{i}' for i in range(2, 11)] + ['DEC', 'BIN' , 'OCT', 'Binary', 'Decimal', 'Octal']

class base_conv(commands.Cog,name='base_conv'):

  def __init__(self,bot):
    self.bot = bot
  async def command_searcher(self: discord.AutocompleteContext):
    return [
      b for b in BASE
    ]
  
  async def get_commands(ctx: discord.AutocompleteContext):
    return [b for b in BASE if b.startswith(ctx.value.lower())]   
  
  @slash_command(name='base',description='base')
  @option("base_from", description="Pick a base", autocomplete=get_commands)
  @option("base_from", description="Pick a base", autocomplete=get_commands)
  async def base(self,ctx, base_from, base_to):
    await ctx.respond('e')

def setup(bot):
  bot.add_cog(base_conv(bot))

main


extensions = [
  'cogs.ping',
  'cogs.time',
  'cogs.image',
  'cogs.help',
  'cogs.dank',
  'cogs.eightball',
  'cogs.mod',
  'cogs.purge',
  'cogs.bmr',
  'cogs.gpt',
  'cogs.font',
  'cogs.utils',
  'cogs.brainfuk',
  'cogs.weather',
  'cogs.wordle',
  'cogs.latex',
  'cogs.funds',
  'cogs.graph',
  'cogs.base_conv'
]
if __name__ == '__main__':  
    for extension in extensions:
        bot.load_extension(extension)  

#

so.. this command isnt showing up

#

all the other commands ARE showing up and are working

#

i didnt see a single error in the console

#

but when i intentionally make errors i do see them

#

and also ik i wrote base from twice in @option but i fixed it later

harsh gust
#

umm so i tried to write that code in a different file. a cog thats actually working

#

turns out i cant make any new commands whatsoever (used different names too)

compact sparrow
#
class AuthNo(discord.ui.Button):
    def __init__(self, *, style=discord.ButtonStyle.secondary, label=None, emoji=None, authask=None, original_message=None):
        super().__init__(style=style, label=label, emoji=emoji)
        self.authask = authask
        self.original_message = original_message

    async def callback(self, interaction: discord.Interaction):
        embed = discord.Embed(
            title="Cancelled Users Authorisation.",
            color=discord.Colour.red(),
            timestamp=discord.utils.utcnow()
        )
        await self.authask.delete()
        await self.original_message.delete()
        await interaction.response.edit_message(embed=embed)

File "C:\Users\jarex\Downloads\TOOLS\Jarexs Tools\HYDRA\hydrabot\bot.py", line 120, in callback
await self.authask.delete()
AttributeError: 'NoneType' object has no attribute 'delete'

outer niche
compact sparrow
#

yeah figured it lol

atomic fern
#

why the danger button not called when i press it? and also no error

class RoleMenu(discord.ui.View):
 def __init__(self, role_data: dict):
   super().__init__(timeout=30)
   ...
   self.danger.label = self.data["red_button_label"]
   
 @discord.ui.select(row=0, custom_id="reusableMenu")
 async def callback(self, select, interaction):
   ... 
     await interaction.response.send_message(message, ephemeral=True)
     
 @discord.ui.button(row=1, style=discord.ButtonStyle.danger)
 async def danger(self, interaction):
      ...
         await interaction.response.edit_original_message(content=message)
     ```
compact sparrow
#
class RoleMenu(discord.ui.View):
    def __init__(self, role_data: dict):
        super().__init__(timeout=30)

        # Assuming role_data contains information about roles and button labels
        self.role_data = role_data

        # Select menu
        self.select = discord.ui.Select(
            placeholder="Select a role",
            options=[discord.SelectOption(label=role['label'], value=str(role['role_id'])) for role in role_data]
        )
        self.add_item(self.select)

        # Danger button
        self.danger_button = discord.ui.Button(
            label="Danger",
            style=discord.ButtonStyle.danger,
            custom_id="danger_button"
        )
        self.add_item(self.danger_button)

    @discord.ui.select(placeholder="Select a role", custom_id="reusableMenu")
    async def callback(self, select, interaction):
        selected_value = select.values[0] if select.values else None

        # Logic to assign roles based on the selected value

        await interaction.response.send_message("Role assigned.", ephemeral=True)

    @discord.ui.button(label="Danger", style=discord.ButtonStyle.danger, custom_id="danger_button")
    async def danger(self, button, interaction):
        await interaction.response.send_message("Danger button pressed.", ephemeral=True)

try this code @atomic fern

atomic fern
#

fixed thanks

sinful juniper
karmic solar
#

Can you tell me what I'm doing wrong?

intents = discord.Intents(messages = True)
bot = commands.Bot(command_prefix="!!", intents=intents, help_command=None)
start_time = datetime.utcnow()

@bot.event
async def on_message(message):
if message.content.startswith('!!'):
channel = message.channel
await channel.send('I moved on /commands')

await bot.process_commands(message)
shell radish
#

you also need message_content = True when you define your intents

karmic solar
outer niche
#

If I run InteractionResponse.edit(file=None, files=None) it still raises TypeError: Cannot mix file and files keyword arguments. How can I fix this?

lofty parcel
outer niche
outer niche
outer niche
shell radish
#

different people think differently

lofty parcel
sour widget
#

is it possible to send photo or any other file after embed, not before in one message?

pliant tusk
#

how do i suppress the error message if i handled it in on_bridge_command_error

#

only some of them, i want the others to still be printed in console

fleet cedar
fleet cedar
pliant tusk
#

"exception ignored in command ..."

#

on_bridge_command_error still receives the exception, and i handle some of them

#

but i want the handled ones to not print the "ignored exception" stuff

fleet cedar
fleet cedar
#

Ah

#

And how do you handle it? Event listeners?

pliant tusk
#

on_bridge_command_error listener

fleet cedar
#

Listeners won’t override the default action

#

You will need to use @bot.event or subclass Bot and override the on_bridge_command_error function to override

sinful juniper
#

does anyone know why the background is not displayed?

I have background.show()

sour widget
atomic fern
#

solved

lapis dock
topaz basin
#

Does anyone know how to get the command id from the slash command that gets executed? Because the command id is different on every guild

shell radish
#

sounds like

#

?tag xy

limber wagonBOT
#

An XY problem is when you're trying to ask about your attempted solution, rather than your actual problem.

You are trying to solve problem X, using solution Y. Instead of asking for help with X, you ask about Y. This only results in frustration as whoever is trying to help you needs to ask several questions before even beginning to help you with your actual issue, wasting both their own, and your time. Always include as much information as you can about your problem, including attempted solutions. If there are solutions you've ruled out, include them along with an explanation as to why you've ruled them out.

delicate shell
#

when moving a text channel with channel.edit(position=...), it seems like the position is relative to all the channels in the server. is there a way to do it relative to only the channels in the category of channel? i know i can write some script to calculate the difference, but wanted to see if there was an easier way

loud kayak
lament tusk
#

anyone here know how to resize a frame so it occupies the entire window?

#

i'm talking about tkinter right now

lofty parcel
lament tusk
lofty parcel
#

Because it is volunteer. But there's a high chance someone who uses tkinter is there, rather than here.

#

Plus this channel is for "basic pycord help"

hallow copper
#

i get this fancy error message when i start my bot :c i just moved it from my macbook to my pc, havent had this problem before
Ignoring exception in on_connect Traceback (most recent call last): File "C:\Users\Jade\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 399, in _run_event await coro(*args, **kwargs) File "C:\Users\Jade\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 1182, in on_connect await self.sync_commands() File "C:\Users\Jade\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 738, in sync_commands registered_commands = await self.register_commands( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Jade\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 537, in register_commands desynced = await self.get_desynced_commands( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Jade\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 360, in get_desynced_commands elif _check_command(cmd, match): ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Jade\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 275, in _check_command as_dict = cmd.to_dict() ^^^^^^^^^^^^^ File "C:\Users\Jade\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 866, in to_dict "options": [o.to_dict() for o in self.options], ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Jade\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 866, in <listcomp> "options": [o.to_dict() for o in self.options], ^^^^^^^^^^^ File "C:\Users\Jade\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\options.py", line 336, in to_dict "type": self.input_type.value, ^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'value'
wut did i do wronggg?

little cobalt
#

That is the same like ```py
text = None

hallow copper
#

i get the error when i run mt bot, the exact same code didnt have an error when i would run it on mac

spark ibex
#

Is there a guaranteed way of getting channel category from a message? Since I'm having issues when a message is sent in a thread it doesn't do it

#

I used message.channel.category.category_id instead of channel.category_id since all types of channel has category

#

But it still returns None

vital leaf
#

Commands of a subgroup not working, error:

Traceback (most recent call last):
  File "d:\Personal\Documents\GitHub\Grass-bot-rewrite\.venv\Lib\site-packages\discord\commands\core.py", line 124, in wrapped
    ret = await coro(arg)
          ^^^^^^^^^^^^^^^
  File "d:\Personal\Documents\GitHub\Grass-bot-rewrite\.venv\Lib\site-packages\discord\commands\core.py", line 1312, in _invoke
    await command.invoke(ctx)
  File "d:\Personal\Documents\GitHub\Grass-bot-rewrite\.venv\Lib\site-packages\discord\commands\core.py", line 372, in invoke
    await self.prepare(ctx)
  File "d:\Personal\Documents\GitHub\Grass-bot-rewrite\.venv\Lib\site-packages\discord\commands\core.py", line 292, in prepare
    if not await self.can_run(ctx):
           ^^^^^^^^^^^^^^^^^^^^^^^
  File "d:\Personal\Documents\GitHub\Grass-bot-rewrite\.venv\Lib\site-packages\discord\commands\core.py", line 390, in can_run
    local_check = cog._get_overridden_method(cog.cog_check)
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: '_MissingSentinel' object has no attribute '_get_overridden_method'

a command under a slash command group works fine, but a command under a subgroup doesn't work

lofty parcel
sage tendon
#

Does on_member_update run when a member is kicked? According to the docs it shouldn't, but it would perfectly explain a weird behaviour my bot has

stray pasture
#

can you add or remove roles of a member without the member object ? Sometime I need to update a member roles, I have the guild_id, member_id and role_id, but the member is not in the cache. It is useless to fetch the member only to call the function to update the roles. Can the library do it, or would I have to call the discord endpoint by myseft ?

sage tendon
#

why is the member not in cache?

stray pasture
#

to save memory

#

As I dont need that member to be in cache, so why have it

sage tendon
#

memory is there to be used

#

and as you can see, you very quickly run into issues like this without cache

stray pasture
#

well it is not a very big issue, I just do a api request

sage tendon
#

why?

#

Just turn on cache or fetch the member

stray pasture
#

I dont need to cache all the members of each guild for my bot usage

#

if I do I will run out of memory

sage tendon
#

how much memory do you have and how many users total

stray pasture
#

I have 1.8 millions users

sage tendon
#

hm

stray pasture
#

and only 4 Gb of ram

#

so is there a way to do a update to a member without the member been in the cache in the library ?

sage tendon
#

i think you can create a tiny placeholder object that only contains the ID, and use that instead

#

i used that before but i dont remember exactly how it worked again, maybe one of the regulars knows what i mean

stray pasture
#

I see that is a good idea ! I will try that, but if one of the regulars know that would be helpfull

#

Thank you !

sage tendon
#

there is a library object specifically for that

#

ill try find it in my code

stray pasture
#

I found finally that you can use that: bot.http.add_role()

sage tendon
#

ah, nice

stray pasture
#

yess very nice ! I wont have to write the api call code 😄

sage tendon
#

i mean thats what a library is for

stray pasture
#

yess that is why I ask before

edgy nest
keen stag
#

How do I make shure the author has the permission to kick users?

lofty parcel
#

.rtfm Member.guild_permissions

sly karmaBOT
lofty parcel
#

Or

#

.rtfm commands.has_permissions

sly karmaBOT
lofty parcel
#

To avoid the check in the command itself

little cobalt
#

.rtfm default_permissions

sly karmaBOT
little cobalt
#

for slash commands

whole needle
#

.rtfm defer

little cobalt
whole needle
#

mb

#

but how do you defer again

little cobalt
#

with ctx

whole needle
little cobalt
#

await

whole needle
#

why is this not ephemeraling

little cobalt
#

did you add it to the defer?

shell radish
#

?tag hidden

limber wagonBOT
#

dynoError No tag hidden found.

shell radish
#

?tag ephemeral

limber wagonBOT
#

An 'ephemeral' message is one that's only visible to the person who invoked a command. If you ever got a command error with a blue background, this is an example of one.

To do this, set ephemeral=True when you first use an ApplicationContext. (This includes .defer()ing it; the choice of whether a message is ephemeral or not must be made up front. If you .respond() to a deferred message, setting the ephemeral flag at that time will have no effect.)

This is the equivalent of hidden=True if you're coming from interactions.py

e.g.

await ctx.respond("Imagine a message!", ephemeral = True)

await interaction.response.send_message("Imagine a message!", ephemeral = True)
keen stag
#

Hey can I group slash commands ? I dont find anything in the docs

rugged lodgeBOT
#

Here's the slash cog groups example.

keen stag
#

thx

plucky moss
#

My slash commands in cogs aren't working: this is my code:

import discord 
from discord.ext import commands

class Fun(commands.Cog):
  def __init__(self, client):
    self.client = client
  
  @commands.command()
  async def ping(self, ctx):
    await ctx.send(f"Pong! {round(self.client.latency * 1000)}ms")

  @commands.slash_command(name='test', description='Test command')
  async def test(self, ctx: discord.ApplicationContext):
    await ctx.respond('Slash Commands are working')

  @commands.user_command(name='Test2')
  async def test2(self, ctx, user: discord.Member):
    await ctx.respond(f'{user.mention} is cool')

  @commands.Cog.listener()
  async def on_ready(self):
    print('Fun cog is ready')

def setup(client):
  client.add_cog(Fun(client))
    

#

Also ping me if you want to help

little cobalt
#

What do you mean with not working?

plucky moss
little cobalt
#

how do you load the cog?

keen stag
#

Hey I get this error when I run my bot on my Debian 11 Server. But on my Windows 11 PC it works fine. ```log
Traceback (most recent call last):
File "/usr/local/lib/python3.9/dist-packages/discord/cog.py", line 774, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
File "<frozen importlib._bootstrap_external>", line 786, in exec_module
File "<frozen importlib._bootstrap_external>", line 923, in get_code
File "<frozen importlib._bootstrap_external>", line 853, in source_to_code
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "/home/admin/dnw/mod-system-dev/src/cogs/config.py", line 28
match rank:
^
SyntaxError: invalid syntax

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/home/admin/dnw/mod-system-dev/src/main.py", line 29, in <module>
MainLoader.LoadCogsFolder()
File "/home/admin/dnw/mod-system-dev/src/main.py", line 19, in LoadCogsFolder
BOT.load_extension("cogs." + f[:-3])
File "/usr/local/lib/python3.9/dist-packages/discord/cog.py", line 910, in load_extension
self._load_from_module_spec(spec, name)
File "/usr/local/lib/python3.9/dist-packages/discord/cog.py", line 777, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.config' raised an error: SyntaxError: invalid syntax (config.py, line 28


It looks like it has something to do with the switch case: 
```py
match rank:
            case 'admin':
                CONFIG['config']['team']['admin'] = role.id
            case 'moderator':
                CONFIG['config']['team']['moderator'] = role.id
            case 'support':
                CONFIG['config']['team']['support'] = role.id
            case _:
                await ctx.send("Rank does not exits!\n Use one of the following: \n- admin \n - moderator \n - support")
                return
#

Could the problem be the version difference?

Windows 11 PC : Python3.11.7
Debian Server : PYthon3.9.2

little cobalt
#

Match case is only Python 3.10+

keen stag
#

ahhh wow such a "big" feature in a update. Ok thx

plucky moss
plucky moss
# lofty parcel Show your main file
import discord
import os
import asyncio
import aiohttp
import random
import time
import requests
import openai
from keepalive import keep_alive
from discord.ext import commands

keep_alive()

intents = discord.Intents.all()
client = commands.Bot(command_prefix='-', intents=intents)

TOKEN = os.environ['TOKEN']
GPT_KEY = os.environ['GPT_KEY']
openai.api_key = GPT_KEY

cogs = ["cogs.Fun", "cogs.Moderation"]



@client.event
async def on_ready():
  print('Monke Bot is online and ready to react!')
  await client.change_presence(activity=discord.Game(name="me is monke"))
  print('Loading cogs...')
  for cog in cogs:
    try:
      client.load_extension(cog)
      print(f"Loaded {cog} cog")
    except Exception as e:
      print(f"Failed to load {cog}\n{e}")

Like I said all other commands are working. Except context menus and slash commsnds

#

I'm using replit btw

lofty parcel
plucky moss
#

I should make a command for them?

lofty parcel
#

You need to load them before so the bot syncs the commands when it connects

lofty parcel
#

Load your cogs after you define your bot instance

plucky moss
#

Then what

plucky moss
#

Ill try it

#

Nope same result,

import discord
import os
import asyncio
import aiohttp
import random
import time
import requests
import openai
from keepalive import keep_alive
from discord.ext import commands

keep_alive()

intents = discord.Intents.all()
client = commands.Bot(command_prefix='-', intents=intents)

TOKEN = os.environ['TOKEN']
GPT_KEY = os.environ['GPT_KEY']
openai.api_key = GPT_KEY

cogs = ["cogs.Fun", "cogs.Moderation"]

print('Loading cogs...')
for cog in cogs:
  try:
    client.load_extension(cog)
    print(f"Loaded {cog} cog")
  except Exception as e:
    print(f"Failed to load {cog}\n{e}")


@client.event
async def on_ready():
  print('Monke Bot is online and ready to react!')
  await client.change_presence(activity=discord.Game(name="me is monke"))
plucky moss
#

Btw this is my cog code

import discord 
from discord.ext import commands

class Fun(commands.Cog):
  def __init__(self, client):
    self.client = client
  
  @commands.command()
  async def ping(self, ctx):
    await ctx.send(f"Pong! {round(self.client.latency * 1000)}ms")

  @commands.slash_command(name='test', description='Test command')
  async def test(self, ctx: discord.ApplicationContext):
    await ctx.respond('Slash Commands are working')

  @commands.user_command(name='Test2')
  async def test2(self, ctx, user: discord.Member):
    await ctx.respond(f'{user.mention} is cool')

  @commands.Cog.listener()
  async def on_ready(self):
    print('Fun cog is ready')

def setup(client):
  client.add_cog(Fun(client))
    

atomic fern
#

do commands.Bot().slash_command() auto-registered? 7 hours but still not showed up why?

#

do i need to set name parameter in slash_command?

little cobalt
atomic fern
#

no

#

i use decorator so will be like @bot.slash_command()

#

i also try this way but still not showed up, i invited the bot with application.commands scope

sour widget
#

This question doesn't directly address pycord, but is there a list of photo extensions that discord embed supports?

plucky moss
#

@little cobalt sorry for the ping but could I get a response for my problem?

little cobalt
plucky moss
little cobalt
#

is the prefix command working at the cog?

plucky moss
#

Yes

#

Only slash commands and context menus don't work

steep cliff
#

tried to pip install py-cord-dev, but got the following errors:

ERROR: Failed building wheel for multidict
  Failed to build aiohttp multidict
ERROR: Could not build wheels for aiohttp, multidict, which is required to install pyproject.toml-based projects
little cobalt
steep cliff
#

using 3.11

#

or that's what I thought, turns out I'm still using 3.12, my bad

little cobalt
#

but only add 3.11 to the path

plucky moss
steep cliff
steep cliff
#

Regarding #library-updates message, should I switch back to py-cord or continue using py-cord-dev for now

edgy nest
#

you could use master

#

it's stable

steep cliff
#

and everything that was fixed while master was down was pushed to master?

#

just checked and it hasn't been updated since march

shell radish
#

do you mean a specific part of the code

fleet cedar
steep cliff
# shell radish idk what you mean since march

There hasn't been a release on py-cord since March, which is why I decided to use py-cord-dev for now. Not sure if that's smart or not. Will the next release be on py-cord again? When working on new features/changing code, do you use py-cord-dev for rc's and then release the final version on py-cord? Or to put it simple, which version should I use (py-cord master, py-cord release or py-cord-dev release)?

shell radish
steep cliff
#

so I guess it's best to use py-cord-dev till the release?

pliant tusk
shell radish
shell radish
#

If anything is broken with pcd, see if it is fixed on master. If not, then open an issue on github

pseudo osprey
#

I'm definitely being stupid here.. changed PC (Fresh install of everything)
Tried to install py-cord to no avail.

pip list before attached
pip list after attached
error attached

Are any of these discord.py libraries? TIA

keen stag
#

Hey I have a problem installing the py-cord package on my Debian 11 server. Im using Python3.12 but cant install via pip

shell radish
pseudo osprey
#

I just downgraded to 3.10

keen stag
#

ahh damn thx

shell radish
pliant tusk
shell radish
pliant tusk
#

on the Bot class?

#

currently using bridge.AutoShardedBot iirc

pliant tusk
#

everytime the bot logs in i get

Ignoring exception in on_connect
Traceback (most recent call last):
  File "/workspace/.pyenv_mirror/user/current/lib/pypy3.10/site-packages/discord/client.py", line 399, in _run_event
    await coro(*args, **kwargs)
  File "/workspace/.pyenv_mirror/user/current/lib/pypy3.10/site-packages/discord/bot.py", line 1182, in on_connect
    await self.sync_commands()
  File "/workspace/.pyenv_mirror/user/current/lib/pypy3.10/site-packages/discord/bot.py", line 757, in sync_commands
    app_cmds = await self.register_commands(
  File "/workspace/.pyenv_mirror/user/current/lib/pypy3.10/site-packages/discord/bot.py", line 534, in register_commands
    prefetched_commands = await self._bot.http.get_guild_commands(
  File "/workspace/.pyenv_mirror/user/current/lib/pypy3.10/site-packages/discord/http.py", line 365, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
#

how do i prevent it

lofty parcel
pliant tusk
#

is there a way to silence all of these Ignoring exception in messages, or process them myself

#

is on_error the handler for this?

#

and can I call super().on_error from an overridden on_error to invoke the default behaviour

loud kayak
#

How long can a select menu placeholder be? Doesn’t say about any character limit in the docs but I know there is one.

#

Nvm it’s 150