#Basic Pycord Help (Quick Questions Only)

1 messages · Page 88 of 1

proud mason
#

how do you initialise the lavalink stuff?

signal sandal
#

one sec

#
        await self.client.wait_until_ready()
        lavaclient = lavalink.Client(user_id=self.client.user.id, player=CustomPlayer)
        lavaclient.add_node(host='127.0.0.1', port=2333, password='gmkwob', region='us')
        lavaclient.add_event_hooks(self)
        self.client.lavalink = lavaclient
proud mason
#

ic

#

all the lavalink related commands stay in a single cog right?

#

so you could make a self variable in the cog init

#

smth like self.lava_ready = asyncio.Event()

signal sandal
#

yeah

proud mason
#

in your connect nodes method, do self.lava_ready.set() at the end

#

and in your cmds, add await self.lava_ready.wait() at the top instead of wait_until_ready

or you could use self.lava_ready.is_set() to return errors n stuff

signal sandal
#

well, i got the error to throw

#

thats nice

proud mason
#

oh cool

signal sandal
#

i had copied the error and footer stuff from a diffrent cog and stuff so it had bot, and i was tired yester day and i didnt catch it lmfao

proud mason
#

like here

signal sandal
#

well ive only got one

#

cool

proud mason
#

oh lol

signal sandal
#
@slash_command(description="Play some music (use again with no music selected to access menu). ")
    async def music(self, ctx, search: Option(str, description="Music query or URL", required=False, default=None)):

       await self.lava_ready.wait():
            embed = discord.Embed(color=0xBEFFE1)
            embed.set_author(name="Error!")
            embed.add_field(name="Spacey Boi",
                            value=" is starting up now, please try again in a few minutes")
            embed.add_field(name="Support Server", value="If you need help, feel free to join my support server over at [support.spaceyboi.com](https://support.spaceyboi.com)")
            embed.set_footer(text="Spacey Boi! • https://spaceyboi.com", icon_url=self.client.user.display_avatar.url)
            await ctx.respond(embed=embed)

        else:
            try:
                channel = ctx.author.voice.channel
            except AttributeError:
                return await ctx.respond(f"You need to be in a voice channel", ephemeral=True)
            player = self.client.lavalink.player_manager.create(ctx.guild.id)
            try:
``` this?
proud mason
#

looks good

#

dont forget to set the event in the connect nodes method

signal sandal
#

my current setup without the asyncio event seems to work okay

#

should i still make the change?

#
 async def music(self, ctx, search: Option(str, description="Music query or URL", required=False, default=None)):

        if not self.client.is_ready():
            embed = discord.Embed(color=0xBEFFE1)
            embed.set_author(name="Error!")
            embed.add_field(name="Initializing",
                            value="Spacey Boi! is still starting up, please try again in a few minutes")
            embed.add_field(name="Support Server",
                            value="If you need help, feel free to join my support server over at [support.spaceyboi.com](https://support.spaceyboi.com)")
            embed.set_footer(text="Spacey Boi! • https://spaceyboi.com", icon_url=self.client.user.display_avatar.url)
            await ctx.respond(embed=embed)

        else:
            try:
#

running this +

    @lavalink.listener(lavalink.events.QueueEndEvent)
    async def event_queue_end(self, event: lavalink.QueueEndEvent):
        guild_id = event.player.guild_id
        guild = self.client.get_guild(guild_id)
        await guild.voice_client.disconnect(force=True)
proud mason
signal sandal
#

ic

proud mason
#

It should be fine tbh

#

Depends on you

signal sandal
#

hope so

#

we wil find out

#

the gap is maybe 1 to 2 seconds

proud mason
#

Mhm

signal sandal
#

doubt any errors will be uncaught

#

any how, thanks for ur help

#

i asuume i will be back

#

im sure there is a far better way to do this but , ```
if not self.client.is_ready():
if uc < 100000:
embed = discord.Embed(color=0xBEFFE1)
embed.set_author(name="Error!")
embed.add_field(name="Initializing",
value="Spacey Boi! is still starting up, please try again in about 30 minutes")
embed.add_field(name="Support Server",
value="If you need help, feel free to join my support server over at support.spaceyboi.com")
embed.set_footer(text="Spacey Boi! • https://spaceyboi.com", icon_url=self.client.user.display_avatar.url)
await ctx.respond(embed=embed)
if 100100 < uc > 200000:
embed = discord.Embed(color=0xBEFFE1)
embed.set_author(name="Error!")
embed.add_field(name="Initializing",
value="Spacey Boi! is still starting up, please try again in a 20 minutes")
embed.add_field(name="Support Server",
value="If you need help, feel free to join my support server over at support.spaceyboi.com")
embed.set_footer(text="Spacey Boi! • https://spaceyboi.com", icon_url=self.client.user.display_avatar.url)
await ctx.respond(embed=embed)
if uc > 250000:

#

cut off bc char limit

proud mason
#

uh are you sure this is correct 100100 < uc > 200000

signal sandal
#

fixed

#

< uc <

#

yeah late night work is a bad idea, yet i do it

#

very pleasing not to see errors spamed

#

fr

#

so clean

#
uc = len(bot.users)
while uc == 50000:
    print("50k")
while uc == 100000:
    print("100k")
while uc == 150000:
    print("150k")
while uc == 200000:
    print("200k")
while uc == 250000:
    print("250k")
while uc == 300000:
    print("300k")
while uc == 350000:
    print("350k")

``` is this stupid or functional
#

basicaly prints when cached list reaches x ammount

#

wait, could i have it like
while uc == 50000+-x ammount:

#

uc = len(bot.users)
while 40000 < uc < 50000:
    print("50k")
while 90000 < uc < 110000:
    print("100k")
while 148000 < uc < 160000:
    print("150k")
while 190000 < uc < 210000:
    print("200k")
while 248000 < uc < 260000:
    print("250k")
while 290000 < uc < 310000:
    print("300k")
while 348000 < uc < 352000:
    print("350k")
``` updated
silver moat
#

why while loop

proud mason
#

exactly 💀

#

uc never gets updated inside the while loop either. so it is basically a while True loop

versed fern
#

?

signal sandal
#

just realized

#

ima sleep

silver moat
signal sandal
#

its 130am for me

#

il fix this tmr

proud mason
#

You could use self.add_item in the view init, and pass instances of discord.ui.Button

Make sure to set the rows for all buttons

topaz ginkgo
#

bot.get_user or guild.get_member is returning none even tho the user exists because its my id

Why? sad

proud mason
#

Also, passing int right?

topaz ginkgo
#

yk like for a dashboard

versed fern
proud mason
#

And how do you deploy?

proud mason
versed fern
#

argh

#

but thank ya

#

Wouldn't it be more intuitive for buttons added in init to be placed on the left and all buttons added after that to be on the right (in chronological order)?

proud mason
#

not sure

#

or wait

#

do you call super init before or after adding your buttons?

#

try calling super init after add_item

versed fern
#

before

#

I'll give it a try, thx

proud mason
#

👍

versed fern
#

doesn't work, since add_item appends the item to self.children which doesn't exist before super init is called

#

Could I just create self.children manually?

proud mason
#

you could see the workings of the decorator if you want

versed fern
#

I'll take a look

proud mason
#

hmm i just had a look. cant really use that

#

making empty functions might be the easiest way here

versed fern
#

That's sad but prob best, thank ya

#

Tbh, I didn't really understand the decorator code, where does it append the button to the view?

proud mason
#

yeah it doesnt. it sets this func.__discord_ui_model_type__ = Button. and then __init_subclass__ picks it up from that

versed fern
#

Shouldn't it be possible to change __init_subclass__ to get it to work?

#

If so, might be wise to change it for the entire library to make it more intuitive

proud mason
#

but yeah a mixture of add_item and decoraor is rare

topaz ginkgo
hazy merlin
#

Can anyone guide me on how to add aliases for prefix commands in bridge module?

silver moat
hazy merlin
#

So that means I just need to do this,
bridge.bridge_command(aliases=["alias1"])

Last time I tried this didn't work, must have missed something, I'll re-check

ocean jackal
#

nice, that worked! thanks again!

raven island
#

Any way I can programmatically get the old username of someone ?

proud mason
#

I'm not sure if bots can access that

raven island
#

I didn’t think so. I was trying to see if I could access the previous username and update my db with the new.

cyan quail
#

please don't tell me you used usernames as a primary key...

full basin
spring hare
#

What is the best away to add new functions to base Classes (for example to Interaction or Context) (maybe monkeypatching?)?
Like add await ctx.debug() to send embed with debug info

young bone
#

degug?

spring hare
#

typo

ionic hull
#

hi, it's me again

#

I continue learning how to use role connections

#

I have already created a connected role using my bot

#

and I see my linked role and app info in my profile

#

the problem is - other server members don't see the app info

#

and even I if i view server as any role I don't see it

#

any thoughts where have I mistaken?

wooden flame
#

Heya, what would this type of view be called in the docs?

candid coral
#

Hello. There was a problem understanding how to work with Cogs. Can you explain? I understood how to use Cogs, but not how to create them...

proud mason
#

Interaction is a Discord Model. Those shouldn't be and cannot be modified

spring hare
proud mason
spring hare
#

Oof

candid coral
spring hare
#

and add _init_ with self.bot

spring hare
candid coral
#

Do I need to create a Cogs folder in the folder where the main code file is located?

spring hare
proud mason
#

If it is a Data Class, you could modify it

proud mason
spring hare
candid coral
#

Will all Cogs be able to access the main database?

spring hare
spring hare
candid coral
#

Thank you

versed fern
#

I tried using await interaction.delete_original_response()but I somehow get the following error:

Ignoring exception in view <EmbedToolView timeout=180.0 children=20> for item <Button style=<ButtonStyle.danger: 4> url=None disabled=False label='Confirm' emoji=None row=4>:
Traceback (most recent call last):
  File "C:\Users\user\Documents\Programming\AIM-Bot\venv\Lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "C:\Users\user\Documents\Programming\AIM-Bot\cogs\messages.py", line 513, in cancel_editing
    await interaction.delete_original_response()
  File "C:\Users\user\Documents\Programming\AIM-Bot\venv\Lib\site-packages\discord\interactions.py", line 506, in delete_original_response
    await func
  File "C:\Users\user\Documents\Programming\AIM-Bot\venv\Lib\site-packages\discord\webhook\async_.py", line 219, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
proud mason
versed fern
#
    @discord.ui.button(label="ᅠᅠCancelᅠᅠ", style=discord.ButtonStyle.red, row=4)
    async def cancel_editing(self, button: discord.ui.Button, interaction: discord.Interaction) -> None:
        """Callback for the cancel button.

        Parameters
        ------------
        button: discord.ui.Button
            The button that was clicked.
        interaction: discord.Interaction
            The interaction that clicked the button."""
        if self.canceled_before:
            await interaction.delete_original_response()
            return
        self.canceled_before = True
        button.label = "ᅠConfirmᅠᅠ"
        await interaction.response.edit_message(view=self)
river summit
#

how can i detect when my bot is abt to go offline/shutting down?

#

i need it so i can close db connections

spring hare
#
class BetterBot(Bot):
    async def close(self):
        await self.aiosqlite_clean_up()
        await super().close()

    async def start(self):
        await self.aiosqlite_start()
        await super().start()```
proud mason
#

||start might be better than login||

spring hare
signal sandal
tribal girder
#

how to get user server name?

coarse spire
rare karma
#

How would I go about sending a message after a button timeout?

proud mason
signal sandal
spring hare
#

💀

proud mason
signal sandal
#

1 hr tho

versed fern
signal sandal
#

There are quite a few replys

#

But, u could make a shutdown function where you disconnect from your db

versed fern
#

Who are you refering to?

signal sandal
#

The reply’s below urs?

#

Oh mb they are for another question

versed fern
signal sandal
#

Gn

midnight ivy
#

hi

#

i added the button

#

but i cant the button how to disabled true on clicked

#

help me

#

@versed fern

#

.rtfm button disabled

proud mason
midnight ivy
#

code:

    def __init__(self, user_id, user_name):
        super().__init__()
        self.user_id = user_id
        self.user_name = user_name

    @discord.ui.button(label="Create", style=discord.ButtonStyle.green)
    async def button_callback(self, button, interaction):
        user_id = self.user_id
        user_name = self.user_name
        # createNewUser(user_id,user_name)
        button.disabled = True
        # await interaction.response.send_message('Kullanıcı oluşturuldu....', ephemeral=True)
        await interaction.response.edit_message(view=self)
        self.stop()
silver moat
#

What IDE/text editor are you using?

midnight ivy
#

what is this IDE?

spring hare
#

💀

midnight ivy
spring hare
midnight ivy
#

vs code

#

yes

silver moat
#

OS?

#

as in Operating System

#

Windows, Mac, Linux, etc.?

midnight ivy
#

Windows

#

11

silver moat
#

pip list in terminal and send output

midnight ivy
#

okay

#
aiosignal               1.3.1
asgiref                 3.6.0
async-timeout           4.0.2
attrs                   23.1.0
certifi                 2022.12.7
cffi                    1.15.1
charset-normalizer      2.1.1
colorama                0.4.6
configparser            5.3.0
discord                 2.2.3
discord.py              2.2.3
discord-py-interactions 5.7.0
discord-typings         0.6.0
Django                  4.2.1
EasyProcess             1.1
emoji                   2.6.0
entrypoint2             1.1
frozenlist              1.3.3
gevent                  22.10.2
greenlet                2.0.2
idna                    3.4
MouseInfo               0.1.3
mss                     9.0.1
multidict               6.0.4
numpy                   1.25.0
opencv-python           4.8.0.74
packaging               23.1
Pillow                  9.5.0
pip                     23.1.2
psutil                  5.9.5
PyAutoGUI               0.9.54
pycparser               2.21
PyGetWindow             0.0.9
PyMsgBox                1.0.9
pyperclip               1.8.2
PyRect                  0.2.0
pyscreenshot            3.1
PyScreeze               0.1.29
pytesseract             0.3.10
pytweening              1.0.7
pytz                    2023.3
requests                2.28.1
screeninfo              0.8.1
setuptools              65.5.0
sqlparse                0.4.4
tomli                   2.0.1
typing_extensions       4.7.0
tzdata                  2023.3
urllib3                 1.26.12
websocket               0.2.1
websocket-client        1.4.2
windows-curses          2.3.1
yarl                    1.9.2
zope.event              4.6
zope.interface          6.0
silver moat
midnight ivy
#

i stopped using it for a long time and so i forgot a lot of things

#

i restarted

silver moat
#

Ok, so switch the interaction and button args here:

class newUser(discord.ui.View):
    def __init__(self, user_id, user_name):
        super().__init__()
        self.user_id = user_id
        self.user_name = user_name

    @discord.ui.button(label="Create", style=discord.ButtonStyle.green)
-   async def button_callback(self, button, interaction):
+   async def button_callback(self, interaction, button):
        user_id = self.user_id
        user_name = self.user_name
        # createNewUser(user_id,user_name)
        button.disabled = True
        # await interaction.response.send_message('Kullanıcı oluşturuldu....', ephemeral=True)
        await interaction.response.edit_message(view=self)
        self.stop()
midnight ivy
#

okayy

#

it worked

#

thanks silly squid

silver moat
#

yw

hearty gorge
#

I want to add 📥 & 📁 to a button, when I copy and paste them into my code they convert to :strings:, which don't render back into an emoji if placed in label= or result in an exception ('Invalid emoji') if placed in emoji=. Copy and pasting the emoji equivalent \📥 & \📁 from a google result into my code works, but doesn't render it in Discord style. How do I get this working?

hearty gorge
harsh dome
#

I'm trying to handle errors globally, but it seems like on_command_error isn't called when I raise(mysql.connector.Error) when using /map. So my question is, is this because global error handling only allows for Pycord's specific errors? If so, how am I supposed to handle non-pycord errors?

@bot.event
 async def on_command_error(ctx, error):
     if (error, mysql.connector.Error):
         print("sql error!")

     print("Error occurs")
     if isinstance(error, commands.MissingRequiredArgument):
         ctx.send(
             "You are missing arguments. Please use `/help` to ensure that you are using the command correctly.")
     else:
         ctx.send(f"An unexpected error occured: {error} ")

@bot.command(name="map", brief="shows map", description="Shows the map of the community")
 async def showMap(ctx):
     # print(ctx.guild.id)
     raise mysql.connector.Error

     await ctx.respond(f"Her's the url: placeholder")
proud mason
hearty gorge
proud mason
#

you can get a fairly decent quality image by right-clicking the emoji in discord web

hearty gorge
proud mason
#

haha no worries

verbal marten
#

I'm trying to get the embed object from an old message. When I fetch the message using it's ID, it returns an _EmptyEmbed object. Is there any way to fix this?

neat flume
#

Greetings, I am trying to ping a role with a slash command however when the slash command goes through, the ping shows up but is not highlighted nor does anyone get a notification. I keep seeing people talking about "allowed_mentions" and I've tried using it in several different ways, but no luck.

I've attached the code that the slash command is in, and an example message when the command is ran. Any help, if possible, would be appreciated

proud mason
#

bot permission are kinda fucked up on discord's end with regards to interactions

#

try doing the same in a normal response message without deferring

somber pelican
#

hey everyone, if i defer() with ephemeral=True, does interaction.response.send() also become ephemeral?

somber pelican
#

ok ok thx

silver moat
somber pelican
#

ah right thanks!

neat flume
silver moat
proud mason
#

Interactions are webhooks under the hood

rare ice
proud mason
#

Makes sense

proud mason
#

Chat input is not the same as input text

rare ice
#

look at the embed

#

</test:1>

#

</test:1>

#

just shows /test with no ui

proud mason
#

Ah my bad

silver moat
rare ice
#

but i even did a valid slash command with the bot's id, and no mention

silver moat
#

you can't just mention non-existing commands

silver moat
#

it's not the bot ID

#

it's the command's ID

rare ice
#

oh

#

how am i supposed to get that without jsk

silver moat
#

or ctx.command.mention to skip the hassle

rare ice
#

ik i mean as a user

proud mason
#

Right click on the command after selecting it in chat input

rare ice
#

but the bot's id was easier

#

oh

silver moat
proud mason
#

Yep

silver moat
#

it doesn't

spring hare
young bone
spring hare
#

Yes, but not on mobile 💀

proud mason
#

Big F

young bone
#

There is so much that doesnt work on mobile xd

somber pelican
#

where do I set guild_only in a command group?

#

do I set it in group.command() or SlashCommandGroup()

silver moat
somber pelican
#

aight thanks

silver moat
#

I don't remember off the top of my head

#

but that seems right

copper pine
#

I'm having a problem with py-cord, and it's that after a while of not having used the bot, when a command is executed, it gives a 404 error as "unknown interaction", but when I run it again (the command), it doesn't happen anymore. Is it a code error or something? It happens with all commands.

silver moat
#

Seems like a Discord thing

harsh dust
#

with modals, is there a way to tell if the user pressed 'Cancel'?

silver moat
spring hare
harsh dust
#

That's not an entirely reliable way of doing it since it could genuinely be just left open for 180 seconds since user is AFK or something
But its fine I'll just do a different approach to what im doing which is buttons being disabled when the modal is open and so far when the user clicks 'Cancel' i need a way to re-enable the buttons

prisma flicker
#

Why do you need to disable the buttons?

clear vault
#

I hope this fits in here but I wanted to ask if anyone can help me with pip venv.

polar linden
#

Hi, is there any testing library for pycord like dpytest?

silver moat
#

not as far as I know?

proud mason
#

you would need to try it and see

#

Although pycord has its own testing extension in the works

proud mason
#

||this pr will take 4 years 7 months to complete. (1677 days)||

fervent cradle
#

does autocomplete not filter if theres not so many items? lets say i have 4 items does it not filter for those?

fervent cradle
#

ah okay i thought it was just something with my code

#
                expansion_amount = round(random.randint(400, 5000), -1)
                if await self.increaseBankCapacity(uid, expansion_amount):
                    l = f"Your bank space has been successfully expanded by **{expansion_amount}**"
                else:
                    l = f"Something went wrong with the transaction!"
                return l``` how can i generate the expansion amount into a variable if the user inputs multiple use items, but i also want to be safe if they input a large number like 1k (if they reach that many items) How can i potentially prevent it from taking a long time to reply as well?
river summit
#

is this an efficient way of removing documents?

async def on_guild_remove(self, guild: discord.Guild):
     guild_id = guild.id

     collections = await self.db.list_collection_names()

     async def delete_documents(collection, guild_id):
           await collection.delete_many({"guild_id": guild_id})

     coroutines = []
     for name in collections:
           collection = self.db[name]
           coro = delete_documents(collection, guild_id)
           coroutines.append(coro)

    await asyncio.gather(*coroutines)
    coroutines.clear()
proud mason
#

also, no need to define delete_documents inside the method??

river summit
# proud mason this part could be better done using TaskGroups
async def delete_documents(self, collection, guild_id):
   await collection.delete_many({"guild_id": guild_id})

async def on_guild_remove(self, guild: discord.Guild):
     guild_id = guild.id

     collections = await self.db.list_collection_names()

     async with asyncio.TaskGroup() as task_group:
          for name in collections:
              collection = self.db[name]
              await task_group.create_task(self.delete_documents(collection, guild_id))

something along the lines of this?

proud mason
river summit
proud mason
copper pine
#

what are de differences between ctx.reply() and ctx.respond() ?

ocean jackal
#

after re-generating a bot token, do you need to do the OAuth2 url thing again?

proud mason
#

ctx.reply is for prefix cmds and ctx.respond is for app cmds

#

But both are the same for bride cmds

ocean jackal
# proud mason No

ah weird, I’m getting a 404 error with ctx.defer() all of a sudden in a new deployment env

cyan quail
#

are you on pycord 2.4.1

ocean jackal
elfin dagger
#

is there a limit to the amount of pages you can have in a paginator

elfin dagger
#

incredible very cool

drowsy python
#

was looking at the docs about editing my bot's username with a command, i see that discord.ClientUser.edit returns a discord.ClientUser

#

do i actually have to set my bot.user to this or what do i do with it

#

actually scratch that bot.user cant be edited, safe to ignore?

silver moat
drowsy python
#

makes sense

#

thanks yo

full widget
#

Is there a simple way to convert mentions to plaintext as discord displays them? (@colin instead of @cosmic fern), without using message.clean_content, as ideally I want to convert them before sending the message.

#

unfortunately clean_content doesn't seem to support escaped mentions, and will return something like <@​ 857027925944696873> instead of the mention as it is displayed in discord (when using for example, allowed_mentions=AllowedMentions.none())

silver moat
full widget
#

Right, though that would still require sending the message first I guess

#

and actually

#

that's essentially what clean_content does, so not sure that would work

#

ah yeah thats exactly what clean_content does. So i'd need to write another set of re.escape functions for escaped mentions I guess

transformations = {
            re.escape(f"<#{channel.id}>"): f"#{channel.name}"
            for channel in self.channel_mentions
        }

        mention_transforms = {
            re.escape(f"<@{member.id}>"): f"@{member.display_name}"
            for member in self.mentions
        }

        # add the <@!user_id> cases as well..
        second_mention_transforms = {
            re.escape(f"<@!{member.id}>"): f"@{member.display_name}"
            for member in self.mentions
        }

        transformations.update(mention_transforms)
        transformations.update(second_mention_transforms)****
midnight ivy
#

hi my bot running with prefix but i want to bot running with slash command

#

how can i change

proud mason
midnight ivy
#

hey i visited the link

#

my bot running with cog

#

i cant changed my bot slash command

errant craneBOT
#

Here's the slash cog example.

#

Here's the slash cog groups example.

proud mason
#

see those for slash cmds in cogs

midnight ivy
#

huh okay

#

TypeError: BotBase.init() missing 1 required positional argument: 'command_prefix'

#
intents = discord.Intents.all()
# shard_count = 1  # toplam shard sayısı
# shard_ids = [0]  # mevcut shard ID'leri
# AutoShardedBot
bot = commands.Bot(intents=intents)```
#

@proud masonbro how can i changed

prisma flicker
midnight ivy
prisma flicker
midnight ivy
#

uh i did not know

#

thank you

prisma flicker
#

The error tells you it's required

midnight ivy
#

yes i understand

#
import discord
from discord.ext import commands

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

    @discord.slash_command(name ="me", aliases=["balance","user"], help="hello komutu")
    async def info(self, ctx):
        if findUser(ctx.author.id):
            # Embed mesajı oluşturma
            embed = discord.Embed(
                title=" :crown: Owner",
                description=":small_red_triangle: {}'s Burger Joint (:hamburger::hamburger::hamburger:) \n *The best burgers are here!*".format(ctx.author.name),
                color=discord.Color.dark_orange()
            )

            # Embed mesajına alanlar ekleme
            embed.add_field(name="Balance", value=":dollar: ${}".format(0), inline=False)
            embed.add_field(name="Income(per hour)", value=":money_with_wings: ${} | :hamburger: {}".format(0, 0), inline=False)
            embed.add_field(name="Total Burger", value=":hamburger: {}".format(0), inline=False)
            embed.add_field(name="Playing Time", value=":hourglass_flowing_sand: {}".format(0), inline=False)
            embed.add_field(name="Level", value=":diamond_shape_with_a_dot_inside: Level {}".format(1), inline=False)

            # Embed mesajına resim ekleme
            user_avatar = ctx.author.avatar
            embed.set_thumbnail(url=user_avatar)
            
            # Mesajı gönderme
            await ctx.respond(embed=embed)


def findUser(user_id):
    import sqlite3

    conn = sqlite3.connect('general.db')
    cursor = conn.cursor()

    # Kullanıcıyı kontrol etmek için SQL sorgusunu oluşturun ve çalıştırın
    cursor.execute('SELECT * FROM users WHERE user_id = ?', (user_id,))
    result = cursor.fetchone()

    # Sonucu kontrol edin
    if result:
        cursor.close()
        conn.close()
        return True  # Kullanıcı varsa True döndürün
    else:
        cursor.close()
        conn.close()
        return False  # Kullanıcı yoksa False döndürün

async def setup(bot):
    await bot.add_cog(Info(bot))
#

i cant used slash command

#

AttributeError: module 'discord' has no attribute 'slash_command'

prisma flicker
#

Isn't it commands.slash_command?

#

And slash commands can't have aliases

#

Have you read the docs or the guide?

midnight ivy
prisma flicker
#

And here is the guide ^

midnight ivy
#

I read but I still can't integrate the slash commands into my bot

#
import discord
from discord.ext import commands
from discord import app_commands

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

    @app_commands.command(name ="ping", description ="ping command")
    async def ping(self, ctx):
        await ctx.respond(f"Pong! Latency is {self.bot.latency}")

async def setup(bot):
    await bot.add_cog(Ping(bot))

#

i run this command in my bot but i can't use the command

#

@prisma flicker

uneven beacon
#

so i have a function
and i want to use it in both a slash command and a normal command
is there a way to check if the command excecuted is a normal command or a slash command?

proud mason
#

Show pip list

#

?tag client

obtuse juncoBOT
#
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
proud mason
#

Use discord.Bot if you only want slash cmds and not prefix cmds

midnight ivy
midnight ivy
#

i don't know how to sync slash commands in my bots

#

global or local

proud mason
#

this is pycord server

#

you should ask for help in dpy server

#

pycord and dpy have completely different way to add slash commands

proud mason
silver moat
midnight ivy
#

you can send me link?

silver moat
#

.gg/dpy

midnight ivy
#

thanks

#

oh no I am banned from dpy server

#

🙄

#

I wonder why

signal sandal
#

maybe its time to move to pycord

midnight ivy
#

bruh

#

What is the difference between pycord and dpy?

silver moat
versed fern
#

I'm working on a embed tool using buttons and modals. What's the easiest way to edit the embed (which has the "Edit Title" button below) in the callback of the edit title modal (which gets send after pressing the "Edit Title" button)? Should I just pass the message to the modal?

proud mason
#

check if the context is instance of discord.ApplicationContext or discord.ext.commands.Context

proud mason
#

edit that

versed fern
#

awesome, thx

proud mason
#

and edit the message using interaction.response.edit_message

#

🙃

frigid crater
#

Is there a way with the autocomplete functionality that it "removes" the non-matching strings?

frigid crater
#

So essentially you do your autocomplete, and when you got to choose your item you are given your list for example

#

and you can click from that list

#

however if I have 3 words, and I type the first 2 letters of 1 of those words, I don't want the other 2 words to appear because they don't match.

#

so the list should essentially "shink" based on the autocompletion

grizzled sentinel
#

Yup, I think this is what you need

frigid crater
#

ty

somber pelican
#

how would I go about implementing a cooldown for on_message?

#
    async def on_message(self, message: Message) -> None:
        if message.author.id == self.user.id:
            return

        try:
            await self.handler.handle_message(message)

        except Exception:
            if isinstance(error, ApplicationCommandInvokeError):
                error = error.original

            self.bot.logger.error(error, exc_info=True)

            await message.channel.send(
                f"""
:confused: An error occurred.
{error}
                """,
                ephemeral=True,
            )

this works fine, but i can't think of a clean way :/

fervent cradle
#

hey wsp

#

Im not sure on how to use has_role with slash commands

full basin
#

The same way you do with prefixed command.

fervent cradle
#

and how do I do it with a prefixed command

full basin
#

.rtfm has_role

winter condorBOT
full basin
#

@has_role(someroleidorname)

fervent cradle
#

oh ok thanks mate

#

discord.ext.commands.errors.MissingRole: Role 1115022176035283035 is required to run this command.

#

great it works but it gives error

#

can I like make it send a message saying u need the role to use the command or smthing?

#

instead of printing the whole error there

full basin
#

on_application_command_error listener

fervent cradle
#

bet

full basin
#

Look for error handling there.

fervent cradle
#

Sorry for me being stupid

#

alr sure

full basin
#

You're not. I've seen real stupid people.

fervent cradle
#

lol

somber pelican
#

i dont know where the error's coming from, nothing in the stacktrace

#

solved

#

intents issue facepalm

brittle fable
#

Is there a decorator for an error handler for an entire slash command group (for example, if I have a slash command group that only server admins can use, what would be the syntax for the error handler for that?)

fervent cradle
#

@proud mason your paginator PR is still in progress right?

full basin
#

Where group is your slash command group name

#

.rtfm group.error

brittle fable
#

Something like this is what I'm trying to do

proud mason
glossy forum
#

Any idea why code like this

# more code unrelated to the embed
embed = discord.Embed(title=f"Newest image from {handle.website_name} for query id = {query_id}",
                      description=f"{text_notif}\n" if len(text_notif) > 0 else "")
embed.set_image(url=post.url_file)
await channel.send(embed=embed)
``` Having style of url like this
<https://website.net/art/the/path/image.png>
Throws an error like this?
```bash
Unhandled exception in internal background task 'check_for_feed'.
 Traceback (most recent call last):
   File "/root/commission_02_2023/bot/lib/python3.11/site-packages/discord/ext/tasks/__in>" # journalctl cut of that part
     await self.coro(*args, **kwargs)
   File "/root/commission_02_2023/bot/cogs/dbserver.py", line 372, in check_for_feed
     await channel.send(embed=embed)
   File "/root/commission_02_2023/bot/lib/python3.11/site-packages/discord/abc.py", line 1616, in send
     data = await state.http.send_message(
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   File "/root/commission_02_2023/bot/lib/python3.11/site-packages/discord/http.py", line 371, in request
     raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.image.url: Not a well formed URL.
#

Like, am I supposed to process the url somehow? I can access the link via my browser just fine

young bone
#

That is not a file image link @glossy forum

glossy forum
# young bone What is post.url_file?

Type of post is a small dataclass I created for storing some of the fetched data from the website
.url_file is a str attribute containing a link to the file

#

which does contain the right value

#

edit: okay, it actually works as expected for one website, but doesn't for the other
so it's on me

simple plover
#

how to get a wavelink server?

hazy vault
#

my slash and message commands aren't being correctly registered
they show up in the integration settings but they don't show up in / and right click on messages
there are no errors in the cog and there should be no issue with registering them
I've waited for over an hour for them to register correctly but it never happened
does anyone know why

simple plover
hazy vault
#

yeah

#

they show up in integration settings but just not usable for users

hazy vault
proud mason
#

debug guilds make commands "guild commads". they will only be registered in those guilds

#

remove debug guilds parameter completely and they will show up in all servers

hazy vault
proud mason
full widget
#

does anyone have experience with passing roles to guild.create_custom_emoji() ? I'm having trouble actually letting people use the emojis I make, right now they don't work unless you have the administrator perm?

young bone
full widget
young bone
full widget
#

ye I don't think that's the problem

candid coral
#

Hello. Which method is responsible for waiting for a message?

young bone
candid coral
hearty gorge
#

Hello, why does the nonce return as None?

await channel.send('testing', nonce=99)
last_message = await bot.get_channel(1111111111111111111).history(limit=1).flatten()
print(last_message[0].nonce)
print(last_message[0].content)

None
testing

true panther
#

Any pointers on implementing something like a timeout? Like, applying a role for a set amount of time, for example.

proud mason
#

message = await channel.send(...) message.nonce

fervent cradle
#

how do i check if a specific slash command was ran in an on message event

astral python
full basin
#

Slash commands don't go through on_message

fervent cradle
proud mason
#

That is set for any bot's slash cmd

#

Not just yours

fervent cradle
proud mason
#

if yes, use global checks

#

.rtfm discord.bot.check

fervent cradle
proud mason
proud mason
#

you can make your own Exception that inherits from ApplicationCommandError, and raise that in the check saying smth like "Bot in maintenance"

#

you can even handle this exception class in your error handler

#

and send a message to the user

proud mason
fervent cradle
#

i have the logic, yes, i want to disable it, it disables all commands though

proud mason
#

then use the check on that commad

#

.rtfm check

proud mason
#

4th

fervent cradle
spring hare
#

How to silently (without log in audit log) delete messages with bot? I saw nqn deleting users messages to replace them with webhook message

proud mason
spring hare
#

webhooks?

#

odd

proud mason
#

maybe

#

not sure

spring hare
#

Odd

spring hare
#

Even bots don't show who deleted the message

#

Like if I deleted it by myself

fervent cradle
torpid wraith
#

Is it possible to have a bot "playing a game" with rich/custom data like this?

torpid wraith
#

sadge

proud mason
proud mason
proud mason
#

otherwise you also have ctx.command.parent

silver moat
#

bot-deleted messages aren't audit-logged?

proud mason
#

hmm are you sure?

#

let me test

spring hare
#

Uhm... Nope?

proud mason
#

yeah thought so

spring hare
proud mason
#

ddevs?

spring hare
#

nqn server

proud mason
#

or nqn support

#

ah

spring hare
#

I don't get it

proud mason
#

.rtfm webhook.delete_m

winter condorBOT
proud mason
#

try that, but i dont it'll work

spring hare
#

Deletes a message owned by this webhook.

proud mason
#

yea

#

but yk. discord™️

silver moat
proud mason
spring hare
#

WTF

proud mason
#

wait wtf really?

spring hare
#

If you delete exactly 1 message, this will not show up in audit logs

#

💀

proud mason
#

oh huh

#

wtf lmao

spring hare
#

WTF

#

💀

proud mason
spring hare
#

This is so stupid

#

wth?

#

Why?

#

💀

wet coral
#

Hi, is it possible to create one event listener for every event?
So the listener would get called when any event occurs and it should be possible to get the name of the event in the callback.

spring hare
#

I think you can replace bot.wait_for

#

I need to check that, GitHub mobile is so bad

#

Nah, need more stuff

spring hare
wet coral
#

I am storing some tasks I want to run on certain events in a database. And when any of the possible events get triggered I retrieve the according rows from the database and execute the tasks.
But the execution is handled by a custom class, so it's always the same code in the event listeners.

And I'm trying to avoid creating multiple listeners with always the same code.

spring hare
#

I know all listeners are listed in bot._listeners

#

You can crate dynamic functions generator I guess

#

Like loop through the list and declare listeners with parameter inside

#

Or... Find low level func

#

Wait for other helpers tbh, I can't really check stuff from phone

wet coral
#

Hm. Well I'll have a look. But can I create two listeners for the same event or can only one listener be created per event?

spring hare
#

In other words:
bot.event will replace original, but bot.listener won't

wet coral
#

oh ok, good to know

spring hare
#

👍

wet coral
#

Another question: Does the bot have to share a guild with the user it's trying to fetch?

spring hare
#

So fetch_guild always works

wet coral
#

So fetch_user will always work?

spring hare
#

Yup

wet coral
#

ok thx

spring hare
#

But get_user only if bot saw user

#

And has intents

wet coral
#

sure

#

and guild.fetch_member only if the member is in the guild, right?

spring hare
#

Guild has fetch_member?

wet coral
#

yes

spring hare
#

You can get info about server members only if your bot on this server and has members intents

#

Otherwise, you can't get info from the server

plucky citrus
#

How do i make a command that has a button in it

#

Do i just add whatevers in the tag

#

?tag buttons2

obtuse juncoBOT
prisma flicker
plucky citrus
#

i see thanks

versed fern
#

What's the best way to set the color of an embed? I'm currently using a button (Edit Color) to open a modal. In here, I set the value to previous_color= str(interaction.message.embeds[0].color). When the modal is submitted, I'm currently trying to set color to the hex code received (e.g. #9b59b6). This currently doesn't work:

Ignoring exception in modal <cogs.messages.ColorModal object at 0x000001ED5020A710>:
Traceback (most recent call last):
  File "C:\Users\bruno\Documents\Programming\AIM-Bot\venv\Lib\site-packages\discord\ui\modal.py", line 341, in dispatch
    await value.callback(interaction)
  File "C:\Users\bruno\Documents\Programming\AIM-Bot\cogs\messages.py", line 574, in callback
    user_embed.color = int(self.children[0].value)
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: invalid literal for int() with base 10: '#9b59b6'

The modal callback:

    async def callback(self, interaction: discord.Interaction) -> None:
        """Callback for when the modal is submitted.

        Parameters
        ------------
        interaction: discord.Interaction
            The interaction that submitted the modal."""
        user_embed: discord.Embed = interaction.message.embeds[0]
        user_embed.color = int(self.children[0].value)
        if self.tutorial_embed:
            await interaction.response.edit_message(embeds=[user_embed, self.tutorial_embed])
            return
        await interaction.response.edit_message(embed=user_embed)

Since this currently doesn't work, I was wondering if this even is a smart approach or if there is a better way?

plucky citrus
#

and i have to rename "MyView" to something else

proud mason
plucky citrus
#

i have no clue what that means i am a sped

proud mason
#
class View(...):
  @discord.ui.button(...)
  async def button1(...):
    ...

  @discord.ui.button(...)
  async def button2(...):
    ...
#

Like that

plucky citrus
#

ah\

true pewter
#

I am using a mongo database which stores information from the server. To speed up the queries I have thought of creating a local variable as a cache where I store temporary information and it is restarted every X hours, if the server does not use it, it is deleted from the system.

#

Do you think this is a good idea?

silver moat
#

if it's not out of sync and doesn't use too much memory, sure

fervent cradle
#

is it a good idea to use different databases for stuff? say postgres for currency and all that more of interactive stuff like afk and all and idk mongo for moderation to store all the servers and their configs? or should i just use postgres for everything

silver moat
true pewter
silver moat
fervent cradle
true pewter
storm oyster
silver moat
true pewter
plucky citrus
#

or it will just stop working after a short time

silver moat
#

if you want buttons that always work:

errant craneBOT
#

Here's the persistent example.

plucky citrus
#

ah

plucky citrus
#

so they normally just stopp working after a short time

queen willow
#

idk what I did wrong here

woeful spindle
#

nvm got it

plucky citrus
#

I figured it out. Is it possible to name thiis other than MyView

fervent cradle
#
@bot.check
async def allChecks(ctx):
    if await bot.isBlacklisted(ctx.author.id): raise blacklistError()

    if bot.checkMaintenance(): 
        if ctx.command.parent == "dev" and ctx.command.name == "maintenance": return True
        raise maintenanceError()

    return True
``` im trying to do a check to see if the command name matches, however, this seems to fail for me im unsure why, it works to enable, but i cannot stop it once its in maintenance
young bone
queen willow
queen willow
#

I already resetted it bth

grizzled sentinel
#

Thats not how envs work

young bone
#

^

fervent cradle
young bone
#

lul

queen willow
#

It was not working before too

fervent cradle
queen willow
grizzled sentinel
# queen willow idk what I did wrong here

The env is basically a dictionary. You should have something like this in your env file
TOKEN = mytoken123
Then os.environ["TOKEN"] (getenv might work to but i know my way works for sure.)

#

jan is right to there should be a tab on the side that lets you set envs and even insert the get statment automatically

fervent cradle
queen willow
grizzled sentinel
queen willow
#

k thanks

grizzled sentinel
proud mason
#

yeah upvote

winter condorBOT
proud mason
#

ah pff

#

but yeah get the name attribute

grizzled sentinel
#

ctx.command.qualified_name == "dev maintenance"

fervent cradle
#

ah yes exactly what i was looking for thank you

#

or not this still doesnt turn it off

@bot.check
async def allChecks(ctx):
    if await bot.isBlacklisted(ctx.author.id): raise blacklistError()

    if bot.checkMaintenance(): 
        if ctx.command.qualified_name == "dev maintenance": return True
        raise maintenanceError()

    return True```

```py
    def checkMaintenance(self):
        r = self.getValue("maintenance")
        return True if r == "1" else False``` currently `r` is set to 1
grizzled sentinel
#

Can you print ctx.command.qualified_name, just to be sure it is returning the right thing

fervent cradle
#

that only prints dev

grizzled sentinel
#

thats weird

plucky citrus
#

I might wound mentwlly special but is it possible to make the bot play a .mp3 when in a vc

#

Play it thru the mic or smt

plucky citrus
grizzled sentinel
fervent cradle
#

slash

#
parent None

    print(f'parent name {ctx.command.parent.name}')
                         ^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'name'
@bot.check
async def allChecks(ctx):
    if await bot.isBlacklisted(ctx.author.id): raise blacklistError()

    if bot.checkMaintenance():
        print(f'parent {ctx.command.parent}')
        print(f'parent name {ctx.command.parent.name}')
        print(f'command name { ctx.command.name}')
        if ctx.command.qualified_name == "dev maintenance": return True
        raise maintenanceError()

    return True
``` command name wont get printed
grizzled sentinel
#

My test seems to work. Can you show how you are creating the group?

fervent cradle
#
from discord.commands import SlashCommandGroup

dev_commands = SlashCommandGroup("dev", "developer commands")```
grizzled sentinel
#
    def __init__(self, bot):
        self.bot = bot
    greetings = discord.SlashCommandGroup("greetings", "Various greeting from cogs!")

    @greetings.command()
    async def ping(self, ctx):
        print(ctx.command.qualified_name)

This gives me greetings ping

fervent cradle
#
    # Sets maintenance mode
    @dev_commands.command(description="Toggles maintenance mode")
    @commands.guild_only()
    @isDeveloper()
    async def maintenance(self, ctx, action: bool):
        await self.bot.maintenance(action)

        embed = discord.Embed(title="Maintenance mode stopped!", color=discord.Colour.embed_background())
        if action: embed.title = "Maintenance mode started!"

        if action: await self.bot.change_presence(status=discord.Status.do_not_disturb, activity=discord.Activity(type=discord.ActivityType.playing, name="in maintenance mode"))
        else: await self.bot.change_presence(activity=discord.Activity(name="for /help", type=discord.ActivityType.watching, status=discord.Status.online))

        await ctx.respond(embed=embed, ephemeral=True)``` this is my command
fervent cradle
plucky citrus
fervent cradle
grizzled sentinel
grizzled sentinel
fervent cradle
#

would be lovely

plucky citrus
grizzled sentinel
fervent cradle
#

well thats that then

#

ill keep it as if ctx.command.qualified_name == "dev maintenance": return True for now tho thanks for the help

grizzled sentinel
fervent cradle
#

thats weird then, i haven't got a clue what shenanigans are going on in the back

#

printing just ctx.command also only returns the group name in my case dev

proud mason
grizzled sentinel
#

Ok, I found something. Both commands are run through the check. So the first time it runs the group command through the check. And then it runs the sub command

grizzled sentinel
grizzled sentinel
#

oh

fervent cradle
#

yeah i can update just a second

proud mason
#

hmmm wait

#

that is only the hooks

fervent cradle
#

another PR for om

proud mason
#

@fervent cradle @grizzled sentinel does the check run 2 times?

grizzled sentinel
#

yes

#

once for the group and once for the command

#

although jans only runs once because the check fails on the group

proud mason
#

ah so you could do if isinstance(ctx.command, discord.SlashCommandGroup): return or smth

fervent cradle
#

just me always having issues with slash groups? lmao

proud mason
#

i really dont get how running hooks and checks for slashgroups is not a feature

proud mason
#

even discord considers the group as the "command" and subcommands as "options"

grizzled sentinel
#
if isinstance(ctx.command, discord.SlashCommandGroup) and ctx.command.name == "dev":
  return True
if ctx.command.qualified_name == "dev maintenance":
  return True

Would this work? So that only one group is returned true automatically

proud mason
#

tbh the 2nd one wont be required

#

the 1st one should be enough

#

or wait

#

are you trying to block the command or allow it?

#

return True allows it

grizzled sentinel
#

allow only that command

proud mason
#

ah

fervent cradle
#

yeah, thanks a lot guys

fervent cradle
#

um is there also a way to make __init__ async?

class SearchView(discord.ui.View):
    def __init__(self, bot, timeout: Optional[float] = 90):
        super().__init__(timeout=timeout)

        search_place = await self.bot.getSearchPlaces(3)

        self.add_item(discord.ui.Button(label=search_place, style=discord.ButtonStyle.blurple))``` im trying to do this
wet coral
#

__init__ cannot be async.
You could put the async call into a load coro and await that after the object creation...

#

e.g.

class SearchView(discord.ui.View):
    def __init__(self, bot, timeout: Optional[float] = 90):
        super().__init__(timeout=timeout)
    
    async def load(self):
        search_place = await self.bot.getSearchPlaces(3)
        self.add_item(discord.ui.Button(label=search_place, style=discord.ButtonStyle.blurple))

view = await SearchView(bot, 100).load()
# or
view2 = SearchView(bot, 200)
await view2.load()
#

@fervent cradle

queen willow
#

Error in the host now:

Traceback (most recent call last):
  File "/home/container/main.py", line 43, in <module>
    bot.run(os.getenv("TOKEN"))
  File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 717, in run
    return future.result()
           ^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 696, in runner
    await self.start(*args, **kwargs)
  File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 659, in start
    await self.login(token)
  File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 509, in login
    raise TypeError(
TypeError: token must be of type str, not NoneType
wet coral
#

Looks like the environment variable "TOKEN" does not exist

queen willow
#

It does, I added it in the .env file

#

TOKEN = ...

silver moat
#

There shouldn't be any spaces iirc

#

and how are you loading the .env file, if at all

wet coral
#

use dotenv.load_dotenv() to load the variables into the environment.
pip install python-dotenv
If you named your .env file anything other than .env you have to use dotenv.load_dotenv("path/to/.env")

silver moat
#

@queen willow hello?

queen willow
#

yeah, here a sec

#

something like this?

silver moat
#

uhh no

wet coral
#

dotenv is an external library
use pip install python-dotenv to install it

sand bone
#

is it possible to hide commands from that list when you type / from certain roles?

queen willow
wet coral
#

then just dotenv.load_dotenv(path)
without the os.

silver moat
wet coral
sand bone
# silver moat yes, but only server moderators can do that

sorry, i missworded it, is it possible to hide certain commands from certain roles? so say the ban command cant be shown to normal people but to mods and stuff it can this is how im doing it rn

@bot.slash_command(name="dm", description="Send a DM to a user")
async def dm(ctx: discord.ApplicationContext, user: discord.User, *, message: str):
    # Check if the user has an allowed role
    if not any(role.id in allowed_roles for role in ctx.author.roles):
        await ctx.respond("You don't have permission to use this command.")
        print(f"User {ctx.author.name} tried to use the DM command but was denied.")
        return
    # Defer the response
    await ctx.defer()
    try:
        # Send a DM to the user
        await user.send(f"`{message}`\n\nThis message was sent by {ctx.author.mention}.\nIf you wish to respond to this message, please do so in the server. I cannot recieve messages.")
        # Let the command invoker know that the DM was sent
        await ctx.respond(f"Message sent to {user.name}.")
        print(f"Message sent to {user.name} and reads as follows: '{message}'. This command was used by {ctx.author.name}")
    except discord.Forbidden:
        # The user has DMs disabled or has blocked the bot
        await ctx.respond(f"Couldn't send a message to {user.name}.")
        print(f"Message could not be sent to {user.name} and reads as follows: '{message}'. This command was used by {ctx.author.name}")
wet coral
#
dotenv.load_dotenv(path)
bot.run(os.getenv("TOKEN"))

@queen willow that should work

silver moat
wet coral
sand bone
fervent cradle
silver moat
#

nope, but you can set a default permission for a command

silver moat
waxen whale
#

good

full basin
waxen whale
#

-to @full basin 1m ok

wanton pondBOT
#

⏱ Timed out dark.py for 1 minute

wet coral
waxen whale
#

:3

fervent cradle
waxen whale
#

you called it

solemn idol
silver moat
solemn idol
#

Hehehe

wet coral
silver moat
#

@solemn idol @waxen whale @full basin leave thanks

wet coral
#

What's the code of the function? @fervent cradle

fervent cradle
#

just random.choice(list)

#

right so i got lied to by py-cord support kek

wet coral
sand bone
wet coral
#

Even if the function call itself may be not blocking, the execution of random.choice is still blocking

queen willow
#

I imported load.dotenv

fervent cradle
#

right so i can remove async from all my functions that arent using anything to communicate with api or whatever

wet coral
fervent cradle
silver moat
wet coral
warm tendon
#

is there a way for the bot to notice reactions to messages without it being an embed or the bot being the message author?

wet coral
#

listen to on_reaction_add or on_raw_reaction_add and filter out the messages you want or don't want

warm tendon
fervent cradle
fervent cradle
#

ah while you're here why not idk why this keeps failing and users can sell stuff they dont own

    async def sell(self, ctx, item: str, amount: str):
        if amount not in ["all", "max", "maximum"]:
            amount = int(dehumanizer.dehumanizer.parse_string(amount))
        else:
            amount = await self.bot.hasItem(ctx.author.id, item, amount)

        if amount <= 0:
            await ctx.respond(embed=discord.Embed(description="You need to sell at least one item", colour=discord.Colour.embed_background()), ephemeral=True)
            return
        
        if amount == 0:
            await ctx.respond(embed=discord.Embed(description="You haven't got enough of this item in your inventory to sell!", colour=discord.Colour.embed_background()), ephemeral=True)
            return
        
        info = await self.bot.getItem(item)

        await self.bot.removeItem(ctx.author.id, info['id'], amount)

        await self.bot.addBalance(ctx.author.id, int(info['price']*self.config.sell_value))
        embed = discord.Embed(colour=discord.Colour.embed_background(), title="Item(s) sold!", description=f"You successfully sold {amount}x {info['emoji']} {item} for **{self.config.currencyEmoji} {humanize.intcomma(int(info['price']*self.config.sell_value))}**")
        await ctx.respond(embed=embed)```

```py
    async def hasItem(self, uid, item, amount):
        val = await self.fetchval("SELECT quantity FROM inventory INNER JOIN items ON inventory.itemID = items.itemSerial WHERE userID=$1 AND items.itemID=$2;", int(uid), item)
        if not val or val < int(amount):
            return 0
        else:
            return val
queen willow
#

in the .env file

wet coral
queen willow
#

exactly what I did lol

wet coral
queen willow
wet coral
fervent cradle
#

yeah

full basin
#

It's not json

wet coral
#

that's what I just wanted to ask too xD

#

what's the full name of your .env file @queen willow
it should be .env
if it is, you don't need the {}

#

just
.env

TOKEN=your token here
queen willow
full basin
#

You should really start using Google to.solve simple matters

queen willow
#

Traceback (most recent call last):
File "/home/container/main.py", line 45, in <module>
bot.run(os.getenv("TOKEN"))
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 717, in run
return future.result()
^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 696, in runner
await self.start(*args, **kwargs)
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 659, in start
await self.login(token)
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 509, in login
raise TypeError(
TypeError: token must be of type str, not NoneType

same error

wet coral
full basin
#

Helping with no code isn't useful

queen willow
wet coral
#

@queen willow try dotent.load_dotenv() without path

#

if the .env is in the same directory as your bot.py

queen willow
#

yes it is

full basin
#

Then don't add a path

wet coral
#

then the path isn't needed

full basin
#

Let the lib do it by itself

versed fern
warm tendon
versed fern
#

Hmm, makes it harder to deal with

wet coral
#

@queen willow and btw, if I were you, I'd regenerate the bot token. One could be able to decipher it from the image...

queen willow
#

k I will

wet coral
versed fern
# full basin Afaik, yes

I use embed.color as a value for the modal, so users see the previous color code. It would be better to allow them the enter hex codes as well. How would I do that?

versed fern
#

Seems like a hex code to me

wet coral
#

discord.Embed().color should return an int afaik...

versed fern
#

But I wasn’t sure if it’s hex or rgb so I figured I might just ask

full basin
#

You can also get the rbg

wet coral
#

ah actually it returns a Colour object. And if you do str(Colour()), you get a hex string

versed fern
#

Oh thank ya

queen willow
wet coral
#

you should be able to use it like an int though

versed fern
#

It said raw int in the docs

wet coral
versed fern
#

Ok thx

versed fern
#

And hash would be hex code right?

wet coral
#

hash is something completeley different xD

versed fern
#

Oh oke haha

wet coral
#

str(Colour()) is hex

versed fern
#

Color codes are confusing af

wet coral
#

and int(Colour()) is int

versed fern
#

RGB is prob the most user friendly right?

#

Actually hex might be better

wet coral
#

I find hex is the most user friendly
but rgb is ok too

fervent cradle
#

u can do discord.Colour.red() or green() or whatever too thats the easiest

fervent cradle
#

if u really want to u can just do .random() always a random colour

queen willow
wet coral
# queen willow example.env

ok, call it just .env and it should work.
if you want to call it example.env you have to load it using dotenv.load_dotenv("example.env")
And please use google more often 🙂

queen willow
#

ah that, I forgot, you already told me to do so

#

It worked, thank you very very much ❤️

#

you too The Silly Squid

wet coral
#

you're welcome. And remember: Use google more often xD

fervent cradle
# wet coral np

one more question since they're blocking it blocks other users from using commands tho no?

wet coral
#

Well, for the millisecond it takes to compute the function, yes, but not really though. The bot will get the request but may delay it because of the function. At least that's my understanding of it. But making the function asyncronous by simply putting an async before it, wouldn't change anything about it.

fervent cradle
#

ah so theres nothing i can do about it

wet coral
#

nothing you can do could improve it significantly imho xD
But even if you could, it wouldn't make any noticeable difference

fervent cradle
#

ah okay

#
def match_search_places(place, coins = 0, item = "Nothing"):
    match place:
        case '...':
            if random.random() < 0.5:
                if random.random() > 0.5:
                    return f"..."
                else:
                    return f"..."
            else:
                return f"..."
        case '...':
            if random.random() < 0.5:
                if random.random() > 0.5:``` is there a more efficient way of doing this deciding if u get an item or a coin, or just dont get anything
proud mason
#

.tag asyncinit

winter condorBOT
#

Add this to you class to allow async init-

    async def __new__(cls, *args, **kwargs):
        obj = super().__new__(cls)
        await obj.__init__(*args, **kwargs)
        return obj
proud mason
#

Just copy paste that into your class

#

Then make your init function async

#

And do await MyClass(...)

#

That's all

wet coral
#

oh wow.
If only I had known this earlier xD

fervent cradle
prisma flicker
fervent cradle
#

easier to use reactions

prisma flicker
versed fern
#

How do I remove the author of an embed? Tried the following:

user_embed.set_author(name=None, icon_url=None)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.author.icon_url: Not a well formed URL.
versed fern
prisma flicker
#

is discord onboarding GA now?

versed fern
#

should be

#

lemme see

prisma flicker
#

nice

prisma flicker
versed fern
#

Cause it wasn't the answer they were looking for

#

Is it even possible set the author to None after it was set?

prisma flicker
#

is there a different method to remove the author?

versed fern
#

nope

silver moat
versed fern
#

where in hell did that come from

silver moat
versed fern
#

I swear I read through all a the methods

silver moat
#

ig not

versed fern
#

Sorry for bothering you, no idea how I didn't see this

topaz meteor
#

how do i create the different type of text in an embed

young bone
#

test test

#

test

silver moat
topaz meteor
#

just add the *, `

silver moat
#

Example:
`hi` is hi
*hi* is hi
**hi** is hi
__hi__ is hi

topaz meteor
#

👍

warm tendon
#

*test*

winged ravine
#

I have a custom bot class with some additional attributes assigned to it, However all the classes from the discord library that reference the bot (E.g. AutocompleteContext.bot) type hint the bot reference as discord.Bot rather than my custom class which means that type-checkers like mypy or Pycharm warn that the additional custom attributes do not exist on the discord.Bot class. How do I fix this without using # type: ignore?

proud mason
#

🤔

proud mason
#

pycords

winged ravine
#

oof, that sounds like a "deal with it until it gets fixed" kinda thing

proud mason
#

as of now, you could make subclasses for each of such classes and type hint bot as your bot class? bad solution ofc

#

and then use these subclasses for typehinting everywhere

winged ravine
#

would I just need to override the typehints in the __init__() method's arguments and the assignment to instance variables?

proud mason
true panther
#

I don't understand how to initialize a cog with bridge commands. I get

Extension 'cogs.badwords' raised an error: TypeError: issubclass() arg 1 must be a class
true panther
true panther
silver moat
#

code would be helpful

proud mason
proud mason
true panther
#

The decorators take the same args as far as I understand? name help alieses etc?

proud mason
#

yes. the args are just passed into the decorators for slash and prefix cmds

true panther
# silver moat code would be helpful
from discord.ext import bridge
from discord.ext.bridge import BridgeContext as Context, Bot

class Badwords(Cog):
    def __init__(self, bot: Bot) -> None:
        super().__init__()
        self.bot: Bot = bot
        
    @bridge.bridge_group(name="badword")
    async def badword(self, ctx: Context):
        if ctx.invoked_subcommand is None:
            return

    @badword.command(name="add")
    @can_have_fun()
    async def add(
        self, ctx: Context, user: Member, lives: Optional[int] = 3, *, words: List[str]
    ):
        ...
        
def setup(bot: Bot):
    bot.add_cog(Badwords(bot))
proud mason
#

hmm and error traceback?

true panther
# proud mason hmm and error traceback?
bot_1  | Traceback (most recent call last):
bot_1  |   File "/usr/local/lib/python3.11/site-packages/discord/cog.py", line 786, in _load_from_module_spec
bot_1  |     setup(self)
bot_1  |   File "/code/cogs/badwords.py", line 184, in setup
bot_1  |     bot.add_cog(Badwords(bot))
bot_1  |   File "/usr/local/lib/python3.11/site-packages/discord/cog.py", line 656, in add_cog
bot_1  |     cog = cog._inject(self)
bot_1  |           ^^^^^^^^^^^^^^^^^
bot_1  |   File "/usr/local/lib/python3.11/site-packages/discord/cog.py", line 548, in _inject
bot_1  |     command._set_cog(self)
bot_1  |   File "/usr/local/lib/python3.11/site-packages/discord/commands/core.py", line 1378, in _set_cog
bot_1  |     subcommand._set_cog(cog)
bot_1  |   File "/usr/local/lib/python3.11/site-packages/discord/commands/core.py", line 603, in _set_cog
bot_1  |     self.cog = cog
bot_1  |     ^^^^^^^^
bot_1  |   File "/usr/local/lib/python3.11/site-packages/discord/commands/core.py", line 830, in cog
bot_1  |     self._validate_parameters()
bot_1  |   File "/usr/local/lib/python3.11/site-packages/discord/commands/core.py", line 708, in _validate_parameters
bot_1  |     self.options: list[Option] = self._parse_options(params)
bot_1  |                                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^
bot_1  |   File "/usr/local/lib/python3.11/site-packages/discord/commands/core.py", line 748, in _parse_options
bot_1  |     option = Option(option)
bot_1  |              ^^^^^^^^^^^^^^
bot_1  |   File "/usr/local/lib/python3.11/site-packages/discord/commands/options.py", line 230, in __init__
bot_1  |     raise exc
bot_1  |   File "/usr/local/lib/python3.11/site-packages/discord/commands/options.py", line 225, in __init__
bot_1  |     self.input_type = SlashCommandOptionType.from_datatype(input_type)
bot_1  |                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
bot_1  |   File "/usr/local/lib/python3.11/site-packages/discord/enums.py", line 807, in from_datatype
bot_1  |     if issubclass(datatype, str):
bot_1  |        ^^^^^^^^^^^^^^^^^^^^^^^^^
bot_1  | TypeError: issubclass() arg 1 must be a class
bot_1  | 
bot_1  | The above exception was the direct cause of the following exception:
bot_1  | 
bot_1  | Traceback (most recent call last):
bot_1  |   File "/usr/local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 178, in wrapped
bot_1  |     ret = await coro(*args, **kwargs)
bot_1  |           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
bot_1  |   File "/code/cogs/service.py", line 46, in load
bot_1  |     self.bot.load_extension(module_name)
bot_1  |   File "/usr/local/lib/python3.11/site-packages/discord/cog.py", line 910, in load_extension
bot_1  |     self._load_from_module_spec(spec, name)
bot_1  |   File "/usr/local/lib/python3.11/site-packages/discord/cog.py", line 791, in _load_from_module_spec
bot_1  |     raise errors.ExtensionFailed(key, e) from e
bot_1  | discord.errors.ExtensionFailed: Extension 'cogs.badwords' raised an error: TypeError: issubclass() arg 1 must be a class
bot_1  | 
bot_1  | The above exception was the direct cause of the following exception:
bot_1  | 
bot_1  | Traceback (most recent call last):
bot_1  |   File "/usr/local/lib/python3.11/site-packages/discord/ext/commands/bot.py", line 347, in invoke
bot_1  |     await ctx.command.invoke(ctx)
bot_1  |   File "/usr/local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 1545, in invoke
bot_1  |     await ctx.invoked_subcommand.invoke(ctx)
bot_1  |   File "/usr/local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 950, in invoke
bot_1  |     await injected(*ctx.args, **ctx.kwargs)
bot_1  |   File "/usr/local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 187, in wrapped
bot_1  |     raise CommandInvokeError(exc) from exc
bot_1  | discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ExtensionFailed: Extension 'cogs.badwords' raised an error: TypeError: issubclass() arg 1 must be a class
proud mason
#

hmm

silver moat
#
        self, ctx: Context, user: Member, lives: Optional[int] = 3, *, words: List[str]
``` probably this line
proud mason
#

yeah i dont think you can use Optional or List

#

you will need to use discord.Option

#

also, avoid this

silver moat
proud mason
#

yea but it might break the slash variant

#

discord.Option should handle it imo

true panther
#

Both worked on text-based commands and are used in converters in examples in docs

#

¯_(ツ)_/¯

proud mason
#

oh well

#

ig its fine

silver moat
true panther
#

Okay, List is a no-no then. Thank you for assistance!

proud mason
#

sometimes i do like dpy's approach of using typing instead of discord.Option

but then it proceededs to use docstrings n stuff to get the description etc... blobpain

true panther
#

Oh, one more question: do I need to sync slash commands somehow? I can't find anything like that in the docs but I remember there was something like that in discord.py thunk5

grizzled sentinel
true panther
grizzled sentinel
#

guild commands <30 secs Global commands <5 min but normally less then 1 min.

naive remnant
#

how can i use pycord in replit

round rivet
#

thou shalt not use replit

naive remnant
grizzled sentinel
#

?tag replit

naive remnant
grizzled sentinel
naive remnant
grizzled sentinel
#

The first section in the link explains why this is a bad idea. But if its your only options I guess it will have to work

grizzled sentinel
#

.tag hosting

winter condorBOT
true panther
grizzled sentinel
winter condorBOT
# true panther They're not getting synced <:nooooooo:832412073912565771>

Checklist for Application Commands Not Showing Up:
• Does your bot have the application.commands scope?
• Are you loading cogs before on_ready and on_connect?
• Is on_connect not overridden?
• Did you update to the newest version of py-cord (tag: install)?
• Is User Settings > Accessibility > Chat Input > Use legacy chat input turned off?
• Did you share your code and errors?
• Do you still have libraries that conflict with the discord namespace (e.g. discord.py)?

Note: you should be able to answer "yes" to all of these queries.

grizzled sentinel
#

It should be all the same stuff minus a few

silver moat
#

• Do you still have libraries that conflict with the discord namespace (e.g. discord.py)?
should be no

true panther
wary rover
#

Hey
I'm surprised to have this error, do you have any ideas?

discord.Bot(intents=intents, command_prefix=os.environ.get('PREFIX'), case_insensitive=True)
^^^^^^^^^^^
AttributeError: module 'discord' has no attribute 'Bot'
#

Has anything changed?

young bone
fervent cradle
#

why is my slash command not showing up when i put /? it doesnt have errors and should clearly work

wary rover
fervent cradle
young bone
fervent cradle
#

it still isnt working idk why

young bone
#

do you use discord.Bot or commands.Bot?

fervent cradle
#

non

young bone
fervent cradle
#

i opened a thread

fervent cradle
#

only py-cord

wary rover
#

But how did the Russian who coded this thing get pycord to work with wavelink???

#

1 + 1 = 4 bigbrain

#

Its code works, it should have been put on python 3.10. I don't understand, he broke the matrix

plucky citrus
#
async def play(ctx, search: str):
  vc = ctx.voice_client # define our voice client

  if not vc: # check if the bot is not in a voice channel
    vc = await ctx.author.voice.channel.connect(cls=wavelink.Player) # connect to the voice channel

  if ctx.author.voice.channel.id != vc.channel.id: # check if the bot is not in the voice channel
    return await ctx.respond("You must be in the same voice channel as the bot.") # return an error message

  song = await wavelink.YouTubeTrack.search(query=search, return_first=True) # search for the song

  if not song: # check if the song is not found
    return await ctx.respond("No song found.") # return an error message

  await vc.play(song) # play the song
  await ctx.respond(f"Now playing: `{vc.source.title}`") # return a message```
how fix when it just plays the song without being in a vc lol. I had to make a command just to make it join
young bone
plucky citrus
#

dont care

young bone
#

lol

plucky citrus
#

its in pycord docs aswell

#

the bot is in 1 singular server

young bone
#

How did you install wavelink?

plucky citrus
#

by installing it?

young bone
#

with pip?

fervent cradle
plucky citrus
#

"pip install wavelink"

#

isnt that how you normally install things in python

#

The one in docs only works with verison 1.3.3 of wavelink and lower btw

full basin
#

That's what zerv is saying

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