#Basic Pycord Help (Quick Questions Only)

1 messages Β· Page 90 of 1

prisma flicker
#

you can manage permissions in the integrations page though under server settings

fervent cradle
#

ohh thats what you mean

#

alr

prisma flicker
#
async def interaction_check(self, interaction: discord.Interaction):
    mods_role = discord.utils.get(interaction.guild.roles, name="Mods")
    is_mod = mods_role in interaction.user.roles
    if not is_mod:
        await interaction.response.send_message(f"Only mods can do thi!", ephemeral=True)
        return False
    else:
        return True
fervent cradle
#

Would have to include that in myview class or appart from it

#

Sorry, Im a bit dumb on buttons

prisma flicker
#

it's part of the view class

fervent cradle
#

ok great

#

then I should do this

#

But in the interaction_check

#

and return True or false

prisma flicker
#

yes

fervent cradle
#

but I would need to add the button to the interaction_check args right?

#

async def interaction_check(self, interaction: discord.Interaction, button):

#

or how

prisma flicker
#

no

#

the interaction check is for all buttons in the view

#

you can get the button's custom_id with interaction.data['custom_id']

fervent cradle
#

Do I have to define that custom_id

prisma flicker
#

if you want to use it, yes

#

you just add it to @button()

fervent cradle
#

Im a bit lost tbh

prisma flicker
#

send your view class

fervent cradle
#

1s

#

well its a bit long lmao

#

will just send the important part

#

because there is a whole txid checking logic

prisma flicker
#

sure, you can leave out the method bodies

fervent cradle
#
class MyView(discord.ui.View):
    def __init__(self, bot_instance, crypto, price, addy, user_id, author_id):
        super().__init__()
        self.ncrypto = NCrypto()
        self.bot = bot_instance
        self.crypto = crypto
        self.txid = ''
        self.price = price
        self.addy = addy
        self.userid = user_id
        self.author_id = author_id

    async def interaction_check(self, interaction: discord.Interaction):
        if self.userid != interaction.user.id:
            button.disabled = True
            button.label = f'You are not <@{self.userid}>'
            button.emoji = '❌'
            button.style = discord.ButtonStyle.red
            return False
        else:
            return True

    @discord.ui.button(label="Sent!", style=discord.ButtonStyle.success, emoji="βœ…")
    async def button_callback(self, button, interaction):
        if self.userid != interaction.user.id:
            button.disabled = True
            button.label = f'You are not <@{self.userid}>'
            button.emoji = '❌'
            button.style = discord.ButtonStyle.red
            return
        button.disabled = True
        await interaction.response.edit_message(view=self)
        await interaction.channel.send('Please send the txid!')```
#

I didnt remove some parts because Im testing tho

prisma flicker
#

you just do @discord.ui.button(label="Sent!", style=discord.ButtonStyle.success, emoji=":white_check_mark:", custom_id="foo")

#

and then in interaction_check you just say if interaction.data['custom_id'] == 'foo' or whatever

#

does that make sense?

fervent cradle
#

ye

#

and then what should I do to edit the button

#

like disable it, change the label and shi

#

if its not the user Id I need

prisma flicker
#

if you disable the button it disables for everyone

#

if you return False, the callback won't run for that user

fervent cradle
#

oh

prisma flicker
#

interaction_check runs before the callback

fervent cradle
#

damn ok

#

aaa alr

#

makes sense

prisma flicker
#

I see what you're asking

fervent cradle
#

but its not possible right

prisma flicker
#

now I need to figure out how my code works πŸ˜‚

#

I have a view where if I push a button I remove the buttons and add another button

#

ah right

#
view.clear_items()
reopen_button = Button(label="Reopen", style=discord.ButtonStyle.grey, custom_id='work_order_view:reopen')
reopen_button.callback = reopen
view.add_item(reopen_button)```
#

that's in a static method in the view, which takes in the view as an argument

#

which I realize is a little confusing

#

in the callback I do await interaction.message.edit(embed=await WorkOrderView.get_work_order_embed(self.bot, self.work_order_id, interaction.message.guild, view=self), view=self)

#

WorkOrderView.get_work_order_embed is the static method

#

so let me take a step back and ask what you want to happen

fervent cradle
#

ok so

#

I want only one user to have the button enabled

#

an user id

#

but disabling it makes it disabled for everyone

#

So how could I make it send a message that only the user that tried to press the button sees that says "You are not <@user.id> and you cant press this button"

prisma flicker
#

Just check the id in interaction_check and return false if it's not the right id

zenith glacier
#

so when i have this exact code, the options dont show at all

@bot.slash_command(name="yeah")
@option("Option", description="Choose your gender", choices=["Embed", "Raw", "Other"])
async def hello(
    ctx: discord.ApplicationContext,
    options: str,
):
    if options == 'Embed':
        await ctx.respond("wha")
    elif options == 'Raw':
        await ctx.respond("kys")
    else:
        await ctx.send("Invalid option!")```
proud mason
#

There is a kwarg in the decorator if they are different

#

Pass the parameter name to it

zenith glacier
#

issue is i dont know

#

right

#

i did what you did

#

thanks for the quick response btw

sleek haven
#

is multiple cooldowns possible?
@ext_commands.cooldown(1, 15, ext_commands.BucketType.user)
this is the cooldown for normal users ^^^ (15 sec cooldown)
but i want it so that premium users only has 10sec cooldown

sleek haven
#

ty

errant craneBOT
#

Here's the cooldown example.

proud mason
#

There should be an example at the end

sleek haven
#

thx a lot ❀️

proud mason
#

np!

spring hare
#

Do bots see pronouns?

proud mason
#

Probably not

novel yacht
#

why i when set respond i having error
Ignoring exception in command kiss:

Traceback (most recent call last):
  File "C:\Users\misha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 124, in wrapped
    ret = await coro(arg)
          ^^^^^^^^^^^^^^^
  File "C:\Users\misha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 982, in _invoke
    await self.callback(ctx, **kwargs)
  File "c:\Users\misha\Desktop\34\test.py", line 28, in kiss
    await ctx.respond(image_url)
  File "C:\Users\misha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\context.py", line 282, in respond
    return await self.interaction.response.send_message(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\misha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 825, in send_message
    await self._locked_response(
  File "C:\Users\misha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 1090, in _locked_response
    await coro
  File "C:\Users\misha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 219, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

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

Traceback (most recent call last):
  File "C:\Users\misha\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\misha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 375, in invoke
    await injected(ctx)
  File "C:\Users\misha\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: NotFound: 404 Not Found (error code: 10062): Unknown interaction
@bot.slash_command(name="waifu")
async def waifu(ctx):
    response = requests.get('https://waifu.pics/api/sfw/waifu')
    data = response.json()
    image_url = data['url']
    await ctx.respond(image_url)

@bot.slash_command(name="kiss")
async def kiss(ctx):
    response = requests.get('https://waifu.pics/api/sfw/kiss')
    data = response.json()
    image_url = data['url']
    await ctx.respond(image_url)

obtuse juncoBOT
#

Use aiohttp.
requests and urllib are blocking. Do not use these libraries within your asynchronous code as they're not asynchronous.
(https://docs.pycord.dev/en/stable/faq.html#what-does-blocking-mean)

Py-cord uses aiohttp, so it should already be installed. An example of code using aiohttp and Py-cord:

async with aiohttp.ClientSession() as cs:
    async with cs.get('https://httpbin.org/json%27') as r:
        res = await r.json()  # returns dict
        await ctx.send(res['slideshow']['author'])β€Š

For more help, see aiohttp's documentation: https://docs.aiohttp.org/en/stable/

proud mason
#

since you are making a web request, it might take more than 3 seconds to respond. you should add await ctx.defer() at the start of any such commands

novel yacht
#

oh thanks

novel yacht
#

hello need help trying respond that channel not nsfw chat use chat with nsfw tag.
code

@bot.slash_command(name="love")
@commands.is_nsfw()  # Decorator to ensure the command is used in an NSFW channel
async def love(ctx):
    try:
        async with aiohttp.ClientSession() as session:
            async with session.get('https://waifu.pics/api/nsfw/waifu') as response:
                response.raise_for_status()  # Raise an exception if the request was not successful
                data = await response.json()
                image_url = data['url']
                await ctx.respond(image_url)
    except commands.NSFWChannelRequired:
        # Send a message in the text channel
        await ctx.channel.send("This command can only be used in NSFW channels.")

but when i use
Ignoring exception in command love:
Traceback (most recent call last):
File "C:\Users\misha\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\misha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 372, in invoke
await self.prepare(ctx)
File "C:\Users\misha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 292, in prepare
if not await self.can_run(ctx):
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\misha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 400, in can_run
return await async_all(predicate(ctx) for predicate in predicates) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\misha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\utils.py", line 699, in async_all
for elem in gen:
File "C:\Users\misha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 400, in <genexpr>
return await async_all(predicate(ctx) for predicate in predicates) # type: ignore
^^^^^^^^^^^^^^
File "C:\Users\misha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 2309, in pred
raise NSFWChannelRequired(ch) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
discord.ext.commands.errors.NSFWChannelRequired: Channel 'general' needs to be NSFW for this command to work.

spring hare
novel yacht
#

I can if channel isn't I can inform user?

spring hare
#

Yes? create on_error and respond with message

novel yacht
novel yacht
#

Thanks

novel yacht
#

i tested and didnt know what paste xD here


@love.error
async def on_application_command_error(ctx: discord.ApplicationContext, error: discord.DiscordException):
    if isinstance(error, commands.notnsfw):
        await ctx.respond("This command can only be used in NSFW channels.")
    else:
        raise error  # Here we raise other errors to ensure they aren't ignored
#

if isinstance(error, commands.notnsfw):
?)

spring hare
#

if isinstance(error, NSFWChannelRequired):

worn void
#

How do I get the actual display name for a member? Like with the new discord username system? discord.member.display_name returns their normal username.

pale mica
worn void
#

ill try that now tho

worn void
# pale mica Ah

you cant get the user object from a member objects with member.user

worn void
# pale mica Ah

is there even a way to get their display name with pycord yet?

young bone
#

With the master branch

pale mica
#

^ I don't think the newest version has global name

worn void
#

how do you force update to the master branch on github

spare juniper
#

Uhhh

#

isnt there a button

#

are you merging a branch or push a commit

worn void
#

use the version thats on github master branch

#

of pycord

spare juniper
#

oh uhh that branch has unreleased stuff

young bone
#

pip install -U git+https://github.com/Pycord-Development/pycord

worn void
worn void
young bone
#

what?

worn void
proud mason
#

?tag pomelo

obtuse juncoBOT
#

Before Pomelo-

member.name          -> username
member.nick          -> guild nick name
member.display_name  -> member.nick OR member.name

After Pomelo-

member.name          -> username
member.global_name   -> global display name (global nick name)
member.nick          -> guild nick name
member.display_name  -> member.nick OR member.global_name OR member.name
proud mason
#

@worn void on master branch ^

worn void
#
    @commands.slash_command(name="test")
    async def test(self, ctx):
        await ctx.respond(ctx.author.global_name)
#

on master

#

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

grizzled sentinel
#

Send pip list please.

worn void
grizzled sentinel
#

Entire

worn void
#

mk

#

aiohttp 3.8.4
aiosignal 1.3.1
async-timeout 4.0.2
attrs 23.1.0
blinker 1.6.2
charset-normalizer 3.1.0
chat-exporter 2.5.3
click 8.1.4
colorama 0.4.6
EasyProcess 1.1
emoji 2.2.0
entrypoint2 1.1
Flask 2.3.2
frozenlist 1.3.3
grapheme 0.6.0
humanfriendly 10.0
idna 3.4
itsdangerous 2.1.2
Jinja2 3.1.2
keyboard 0.13.5
mariadb 1.1.6
MarkupSafe 2.1.3
mss 9.0.1
multidict 6.0.4
mysql-connector-python 8.0.33
packaging 23.1
Pillow 9.5.0
pip 23.1.2
protobuf 3.20.3
py-cord 2.4.1.dev145+gcada37a4
pygame 2.4.0
PyGetWindow 0.0.9
PyMsgBox 1.0.9
pynput 1.7.6
pyperclip 1.8.2
pyreadline3 3.4.1
PyRect 0.2.0
python-dotenv 1.0.0
pytweening 1.0.7
pytz 2023.3
setuptools 65.5.0
simple-pid 2.0.0
six 1.16.0
urllib3 1.26.15
vgamepad 0.0.8
Werkzeug 2.3.6
yarl 1.9.2

proud mason
#

Hmm weird

proud mason
worn void
#

author.user doesnt exist i think

proud mason
#

.rtfm member.user

winter condorBOT
#

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

proud mason
#

Huh

worn void
#

.rtfm author.user

winter condorBOT
#

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

worn void
#

.rtfm ctx.author.user

winter condorBOT
#

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

proud mason
#

Author would return a member object

worn void
#

oh

#

true

proud mason
#

Try checking the docs page for Member

#

Switch to master branch

#

.rtfm Member

worn void
#

member.global_name is correct.

worn void
grizzled sentinel
#

.rtfm send

grizzled sentinel
#

There is a stickers argument

raw orchid
#

wait NVM I understand it now

prisma flicker
worn void
worn void
#

reinstalled master branched like 4 times

#

^ uninstalled before each time

proud mason
sage bear
#

is it possible to restrict one select value in a drop-down menu to a user with a particular role?

worn void
proud mason
#

Oh how

grizzled sentinel
sage bear
grizzled sentinel
#

That is the concept yes

sage bear
#

okay sweet

#

thanks

finite flame
#

hey, does @discord.default_permissions(administrator=True, manage_guild=True) mean I need both permissions or either of them?
and if it means both, how can I make it only need either?

proud mason
#

If not, you use use local checks instead of discord ones

sweet wren
#
File "/home/container/247-casino-bot.py", line 30, in <module>
    from discord.commands import Option
  File "/home/container/.local/lib/python3.9/site-packages/discord/commands/__init__.py", line 27, in <module>
    from .core import *
  File "/home/container/.local/lib/python3.9/site-packages/discord/commands/core.py", line 49, in <module>
    from ..enums import MessageType, SlashCommandOptionType, try_enum
ImportError: cannot import name 'SlashCommandOptionType' from 'discord.enums' (/home/container/.local/lib/python3.9/site-packages/discord/enums.py)```
#

how do i go about fixing this issue

young bone
sweet wren
young bone
sweet wren
young bone
#

The pip one doenst work with py-cord

sweet wren
#

gotcha ill give it a shot now

#
CLIENT.topggpy = topgg.DBLClient(CLIENT, 'mytokenhere', autopost=True, post_shard_count=True)```

```py
  File "/home/container/247-casino-bot.py", line 89, in <module>
    CLIENT.topggpy = topgg.DBLClient(CLIENT, 'myactualtokenhere')
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: DBLClient.__init__() takes 2 positional arguments but 3 were given``` im no longer getting that previous error but im getting a new one
young bone
halcyon gorge
#

is there a function that basically does what the hovering x does on an embed?

prisma flicker
#

.rtfm embed

halcyon gorge
#

yes but not the embed the bot is sending

#

like essentially removing the autoembed from someone elses message

prisma flicker
#

m.edit(suppress=True)

halcyon gorge
#

I was under the assumption they can only delete

prisma flicker
#

no, but they can remove embeds

halcyon gorge
prisma flicker
#

Raises:
Forbidden – Tried to suppress a message without permissions or edited a message’s content or embed that isn’t yours.

#

you need manage_messages to remove embeds from other people's messages

halcyon gorge
#

alright thanks!

sage bear
#

im making a game bot so a user can input a purchase with their coins, now they will input their order like x10 apples, x3 oranges, x5 bananas, however i want to store this in a list so ["10", "apple", "3", "orange"...] but i dont know how to split the numbers from the text

prisma flicker
#

can you send the code you have now?

sage bear
#

so im having them input it into a modal:

  class Start(Modal): # interaction_4th, modal questions & response
            def __init__(self, *args, **kwargs) -> None:
              super().__init__(*args, **kwargs)
              # add the questions:
              self.add_item(InputText(label="Your order", placeholder="x5 apples, x4 oranges..", min_length=10, max_length=1000, required=False, style=discord.InputTextStyle.long))

            async def callback(self, interaction_4th: discord.Interaction): # once the submit button is clicked..
                overwrites = {
                    interaction_4th.guild.default_role: discord.PermissionOverwrite(view_channel=False),
                    interaction_4th.user: discord.PermissionOverwrite(send_messages=True, view_channel=True, attach_files=True, embed_links=True, read_message_history=True, use_slash_commands=True),
                            }
                
                guild = bot.get_guild(GUILD_ID)
                category = bot.get_channel(ORDERS_ID)
                order = self.children[0].value
                split_order = order.split(",")
                order1 = split_order[0]
                order2 = split_order[1]
                order3 = split_order[2]

                total1 = extract_numbers(order1)
                total2 = extract_numbers(order2)
                total3 = extract_numbers(order3)

                print(total1 + total2 + total3)```
prisma flicker
#

I would suggest reading up on python string manipulation and list slices

sage bear
#

i know partly how they work

prisma flicker
#

sounds like you have a good starting point then

#

another option would be to have a modal with 4 fields, quantity/text/quantity/text and then they can submit that multiple times for bigger orders. that way you don't have to do any manual parsing

sage bear
#

its just i can only have 5 fields in a modal and for people wanting to order more wouldnt be able to

prisma flicker
#

yep

#

hence submitting multiple orders

#

not the best solution but it's an option

#

or just have a slash command with a bunch of options

sage bear
#

so id have to use multiple modals?

prisma flicker
#

well they could submit the same modal multiple times

sage bear
#

would that work if i had multiple different items?

prisma flicker
#

I don't see why not

#

you submit it once for 3 apples and 2 oranges

#

and again for 4 bananas and 8 pears

#

and then you just execute the orders one at a time

sage bear
#

how would i do that?

prisma flicker
#

you don't have to do anything special...

sage bear
#

i didnt know you could submit them twice

prisma flicker
#

your callback just treats each order as an order

#

you shouldn't have to care if it's their 1st or 100th order

sage bear
#

ohh i see

#

oh that seems easier now

prisma flicker
#

yes

sage bear
#

thanks :)

prisma flicker
#

no problem πŸ™‚

sage bear
prisma flicker
grizzled sentinel
#

Not json plz 🀞

sage bear
#

a database

prisma flicker
#

do you not want to store the orders in the database?

#

do you need to store anything or would you just execute the order and store the results

sage bear
#

i need to store it because later on i need to calculate the price and therefore get the items and quantity again

prisma flicker
#

when is "later on"?

buoyant pier
#

Is there some better way to make like counting then on every message to get channel and and check if its same as in database? i think is so bad for performce of bot to check every message.

i had idea to make instances of every guild where bot counting is setup on bot start and save channel.id into class instance but still i need to check every message

prisma flicker
#

if it were me, I would deduct the money and add the items to the inventory right there in the callback

sage bear
#

i have an embed that they can choose which payment to continue with

grizzled sentinel
#

Like a counting bot?

prisma flicker
#

I can't answer that for you, but I would probably just store it in memory (in a variable), I don't see the need to put it in the db

grizzled sentinel
sage bear
#

im confused about how to store the values if the modal has been answered more than once

prisma flicker
#

as a list

buoyant pier
sage bear
prisma flicker
buoyant pier
prisma flicker
sage bear
#

ohh so just append

prisma flicker
sage bear
#

do i need to call it self.order?

prisma flicker
#

the assumption is you're in a class (a cog) and you have an instance variable named order

grizzled sentinel
grizzled sentinel
buoyant pier
buoyant pier
grizzled sentinel
#

But the intent is for it to grow πŸ‘

prisma flicker
#

you could just ignore everything that happened while the bot was down

#

although as I think about it I can see the issues that would cause

#

just wouldn't be a good user experience

buoyant pier
prisma flicker
#

I know some bots add a reaction on every message for counting

#

that would let you know you've already checked that message

#

and also let users know the bot stopped tracking

buoyant pier
#

i already put reaction to messages that bot check and delete messages that arent numbers in that channel but still people dont stop counting when bot is offline

prisma flicker
#

right, but then when you're checking on startup you just skip messages that have the reaction

prisma flicker
#

and does that solve the issue

buoyant pier
#

i think it can work i will try that. thank you guys

prisma flicker
#

an optimization once your bot gets big enough is to not build in a check on startup, but only check in on_message

#

so if a guild stops counting for a while you don't have to waste resources looking them up until someone starts counting again

grizzled sentinel
#

It is a hard to solve issue. Its what programming is all about.

buoyant pier
novel yacht
#

im so sorry but some body pls help when i moved to cog and i have
when not


    @love.error        
    async def on_application_command_error(ctx: discord.ApplicationContext, error: discord.DiscordException):
        if isinstance(error, commands.NSFWChannelRequired):
            await ctx.respond("This command can only be used in NSFW channels.")

raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: pics.on_application_command_error() takes 2 positional arguments but 3 were given

proud mason
#

||basics of a Class in python||

novel yacht
#

im first time coding and some time can losedoggokek

novel yacht
# novel yacht Like that https://guide.pycord.dev/popular-topics/error-handling#per-command-ha...

stop i founded in site cog

    @pics.command(name="love")
    @option("choice", description="choice", choices=CHOICES)
    @commands.is_nsfw()
    async def love(self, ctx: discord.ApplicationContext, choice: str):
        choice = choice.lower()
        async with aiohttp.ClientSession() as session:
            async with session.get(f'https://api.waifu.pics/nsfw/{choice}') as response:
                response.raise_for_status()
                data = await response.json()
                image_url = data['url']
                embed = discord.Embed(colour=0xfee692)
                embed.set_image(url=image_url)
                await ctx.respond(embed=embed)

    async def cog_command_error(self, ctx: commands.Context, error: commands.CommandError):
        if isinstance(error, commands.NSFWChannelRequired):
            await ctx.respond("Sorry, you can only use this in private messages!", reference=ctx.message)
        else:
            raise error```
halcyon gorge
prisma flicker
#

wut

#

are you sure?

#

sounds like a bug

halcyon gorge
#

yea

#

sent from mobile, embed not suppressed but checked the same message on discord desktop and it was suppressed

sage bear
#

im getting myself confused

shadow gate
#

Is there any way to check if a user in voice is speaking? I searched google and found nothing useful, so I wanted to see if anyone here has figured it out

#

The following method only works on actual user mute status:

@bot.event
async def on_voice_state_update(member, prev, cur):
    if cur.self_mute and not prev.self_mute:
        print(f"{member} stopped talking!")
    elif prev.self_mute and not cur.self_mute:
        print(f"{member} started talking!")```
shadow gate
silver moat
shadow gate
#

oof

shadow gate
#

I may have to go to the dark side and create a discord.js script. If nothing else, than to make an event listener to pass to python

hushed cargo
#
response = await ctx.respond(content="music player")
message = await ctx.channel.fetch_message(response.id)
#

when i run this it gives me an unknown message error

round rivet
#

assuming you're using slash commands you can get the response message with ctx.interaction.original_message scratch that, one sec scratch that x2, it's right

hushed cargo
#

bc im tryna send the message as a response to a slash command then edit the message later

#

i just wanna get the message object from that message so i can do message.edit()

hushed cargo
#

ohhhh that makes sense thank you-

round rivet
#

you can also use ctx.edit

hushed cargo
#

its because im using this for my music player

round rivet
#

if it's the initial response (no defer or anything before) then response.id is the interaction id

hushed cargo
#

its gonna need to store the message object to use later

round rivet
#

since it returns Interaction

hushed cargo
#

ohhh im dumb-

round rivet
#

if you defer first it'll return a message

hushed cargo
#
await ctx.respond(content="music player", ephemeral=False)
message = ctx.interaction.original_message

when i do this i get this error

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'function' object has no attribute 'edit'
#

wait no

#

that

full basin
#

ctx.edit is easier on your case

silver moat
#

it's a coro

hushed cargo
#

its bc i store the message

silver moat
#
message = await ctx.interaction.original_message()
#

it's a coro

full basin
#

Is Interaction.message the same as the View.message

silver moat
hushed cargo
#

if the bot isnt playing any music it sends this message
else it sends a message with an ephemeral, i need to store the first message to edit it later

full basin
proud mason
full basin
#

Ok. Am not on master

#

Ty

timber mica
#

I assume running User.mutual_guilds on a sharded bot would only return the ones on that shard; if this is the case what would be a way to see all guilds that the bot shares with the user, across all shards?

round rivet
#

An AutoShardedBot functions code-wise as if it were single shard iirc

#

unified cache and all that

timber mica
#

alright, tnank you

hazy mango
#

Is there a way i can complete a slash command without having to return a response? the bot has a command which juts dm's some information. If i dont use interaction.response.defer() it shows the interaction did not respond error on discord app, but if i use the defer method it just says bot is thinking... is there a way to remove that option as well?

coarse spire
hazy mango
#

thats what i did but i thought there might have been a better solution for it. Thanks you, ill just stick with this method then

coarse spire
#

Ah, ok. Well, there aren't really any other methods at the moment to not respond to an interaction without getting the error that the application didn't respond.

hazy mango
#

thank you

warm tendon
#

what happens when you defer and do nothing else? (never tried this approache)

#

@coarse spire @hazy mango

hazy mango
#

The commands keeps looping on "the bot is thinking" message

proud mason
warm tendon
proud mason
#

best way would be to send an ephemeral message saying "Sent DM!" or "Please check your DMs"

hazy mango
#

Oh damn I forgot ephimeral messages existed

warm tendon
#

Sorry I am not helpful, I just got curious after reading

#

talking about messages, I do have a problem with paginator.
it does send embeds the way its supposed to and the timeout works also.

it becomes problematic when its message reaches the end of timeout and was deleted.

#

I tried with try/except but still get an error each time that happens

#
# embeds is a list filled with embeds
            try:
                paginator = Paginator(pages=embeds, author_check=True, disable_on_timeout=True, timeout=300)
                await paginator.respond(interaction=ctx.interaction)
            except discord.errors.NotFound:
                return
#

any ideas?

proud mason
proud mason
#

but you can subclass Paginator and override on_timeout

#

the error is raised from there

#

not from paginator.respond

#

also which version are you using?

warm tendon
proud mason
#

hm

#

what happens on master branch?

warm tendon
#

I may have an idea

light river
#

how do you access someone's display name?

#

because when i update my display name, it fires a member_update event

#

and i literally can't find any way to access the display name

proud mason
#

?tag pomelo

obtuse juncoBOT
#

Before Pomelo-

member.name          -> username
member.nick          -> guild nick name
member.display_name  -> member.nick OR member.name

After Pomelo-

member.name          -> username
member.global_name   -> global display name (global nick name)
member.nick          -> guild nick name
member.display_name  -> member.nick OR member.global_name OR member.name
light river
#

what is pomelo in this case

#

also what pycord version do i have to be in

#

for this to work

proud mason
proud mason
light river
#

how do i get it

vast sun
#

Hi, is possible to get display name?

prisma flicker
proud mason
obtuse juncoBOT
#
  1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
    python -m pip uninstall discord.py discord -y

2a. Install py-cord
python -m pip install py-cord

2b. Update py-cord
python pip install -U py-cord

Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.

Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord

proud mason
#

Last line

proud mason
light river
#

?tag git

obtuse juncoBOT
vast sun
vast sun
#

πŸ‘€

hushed cargo
#

So ifound a problem with my music bot, the view for the song doesn't always last long enough for the song to end, so near the end of the song it just won't respond to any of the buttons, any idea how I'd fix this?

proud mason
coarse spire
#

change the timeout for the buttons

proud mason
#

Maybe 10 mins

hushed cargo
#

Ohh wait yea I can just set the timeout to the length of the song

#

Bc I do have that info

proud mason
#

That might cause problems if someone pauses

hushed cargo
#

Crap true- lmao thanks

proud mason
hushed cargo
#

Wait

#

What if someone just leaves it paused-

#

For some dumb reason

#

There's no way to unpause it-

proud mason
#

Set to None

#

Any reason to have it timeout?

hushed cargo
#

Well it's bc I didn't set the timeout-

#

So by default it wasn't bone 😭

#

None*

proud mason
#

Yea by default it is 3 mins

hushed cargo
#

Almost perfect for most songs

#

Also is there a way to see how long it's been playing a song? Without storing the time it started it no?

proud mason
hushed cargo
#

Can't

#

It sends the message for the first song

#

Then edits it for every sobg after that

proud mason
#

Ah

hushed cargo
#

That message kinda becomes the player

proud mason
#

Edit time?

hushed cargo
#

Tree hats a thing? Lmao

#

That's*

proud mason
#

.rtfm message.edited

proud mason
#

Ye

hushed cargo
#

:0 thank you I'll look into that

proud mason
#

Never really thought it would come to use for anyone πŸ˜‚

hushed cargo
#

Well thinik Abt it

#

If you press last song button

#

In the first like 10 secs

#

It plays last song

#

Else it restarts the song

#

This is actually really useful lmao

hushed cargo
flat kite
#

Is there a way to get a users status?

#

Thought of something like discord.User.status but thats not an attribute

proud mason
#

.rtfm user.activity

winter condorBOT
#

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

proud mason
#

Hmm

iron halo
#

how do i pick a type of option using the @option decorator? or do i have to use the other way

silver moat
iron halo
#

no like attachment

#

or member or whatever

#

the only thing on the docs is doing it without the decorator

silver moat
iron halo
#

yes yes

silver moat
#

would you like an example?

iron halo
#

sure

#

unless it does it automatically when i do async def dspjfidso(ctx, osdjaoi: discord.Member)?

full basin
#

love the func name

iron halo
#

thank u

silver moat
#
@bot.slash_command(name = "upload")
@discord.option(name = "photo", description = "You can upload a photo here", input_type = discord.SlashCommandOptionType.attachment)
async def upload(
  ctx: discord.ApplicationContext,
  photo: discord.Attachment
) -> None:
  ...
#

I think something like that would work

iron halo
#

ah thank you

#

lets try

silver moat
#

If I made a typo, oops

iron halo
#

it shows the attachment thing on discord but doesnt like it clearly

#

omg

#

i forgot await

#

ok it works thank you

#

now to figure out how to send the attachment

slow vector
#

File = discord.File(photo)
Ctx.send(File)

young bone
#

that was random

iron halo
#

i feel like thats too easy

slow vector
#

Nope

iron halo
#

well it did not work

#
  File "/home/ubuntu/.local/lib/python3.8/site-packages/discord/client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "bot.py", line 1210, in on_application_command_error
    raise error
  File "/home/ubuntu/.local/lib/python3.8/site-packages/discord/bot.py", line 992, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "/home/ubuntu/.local/lib/python3.8/site-packages/discord/commands/core.py", line 358, in invoke
    await injected(ctx)
  File "/home/ubuntu/.local/lib/python3.8/site-packages/discord/commands/core.py", line 135, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: send_message() takes from 1 to 2 positional arguments but 3 were given```
silver moat
iron halo
#

await ctx.respond("hey", file)

#

i knew it was not that easy

#

also file=file says discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: InvalidArgument: file parameter must be File

#

and attachment=file does not exist

iron halo
#

async def sdfsds(ctx, file: discord.Attachment):

cyan quail
#

Oh so you want to resend the file the user uploaded?

iron halo
#

yes

cyan quail
#

You should use attachment.to_file then

iron halo
#
    await ctx.respond("hey", file=newfile)```
i saw that on stackoverflow but it still says must be file
#

unless id id it wrong

cyan quail
#

you need to await the first line

iron halo
#

ah ok ty

#

after putting await in the wrong place somehow it finally worked ty

tribal girder
#

how to get which menu is selected (discord.ui.select) by user but in int? used to acces list index

trim cipher
#

how can I edit a previously sent response ? like for a music bot, once the 1st song plays... it says the song name and when the next song plays, it just edits the previous message with new song's name?

silver moat
hushed cargo
#

so for my music bot i made a way to add all songs from a playlist to the queue, how do i display the full queue when its length could easily surpass 4096?

prisma flicker
#

Use paginator

hushed cargo
#

would that prevent this?

discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds: Embed size exceeds maximum size of 6000
prisma flicker
#

yep

hushed cargo
#

hmm

#

can still send a message like that in an ephemeral ?

prisma flicker
#

yep

trim cipher
#

and how can I send message without using ctx? coz trying this:

@bot.event
async def on_wavelink_track_end(payload:wavelink.TrackEventPayload, ctx: bridge.BridgeContext):
    vc = payload.player
    vc.autoplay = False
    try:    
        if vc.queue or vc.autoplay == False:
            next_song = vc.queue.get()  
            await vc.play(next_song) 
            await ctx.send("Now playing: `{}`".format(next_song.title))
    except wavelink.exceptions.QueueEmpty:
        pass

gives me this error:

Ignoring exception in on_wavelink_track_end
Traceback (most recent call last):
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 378, in _run_event
    await coro(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^
TypeError: on_wavelink_track_end() missing 1 required positional argument: 'ctx'
proud mason
#

get the channel object from there and send

#

cant get ctx like that

trim cipher
hushed cargo
hushed cargo
#

with mine i just needa do this as the view an works perfectly
view=paginator(embeds)

proud mason
sharp talon
#

can anybody help me since im lost in the

#

ok i just use rtfm found out it was guild_id

#

imma test it

#

i returns None, weired

#

weird*

proud mason
#

hmm

#

what are your intents?

#

also, did you try interaction.guild_id?

sharp talon
#

yes

sharp talon
#

thanks

#

❀️

#

(i told my mind to do it later lol)

sharp talon
#

i added intents

proud mason
# sharp talon

the parameter name is intents

but interaction.guild_id should return regardless of intents. are you sending this in a dm?

#

also, show pip list

sharp talon
#

OH YEAGH

#

i am on dm

#

im dumb

#

ok thanks so much

proud mason
#

lmao

trim cipher
primal furnace
#

Hey I have a question. My bot is now in 1,400 servers and I've noticed the on_ready is quite terribly slow. I wanted to start sharding, but I have no knowledge on it. I don't develop much anymore and I run my free bot for fun. Any easy way to just implement sharding rq so I can go attend to my life and let my bot function without being super slow?

#

Sorry! I checked the docs and it did say Sharding is easy. But it was confusing to me.

#

Using translate btw.

coarse spire
#

then, PyCord will automatically shard your bot

primal furnace
#

I don't have to manually do it for each command?

#

client = commands.AutoShardedBot(intents=intents,chunk_guilds_at_startup=False)

#

I'm assuming you mean like this?

coarse spire
primal furnace
#

How do you define how many shards you want / how many are split between them

#

Is there like shard=

coarse spire
#

You can just pass shards to commands.AutoShardedBot as well. For example: commands.AutoShardedBot(shards=4)

primal furnace
#

So it isn't shard_count

#

It's shards ?. And I'm assuming it'll just devide them across right.

coarse spire
#

Yeah, it's just shards

primal furnace
#

Alright. And for everything in my bot using bot. Like self.bot, does that need to change?

young bone
#

Self bot?

primal furnace
#

self.bot.guilds.

#

Does this need to be self.bot.AutoShardBot.guilds

trim cipher
#

ig no

primal furnace
#

Yeah it's working now.

#

Do shards have to restart seperately?

#

Or is it still all gonna be in 1

trim cipher
#

sry idh any idea abt it.. maybe someone else with better understanding could help

primal furnace
#

Docs say to use shard_count

cyan quail
primal furnace
cyan quail
#

1400 and 400 is quite a large difference...

primal furnace
#

So if I shard it should let me avoid turning chunking off.

cyan quail
#

if sharding does fix it then that's good, but if not then you either have to accept that your on_ready will be slow (just manage your restarts better) or disable chunking entirely

primal furnace
cyan quail
#

whatever the docs say

#

but at your size you don't really need to specify it

#

discord can set a recommended shard count

primal furnace
#

How do some bots manage their restarts differently per shard?

cyan quail
#

well strictly speaking shards are different processes

#

AutoShardedBot just manages it all in one client

primal furnace
#

Well upon sharding the on_ready started quicker and my ram usage went down

cyan quail
#

fair enough then

primal furnace
#

I didn't provide a shard count though

#

Do you know how I can print out the shard info?

cyan quail
#

yeah you don't have to

primal furnace
#

I'd like to know whats going on. Such as how many are being used.

cyan quail
#

probably on that docs page hold on

primal furnace
#

I saw get_shard. It doesn't make sense.

#

It said there is shard IDS

cyan quail
#

there's Bot.shards which will be a list of them

primal furnace
#

So print(Bot.shards)

#

Hey @cyan quail

#
@client.event
async def on_ready():
  activity = discord.Activity(type=discord.ActivityType.listening, name="/help")
  await client.change_presence(activity=activity)
  print(bot.shards)```
#

How can you put this outside of an on_ready

#

So I can restart and always have the status

#

sorry for pinging

cyan quail
#

Don't do change presence in on_ready, there's a kwarg in the Bot class itself

#

Probably activity, check on the docs

primal furnace
#

got it

woeful spindle
#

I’m getting random 404 unknown interaction errors even tho im defering ?

trim cipher
# proud mason well the bot can only be in 1 vc in a guild.. so whenever a user runs a music co...

hi, I did what you said... and the program is working as intended. here is what I did:

# Create an empty dictionary to store the channels
channel_dict = {}

@bot.event
async def on_wavelink_track_end(payload: wavelink.TrackEventPayload):
    vc = payload.player
    vc.autoplay = False
    try:
        if vc.queue or vc.autoplay == False:
            next_song = vc.queue.get()
            await vc.play(next_song)
            
            # Get the guild ID from the context
            guild_id = vc.guild.id
            
            # Check if the guild ID exists in the dictionary
            if guild_id in channel_dict:
                channel = channel_dict[guild_id]
                await channel.send("Now playing: `{}`".format(next_song.title))

    except wavelink.exceptions.QueueEmpty:
        pass
    
    # Clear the channel_dict dictionary if the queue is empty
    if not vc.queue:
        guild_id = vc.guild.id
        if guild_id in channel_dict:
            del channel_dict[guild_id]

@bot.bridge_command()
async def play(ctx: bridge.BridgeContext, search: str):
    """Simple play command."""
    guild_id = ctx.guild.id
    channel_dict[guild_id] = ctx.channel
    await ctx.defer()

    if not ctx.voice_client:
        vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
    else:
        vc: wavelink.Player = ctx.voice_client

    try:
        tracks = await wavelink.YouTubeTrack.search(search)
        if not tracks:
            await ctx.send(f'No tracks found with query: `{search}`')
            return
        track = tracks[0]
        await vc.play(track)
        await ctx.guild.me.edit(deafen=True)
        await ctx.reply("Now playing: `{}`".format(track.title))

    except TypeError:
        try:
            pl = await wavelink.YouTubePlaylist.search(search)
            if not pl.tracks:
                await ctx.respond(f'Unable to access the url: `{search}`')
                
            await vc.play(pl.tracks[0])
            await ctx.reply("Now playing: `{}`".format(pl.tracks[0].title))
            await ctx.guild.me.edit(deafen=True)
            for i in pl.tracks[1:len(pl.tracks)+1]:
                await vc.queue.put_wait(i)

        except Exception as e:
            raise e

I just want your review on this, is this ok? Please improve me if you think I could do anything better in the code . Thanks :D

proud mason
#

i would make 1 change tho

trim cipher
#

πŸ‘€

proud mason
#

it might be better to store the channel only if the song played successfully

#

also, forgot a return at the end of this?

trim cipher
#

oh yea.. and also I have an idea:
I should just add the song in queue here:

#

maybe?

proud mason
#

πŸ€”

trim cipher
#

so that if I use play after adding a playlist, it just adds into the queue instead of skipping the queue and playing the recently requested song?

proud mason
#

oh yea makes sense

shadow gate
#

Are there any workarounds for determining speaking status start and end?

proud mason
shadow gate
#

The best I have right now is exporting discord.js user speaking status. I mean it works but it's resource heavy and might need two bots

proud mason
#

speaking status?

#

oh the green thing?

shadow gate
#

an event when a user starts speaking in a voice chat, and when they end

proud mason
#

voice events dont come through the main gateway iirc. so it might be weird to dispatch that as a normal event

#

most voice stuff isnt documented too unfortunately

#

##1984 was already a giant headache (it had to workaround bugs in discord clients) 😭

errant craneBOT
shadow gate
#

I'll back up to explain what I'm trying to do. I have a voice bot speaking to gpt. What I want to do is have the user speak to initiate the recording, and when he stops add that to the buffer and send that to openai's whisper for transcript

shadow gate
#

Right now I have to use a command to initiate the recording. Soo.... after searching I just found discord.js could give me an event on speaking. I just export that now. But it's clunky

proud mason
#

you could determine the pause on your own

#

not super easy, but possible

#

decide a timeout duration

shadow gate
#

read the buffer I guess?

proud mason
#

create your own Sink and override the write method. this is called for every packet, and the bytes are passed to it

#

beware tho. voice on discord is a very dark place blobpain

shadow gate
#

o.o hows that?

full basin
#

Can a tasks.loop() get started as multiple instances? or how could I create a task that i can start with different params

fervent cradle
#

I can't send a custom emoji through a webhook

full basin
#

Yes you can

proud mason
fervent cradle
proud mason
full basin
#

would asyncio.create_task with a coro be better then

#

cause i assume asyncio just creates the task and doesnt care if theres already one

proud mason
full basin
#

hm

proud mason
#

it just takes a coroutine.. there is no such thing as a "duplicate" task

#

you can make your own version of a task loop pretty easily tbh

full basin
#

do i look smart om

sage bear
#

i’m wanting to store the inputted values from a modal that can be submitted multiple times so that i can use the inputted information later. but i’m not sure how to store it and how to store the values if the nodal has been answered more than once

shadow gate
#

What's the event on a user start speaking and end speaking?

proud mason
#

So there isn't really an explicit event for start speaking and end speaking

Discord has a general SPEAKING event, and it should have the currently speaking members

#

Pycord doesn't directly expose any of this, but you might be able to work your way around stuff

shadow gate
#

oof

proud mason
#

The voice client will have a ws attribute

#

This is of the DiscordVoiceWebSocket class

#

At the end, it calls _hook

#

You can override this method

shadow gate
#

This is incredible so far

proud mason
shadow gate
#

Even if it doesn't it's still huge

proud mason
#

Lul

#

And use that when connecting

#

You can bubble the websocket events up into the VoiceClient if that makes life easier

proud mason
proud mason
shadow gate
#

You are amazing :3

proud mason
#

Lol no worries

full basin
#

@proud mason I used asyncio.create_task tbh

#

Does what i need it to

shadow gate
#

This is probably entirely wrong >.>```from discord.voice_client import VoiceClient
from discord.gateway import DiscordVoiceWebSocket

class CustomDiscordVoiceWebSocket(DiscordVoiceWebSocket):

async def _hook(self, args):
    msg = args[1]
    op = msg['op']
    data = msg.get('d')

    # Handling the speaking event
    if op == self.SPEAKING:
        user_id = data['user_id']
        speaking = data['speaking']

        if speaking:
            print(f'User {user_id} started speaking')
        else:
            print(f'User {user_id} stopped speaking')

    await super()._hook(args)

class CustomVoiceClient(VoiceClient):

# A method where we handle the connection
async def connect(self, *, timeout, reconnect):
    self.ws = await CustomDiscordVoiceWebSocket.from_client(self)
    self._connected.clear()
    await self.ws.poll_event()
    self._connected.set()

async def on_voice_state_update(self, data):
    await super().on_voice_state_update(data)
    self.channel = self.guild.get_channel(int(data['channel_id']))
    await self.channel.connect()

async def connect_websocket(self):
    self.ws = await CustomDiscordVoiceWebSocket.from_client(self)
    self._connected.clear()
    while self.ws.secret_key is None:
        await self.ws.poll_event()
    self._connected.set()
    return self.ws```
proud mason
proud mason
#

not sure what you are doing here tho

        self.channel = self.guild.get_channel(int(data['channel_id']))
        await self.channel.connect()
#

also, why this part?

#
    # A method where we handle the connection
    async def connect(self, *, timeout, reconnect):
        self.ws = await CustomDiscordVoiceWebSocket.from_client(self)
        self._connected.clear()
        await self.ws.poll_event()
        self._connected.set()
shadow gate
#

I'm a moron πŸ˜„

warm grotto
#

How do I change the discord.ScheduledEventLocation value to a discord.StageChannel?

cyan quail
warm grotto
cyan quail
#

you just pass the channel in

#

admittedly the docs aren't very clear on this, but location allows channel objects

warm grotto
cyan quail
#

huh hold on

warm grotto
#

Also tried: py event.edit(location = discord.ScheduledEventLocation(value=StreamServer.get_channel()), but a state parameter is required, and don't know where state comes from, looking at the documentation and GitHub code

cyan quail
#

what you did the first time is correct

#

just checking, does this line return a real channel object if you print it?

cyan quail
#

i think i've found the issue anyway, will PR a fix

warm grotto
#

Great! Thanks

cyan quail
#

wait huh

#

the error just randomly stopped...?

warm grotto
#

So if I try again it works?

cyan quail
#

...hopefully?

#

i got the error the first time i tried editing

#

then added prints to debug on a different bot

#

but then it never errored again on either

#

possibly a discord issue since i didn't actually change anything

young bone
#

Isn`t also better to use get_channel and fetch_channel if get doesnt really get the channel?

cyan quail
#

perhaps but that wasn't the issue here

#

(and you can assume get to be reliable for the most part)

left flame
#

Is there a way to remove a cooldown set with @commands.cooldown() if, for example, there is an error in the command format?

twilit valley
#

I would like to store data about who was most recently awarded a certain role. I would assume that involves storing the user ID in a certain place and overwriting it when a new user is awarded that new role.

I could use a SQL database but that seems a bit overkill, is there a better way to do this or is it best to stick with the database?

shadow gate
#

I think I'll give up for now. If I can commission somebody to get it working I would! πŸ˜‰

shadow gate
#

I think for now I'll use a twin bot and pass the status from discord.js

proud mason
#

does received_message get called?

shadow gate
#

I get this from some print to consoles I got

GPT-Voice#4094 voice state updated: <VoiceState self_mute=False self_deaf=False self_stream=False suppress=False requested_to_speak_at=None channel=None> -> <VoiceState self_mute=False self_deaf=False self_stream=False suppress=False requested_to_speak_at=None channel=<VoiceChannel id=1111734121857826846 name='GPT-4-Voice' rtc_region=None position=0 bitrate=128000 video_quality_mode=<VideoQualityMode.auto: 1> user_limit=0 category_id=1088622266100756590>>
alphabeta.#0 voice state updated: <VoiceState self_mute=False self_deaf=False self_stream=False suppress=False requested_to_speak_at=None channel=<VoiceChannel id=1111734121857826846 name='GPT-4-Voice' rtc_region=None position=0 bitrate=128000 video_quality_mode=<VideoQualityMode.auto: 1> user_limit=0 category_id=1088622266100756590>> -> <VoiceState self_mute=False self_deaf=False self_stream=False suppress=False requested_to_speak_at=None channel=None>
alphabeta.#0 voice state updated: <VoiceState self_mute=False self_deaf=False self_stream=False suppress=False requested_to_speak_at=None channel=None> -> <VoiceState self_mute=False self_deaf=False self_stream=False suppress=False requested_to_speak_at=None channel=<VoiceChannel id=1111734121857826846 name='GPT-4-Voice' rtc_region=None position=0 bitrate=128000 video_quality_mode=<VideoQualityMode.auto: 1> user_limit=0 category_id=1088622266100756590>>
#

Not that I can tell from this at least

proud mason
#

hmm doesnt seem useful

shadow gate
#

I'll stop for now. Maybe when I come back to it I'll find something obvious I'm missing

iron halo
#

if i change the code in a cog and reload is it meant to update with the changes? or have i done something wrong

sage bear
#

@prisma flicker

proud mason
iron halo
proud mason
iron halo
#

i just changed the text in an embed

#

to see if it worked

sage bear
#

i’m wanting to store the inputted values from a modal that can be submitted multiple times so that i can use the inputted information later. but i’m not sure how to store it and how to store the values if the nodal has been answered more than once

proud mason
proud mason
proud mason
# sage bear yes and yes

so you could have a dict with the message id as they key, and your data as the value (probably a list/dict)

sage bear
#

wait, wdym?

novel yacht
#

is that correct?πŸ˜… when i pasting

@mod.command(name="action", description="Create a moderation action")
    @option(name="user", description="The user to take action on", type=option, required=True)
    @option(name="action", description="The type of action", type=option, required=True, choices=ACTIONS)
    @option(name="timeend", description="The duration of the action (optional)", type=option)
    @option(name="reason", description="The reason for the action", type=option, required=True)
    async def action(self, ctx: commands.Context, user: discord.User, action: str, reason: str, timeend: str = None):```

````   from discord.commands import SlashCommandGroup, OptionType
ImportError: cannot import name 'OptionType' from 'discord.commands' (/usr/local/lib/python3.8/dist-packages/discord/commands/__init__.py)

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

Traceback (most recent call last):
  File "core.py", line 114, in <module>
    bot.load_extension(cog)
  File "/usr/local/lib/python3.8/dist-packages/discord/cog.py", line 910, in load_extension
    self._load_from_module_spec(spec, name)
  File "/usr/local/lib/python3.8/dist-packages/discord/cog.py", line 777, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cmd.mod.mod' raised an error: ImportError: cannot import name 'OptionType' from 'discord.commands' (/usr/local/lib/python3.8/dist-packages/discord/commands/__init__.py)```
cyan quail
#

so you don't need the import at all

#

also type=option will break the whole thing, you don't need that either because it will inherit from the annotation

young bone
#

Also dont use ctx: commands.Context that is a slash command and not a prefix command ;3

novel yacht
#
@mod.command(name="action", description="Create a moderation action")
    @option(name="user", description="The user to take action on", required=True)
    @option(name="action", description="The type of action", required=True, choices=ACTIONS)
    @option(name="timeend", description="The duration of the action (optional)")
    @option(name="reason", description="The reason for the action", required=True)
    async def action(self, ctx, user: discord.User, action: str, reason: str, timeend: str = None):

like that?
upd
upd

copper pine
#

The buttons on my bot don't last very long, after a couple of minutes they stop working. I think it's a timeout issue, but I've seen bots with buttons that last much longer. Does anyone know how I can solve this?

cyan quail
copper pine
#

thank you

cyan quail
#

otherwise the changes you're making are correct

#

oh well

#

you still need ctx after self

grizzled sentinel
cyan quail
#

just that the previous typehint was wrong

novel yacht
cyan quail
#

ok you're BASICALLY there py ctx: commands.Contextwhat zerv was pointing out here is that this shouldn't be commands.Context, but rather discord.ApplicationContext (or just leave it as ctx)

novel yacht
#

but again i removed/updated, and again that problem

  File "/usr/local/lib/python3.8/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 848, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/mikis/cmd/mod/mod.py", line 7, in <module>
    from discord.commands import SlashCommandGroup, OptionType
ImportError: cannot import name 'OptionType' from 'discord.commands' (/usr/local/lib/python3.8/dist-packages/discord/commands/__init__.py)

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

Traceback (most recent call last):
  File "core.py", line 114, in <module>
    bot.load_extension(cog)
  File "/usr/local/lib/python3.8/dist-packages/discord/cog.py", line 910, in load_extension
    self._load_from_module_spec(spec, name)
  File "/usr/local/lib/python3.8/dist-packages/discord/cog.py", line 777, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cmd.mod.mod' raised an error: ImportError: cannot import name 'OptionType' from 'discord.commands' (/usr/local/lib/python3.8/dist-packages/discord/commands/__init__.py)
cyan quail
#

just remove the import...

#

it doesn't exist and you aren't using it

iron halo
novel yacht
young bone
cyan quail
iron halo
#
class Admin(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @admin.command(name="givemoney", description = "Bot owner only")
    @option("member", description = "The user that you want to give money to", required = True)
    @option("amount", description = "The amount of money you want to give", required = True)
    @option("reason", description = "The reason for giving the money", required=True)
    async def givemoney(self, ctx: discord.ApplicationContext, member: discord.Member, amount: int, reason: str):
      await ctx.respond("abc")
#

that gives the nonetype thing error

cyan quail
#

how is admin defined

iron halo
#

admin = bot.create_group("admin", "Admin commands", guild_ids=[1129032612288147526])

cyan quail
#

ok slight readjustment

#

wait

cyan quail
#

is that cog in the same file as your bot?

#

nice

iron halo
#

no i imported it

cyan quail
#

hmmm don't do that

#

you shouldn't import bot to cogs

#

slash groups in cogs are defined a bit differently

#

inside the class but outside the init, you should create a SlashCommandGroup ```py

admin = discord.SlashCommandGroup(...)

@admin.command()
async def command(...)```
iron halo
#

ah reloading works now thanks

cyan quail
#

allgood

cunning furnace
#

Sorry to bother but does anyone know how i'd go about making a slash command option where I type in lets say 100 and it'll then display the choices as 100k, 100m, 100betc.

full basin
#

Autocomplete

errant craneBOT
#

Here's the slash autocomplete example.

fervent cradle
#

how could I add a role to an user?

#

By pressing a button

full basin
#

.rtfm member.add_roles

winter condorBOT
cunning furnace
fervent cradle
#

like when he presses the button

#

it gives a role by id

full basin
#

The method is the same

fervent cradle
#

oh ok

#

U got like an example or smthing?

full basin
#

You just apply the method to interaction.user

#

Get the role like any other role

iron halo
#

In 1: Application command names must be unique can it at least tell me which i have like 100

full basin
#

You have to check your code

iron halo
#

i commented like half of them out and it still says it ajfoisdjfds

fervent cradle
#

alr thanks

#

ye it works, ty

meager heron
#

Is it yet possible to allow multiple selection on a slash command option?

silver moat
prisma flicker
iron halo
#

reloading cogs wont add new slash commands is that normal or

solemn idol
simple canopy
#

is there an easy way to get all emojis from message?

#

i think there was something like that

iron halo
#

thats not what i mean

#

if you make a new slash command and then reload the cog then it doesnt show up you have to restart the whole bot

simple canopy
#

seems to be the only way i guess

#

is there an expression i can borrow

silver moat
#

I don't know how you are returning it

simple canopy
#

im stealing it

solemn idol
iron halo
#

i did

#

i dont see how its the same as what i said tho

#

im not unloading anything

silver moat
#

I think that should work

simple canopy
#

i think that works on :emoji_name: and the lower one

#

i am pretty sure discord.Message.content, and clean_content as well, returns emojis in <:name:id> format, and i only need that

#

i think i'll figure it out

#

thanks anyways

solemn idol
silver moat
simple canopy
#

yeah, i only need the "complicated" one

#

did it already anyways

silver moat
#

alright

undone falcon
#

if only one role fail to delete(exemple roles is 5 roles) (Forbiden), will it steal delete the 4 other roles that the bot have permisisosn to delete

undone falcon
#

I see but how do you know which one(s) failed ?

silver moat
#

you can check the member again

undone falcon
#

I see thank you !

#

🀩

#

I could also call the method on each role and it woudl be equivalent on atomic=True ?

#

but I would know for each roles if it failed without checking the member

silver moat
#

if you do it role by role and atomic is false, you would be able to catch which role removals didn't work

undone falcon
#

I see, I will do this yes thank you !

silver moat
#

at least I think this is how it works

undone falcon
#

Will try it thank you for you help

woeful spindle
#

anyone know why I’m getting random 404 unknown interaction errors even tho im defering?

hushed cargo
#

is there a way to get a list of the bots dm channels? i tried "bot.private_channels" but that returns an empty list

wet tartan
#

Anyone know?

#

i installed opus with homebrew

hushed cargo
#

is there a way i can have a button with a url that uses a different style

silver moat
#

but you could have a styled button that sends an ephemeral message containing the link or something

#

but that seems kinda clunky

hushed cargo
#

yea bc i made a better looking emoji i wanna use instead of the dumb one that style uses-

#

im guessing theres no way i could do that?

silver moat
#

url buttons can have emojis is that's what you're looking for?

hushed cargo
#

i want just the emoji not the emoji and the url icon thingy

silver moat
#

yeah sorry, I don't think that's possible

hushed cargo
#

dammit

#

oki- ty

silver moat
#

no worries

hushed cargo
#

no way i could like fork pycord and just change that? or is that pic a discord thing?

full basin
#

It's Discord's

hushed cargo
#

is there no way to have no text or anything with the button? closest thing i found was using an invisible unicode thingy but that makes the icon off centre

#

i really dont see why id want a label or anything here-

hushed cargo
silver moat
hushed cargo
#

i plan of having multiple buttons and they all just gonna have emojis so having one button thats a lil wider than the others wont look nice

#

like imma have at least another row hopefully full

silver moat
#

ok whatever floats your goat

hushed cargo
#

but yea ill see how i like this might change

primal furnace
#

If my bot is in 1,000 servers and I restart it. Do I need to wait some time before using guild.member if I wanna accurately fetch everyone?

proud mason
coarse spire
#

So, I'm responding to an interaction (when the user clicks a button) with another view. Is there any way to edit the original interaction and disable that button but still keeping the response to the interaction?

#

I've tried many different ways but none seem to work

storm oyster
coarse spire
storm oyster
#

Pass in ephemeral=True while replying then

coarse spire
#

ephemeral doesn't exist for interaction.message.edit

storm oyster
#

ephemeral can be only used in interactions

#

Here you wanted to disable the button so we used interaction.mrssage.edit

#

To send a new ephemeral message you'd want to do await interaction.response.send_message(..., ephemeral=True) if I'm not wrong

coarse spire
#

But if I edit the message first and disable the button, I get discord.errors.InteractionResponded: This interaction has already been responded to before when I try to respond to it

#

and if I disable the buttons after i've responded with the new view, it modifies the new view to the old one

storm oyster
#

Can you show your code

coarse spire
#

I know, I am doing that

coarse spire
# storm oyster Can you show your code
@discord.ui.button(label="Auto-setup", custom_id="autosetup", style=discord.ButtonStyle.blurple, row=0)
    async def auto_setup_callback(self, button, interaction):
        button.disabled = True
        await interaction.message.edit(view=self)
        await interaction.response.send_message("Do you wish to automatically configure the bot for this server?", view=confirm_auto_setup(), ephemeral=True)```
storm oyster
#

You get any errors?

coarse spire
#

Yeah. discord.errors.InteractionResponded: This interaction has already been responded to before

storm oyster
#

Use await interaction.followup.send()

#

Instead of interaction.response.send

coarse spire
#

That worked, thank you so much πŸ˜„

storm oyster
#

Np πŸ‘

spring hare
# woeful spindle bump

Depends on your code, but in my experience, discord just sometimes does that for no apparent reason (maybe ping or slow code, idk?)
If it doesn't affect your bot, then just ignore it.

woeful spindle
#

ill send my code one second

#
@shift.command(description = "Send a shift start message in #sessions.")
    @discord.guild_only()
    @checks.mr_only()
    @commands.cooldown(1, 3600, commands.BucketType.guild)
    async def start(self, ctx: discord.ApplicationContext):
        await ctx.defer()
        e = discord.Embed(colour = 0x2B2D31)
        e.title = "Bakery Shift"
        e.description = "A shift is happening!"
        nam = ctx.author.nick if ctx.author.nick else ctx.author.name
        e.set_footer(text = f"Hosted by {nam}", icon_url = ctx.author.avatar.url)
        e.timestamp = discord.utils.utcnow()
        ses = self.bot.get_channel(1110287864262033510)
        await ses.send("<@&1086399112922009650>")
        await ses.send(embed = e)
        await ctx.respond("Success! Shift successfully started.")

ignore indentation I’m on mobile rn

spring hare
#

Why are you... deferring?

#

I don't see any reason to defer in this code tbh

#

afaik ctx.respond can automatically defer if you respond after 3 seconds

woeful spindle
#

before i was deferring i was still getting unknown interaction but I can try again

spring hare
#

odd

#

Try without defer

#

Or.... use logger/profiler to check where you have bottlenecks

spring hare
cinder pilot
#

How to check if bot has perms to mention a role in a specific channel

woeful spindle
spring hare
cinder pilot
spring hare
#

Wdym?

#

You mean that?

cinder pilot
#

oh yes

spring hare
#

Or that?

cinder pilot
#

so I just need to check if it has mention everyone permission?

#

Okay got it

wet coral
cinder pilot
#

Thanks

cinder pilot
#

I don't think most people would give it

wet coral
#

Well but to be able to use it, you have to request it nevertheless.

cinder pilot
#

I just wanted to check something

#

I'll think about that later

#

thanks for your help

spring hare
#

Wait

wet coral
#

Whether that is before or after the bot joins you have to "ask" for it. Either in the bot adding menu or through some kind of message...

spring hare
#

You can check it easily

#

Member.guild_permissions -> Permissions

#

and mention_everyone

cinder pilot
#

yes I wasn't sure if mention_everyone could mention roles

spring hare
#

guild.me.guild_permissions.mention_everyone

cinder pilot
#

thank you

spring hare
wet coral
spring hare
#

Or... Not give perms when inviting

wet coral
spring hare
#

You can't delete or take role, but can easily change perms

wet coral
#

oh alright, I thought you can't do anything with it xD

spring hare
#

Yup

sage bear
#

does anyone know how i would input the data that has been inputted into a modal into a database but the modal has been answered multiple times?

fervent wing
#

how can i get someones display name with the new user name system?

young bone
young bone
#

?tag pomelo

obtuse juncoBOT
#

Before Pomelo-

member.name          -> username
member.nick          -> guild nick name
member.display_name  -> member.nick OR member.name

After Pomelo-

member.name          -> username
member.global_name   -> global display name (global nick name)
member.nick          -> guild nick name
member.display_name  -> member.nick OR member.global_name OR member.name
young bone
#

@fervent wing

prisma flicker
sage bear
sage bear
strange beacon
#

What are you wanting to know?

sage bear
#

okay so ive written this:

      con,cur = openCON()
      cur.execute(f"INSERT INTO details (userID) VALUES ('{interaction_1st.user.id}')")
      con.commit()
      closeCON(cur,con)```
however it doesnt insert anything
#

and i think thats why im getting an error later on

prisma flicker
#

Don't ever use f strings for sql

#

That's how you get sql injection attacks

sage bear
#

its not. a public bot

#

im just testing

prisma flicker
#

Still you should learn best practices

#

ReadTheDocs for your sql library, they'll show you the right way to do it

sage bear
#

ill stick with f strings for now

strange beacon
#

if you are building a f-string.. print it is it valid SQL

sage bear
#

it should work because ive used the exact same format before except this time its not inserting snything

strange beacon
#

should != is working

sage bear
#

wdym?

strange beacon
#

do you want to troublehsoot the issue, or believe something that is not working "Should" work

sage bear
#

oh wait

#

it is working, i was just looking in the wrong place

#

although

strange beacon
sage bear
#

i get an error later on mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE userID='1037772222145765406'' at line 1

#
                con,cur = openCON()
                sql = f"INSERT INTO details (order_details) VALUES (%s %s %s %s) WHERE userID='{interaction_4th.user.id}'"
                data = [q1, order1, q2, order2]
                cur.execute(sql, data)```
strange beacon
#

ID is an INT

prisma flicker
#

You're mixing %s with f strings? whyyyy 😭 just throw in one more %s

sage bear
#

it’s easier

sage bear
strange beacon
#

in your DB schema is id an int or a string?

sage bear
#

i’ve got it as a BIGNIT

strange beacon
#

but you are comparing it to a string... which mysql wont do without you converting it...

sage bear
#

so it will have to be INT?

strange beacon
#

so leave it as int

sage bear
#

okay

#

but i get an sql error if i set it as INT

strange beacon
#

there is no need to set it to an int... the varable will be an int

sage bear
#

so what data type shall i set it as

strange beacon
#

try this: userID={interaction_4th.user.id}

sage bear
#

same error

strange beacon
#

print the completed f-string and test it in a mysql client so trouble shoot the query itself.. as this is not really a pycord issue

topaz meteor
#

how do i end a previous user interaction if the same user initiates the same new interaction by using the same slash command

frigid crater
#

Can anyone explain to me why a slashcommand within a "cog" works fine for one, but when I try and add a second it just doesn't populate, neither does my code seem to reach the breakpoint and for the life of me I can't find out why! I have code readily available to read. I'm tearing my hair out.

prisma flicker
#

are the methods for your slash commands the same name?

frigid crater
#

I literally copy and pasted my working slashcommand (with autocomplete) and changed the appropriate variables and function names and it doesn't work. Doesn't even breakpoint.

prisma flicker
#

can you share the code please

frigid crater
#

How would you like it shared?

#

DM it you?

prisma flicker
#

how long is it?

#

you can just send it here

frigid crater
errant craneBOT
frigid crater
#

the "unitget" command and its associated autocomplete works perfectly fine.

#

however the mapget command refuses to even populate the autocomplete field

prisma flicker
#

in mapget you take an argument gametype but your @option is named mapget

frigid crater
#

oh shit

#

when the command is called from the slash command

#

which name does it take the function name?

prisma flicker
#

the names just need to match

frigid crater
#

right OK

prisma flicker
#

for unitget they're both unit

frigid crater
#

completely overlooked it, you know when you spend so long looking at something

#

You sir are a legend.

prisma flicker
#

happy to help πŸ™‚

wet coral
#

Can someone please explain to me this docstring of discord.Member.add_roles():

|coro|

Gives the member a number of Role\s.

You must have the ~Permissions.manage_roles permission to
use this, and the added Role\s must appear lower in the list of roles than the highest role of the member.

Given this role structure in my server:

  • Admin
  • Mod
  • User
  • something

Does that mean that if the user has only the User Role, I cannot add the Mod Role to them? That doesn't make any sense in my opinion but maybe I'm understanding it wrong...

#

||Oh and since when does discord format - as bullet points lol?||

full basin
#

the bots role must be higher than the users highest role

wet coral
#

yeah ok that's what I thought

full basin
#

its normal discord hierarchy, works the same way

wet coral
#

So the docstring is just a bit wrong