#Basic Pycord Help (Quick Questions Only)

1 messages Β· Page 91 of 1

full basin
#

you cant add roles to someone higher than you and you cant add roles higher than you

echo needle
#

Yo. Is there any way to send a message to a channel without using await?

full basin
#

no? .send is a coro..

#

kinda, they look confusing

echo needle
grizzled sentinel
spring hare
wet coral
#

he probably wants to send a message in an __init__ xD

echo needle
# grizzled sentinel Not a good way. You are likely doing something wrong. Can you show your code
from javascript import require, On
bedrock = require('bedrock-protocol')

import discord
from discord.ext import tasks

def start(ip, port, bot, relaychannel):
    from javascript import require, On
    bedrock = require('bedrock-protocol')

    client = bedrock.createClient({
        'host': ip,
        'port': int(port),
        'profilesFolder': "./authCache",
        'skipPing': True,
        'skinData': {
            'CurrentInputMode': 3,
            'DefaultInputMode': 3,
            'DeviceModel': 'Xbox Series X',
            'DeviceOS': 11
        }
    })


    print("joining...")
    @On(client, 'join')
    def handle(event):
        print(f"joined the game baby!")

    @On(client, 'text')
    def handle(name, packet):
        print(packet)
        print("Received text:", packet['message'])
        channel = bot.get_channel(1129506516215537684)
        #Cant Await to send to the channel
spring hare
#

wtf

echo needle
#

yep

spring hare
#

why you need 2 import?

wet coral
#

mc client?

spring hare
#

minecraft

echo needle
#

didnt see thaat

echo needle
wet coral
#

isn't there an async version of the lib?

echo needle
#

i dont think so

full basin
#

you dont think you or you didnt google it?

spring hare
echo needle
# spring hare Try to make handle function async?

I just get this error

C:\Users\George\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\javascript\pyi.py:201: RuntimeWarning: coroutine 'start.<locals>.handle' was never awaited
  del self.m[i]
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
spring hare
#

oof

wet coral
#

I think you may be able to do bot.loop.create_task(bot.send()), but this way you cannot get the result...

echo needle
#

wdym by the result?

wet coral
#

you can't get the return value of .send

#

The function executes but the return value is lost

echo needle
#

ah

spring hare
#

Isn't asyncio.run also works?

wet coral
#

The loop is already running afaik

#

so no

full basin
#

you could uh, get the event loop

#

and add a task

#

.rtfm bot.loop

winter condorBOT
#

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

full basin
#

.rtfm bot.event_loop

winter condorBOT
#

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

full basin
#

that

spring hare
#

pool

full basin
#

poll

prisma flicker
#

pull

silver moat
#

reset HEAD

wet coral
#

oh yeah xD
Am currently working with db pools...

#

@echo needle bot.loop, not bot.pool, what I wrote earlier

echo needle
#

okay

wet coral
#

so bot.loop.create_task(bot.send())

echo needle
#

ill try it

echo needle
#

thanks

#

it works, ive spent like 2 hrs tryna figure this out

#

luv u

wet coral
#

np πŸ™‚

topaz meteor
#

how do i end a user interaction

full basin
spare juniper
#

return ctx*2

gleaming falcon
#

I'm having a bit of a skill gap. I'm writing to a CSV file in memory; how do I pass that to discord.File so I can add it in a response? (I'm assuming I need to use discord.File?)

... stuff

output = io.StringIO()
writer = csv.writer(output)

writer.writerow(blah)

await ctx.respond(content="Your data...", file=discord.File(output.getvalue()))

But Discord is whining that the embed size is larger than 6000. I assumed this would be added as an attachment; should I be doing something else to force it?

gleaming falcon
#

Ah, apparently I had to send the output back into an io.BytesIO() instance

tribal girder
#

which one to edit the command message? (ctx.send) message?
discord.InteractionMessage.edit
discord.Interaction.edit_original_message
discord.InteractionResponse.edit_message

hushed cargo
#

youtube_dl sometimes returns a manifest link instead of the actual url i got past this by checking if several formats retured the proper link, first one that did was used, is there a better way to do this

proud mason
fervent cradle
#

I'm kinda confused about how to add a link button component since it doesn't have a callback

winter condorBOT
proud mason
#

using that

fervent cradle
#

πŸ‘

tribal girder
#

after selecting

proud mason
tribal girder
#

ty

proud mason
#

Sorry for the double pong

midnight ivy
#

hi

#

I want to set up a pagination with the / command but I don't understand anything for how many hours

midnight ivy
#

um yes

#

I don't understand the logic of pagination

coarse spire
#

Here's an example of pagination with embeds for a slash command:

my_pages = [
    Page(
        embeds=[
            discord.Embed(title="Page 1", description="This is page 1"),
        ],
    ),
    Page(
        embeds=[
           discord.Embed(title="Page 2", description="This is Page 2")
        ],
    ),
    Page(
        embeds=[
            discord.Embed(
                title="Page 3",
                description="This is page 3",
            )
        ],
    ),
]

@client.command()
async def test(ctx):
   paginator = Paginator(pages=my_pages)
   await paginator.respond(ctx.interaction)```
#

Basically, you pass all pages you want in the my_pages list, then you just pass the list to the paginator in the command and respond with it. The paginator does the rest.

midnight ivy
#

I usually set my commands with cog

#

Would the example you show work for my command?

coarse spire
#

Yeah. Just modify the slash command to work with the cog, and modify the paginator to be paginator = Paginator(pages=self.my_pages)

midnight ivy
#

and i worked with database sqlite

#

oky

sage bear
#

im looking for a value in one list, then once i have this value, i will use its index position to find a value in another list, however the code i have now gives me an index number that doesnt work and idk why

      if "orange" in values:
        position = order_details.index("orange")
        print(position)
        multiplier = amount[position]
        print(multiplier)
        price = multiplier * 6.95
        total_price.append(price)
        print(price)```
full basin
sage bear
#

yea but i wanna see if this way works

full basin
#

@sage bear show the lists

#

And the index

sage bear
#

this is my code

      con,cur = openCON()
      cur.execute(f"SELECT * FROM order_details WHERE userID = '{interaction.user.id}'")
      i = cur.fetchall()[0]

      order_details = i['order_contents']
      values = str(order_details.split(","))
      print(values)

      amount = extract_numbers_with_order(values)
      
      if "ss" in values:
        position = values.index("ss")
        print(position)
        multiplier = amount[position]
        print(multiplier)
        price = multiplier * 6.95
        total_price.append(price)```
#

i found out that its not giving me the position

#

its giving me the total number of characters before "ss"

silent meadow
#

how do I get the usrname of author 😭 i forgot how to code

full basin
silent meadow
#

pls send help

proud mason
winter condorBOT
#

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

proud mason
#

Yikes

winter condorBOT
proud mason
#

Lul

silent meadow
#

😭 whyd they change from ctx.username 😭

proud mason
#

I don't think that was ever a thing

loud sail
#

await ctx.message.clear_reactions() is this so correct?

proud mason
#

for prefix cmds, yes

loud sail
#

I would like to add reaction there and then remove them all again.

proud mason
#

ctx.message doesnt exist for slash cmds

#

you will need to fetch the message after responding

#

like message = await ctx.interaction.original_response()

loud sail
#

at this too?


message = ctx.respond("click")
        await message.add_reaction("βœ…")

proud mason
#

await respond btw

loud sail
# proud mason yes

what is the correct name for this?

# Remove all reactions from the message
        await ctx.respond.clear_reactions()

        # Edit the message with the time reached
        await ctx.respond.edit(content=f "You won the game in {time_taken_seconds} seconds!")

jaunty raft
jaunty raft
proud mason
#

you can use ctx.edit

fading vector
#

Why is this not accessible?

#

fsr if I comment out this line it does work again, why?

elfin dagger
#

it's probably because of global and local variables, try adding global end_time just under your async def

fading vector
#

I would but that just can't do since multiple functions have the end_time as a local variable.

#

I'm just curious why that local variable isn't in scope?

#

It should be right?

elfin dagger
elfin dagger
#

python probably sees the last line and thinks end_time is now a local variable

fading vector
#

Oh god in like every other language it works way different

#

I'm really used to C# and C++

elfin dagger
#

funny blue and yellow snake Python

prisma flicker
#

You could use classes and have instance variables instead

fading vector
#

I could but I'm too lazy to do that kek

#

I've already resolved the issue btw, I just removed the line. 200 iq play

prisma flicker
#

You could just rename one of the variables

iron halo
#

await ctx.respond("hfuioeshus", ephemeral=True") why is it not being ephemeral.

iron halo
#

i am

#

i need await ctx.defer(ephemeral=True) or something?

iron halo
#

ok ty

merry dune
#

Heya, i have question blobpain
creation of a cmd using the UID verify event and entering the role for 3 and more servers for one gamethinkCat

topaz meteor
merry dune
obtuse juncoBOT
#

dynoInfo No emotes match your search

trim cipher
#

why guild.owner returns None everytime?

wet coral
#

Where do you get the guild object from?

silver moat
trim cipher
#

oh yes, i am dumb nvm

#

and how do I fix tht #0 thing after usernames? is it possible?

silver moat
#

just remove it

trim cipher
#
@bot.event
async def on_command_usage(ctx: bridge.BridgeContext):
    """Simple command usage event."""
    user = ctx.author
    command = ctx.command
    await bot.get_channel(1129841517457051648).send(f"**{user}** (`{user.id}`) used **{command}** in **{ctx.guild.name}** (`{ctx.guild.id}`)")

error:

  File "C:\Users\Administrator\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\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 375, in invoke
    await injected(ctx)
  File "C:\Users\Administrator\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: HTTPException: 400 Bad Request (error code: 40060): Interaction has already been acknowledged.

Full Traceback: https://paste.zorino.in/capizomurabokaza.sql

#

but I am not responding to the application cmd, I just want to send a message to a specific channel

wet coral
#

are you sure the code part is where the error occurs?

#
File "c:\Users\Administrator\Documents\GitHub\Krishna\main.py", line 338, in help
    await ctx.respond(embed=embed1)

That's where the error occurs

trim cipher
#

but still, the event above doesn't work.. it neither gives any error nor sends the msg in required channel

wet coral
#

.rtfm on_command_usage

winter condorBOT
#

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

wet coral
#

on_command_usage doesn't seem like a valid event

trim cipher
#

uhmm, so wht can i use instead?

wet coral
#

.rtfm on_command

wet coral
#

you may be looking for just on_command

trim cipher
#

ohk

wet coral
#

but apparently doesn't work with slash commands...

#

if you want application commands (too) use on_application_command

proud mason
#

If you are using bridge commands, there is an event on_bridge_command too

#

@trim cipher ^

#

It will be fired for both, prefix and slash version

merry dune
# silver moat sorry, what's the question?

I doubt that the code will catch everything newly added from the database, especially if this database is of a global type, but it seems that I have already found a solution, it's always worth complaining before I understand how to do it blobpain

trim cipher
proud mason
#

Forgot that πŸ’€

trim cipher
#

lol, so I have to go with on_application_command atm

proud mason
#

You would need both, on_command for the prefix version, and on_application_command for the Slash version

Also do you have any other non-bridge commands? Those will trigger that too

trim cipher
#

nah, every cmd is a bridge cmd..

#

I will go with adding both events until bridge cmd comes out on pypi

proud mason
#

πŸ‘

wet coral
#

Is it possible for an api-using pycord function (like fetch or send) to raise an error because of connection issues? Do I have to account for that using try: excepts?
And when do HTTPExceptions actually happen? Retrieving the channel failed., how can it fail other than not found and missing permissions, which are 2 other exceptions?

sage bear
#

how do i disable a dropdown menu after it has been interacted with?

wet coral
#
select.disabled = True
#and
await interaction.edit_response(view=view) # the view object where the select is part of
#

Exact way depends on the way you define the view

silent meadow
#

any idea how I can mention such commands? in normal messages and in embeds??

sage bear
wet coral
#

You can get the command id by typing a command and right clicking it. You must have developer settings enabled

wet coral
sage bear
#

oh

#

whats wrong with it

wet coral
#

How do you define your Select menu? Subclassing or decorator in a view?

sage bear
#
class Select(discord.ui.View): # interaction_2nd, select menu
                    def __init__(self):
                        super().__init__(timeout=None)   ```
wet coral
#

and also generally the guide

silent meadow
#

@wet coral they also have a property right? for mentioning?

#

like slash_command.mention

sage bear
wet coral
#

</avatar:963218584404914247>
</avatar:963218584404914247>

true pewter
#

I am looking for the option to create a /mute command that uses the discord application to users without the need to add a role.

wet coral
sage bear
wet coral
#

oh yeah, sorry.

silent meadow
#

wait i still dont seem to get it :/

#

wai-

wet coral
#

disable it and then use self as view

silent meadow
#

i got it thanks mama

wet coral
silent meadow
#

i am pretty sure i can

slash_command.mention(name= command_name)

can I

wet coral
#

.rtfm ApplicationCommand

wet coral
#

.rtfm ApplicationCommand.mention

winter condorBOT
#

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

wet coral
#

no, you can't xD

silent meadow
#

ah duck

#

so I have to painstakingly find ids ow?

#

.rtfm discord.SlashCommand.mention

winter condorBOT
wet coral
#

nevermind, you can

silent meadow
#

would you look at that

wet coral
#

yeah

silent meadow
#

okay so

wet coral
#

sorry, thought ApplicationCommand is the real one

silent meadow
#

discord.SlashCommand.mention(name = name)?

#

haha no probs

wet coral
#

mention is a property, it doesn't have args

silent meadow
#

🀨

wet coral
#

so you need to have a SlashCommand instance for it to work

silent meadow
#

oh yea right

proud mason
#

.rtfm member.timeout

winter condorBOT
silent meadow
#

this is what it comes up w
<property object at 0x0000020071A952B0>

#

πŸ₯΄ whats goin on ong

wet coral
#

where do you want to mention the command? In a slash command callback?

#

do you want to mention the invoked command?

silent meadow
#

oh yea got it

#

</name:id> is the only way

proud mason
#

command.mention works tho

silent meadow
#

bro.

proud mason
#

how did you use it?

silent meadow
#

manually

#

like, find the id, and then use </name:id>

proud mason
wet coral
proud mason
silent meadow
#

idk I did use my cheap LOJIK and did command.mention(name = name)

#

πŸ’€

wet coral
#

Actually, if we're on that matter @proud mason, is it possible to mention a command and already pre-fill it?

proud mason
proud mason
silent meadow
#

lmao oke i get it now i see

wet coral
#

😦

#

would be cool

proud mason
#

discord limitation ig. try asking in ddevs server

wet coral
#

nah, don't need it currently anyways

proud mason
#

πŸ˜‚

wet coral
#

was just wondering xD

true pewter
proud mason
#

might be there from before too

true pewter
#

i have py-cord==2.4.1

proud mason
#

yes so it will work

proud mason
loud sail
#

I don't understand how to do it better right now. Pylance in vsc says it would be wrong.


await interaction.response.send_message(content=f"> **d - Dein Rivale ist {rival_user_name}\n- **Bestzeit des Users:** {rival_user_time}\n- **Zeitunterschied zwischen dir und dem User:** {time_difference} Sekunden", ephemeral=True)
        else:
            await interaction.response.send_message(content=f"- Du hast __keinen Rivalen__ im Leaderboard!", ephemeral=True)
    else:
        await interaction.response.send_message(f'- Es wurde leider kein Eintrag mit deiner User-ID in unserer Datenbank gefunden, {interaction.user}. Bitte spiele zuerst mit `/tens` eine Runde.', ephemeral=True)

wet coral
#

weird indentation

#

where does the if statement begin?

loud sail
# wet coral where does the if statement begin?
if rival_index <= len(self.leaderboard_list):
                rival_user = self.leaderboard_list[rival_index - 1]
                rival_user_name = rival_user[0]
                rival_user_time = rival_user[1]
                time_difference = rival_user_time - current_user_time

            await interaction.response.send_message(content=f"> **d - Dein Rivale ist {rival_user_name}\n- **Bestzeit des Users:** {rival_user_time}\n- **Zeitunterschied zwischen dir und dem User:** {time_difference} Sekunden", ephemeral=True)
        else:
            await interaction.response.send_message(content=f"- Du hast __keinen Rivalen__ im Leaderboard!", ephemeral=True)
    else:
        await interaction.response.send_message(f'- Es wurde leider kein Eintrag mit deiner User-ID in unserer Datenbank gefunden, {interaction.user}. Bitte spiele zuerst mit `/tens` eine Runde.', ephemeral=True)
wet coral
#

well there you have it. Just fix the indentation...

#

that looks gruesome, nothing fits together. We're using python, indentation matters here xD

loud sail
#

ah, it was due to an error above

wet coral
#

did you fix the indentation?

loud sail
#

yes πŸ™‚

wet coral
#

πŸ‘

sharp saddle
#

Is this normal that a slash command needs a long time to be registered and appear on the user's commands menu?

young bone
#

What do you mean?

sharp saddle
#

I have coded a slash command and I can't see any errors when I start my bot. However, I can't find the slash command when I type the keywords

rose flare
#
for member in ctx.guild.members:
    async for message in member.history(limit=1):

"discord.errors.HTTPException: 400 Bad Request (error code: 50007): Cannot send messages to this user"

what am I missing? I have default, members and message_content intents set up

rose flare
#

yeah, sorry, I just managed to figure it out:
the first Member it found was the bot itself, and it couldn't open a DM channel with itself

spring hare
#

oh, lmao

rose flare
#

also, apparently I misunderstood what the "async for x in member.history" does
I'm trying to get their last message from a specific guild

spring hare
#

Just don't reload your bot every 10 seconds on every command change

spring hare
#

You can get history as list if you want

#

messages = await channel.history(limit=123).flatten()
// messages is now a list of Message...

rose flare
#

somehow this lead to the bot trying to create a dm channel with itself

spring hare
#

Oh, sorry

#

Wait, member.history returns all users messages?

rose flare
#

I'm not sure yet, but on the first member it finds (which I've verified is the bot itself), it returns this error:

Traceback (most recent call last):
  File "/home/silk/.local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 178, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/silk/proj/malbot/cogs/test.py", line 124, in activity
    async for message in member.history(limit=1):
  File "/home/silk/.local/lib/python3.10/site-packages/discord/iterators.py", line 123, in __anext__
    return await self.next()
  File "/home/silk/.local/lib/python3.10/site-packages/discord/iterators.py", line 325, in next
    await self.fill_messages()
  File "/home/silk/.local/lib/python3.10/site-packages/discord/iterators.py", line 344, in fill_messages
    channel = await self.messageable._get_channel()
  File "/home/silk/.local/lib/python3.10/site-packages/discord/member.py", line 392, in _get_channel
    ch = await self.create_dm()
  File "/home/silk/.local/lib/python3.10/site-packages/discord/member.py", line 189, in general
    return await getattr(self._user, x)(*args, **kwargs)
  File "/home/silk/.local/lib/python3.10/site-packages/discord/user.py", line 519, in create_dm
    data: DMChannelPayload = await state.http.start_private_message(self.id)
  File "/home/silk/.local/lib/python3.10/site-packages/discord/http.py", line 371, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50007): Cannot send messages to this user
spring hare
#

wth? data: DMChannelPayload = await state.http.start_private_message(self.id)

#

uhm

sharp saddle
spring hare
rose flare
# spring hare uhm

I assume that, instead of trying to get only the messages from the Member's guild,
it tries to get all the User's messages,
including those in private DMs with the bot,
and it creates a DM channel to see if there's... messages from the User...

spring hare
#

If I understand correctly, member.history just tries to get dm messages instead of all messages in guild

#

Which is really strange

loud sail
#

intents etc. I have activated everything, and everything works without problems with the slash commands below.

spring hare
loud sail
spring hare
#

yes

wintry cosmos
#

Are Bots able to super react?

spring hare
#

wdym?

rose flare
wintry cosmos
#

^ this for e.g

spiral spruce
#

Members are Messageables

spring hare
#

I just never saw super reactions with bots

spring hare
#

Or... Go through the history of each channel and find a message there

rose flare
loud sail
# spring hare yes

what is the other name for it?

from discord.commands import slash_command, Option, SlashCommandGroup
#

from discord import slash_command ?

spring hare
#

yes

wintry cosmos
loud sail
loud sail
sharp saddle
#

I want to create a slash command with option required integer input and option with choices. Is their any example or guide about it?

errant craneBOT
#

Here's the slash options example.

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?

twilit valley
# silver moat check the audit log?

I guess that could work too... though id prefer to know how to accomplish this in case I have to solve similar problems requiring the bot to store data in a similar manner to this

#

ig what im looking for is that I could store it in some config-like file under, idk, "LAST_USER_AWARDED_ROLE", and I can easily manipulate what that is set equal to

silver moat
twilit valley
#

yes I know but I would like to know if there is something similar to this that I could store data in

#

im sure other programs have to do something similar to what I would like to do. How do they accomplish it?

silver moat
#

they would use some type of database

wet coral
#

Is interaction.custom_id == button.custom_id when a button is pressed?

proud mason
#

you could also tias

#

.tias

winter condorBOT
wet coral
#

but that would involve writing a new (small) bot and creating an application because I can't use the bot that I'm currently working on yada yada yada xD

silver moat
#

wait you guys test on production?

wet coral
#

who?

#

oh, me xD

#

No, I test on my test bot, but I mostly do everything there so I'd need a test-test bot xD

atomic python
#

Hello, can I send a variable to my button from a slash command ?
/search forthis
function to search for something on a db and return one id
PressButton > send id to client

full basin
#

Pass the variable to the view init

atomic python
#

thanks I got it working !

clear vault
#

I have a banner and if i try to print it the bot says i dont have one?!

clear vault
#

Random xD

young bone
#

I dont know?

clear vault
#

Useless xD

young bone
#

Why?

clear vault
#

Its dumb

spring hare
clear vault
silver moat
clear vault
#

Nvm got it. Its in jda too. My mistake

#

@silver moat how can i get the banner if i fetched the user? user.banner isnt working

full basin
#

.rtfm user.banner

winter condorBOT
clear vault
silver moat
#

you didn't await the fetch

full basin
#

You didn't await your fetch

clear vault
#

Ohhhhhhh oops

silver moat
#

idk

solemn idol
#

your fetch is awaiting you didn't it

clear vault
#

display_banner?!

full basin
#

There's no display banner

wintry cosmos
#

What to instead of interaction.response.defer since there already was a response?
If i just use interaction.defer() ill get this:
AttributeError: 'Interaction' object has no attribute 'defer'

full basin
#

You can't do .response.send_message if you defer

wintry cosmos
#

Got it, but i havent had deferred yet

#

i want to

full basin
#

interaction.response.defer

#

Just like you said

wintry cosmos
#

Wont work

raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before```
wintry cosmos
#
class Menu4(discord.ui.View): 
    def __init__(self):
        super().__init__(timeout=None)
    @discord.ui.button(label="Lock", style=discord.ButtonStyle.red, emoji="πŸ”’", row=0, custom_id="LockThread") 
    async def LockThread(self, button, interaction):
      embed = discord.Embed(color=discord.Color.green())
      embed.add_field(name="\n",value=f"Thread wurde geschlossen!")
      await interaction.response.defer()
      async with interaction.channel.typing():
        await asyncio.sleep(3)
        await interaction.response.send_message(embed=embed)
        await interaction.channel.edit(locked=True)
    @discord.ui.button(label="Archivieren", style=discord.ButtonStyle.red, emoji="πŸ“‚", row=0, custom_id="ArchiveThread") 
    async def ArchiveThread(self, button, interaction):
      embed = discord.Embed(color=discord.Color.green())
      embed.add_field(name="\n",value=f"Thread wurde archiviert!")
      await interaction.response.defer()
      async with interaction.channel.typing():
        await asyncio.sleep(3)
        await interaction.response.send_message(embed=embed)
        await interaction.channel.edit(archived=True)
silver moat
#

yeah defer is a response

wintry cosmos
#

i know for the send_message i should use interaction.followup.send now

silver moat
#

use

      embed = discord.Embed(color=discord.Color.green())
      embed.add_field(name="\n",value=f"Thread wurde geschlossen!")
      await interaction.response.defer()
      async with interaction.channel.typing():
        await asyncio.sleep(3)
-       await interaction.response.send_message(embed=embed)
+       await interaction.followup.send(embed=embed)
``` instead
#

k

full basin
#

Your defer isn't raising the error, it's the send_message

full basin
#

Literally explained it here

wintry cosmos
silver moat
#

average coding moment

sage eagle
#

hello there, is there any possible way to make like a middleware to intercept await ctx.respond? Or is there like a event that runs when a slash command has been executed and has NOT send anyhting?

silver moat
#

but that's for interactions in general as the name suggests

sage eagle
# silver moat `on_interaction`?

not really what i meant. I wanna intercept an embed from await ctx.respond, give it to an function and release the await ctx.respond with new embed

full basin
sage eagle
#

i wanna somehow automate this process and not copypasting some lines of code to do that 🀨

#

same thing when i want to add a new command and then forget about this embed editing part, that would be awful

silver moat
#

functions exist wow

silver moat
sage eagle
#

bro i am answering you with my message

silver moat
#

same

elfin dagger
#

if you're sending an embed with ctx.respond you're gonna be doing ctx.respond(embed = embed) can you not just, not do ctx.respond and just do work on the embed

#

i mean you're supplying all the data for responding yourself why would you need to respond then immediately intercept it

proud mason
shadow gate
#

How do I play an audio stream on a voice channel rather than a full file? I have an audio stream from elevenlabs. Just trying to reduce wait time on my bot

proud mason
#

You can use that

#

If I understood the docs correctly

#

In case the stream is not encoded,

#

.rtfm discord.FfmpegPCMAudio

trim cipher
#

hi! I actually was using wavelink with py-cord for sometime now. and I recently tried to update it to latest version from their GitHub repo. But I think it actually installed discord.py and other dependencies too. Now my code won't work coz I wrote it in py-cord.. so I uninstalled discord.py and wavelink and then re-installed wavelink with cmd shell pip install Wavelink --no-deps
Still, the code doesn't works. Any idea how can I fix it?

The error (if it helps):

  File "c:\Users\Administrator\Documents\GitHub\Krishna\main.py", line 2, in <module>
    import wavelink
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\wavelink\__init__.py", line 30, in <module>
    from .enums import *
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\wavelink\enums.py", line 24, in <module>   
    from discord.enums import Enum
ModuleNotFoundError: No module named 'discord.enums'
silver moat
trim cipher
sharp saddle
#

How to know how many commands do the bot registers or syncs?

wet coral
#

You may be looking for bot.commands or bot.all_commands

sharp saddle
#

My bot has two slash commands but it only shows that it has one command.

proud mason
#

.rtfm bot.walk_app

proud mason
#

Use this ^

lean iron
#

how do i get the latest version (2.5 or 2.5.x or else) of pycord?
is something like pip install -U git+https://github.com/Pycord-Development/pycord ? or
pip install -U git+https://github.com/Pycord-Development/pycord@ad2e0722f00aa44c923b70de942042d0fdb1ea62 ?
and where can i find the current change between 2.4.1 and 2.5 or 2.5.x

coarse spire
#

?tag install

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

coarse spire
lean iron
#

omg, thanks a lot

coarse spire
#

np πŸ™‚

true pewter
#

I have seen that in the documentation you can set the default permissions when creating the group but I don't understand how it works. I only know how to do it in the method itself.

#
    ban = SlashCommandGroup("ban", "Commands for ban a user from the server", guild_only=True,
                            permissions=["administrator", "ban_members"])

I only know how to do it like this

@discord.default_permissions(
        administrator=True
    )
summer rock
#

Hey guys. I tried make custom commands, but it only register one slash command per guild id. When I make other slash command it just dont register, but first still works. Do anyone know solution? Both commands by structure are almost the same.

clear vault
winter condorBOT
# summer rock Hey guys. I tried make custom commands, but it only register one slash command p...

Application Commands Not Showing Up?

  • Uninstall libraries that conflict with the discord namespace (e.g. discord.py).
  • Invite your bot with the application.commands scope.
  • Load cogs before bot.run() (e.g. not in on_ready).
  • Do not override on_connect.
  • Update to the newest version of py-cord (see ?tag install).
  • Turn off User Settings > Accessibility > Chat Input > Use legacy chat input.
  • Share your code and errors.
summer rock
proud mason
#

both

summer rock
#

okay

full basin
summer rock
# proud mason both

In CustomCommandCog load extension function def load_custom_commands(self): for filename in os.listdir(self.command_dir): if filename.endswith(".py"): extension_name = filename[:-3] full_extension_name = f"cogs.commands.customcommands.{extension_name}" module = importlib.import_module(full_extension_name) self.bot.load_extension(full_extension_name) print(f"Loaded {full_extension_name}") print(f"[{timestamp}] Custom Commands loaded!") and custom command ***_hello.py ```
import discord
from discord.ext import commands
from discord.commands import slash_command

class CustomCommand798155873435910154_hello(commands.Cog):
def init(self, bot):
self.bot = bot
self.admin_rights = False

@commands.slash_command(name="hello", description="Custom command for guild Limro CodeX created by Limro-Sama.", guild_ids=[837053695040159764])
async def hello(self, ctx):
    if ctx.author == self.bot.user:
        return

    if self.admin_rights and not ctx.author.guild_permissions.administrator:
        return

    await ctx.respond('hello')

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

#

now slash commands does not register at all. Only prefix commands work fine

clear vault
clear vault
summer rock
clear vault
summer rock
#

nope

clear vault
#

show me your code

summer rock
#
import os
import datetime
import asyncio

from discord.ext import commands
from dotenv import load_dotenv
from cogs.commands.createcustomcommand import CustomCommandsCog
from get_cogs_list import GetCogsList

cogslist = GetCogsList.cogslist
load_dotenv("./cogs/creds/credentials.env")
TEST = os.getenv("TEST")
MAIN = os.getenv("MAIN")
now = datetime.datetime.now()
timestamp = now.strftime("%d-%m-%y | %H:%M:%S")
bot = commands.Bot(intents=discord.Intents().all())

@bot.event
async def on_ready():
    await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="/help | =3"))
    cache_path = "./cogs/commands/customcommands/__pycache__"
    for file_name in os.listdir(cache_path):
        if file_name.endswith(".pyc"):
            file_path = os.path.join(cache_path, file_name)
            os.remove(file_path)
    print(f"[{timestamp}] Custom Commands .pyc cache cleared!")
    custom_commands_cog = bot.get_cog("CustomCommandsCog")
    if custom_commands_cog:
        custom_commands_cog.load_custom_commands()
    giveaway_check_cog = bot.get_cog("GiveawayCheck")
    if giveaway_check_cog:
        await giveaway_check_cog.giveaway_check()
    giveaway_cog = bot.get_cog("Giveaway")
    if giveaway_cog is None:
        print("Error: Giveaway cog is not loaded.")
        return
    print(f"[{timestamp}] Connected! Synced commands successfully!")

for ext in cogslist:
    try:
        bot.load_extension(ext)
        print(f"Loaded {ext} cog")
    except Exception as e:
        print(f"Failed to load {ext} cog: {e}")

#bot.run(MAIN)
bot.run(TEST)```
proud mason
#

and where do you call load_custom_commands ?

#

ah

clear vault
#

ok wait

summer rock
#

main slash commands are working fine

proud mason
#

dont load them inside on_ready

summer rock
#

you mean get_cogs?

proud mason
#

custom_commands_cog.load_custom_commands() this thing

#

dont do it inside on_ready

#

do it before bot.run()

summer rock
#

what about other cogs in on_ready? move them outside too?

proud mason
#

yes

#

also, dont change presence on_ready

you can just pass it to bot = commands.Bot(..., activity=discord.Activity(...))

clear vault
proud mason
# clear vault why? xD

commands are synced on startup, before on_ready gets fired. if you load after it gets fired, they wont get synced

summer rock
#

Okay thanks! custom commands are working now. Presence too.

proud mason
#

nice

full basin
#

You're not getting it from a guild

clear vault
frigid crater
#

Sorted it - removed my messages so as not to waste someones time fyi.

sage bear
#

is there anyway that i can avoid this?

ValueError: 'corrupt' is not in list```

```py
      if "corrupt" in details.lower():
        position = values.index("corrupt") - 1
        multiplier = float(values[position])
        price = multiplier * 8.65
        total_price.append(price)
      elif "corrupts" in details.lower():
        position = values.index("corrupts") - 1
        multiplier = float(values[position])
        price = multiplier * 8.65```
#

if i input corrupts, then it thinks ive inputted corrupt and throws an error

foggy tartan
#

How can I get the guild_id to use it for creating different tables in mysql, for every guild? Just cant find anything

Want to do someting like this:
mySql_Create_Table_Query = """CREATE TABLE DB_""" + int(guildid) + """ ( Id int(11) NOT NULL AUTO_INCREMENT, User varchar(250) NOT NULL, Message varchar(5000) NOT NULL, PRIMARY KEY(Id)) """

elfin dagger
elfin dagger
elfin dagger
#

if this is intended you can put it in a try except which will catch the error and then you can handle it yourself

left flame
cinder pelican
#

Is it possible to keep messages ephemeral through multiple followups after a defer? As in, they're still ephemeral-like when you do it the obvious way, but with multiple followups, the bot is responding to itself, so it doesn't seem to keep the intended privacy

nvm, it turns out it works if you use ctx.send_followup() instead of interaction.followup.send()

modest mica
#

Hey there! I want to check if someone uploads a video to a channel, but when I check if a user has attachment, it just simply gives me back an empty array for any attachment

    @commands.Cog.listener()
    async def on_message(self, message):
        if message.author.bot:
            return
        print(message.attachments)
        if message.author.id == 378801849496764416:
            print(message.attachments)
modest mica
#

Okay, I actually managed to do a workaround by fetching the message

#
    @commands.Cog.listener()
    async def on_message(self, message):
        if message.author.bot:
            return
        if message.author.id == 378801849496764416:
            msg = await message.channel.fetch_message(message.id)
            print(msg.attachments)

And now I can see the attachments

proud mason
proud mason
silver moat
#

you probably have conflicting dependencies/packages

#

Do you have a requirements.txt?

#

yeah and re-install pycord

#

you did re-install py-cord right?

#

as in uninstall and install

wild elm
#

Question
Is it possible to resize or scale the image for embeds?

young bone
#

1 sec.

#

Im not 100% sure if its possible to do it

#

probatly not

wild elm
#

It doesnt appear so. This has no effect, regardless of what I input. I guess I need to play around with the image size manually to get things looking right.

wild elm
wild elm
#

No 😦

young bone
#

Can you show your pip list pls?

#

pip list > pip.txt would create a text file with your list at cmd

mossy holly
#

#faq message

young bone
#

jishkucord, topggpy, py-cord, discord.py uninstall all 4

mossy holly
young bone
#

you have to uninstall and reinstall only py-cord

#

it would not work if you just uninstall the other library's

proud mason
#

topggpy will install dpy

#

install it with no-deps flag

#

are you using a requirements.txt file?

#

how does it look?

#

did you freeze all libraries, or typed manually?

#

if you freezed all libs, you can remove dpy, and then use the no-deps flag in pip install

#

oof

young bone
#

For the pip stuff

proud mason
#

yea

young bone
#

like pip list > pip.txt stuff

#

how many items have choices?

warm spire
#

any way to get the voice history of a voice channel? like when members connected/disconnected?

warm spire
cinder pelican
#

I found a small bug, I think.

ctx.defer(ephemeral=True)
await paginator.respond()

leads to the buttons failing on the paginator. Easy workaround is adding ephemeral=True to the paginator call.

Is this worth a full bug report?

proud mason
#

also, 2.4.1? what happens on master?

cinder pelican
proud mason
#

ah

cinder pelican
# proud mason also, 2.4.1? what happens on master?

I can check, but idk off the top of my head. If anyone cares I can do a serious bug report. I just wanted to see, since it's a small thing with an easy workaround that will probably suck to actually fix

#

It has something to do with the paginator trying to find the message it's responding to, but it can't for some reason.

proud mason
#

hmm

#

seems like a legit bug? πŸ€”

cinder pelican
#

I think so, yes. It was very consistent

proud mason
#

can you send a non-ephemeral followup to an ephemeral defer?

cinder pelican
#

Sort of. It doesn't error there. It shows in an ephemeral, but raises whenever you try to change pages

#

So make the bug report?

proud mason
#

sure. no harm in making one

cinder pelican
#

Can do

proud mason
#

also, could you check if the issue is only with paginators, or any normal view too?

#

that will help the debugging process

cinder pelican
#

For sure. Do you just mean other ui elements?

proud mason
#

yes

cinder pelican
#

Gotcha. Yeah, I'll get on that now. Just finished my actual work for the day

cinder pelican
# proud mason also, could you check if the issue is only with paginators, or any normal view t...

It was only with paginators and yes I'm on 2.4.1. Here's the bug report: https://github.com/Pycord-Development/pycord/issues/2173

GitHub

Summary Paginator fails when not labeled ephemeral and responding to an ephemeral defer Reproduction Steps See minimal example and attempt to change pages Minimal Reproducible Code import discord i...

hushed cargo
#

how do i check if a user input is a valid emoji?

dusky tartan
#

can anyone help me figure why i get an error from this? the error is:

  File "c:\Users\kenan\OneDrive\Desktop\TBD Bot\bot.py", line 21, in <module>
    bot=discord.bot()
        ^^^^^^^^^^^^^
TypeError: 'module' object is not callable

the code is:

import os # default module
from dotenv import load_dotenv
from discord.ext import tasks, bridge
import pymongo
import httpx
import json

intents = discord.Intents.all()
intents.message_content = True
bot = bridge.Bot(command_prefix=".", intents=intents)

client = pymongo.MongoClient("db")
mydb = client["Users"]
mycol = mydb['Accounts']

sus = json_data = json.load(open('sus.json'))
cogs = sus['cogs']

load_dotenv()
bot=discord.bot()
intents = discord.Intents.default()
intents.guilds = True


@bot.event
async def on_ready():
    print(f"{bot.user} is ready and online!")
    await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f"{len(bot.guilds)} servers"))
    print(f"Currently in {len(bot.guilds)} servers.")
    servers = len(bot.guilds)
    await bot.change_presence(activity=discord.Game(name=f"Watching {servers} servers!"))


for cog in cogs:
    print('Loading', cog)
    bot.load_extension(f'cogs.{cog}')
    print('Loaded', cog + '!')


bot.run(os.getenv('TOKEN'))```
prisma flicker
#

Your code says bridge.bot not discord.bot like the error

young bone
#

Its two lul

prisma flicker
#

Oh yeah two bots

tall bear
#

How can I disable the explicit content filter for my bot?

brittle fable
#

Hey, does anyone know why my user mentions sometimes aren't being formatted properly? Example here - it happens pretty inconsistently

full basin
brittle fable
#

Ahh I see. Assuming that I can't do anything about it then since it's on the client side?

spring hare
wet coral
#

why is the View.message attribute not available in a View's on_timeout?

#

At least I get this error in the on_timeout, when trying to use self.message: AttributeError: 'NoneType' object has no attribute 'edit'

wintry cosmos
#

Why does this return NoneType?
thread_message = await interaction.channel.fetch_message(interaction.message.id)

its a channel created thread

wintry cosmos
#
thread_channel_name = bot.get_channel(interaction.channel.id)
      thread_channel_id_fetch = await interaction.channel.fetch_message(interaction.message.id)
      match = re.search(r'Thread id=(\d+)', str(thread_channel_id_fetch))
      if match:
          thread_id = match.group(1)
          print(thread_id)

This works, but wont work for a /reopen call.

#

And this seems waaay to complicated to "just" get the thread id but no other way worked.

shadow gate
#

when I try to just directly use voice.play on the audio object I get "TypeError: source must be an AudioSource not generator"

proud mason
#

you will probably need to create your own class

shadow gate
#

The client thing

from elevenlabs import generate, play

audio = generate(
    text="Hi! My name is Bella, nice to meet you!",
    voice="Bella",
    model='eleven_monolingual_v1',
    stream=True
)

play(audio)
#

That was just the example, in my code I returned "audio" to discord for the voice client to try to play

#

"returns audio as an audio stream"

#

hmm I'll try

import requests

CHUNK_SIZE = 1024
url = "https://api.elevenlabs.io/v1/text-to-speech/<voice-id>/stream"

headers = {
  "Accept": "audio/mpeg",
  "Content-Type": "application/json",
  "xi-api-key": "<xi-api-key>"
}

data = {
  "text": "Hi! My name is Bella, nice to meet you!",
  "model_id": "eleven_monolingual_v1",
  "voice_settings": {
    "stability": 0.5,
    "similarity_boost": 0.5
  }
}

response = requests.post(url, json=data, headers=headers, stream=True)

with open('output.mp3', 'wb') as f:
    for chunk in response.iter_content(chunk_size=CHUNK_SIZE):
        if chunk:
            f.write(chunk)

Then play the mp3

proud mason
#

you can even "stream" it instead of loading everything

shadow gate
#

thats the goal

#

to reduce latency for the user

proud mason
#

let me go through source. one sec

shadow gate
#

I already have it working if I output the entire file

proud mason
#

ic

shadow gate
#

well, I return a path after it does a save(audio, file_path)

proud mason
#

hmm so you can subclass discord.AudioSource

proud mason
shadow gate
#

main function with on message event:
voice = get(bot.voice_clients, guild=message.guild)
file_path = sendtts(str(reply))
source = FFmpegPCMAudio(file_path)
voice.play(source)

(in the sendtts def):
audio = generate(
text=message,
#voice="Rachel",
voice="3EUfPs00hQIYWy6Kxcrx",
model="eleven_monolingual_v1",
)

    save(audio, file_path)
    return file_path
proud mason
#

so now what you should do is

proud mason
#

save it on a self variable

#

then override read and return next(self.stream)

#

ez

shadow gate
#

might be wrong docs

proud mason
shadow gate
#

mp3

#

as shown here:

import requests

CHUNK_SIZE = 1024
url = "https://api.elevenlabs.io/v1/text-to-speech/<voice-id>/stream"

headers = {
  "Accept": "audio/mpeg",
  "Content-Type": "application/json",
  "xi-api-key": "<xi-api-key>"
}

data = {
  "text": "Hi! My name is Bella, nice to meet you!",
  "model_id": "eleven_monolingual_v1",
  "voice_settings": {
    "stability": 0.5,
    "similarity_boost": 0.5
  }
}

response = requests.post(url, json=data, headers=headers, stream=True)

with open('output.mp3', 'wb') as f:
    for chunk in response.iter_content(chunk_size=CHUNK_SIZE):
        if chunk:
            f.write(chunk)
proud mason
#

mp3 is the compression format

shadow gate
#

er, mpeg?

proud mason
#

if i understand correctly, pcm or opus are encoding formats

#

not sure

#

another thing to note. generate is blocking. you might want to do stuff on your own using aiohttp

obsidian ermine
#

Possible to get the roles from a role select like the order they were added?
Discord sorts them after selecting to the role hierachie. I guesst not but any idea to do that programming wise?

wet coral
#

you'd need to keep track of adding roles to members and store that in a db I guess...

proud mason
wet coral
#

but you can sort them in the order the roles were created... if that helps

#

Is it possible to delete or edit views of a message, when the bot shuts down?
I suppose the on_timeout isn't called when the bot stops?

spring hare
#
class BetterBot(Bot, ABC):
      async def close(self):
        self.cooldowns_save()
        await self.aiosqlite_clean_up()
        await super().close()
wet coral
#

yeah, but how can I edit the messages that have view attached to them?

#

Probably save them somewhere right?

#

There isn't any bot attribute that stores all views or anything like that?

proud mason
#

it is not intended for public use iirc, so you will have to go through the source

#

but it might be smth related to bot._view_store

wet coral
#

oh, so you don't know what it is xD

#

Yeah, I saw something like that

proud mason
#

yea check that

scenic raven
#

Is there a way to make a text input box in a model bigger (i know you can have a single line one and a bigger one, but even bigger than that)?

spring hare
scenic raven
#

rip ty ✨

spring hare
#

You don't really have any other options πŸ’€

young bone
#

Also text only for a modal ;3

proud mason
#

lots of _ πŸ’€

young bone
wet coral
#

but thanks

#

Some documentation for all the "invisible" code would sometimes be great xD

proud mason
#

its supposed be "invisible" yk

spare hedge
#

how do i run the bot

spring hare
#

omfg

wet coral
coarse spire
#

lmao

full basin
#

I can't lmfao

elfin dagger
#

you feed it batteries

#

double a or triple a depending on the make and model

wet coral
#

I don't really understand the purpose/usage of the message_id parameter

summer rock
#

hey guys. Can pycord use localization on option names and descriptions? can I add localization to option names? @option("prize", description="Enter giveaway prize.")

wet coral
#

afaik yes, but don't ask me how xD

summer rock
river summit
#

.rtfm localization

summer rock
#

ok ty

wet coral
#

Is it safe to pass a discord.Message object to other functions and have it "waiting" there for usage or can it timeout or something?

#

or should I use a partial message instead?

proud mason
#

As long as you have a "strong reference" to the object, it should be fine

wet coral
#

it's a strong reference by default, right? Because I saw that pycord also uses weakrefs somewhere

shadow gate
# proud mason mp3 is the compression format

after doing some digging the output is lame encoding.
looks like this:
\xcaLAME3.100\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\x04(\xda\x8c\xb2\xed\x956T\x81\x84`\xd0\n\xe0\x00\xa4\xe0b\x8c\xf5\xba\x16\xc9%\x1d\xd0g\x8f\xf6aNB$\n\xc73}\xf2"\xe8\xb4T\x8a\xe4\xc1<x\x899\xd4J\x07\x06/\x9b.\x16\x1a"\xf6\x85\x19\x97E\x03\xcd\xdf\xfb\x96tT\\,\x11\x08\x01\xeck\xd5\xb9X\xd2\x15\xa3C\x138\xff\xff\xec\xd7i.2\x151\x99\xa5\x83C\xa8\x90X<J\xe3\xd1{\xd1T\xb9c\x8f\xdf\xff\xff\xf3o\xcd8\xa3\x1d\x0br\xca\x93Iec\xa0\x98n~\x8dy\x9a\xed\x95\xcc\xfc3}\xc3%7 C\xa0\x9bcv&\xd6\x8c\x82\xc2\x8

#

Their TTS class looks like this:

    @staticmethod
    def generate(
        text: str, voice: Voice, model: Model, api_key: Optional[str] = None
    ) -> bytes:
        url = f"{api_base_url_v1}/text-to-speech/{voice.voice_id}"
        data = dict(
            text=text,
            model_id=model.model_id,
            voice_settings=voice.settings.dict() if voice.settings else None,
        )  # type: ignore
        response = API.post(url, json=data, api_key=api_key)
        return response.content

    @staticmethod
    def generate_stream(
        text: str,
        voice: Voice,
        model: Model,
        stream_chunk_size: int = 2048,
        api_key: Optional[str] = None,
    ) -> Iterator[bytes]:
        url = f"{api_base_url_v1}/text-to-speech/{voice.voice_id}/stream"
        data = dict(
            text=text,
            model_id=model.model_id,
            voice_settings=voice.settings.dict() if voice.settings else None,
        )  # type: ignore
        response = API.post(url, json=data, stream=True, api_key=api_key)
        for chunk in response.iter_content(chunk_size=stream_chunk_size):
            if chunk:
                yield chunk```
#

the generate_stream is called and it chunks this lame encoding

fading vector
#

How can I get the global display name of a user?

#

e.g. in my case

shadow gate
fading vector
#

Yeah I thought that as well but I don't think that works, pretty sure it's just the username without the descriminator, which isn't a thing anymore for most anyway

shadow gate
#

ah

cyan quail
fading vector
cyan quail
#

(we are being ghosted)

fading vector
#

Is there an ETA?

cyan quail
#

no clue

#

master isn't particularly buggy tbf

#

we just can't make any guarantees

fading vector
#

I'll stick to current for now

#

My users are just gonna have to suffer with usernames for a bit

sage bear
#

if i input harvs, then it prints 2x the price, anyone know how to stop it from happening?

      for word in "harvester", "harvesters", "harv", "harvs":
        if word in values:
          position = values.index(word) - 1
          multiplier = float(values[position])
          price = multiplier * 8.50
          total_price.append(price)```
bleak jay
#

Question: what do you all think of storing data in fs? Surely Im not the only one who hates databases

bleak jay
bleak jay
#

For storing data

silver moat
#

dumb idea

#

because there's no failsafe

young bone
bleak jay
#

Databases are so confusing

silver moat
#
  1. Lack of data integrity
  2. Limited querying capabilities
  3. Poor performance with large datasets
  4. Limited concurrency and transaction support
  5. Lack of security and access controls
  6. Lack of scalability
cyan quail
#

you can create failsafes but learning sql or whatever language is easier for the most part

silver moat
#

These are just some that I thought of on the top of my head, if you would like me explain any of them further, please say so

bleak jay
#

I try to avoid storing data

#

Wait. SimonSays is stored in a dictionary. Tell me how angry u are

silver moat
#

Discord just stored that message you sent in JSON format

bleak jay
#

Jk lol. For extreme data protection I store user data in .env

|| this is obviously a joke||

silver moat
#

@round rivet what

round rivet
#

your mom

silver moat
#

thanks

bleak jay
#

I ❀️ files.

silver moat
bleak jay
silver moat
#

you have to learn some type of database eventually Β―_(ツ)_/Β―

prisma flicker
#

If you wrap your saving code in a single class/library you can replace the underlying storage without any code changes

rare ice
#

How can I add an asynchronous function to the discord.User class? Do I have to subclass?

wanton dock
#

I was wondering how to use slash commands with a bot created by commands.Bot (commands from discord.ext)? I've tried @bot.command(), @bot.slash_command(), and @bot.command(description="desc"). Thanks!

young bone
lime totem
#

how to read attachment ?
the Attachment.read() no work, because return me an bytes

cyan quail
cyan quail
#

it's meant to return bytes

rare ice
cyan quail
silver moat
#

why not add the method to your db class

rare ice
#

I want to do something like await user.get_economy_profile()

cyan quail
#

subclassing isn't worth it because then you'd have to override the class everywhere

#

this is why forking exists

silver moat
#

db.get_economy_profile(user)

rare ice
cyan quail
#

idk you don't have many other options

#

squid's idea is likely more sustainable

#

or fork it on github and install your own branch, then you can sync the changes from the main repo whenever necessary

silver moat
#

oh no merge conflicts

cyan quail
#

eh if you're adding your own single function then in theory you'd never conflict

rare ice
#

I only need it on one bot so I’ll probably just edit the files

silver moat
#

I have a feeling that vNziie just isn't reading my messages lol

rare ice
lime totem
#

(only .txt files) because i need to read the file

#

but, the read return me b'' as binary

cyan quail
#

probably with mode="rb"

lime totem
#

file: discord.Attachment

cyan quail
#

what's wrong...?

#

you read the attachment, which returns binary data, and then you use that with the builtin open function that you normally use with files

lime totem
#

thanks for your help πŸ˜‰

magic pendant
#

Can I get how long ago the user was last online?

candid coral
#

Hello. I don't understand how to get the list of roles of the member who wrote the message.

@client.event
async def on_message(message):
    if message.guild.get_roles(...) in message.author.roles:
        ...

This doesn't work because the User class doesn't have a roles variable. The message were sent to the server, not to the DM. The code runs but every time someone sends a message with the right role or someone is given or removed this role an error occurs

green hinge
#

Is it possible to have a Discord bot create an event?
My thought is that I create a slash command where I query all the data and then automated at a later time I specify in the slash command will create the event from the bot and published?

bleak jay
full widget
#

Is it possible to edit integration permissions in a server with a bot, other than via default permissions?

#

Can't see anything in the docs so guessing no, but figured I'd ask

slow vector
#

Best thing to do is have a json β€œconfig” file with your IDS and just import them into your cogs

candid coral
candid coral
# young bone And what is the error?
Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 399, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»ΡŒ\Desktop\ΠŸΡ€ΠΎΠ΅ΠΊΡ‚Ρ‹\server\bot.py", line 45, in on_message
    if not message.guild is None and message.guild.get_role(1131159247879680021) in message.author.roles \
AttributeError: 'User' object has no attribute 'roles'```
slow vector
#

The section

candid coral
#

Maybe I misunderstood your question

#

The code is not in Cogs, it is in the main bot file

coarse spire
#

You need to get the 'Member' object to retrive the user's roles. You can't use a 'User' object for it

clear vault
#

Code:

if not user.id in member.id:```
slow vector
slow vector
#

Try if member id == {}, unless that isn't what you're trying to do

clear vault
#

how is the best way to check if a user is on the same server?

slow vector
#
if member: discord.Member in ctx.guild:
    ... # pass true: member is in discord
else:
    ... # pass false: member not in discord
#

or you could just pass it as if member in ctx.guild if you define the member in the command

sage galleon
#

I’ve been out of the loop for a bit. Has there really not been any updates since March?

coarse spire
#

There have been no new releases since March, but a lot of progress has been made on the Master branch

summer rock
#

Will slash command description_localizations update every time user changes localization on discord? Or only after bot restart?

young bone
#

if not you have to restart the bot everytime

summer rock
#

where I have to add it?

#

.rtfm sync_command

young bone
#

Im not sure if sync_command is working well

#

@proud mason are you there?

summer rock
#

so I just have to add loop every for example 5 mins sync commands?

cyan quail
cyan quail
#

yes

#

as long as you've defined the language

summer rock
#

after how many mins?

cyan quail
#

should be instant, it's client sided

#

you don't do anything on the bot's end

summer rock
#

kk, I will check one more time

#

for me it changes only after I refresh server (go to other and then back to server)

cyan quail
#

well that's still client sided, not sure on how well it works with cache but as long as you've added the necessary languages you don't need to do anything extra

young bone
#

Are you sure about that?

cyan quail
#

wdym??

#

what else are you meant to do

#

they're talking about a user changing the language on their discord app

young bone
#

oh wait nvm

summer rock
#

also about sync_commands(). I am trying to sync custom commands guild_id after creating using this await self.bot.sync_commands(guild_ids=[guild.id]) , but it shows me Error: 400 Bad Request (error code: 50035): Invalid Form Body In 62: Application command names must be unique custom command name look like this ``` @commands.slash_command(name="hello", description="Test", guild_ids=[837053695040159764])
async def hello(self, ctx):

proud mason
clear vault
#

@slow vector py if user in ctx.guild: TypeError: argument of type 'Guild' is not iterable
Code:

    async def whois(self, ctx, user: discord.User = None):
        if user == None:
            user = ctx.author
        if user in ctx.guild:
            member = user```
proud mason
#

also, you should use user: discord.Member = None

slow vector
clear vault
slow vector
#

if user not in ctx.guild.members

clear vault
twin vale
#

How to do it?

proud mason
#

see this

novel yacht
#
import discord
from discord.ext import commands

class MyModal(discord.ui.Modal):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs, timeout=120)

        action_row = discord.ui.ActionRow()
        action_row.add_item(discord.ui.InputText(label="What is your name?"))
        action_row.add_item(discord.ui.InputText(label="How old are you?"))
        action_row.add_item(discord.ui.InputText(label="Have you worked in this line of work before?"))
        action_row.add_item(discord.ui.InputText(label="Why do you want to work with us?"))

        self.add_item(action_row)

    async def callback(self, interaction: discord.Interaction):
        embed = discord.Embed(title="Job Application")
        embed.add_field(name="What is your name?", value=self.children[0].values[0])
        embed.add_field(name="How old are you?", value=self.children[0].values[1])
        embed.add_field(name="Have you worked in this line of work before?", value=self.children[0].values[2])
        embed.add_field(name="Why do you want to work with us?", value=self.children[0].values[3])

        channel = interaction.guild.get_channel(1130274326281719848)  # Replace CHANNEL_ID with the specific channel ID you want to send the callback
        if channel:
            await interaction.response.send_message(embed=embed)
        else:
            await interaction.response.send_message(content="Error: Unable to find the specified channel.")

class Testing(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.slash_command(name="apply", description="Apply for a job")
    async def apply(self, interaction: discord.Interaction):
        modal = MyModal(title="Modal via Slash Command")
        await interaction.response.send_message(view=modal)

def setup(bot):
    bot.add_cog(Testing(bot))
``` started learning forms but i have error

Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 124, in wrapped
ret = await coro(arg)
File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 978, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "/home/mikis/testing/form.py", line 35, in apply
modal = MyModal(title="Modal via Slash Command")
File "/home/mikis/testing/form.py", line 8, in init
action_row = discord.ui.ActionRow()
AttributeError: module 'discord.ui' has no attribute 'ActionRow'

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

Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 375, in invoke
await injected(ctx)
File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: module 'discord.ui' has no attribute 'ActionRow'```

novel yacht
#

i ops its old guid

#
import discord
from discord.ext import commands

class MyModal(discord.ui.Modal):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs, timeout=120)

        self.add_item(discord.ui.InputText(label="What is your name?"))
        self.add_item(discord.ui.InputText(label="How old are you?"))
        self.add_item(discord.ui.InputText(label="Have you worked in this line of work before?"))
        self.add_item(discord.ui.InputText(label="Why do you want to work with us?"))

    async def callback(self, interaction: discord.Interaction):
        embed = discord.Embed(title="Job Application")
        embed.add_field(name="What is your name?", value=self.children[0].values[0])
        embed.add_field(name="How old are you?", value=self.children[0].values[1])
        embed.add_field(name="Have you worked in this line of work before?", value=self.children[0].values[2])
        embed.add_field(name="Why do you want to work with us?", value=self.children[0].values[3])

        channel = interaction.guild.get_channel(1130274326281719848)  # Replace CHANNEL_ID with the specific channel ID you want to send the callback
        if channel:
            await interaction.response.send_message(embed=embed)
        else:
            await interaction.response.send_message(content="Error: Unable to find the specified channel.")

class Testing(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.slash_command(name="apply", description="Apply for a job")
    async def apply(self, interaction: discord.Interaction):
        modal = MyModal(title="Modal via Slash Command")
        await interaction.response.send_message(content="Please fill out the job application form:", view=modal)

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

correct?

proud mason
#

you add InputTexts like this

class MyModal(discord.ui.Modal):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs, timeout=120)
        self.add_item(...)
        self.add_item(...)
#

yes

novel yacht
#

and... i getting that

Ignoring exception in command apply:
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 124, in wrapped
    ret = await coro(arg)
  File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 978, in _invoke
    await self.callback(self.cog, ctx, **kwargs)
  File "/home/mikis/testing/form.py", line 33, in apply
    await interaction.response.send_message(content="Please fill out the job application form:", view=modal)
  File "/usr/local/lib/python3.8/dist-packages/discord/interactions.py", line 825, in send_message
    await self._locked_response(
  File "/usr/local/lib/python3.8/dist-packages/discord/interactions.py", line 1090, in _locked_response
    await coro
  File "/usr/local/lib/python3.8/dist-packages/discord/webhook/async_.py", line 221, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
In data.components.1.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
In data.components.2.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
In data.components.3.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).

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

Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/discord/bot.py", line 1114, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 375, in invoke
    await injected(ctx)
  File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
In data.components.1.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
In data.components.2.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
In data.components.3.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).```
proud mason
#

oh right

#

sue interaction.response.send_modal

#

you cant send a message and a modal

novel yacht
#

hm

twin vale
proud mason
errant craneBOT
#

Here's the slash perms example.

proud mason
#

they will for work context menu cmds too

twin vale
novel yacht
# proud mason oh right

        channel = interaction.guild.get_channel(1130274326281719848)  # Replace CHANNEL_ID with the specific channel ID you want to send the callback
        if channel:
            await interaction.response.send_modal(embed=embed)
        else:
            await interaction.response.send_message(content="Error: Unable to find the specified channel.")

class Testing(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.slash_command(name="apply", description="Apply for a job")
    async def apply(self, interaction: discord.Interaction):
        modal = MyModal(title="Modal via Slash Command")
        await interaction.response.send_modal(content="Please fill out the job application form:", view=modal)

like that?

proud mason
#

nope

#

await interaction.response.send_modal(modal)

#

thats all

#

also, wtf is
await interaction.response.send_modal(embed=embed)

novel yacht
#

its where it will send

proud mason
#

even though Modal is related to View, dont mix those two

novel yacht
#

testing*

young bone
#

isn't it better to use ctx instead of interaction at the slash command?

proud mason
#

oh right

novel yacht
#
Ignoring exception in modal <testing.form.MyModal object at 0x7f12e04c0be0>:
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/discord/ui/modal.py", line 341, in dispatch
    await value.callback(interaction)
  File "/home/mikis/testing/form.py", line 17, in callback
    embed.add_field(name="What is your name?", value=self.children[0].values[0])
AttributeError: 'InputText' object has no attribute 'values'```
proud mason
#
- async def apply(self, interaction: discord.Interaction):
+ async def apply(self, ctx: discord.ApplicationContext):
young bone
#

@novel yacht take a look at this ^

novel yacht
#

i broke something, angy

novel yacht
#
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 378, in _run_event
    await coro(*args, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/discord/bot.py", line 1164, in on_connect
    await self.sync_commands()
  File "/usr/local/lib/python3.8/dist-packages/discord/bot.py", line 719, in sync_commands
    registered_commands = await self.register_commands(
  File "/usr/local/lib/python3.8/dist-packages/discord/bot.py", line 534, in register_commands
    desynced = await self.get_desynced_commands(
  File "/usr/local/lib/python3.8/dist-packages/discord/bot.py", line 360, in get_desynced_commands
    elif _check_command(cmd, match):
  File "/usr/local/lib/python3.8/dist-packages/discord/bot.py", line 275, in _check_command
    as_dict = cmd.to_dict()
  File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 844, in to_dict
    "options": [o.to_dict() for o in self.options],
  File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 844, in <listcomp>
    "options": [o.to_dict() for o in self.options],
  File "/usr/local/lib/python3.8/dist-packages/discord/commands/options.py", line 333, in to_dict
    "type": self.input_type.value,
AttributeError: 'NoneType' object has no attribute 'value'```
```py
import discord
from discord.ext import commands

class MyModal(discord.ui.Modal):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs, timeout=120)

        self.add_item(discord.ui.InputText(label="What is your name?"))
        self.add_item(discord.ui.InputText(label="How old are you?"))
        self.add_item(discord.ui.InputText(label="Have you worked in this line of work before?"))
        self.add_item(discord.ui.InputText(label="Why do you want to work with us?"))



    async def callback(self, interaction: discord.Interaction):
        embed = discord.Embed(title="Job Application")
        embed.add_field(name="What is your name?", value=self.children[0].value)
        embed.add_field(name="How old are you?", value=self.children[1].value)
        embed.add_field(name="Have you worked in this line of work before?", value=self.children[2].value)
        embed.add_field(name="Why do you want to work with us?", value=self.children[3].value)

        channel = interaction.guild.get_channel(1130274326281719848)  # Replace CHANNEL_ID with the specific channel ID you want to send the callback
        if channel:
            await interaction.response.send_message(embed=embed)
        else:
            await interaction.response.send_message(content="Error: Unable to find the specified channel.")

class Testing(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.slash_command(name="apply", description="Apply for a job")
    async def apply(self, ctx, interaction: discord.ApplicationContext):
        modal = MyModal(title="Modal via Slash Command")
        await ctx.respond("please apply")
        await interaction.response.send_modal(modal)
def setup(bot):
    bot.add_cog(Testing(bot))```
young bone
#

Why is it now ctx and interaction at the slash command?

#

@novel yacht

novel yacht
#

beacuse when it wasnt i getting error but modal opened

#

hello again how fix?
after pushing button

full basin
#

diff

twin vale
#

make ctx.respond visible only for user

novel yacht
# novel yacht hello again how fix? after pushing button
import discord
from discord.ext import commands

class MyModal(discord.ui.Modal):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs, timeout=120)

        self.add_item(discord.ui.InputText(label="What is your name?"))
        self.add_item(discord.ui.InputText(label="How old are you?"))
        self.add_item(discord.ui.InputText(label="Have you worked in this line of work before?"))
        self.add_item(discord.ui.InputText(label="Why do you want to work with us?"))



    async def callback(self, interaction: discord.Interaction):
        embed = discord.Embed(title="Job Application")
        embed.add_field(name="What is your name?", value=self.children[0].value)
        embed.add_field(name="How old are you?", value=self.children[1].value)
        embed.add_field(name="Have you worked in this line of work before?", value=self.children[2].value)
        embed.add_field(name="Why do you want to work with us?", value=self.children[3].value)
        embed.set_footer(text=f"Application submitted by {interaction.user.display_name}")
        # try:
        #     await interaction.response.send_message(content="Please fill out the job application form:", view=MyModal(title="Modal via Slash Command"))
        # except discord.HTTPException:
        #     pass

        channel = interaction.guild.get_channel(1130274326281719848)  # Replace CHANNEL_ID with the specific channel ID you want to send the callback
        if channel:
            await channel.send(embeds=[embed])
        else:
            await interaction.followup.send_message(content="Error: Unable to find the specified channel.")

class Testing(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.slash_command(name="apply", description="Apply for a job")
    async def apply(self, ctx: discord.ApplicationContext):
        modal = MyModal(title="Modal via Slash Command")
        await ctx.send_modal(modal)
def setup(bot):
    bot.add_cog(Testing(bot))
``` how fix this error?
silver moat
novel yacht
silver moat
#

for the modal callback?

twin vale
#

how make ctx.respond visible only for user

silver moat
obtuse juncoBOT
#

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)
novel yacht
slow vector
novel yacht
#

i fixed thanks

slow vector
#
class ExampleModal(discord.ui.Modal):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.add_item(discord.ui.InputText(label="Type STUPID if you are stupid!"))

    async def callback(self, interaction: discord.Interaction):
        response = (self.children[0].value).upper()
        if response == "STUPID":
            await interaction.response.send_message("You confirmed you are stupid!", ephemeral=True)
        else:
            await interaction.response.send_message("You did not confirm the stupidity, therefore I don't think you're stupid")

... # Within Cog Class
    @commands.slash_command(name="example")
    async def example(self, ctx: discord.ApplicationContext):
        modal = ExampleModal(title="Are you sure you aren't stupid?")
        await ctx.send_modal(modal)
#

Is pretty much the break down

haughty sluice
#

Is it possible to send dms to ppl in a server with a button attached to it that would spawn a modal?

wary rover
#

Hi, there,
Question, why does my bot manage to rename channels once every 2 to 5 minutes only twice? Has Discord changed anything?

wary rover
#

? kek

#

Is this a joke?

young bone
#

Because of the rate limit it works only every 10 minutes

#

Its not a joke

wary rover
#

Is Elon Musk the owner of Discord?

#

I can create and delete 50 channels but rename only once...

young bone
#

Yes phantomLOL

summer rock
#

Is this possible to get other user locale by user id?

lean marten
#

Ephemeral Messages suddenly stopped working anymore.

I have changed nothing.

proud mason
#

Are you 100% sure you didn't change anything and it worked earlier

grizzled sentinel
fervent cradle
#

Hello! How can I ping a role through a button?

await interaction.response.send_message(f"НовыС Ρ‚ΠΎΠ²Π°Ρ€Ρ‹ ΠΎΡ‚ **{interaction.user}** β€” {role.mention}")
slow vector
#

<@&roleid>

#

Or in your case "<@&{role.id}>"

fervent cradle
fervent cradle
#

whats the best way to removed expired powerups should i keep it in an on message event or in a on_application_command or something? where it would delete the users powerups or all power ups from the db?

proud mason
#

from slash cmd?

#

oh sorry

#

i misunderstood

#

you might need to play around with allowed_mentions

#

.rtfm AllowedMentions

proud mason
#

pass an object of that to the allowed_mentions parameter in interaction.response.send_message

fervent cradle
proud mason
fervent cradle
fervent cradle
proud mason
#

ah ok

#

you can add a before_invoke to the economy cog

fervent cradle
#

how?

proud mason
#

or maybe the Slash Group

#

one sec

fervent cradle
#

there isnt a group, its multiple commands

#

theres multiple groups i mean

proud mason
#

ah

#

single cog?

fervent cradle
#

yes

proud mason
#

let me just find

fervent cradle
#

and is it best to remove all of them? Or just the users that ran the command and let them know that what powerups were removed? Or maybe the person thats mentioned and the author or something idk

proud mason
#

.rtfm cog_before_invoke

winter condorBOT
proud mason
#

sql is powerful enough with the filtering

proud mason
fervent cradle
fervent cradle
fervent cradle
#

okay sick

fervent cradle
# proud mason yep

while not py-cord related


def handle_place(place: str) -> tuple[str, str]:
    places = response_json()['search_place_responses']
    place_data = places.get(place)
    if place_data is None:
        return None, None

    get_choice = random.choice(place_data)
    messages = get_choice.get("messages")
    item_probs = get_choice.get("gained", {})

    if messages is not None:
        sentence = random.choice(messages)
    else:
        sentence = None

    if item_probs:
        items = list(item_probs.keys())
        probabilities = list(item_probs.values())
        rand_item = random.choices(items, probabilities)[0]
        return sentence.format(str(rand_item)), rand_item, "item"

    if (coins_minmax := get_choice.get("coins")) is not None:
        coins_gained = random.randint(*coins_minmax)
        return sentence.format(str(Config().currencyEmoji), str(coins_gained)), str(coins_gained), "coin"

    return sentence, None, None
``` this is my function for the search command, and my json structure looks something like this
```json
"search_place_responses": {
        "Hospital": [
            {
                "messages": [
                    "You found yourself walking on top of needles, you fell to the floor and woke up years later"]
            },
            {
                "messages": [
                    "... gives you a **{}**",
                    "The nice nurse gave you a **{}**"
                ],
                "gained": {
                    "Silverware": 0.25
                }
            },
            {
                "messages": [
                    "You found **{} {}** ..."
                ],
                "coins": [200, 250]
            }
        ],}``` i was curious as to how can i make the chance of receiving the items smaller as in you would get coins more often than items since if theres just 1 item in the gained then the chance would be 100% for it, how can i make it a little smaller?
proud mason
#

but you could add a None or some placeholder entry at the end

#

and give it highest probability

#

you can use weights with random.choice to control the probability

fervent cradle
#

yeah i am in the gained

proud mason
fervent cradle
#

and what if its not? Then i tell them they gained None

#

cus i already have something for no items

proud mason
#

ig

#

thats what most bots do iirc

#

or maybe smth like You couldn't find anything

#

add it to your messages and give it a high weight

fervent cradle
#

but i am?

#
  "messages": [
                    "You found yourself walking on top of needles, you fell to the floor and woke up years later"]``` b asically for when u dont find anything, i sort of want to make the chance smaller cus theres a 3 in 1 chance u get the item, and if its lets say a rare item but theres just 1 u get it 100% No matter what
proud mason
#

or what?

fervent cradle
#

yeah, if its just 1 rare item its still got 100% chance to get it i want to lower that chance

proud mason
#

you could add noodles at all such things? πŸ€”

fervent cradle
#

wdym

proud mason
#

nvm im confused

#

wait for someone else

slow olive
#

Why is callback() not working?

full basin
#

That's nothing specific nor helpful for anyone

slow olive
#
Class Setup(ui.Modal):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.add_item(ui.InputText(
            style=discord.InputTextStyle.long,
            label="Label 1",
            placeholder="placeholder 1",
            required=True
        ))
        self.add_item(ui.InputText(
            style=discord.InputTextStyle.long,
            label="label 2",
            placeholder="placeholder 2",
            required=True
        ))

        async def callback(interaction: Interaction): ...

        async def on_error(interaction: Interaction): ...
#

Its not even calling the callback function

#

I tried with and without self doesnt work

full basin
#

You're missing self

full basin
#

And you're not even telling what the error exactly is

slow olive
#

Doesnt work with self either

#

No error

full basin
#

You must put self in the functions

#

It is a class. It isn't some optional thing

young bone
#

(self, interaction)

slow olive
#

It didnt work

full basin
#

Console errors?

slow olive
#

So i removed self but still doesnt work

full basin
#

What's the callback

slow olive
#

Nope no errors

young bone
full basin
#

You're not providing relevant code at all

slow olive
#

After the callback function the first thing is print("ok")

#

It doesnt print it

young bone
#

you need a line with interaction.response.send_message() without it, its not gonna work

slow olive
#

I have this await interaction.response.send_message(embed=embed)

#

Doesnt work

full basin
#

Show the actual code

full basin
#

Isn't it discord

slow olive
#
class Setup(ui.Modal):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.add_item(ui.InputText(
            style=discord.InputTextStyle.long,
            label="Project URL",
            placeholder="Local database - Create a database on Supabase and use its URL. Make sure the database is empty.",
            required=True
        ))
        self.add_item(ui.InputText(
            style=discord.InputTextStyle.long,
            label="API Key",
            placeholder="Local database - Create a database on Supabase and use its key. Make sure the database is empty.",
            required=True
        ))

        async def callback(interaction: discord.Interaction):
            print("ok")
            children = self.children

            await Essential.hook_local_database(url=children[0].value, key=children[1].value)

            embed = discord.Embed(
                title="Setup Successful",
                description="Your bot has been successfully set up.",
                color=discord.Color.from_rgb(204, 0, 0))
            embed.set_author(
                name=f"Requested by {interaction.user.name}",
                icon_url=interaction.user.avatar
            )
            await interaction.response.send_message(embed=embed)

        async def on_error(interaction: discord.Interaction):
            print("ok")
            exc_type, exc_value = sys.exc_info()
            embed = discord.Embed(
                title=exc_type.__name__,
                description=str(exc_value),
                color=discord.Color.from_rgb(204, 0, 0))
            embed.set_author(
                name=f"Requested by {interaction.user.name}",
                icon_url=interaction.user.avatar
            )
            await interaction.response.send_message(embed=embed)
cyan quail
#

not necessarily? it starts fine at the top

#

see

full basin
#

Yea

cyan quail
#

unindent callback and on_error by one level

full basin
#

They're in the init

slow olive
#

Oh bruh

cyan quail
#

also they should both have self as first parameter

slow olive
#

Yea i put it ty :D

candid coral
slow vector
#

Do you have conflicting libraries? Because that code works fine

prisma flicker
#

Oh you said it's not in a dm, my bad

#

But you should still have that to catch dms

candid coral
# prisma flicker You can do member = guild.get_member(message.author.id)

Unfortunately still an error
Code:

@client.event
async def on_message(message):
    if not message.guild is None and discord.utils.get(message.guild.roles, id=1131159247879680021) in \
            message.guild.get_member(message.author.id).roles and not "text" in message.content.lower():
        await message.delete()
        await message.channel.send("Wrong form.", delete_after=10.0)```

Error:
```py
Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 399, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\User\Desktop\Projects\server\bot.py", line 46, in on_message
    message.guild.get_member(message.author.id).roles and not "text" in message.content.lower():
AttributeError: 'NoneType' object has no attribute 'roles'```
#

The error is still displayed but code works too

#

I tried everything and the error still comes up... I'm sad

young bone
#

can you show your intents?

candid coral
young bone
#

why do you have also message_content intents?

#

you can remove this line intent.message_content = True @candid coral

candid coral
candid coral
grizzled sentinel
candid coral
candid coral
#

Even with this code, the bot doesn't see other commands