#discord-bots

1 messages · Page 304 of 1

lyric sigil
#

nvmd working

#

but when i fill the info and click send i have an error

#

the error :

 2023-09-17 19:13:37 ERROR    discord.ui.modal Ignoring exception in modal <Questionnaire timeout=None children=2>:
Traceback (most recent call last):
  File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\modal.py", line 188, in _scheduled_task
    await self.on_submit(interaction)
  File "c:\Users\canai\Desktop\bots\Partins\main_partins.py", line 282, in on_submit
    await interaction.response.send_modal(f'Thanks for your response, {self.name}!')
  File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 971, in send_modal
    params = interaction_response_params(InteractionResponseType.modal.value, modal.to_dict())
                                                                              ^^^^^^^^^^^^^
AttributeError: 'str' object has no attribute 'to_dict'
#

fixed

#

but how do i get the responses from it ? @slate swan

slate swan
lyric sigil
#

seen but when people submit their answer i want the bot to send a copy in a channel how do i do that ?

slate swan
#

.send_modal takes Modal not text

lyric sigil
#

??

#

what

slate swan
#

await interaction.response.send_modal(f'Thanks for your response, {self.name}!') ??

lyric sigil
#

yes but no

lyric sigil
# slate swan `await interaction.response.send_modal(f'Thanks for your response, {self.name}!'...
2023-09-17 19:24:30 ERROR    discord.client Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\canai\Desktop\bots\Partins\main_partins.py", line 35, in f4
    print(f"{str(message.author)} in {message.guild.name}: {message.content}")
                                      ^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'name'
Task exception was never retrieved
future: <Task finished name='discord-ui-modal-dispatch-269555a07cf95aa993f7d689c862e3f4' coro=<Modal._scheduled_task() done, defined at C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\modal.py:179> exception=NameError("name 'traceback' is not defined")>
Traceback (most recent call last):
  File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\modal.py", line 188, in _scheduled_task
    await self.on_submit(interaction)
  File "c:\Users\canai\Desktop\bots\Partins\main_partins.py", line 303, in on_submit
    await interaction.response.send_modal(f'Thanks for your demand, {self.name.value}!', ephemeral=True)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: InteractionResponse.send_modal() got an unexpected keyword argument 'ephemeral'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\modal.py", line 190, in _scheduled_task
    return await self.on_error(interaction, e)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "c:\Users\canai\Desktop\bots\Partins\main_partins.py", line 309, in on_error
    traceback.print_exception(type(error), error, error.__traceback__)
    ^^^^^^^^^
NameError: name 'traceback' is not defined

slate swan
naive briar
#

Do you know the difference between send_modal and send_message

lyric sigil
#

yes

naive briar
#

Doesn't seem like it

slate swan
lyric sigil
#

send modal sends a modal and send message sends a message

slate swan
#

So, why are you trying to make a modal ephemeral or send some message with it

slate swan
lyric sigil
unkempt canyonBOT
#

examples/modals/basic.py lines 57 to 58

async def on_submit(self, interaction: discord.Interaction):
    await interaction.response.send_message(f'Thanks for your feedback, {self.name.value}!', ephemeral=True)```
slate swan
#

There's a difference which apparently you "know"

#

nah blud be making those mistakes on purpose

lyric sigil
# slate swan No you didn't
#whitelist
class Whitelist(discord.ui.Modal, title='Whitelist'):
    # Our modal classes MUST subclass `discord.ui.Modal`,
    # but the title can be whatever you want.

    # This will be a short input, where the user can enter their name
    # It will also have a placeholder, as denoted by the `placeholder` kwarg.
    # By default, it is required and is a short-style input which is exactly
    # what we want.
    name = discord.ui.TextInput(
        label='IG Name',
        placeholder='Your IG name here...',
    )

    # This is a longer, paragraph style input, where user can submit feedback
    # Unlike the name, it is not required. If filled out, however, it will
    # only accept a maximum of 300 characters, as denoted by the
    # `max_length=300` kwarg.
    feedback = discord.ui.TextInput(
        label='Your infos?',
        style=discord.TextStyle.long,
        placeholder='Give us your hours on Astroneer , platforms and why you want to join the server',
        required=False,
        max_length=300,
    )

    async def on_submit(self, interaction: discord.Interaction):
        await interaction.response.send_message(f'Thanks for your demand, {self.name.value}!', ephemeral=True)

    async def on_error(self, interaction: discord.Interaction, error: Exception) -> None:
        await interaction.response.send_message('Oops! Something went wrong.', ephemeral=True)
        traceback.print_exception(type(error), error, error.__traceback__)


slate swan
slate swan
#

It's literally the example, so I think it's possible yes

lyric sigil
#

but

#

when i copy paste the example it is not working

naive briar
#

You copy pasted and edited it

lyric sigil
#

now i have this error :

Traceback (most recent call last):
  File "c:\Users\canai\Desktop\bots\Partins\main_partins.py", line 353, in <module>
    client.run(TOKEN)
  File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 860, in run
    asyncio.run(runner())
  File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 849, in runner
    await self.start(token, reconnect=reconnect)
  File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 777, in start
    await self.login(token)
  File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 621, in login
    await self.setup_hook()
  File "c:\Users\canai\Desktop\bots\Partins\main_partins.py", line 303, in setup_hook
    await self.tree.sync(guild=TEST_GUILD)
  File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1069, in sync
    data = await self._http.bulk_upsert_guild_commands(self.client.application_id, guild.id, payload=payload)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\http.py", line 739, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
#

it says missing acces but my bot is an admin on my server and has the admin rights

naive briar
#

Admins can't create app commans 🤷

#

You need to enable the app commands scope when inviting the bot

lyric sigil
#

i enabled all but still the same error

slate swan
#

you enabled all what

naive briar
#

All scopes?

slate swan
#

all scopes?

naive briar
#

That doesn't sound like a good idea

lyric sigil
slate swan
#

Do you even know what a scope is

lyric sigil
#

yes

slate swan
#

So, why do you say you've enabled all scopes and "not at the good place"

lyric sigil
#

it should look like this ?

lyric sigil
slate swan
#

Right so you haven't enabled all scopes

slate swan
lyric sigil
slate swan
#

So you didn't know what scopes are, at least before

slate swan
#

Meaning, is the guild ID correct

lyric sigil
#

in the code ?

slate swan
#

Where else

lyric sigil
#

i need to replace the 0 ?

slate swan
#

..

#

did you even read the comments?

#

or you just think they are there for fun

lyric sigil
#

readed them but its the only place where i can see guild can be placed

slate swan
#

yes replace the 0 with actual guild id

lyric sigil
#

blocked here

#

okay same issue

#

"Missing Access

slate swan
#

What's your thing now

lyric sigil
#

my "thing" ?

slate swan
#

About what you've edited duh Facepalm

lyric sigil
#
TEST_GUILD = discord.Object(MY_GUILD_ID)
slate swan
#

and what MY_GUILD_ID is?

lyric sigil
#

the bot guild id

slate swan
#

Which is

lyric sigil
#

1140326509920395374

slate swan
#

So, how does your code look like

#

No, not that.

#

Anyways, good I can scroll

lyric sigil
#
PS C:\Users\canai\Desktop\bots\Partins> & C:/Users/canai/AppData/Local/Programs/Python/Python311/python.exe c:/Users/canai/Desktop/bots/Partins/main_partins.py
2023-09-17 19:47:18 INFO     discord.client logging in using static token
Traceback (most recent call last):
  File "c:\Users\canai\Desktop\bots\Partins\main_partins.py", line 353, in <module>
    client.run(TOKEN)
  File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 860, in run
    asyncio.run(runner())
  File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 849, in runner
    await self.start(token, reconnect=reconnect)
  File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 777, in start
    await self.login(token)
  File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 621, in login
    await self.setup_hook()
  File "c:\Users\canai\Desktop\bots\Partins\main_partins.py", line 303, in setup_hook
    await self.tree.sync(guild=TEST_GUILD)
  File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1069, in sync
    data = await self._http.bulk_upsert_guild_commands(self.client.application_id, guild.id, payload=payload)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\http.py", line 739, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
slow fog
slate swan
#

Not code either but yeah whatever

lyric sigil
#

wdyw

#

the wole 353 lines ?

slate swan
#

Is the bot actually in that guild

slate swan
lyric sigil
#

okay

#

so i've out the bot guild into the code

#

and it is not working

#

and you want to see my code

slate swan
#

Again, is the bot actually in that guild and how did you get the guild ID

lyric sigil
#

how do i know he's in it

#

i've got the guild id from dev portals

slate swan
#

you invite it to it ??

#

By looking at the members list Facepalm

lyric sigil
#

okay the discord

#

yes he's in

slate swan
slate swan
lyric sigil
#

hold on

slate swan
#

Guild == Server

lyric sigil
#

....

slate swan
#

Right click on the guild in the Discord client and copy the ID from there, that's the actual guild ID

lyric sigil
#

done that

#

but my code takes ages to launch

#

just staying like that

slate swan
lyric sigil
#

normally its says logged in as ... and synced x commands

slate swan
#

Then you eventually got rate limited from syncing commands LULW

naive briar
#

Me when my bot doesn't immediately exit when it's connected to Discord ducky_cloudflare

lyric sigil
#

already have that :

@client.event
async def on_ready():
    # this runs when the account is logged into
    print("We have logged in as {0.user}".format(client))
    try:
        synced = await client.tree.sync()
        print(f"Synced {len(synced)} commands(s)")
    except Exception as e:
        print(e)    
slate swan
#

Yeah then wait 24 hours and see after 24 hours

lyric sigil
#

wat

slate swan
#

It's called a rate limit on syncing commands

lyric sigil
#

no

slate swan
#

And that rate limit gets reset after some hours or a day depends, so try later

naive briar
#

Most useful try-except ever

lyric sigil
#

a friend gave me this

#

i can even give you his repo

slate swan
#

GPT wouldn't put this nonsense comment

lyric sigil
#

i do 🤓

slate swan
#

It's not because you don't that people don't. I do comment on lots of things....

lyric sigil
#

okay lets put that away

#

now that the command is working

#

when i enter the infos i dont have a copy of the responses

slate swan
#

Why not?

#

I'm asking why it shouldn't be done since you're so sure about it KEK

slate swan
#

Which is unrelated to bot dev, thanks

slate swan
#

There's a rule called staying on the channel topic which I'd like to follow ^-^

lyric sigil
slate swan
#

So, what's the issue

lyric sigil
#

i dont have a copy of that

#

relax bro

#

no need to insult eachother

#

i'm upset that they're making fun of me but i dont say it

slate swan
#

Send the actual code and the results you see

lyric sigil
slate swan
#

how is that code 😭

lyric sigil
lyric sigil
slate swan
#

Well there you have it?

#

It sends the aaa of the name krShrug

lyric sigil
#

i want a copy of the responses

buoyant quail
slate swan
#

If you want the aaa of the "What do you think...." then just add it to the message you send

lyric sigil
# slate swan <:ducky_sus:987918033504854066>
#whitelist

# The guild in which this slash command will be registered.
# It is recommended to have a test guild to separate from your "production" bot
TEST_GUILD = discord.Object(1152621828641140796)


class MyClient(discord.Client):
    def __init__(self) -> None:
        # Just default intents and a `discord.Client` instance
        # We don't need a `commands.Bot` instance because we are not
        # creating text-based commands.
        intents = discord.Intents.default()
        super().__init__(intents=intents)

        # We need an `discord.app_commands.CommandTree` instance
        # to register application commands (slash commands in this case)
        self.tree = app_commands.CommandTree(self)






    async def setup_hook(self) -> None:
        # Sync the application command with Discord.
        await self.tree.sync(guild=TEST_GUILD)


class Feedback(discord.ui.Modal, title='Feedback'):
    # Our modal classes MUST subclass `discord.ui.Modal`,
    # but the title can be whatever you want.

    # This will be a short input, where the user can enter their name
    # It will also have a placeholder, as denoted by the `placeholder` kwarg.
    # By default, it is required and is a short-style input which is exactly
    # what we want.
    name = discord.ui.TextInput(
        label='Name',
        placeholder='Your name here...',
    )

    # This is a longer, paragraph style input, where user can submit feedback
    # Unlike the name, it is not required. If filled out, however, it will
    # only accept a maximum of 300 characters, as denoted by the
    # `max_length=300` kwarg.
    feedback = discord.ui.TextInput(
        label='What do you think of this new feature?',
        style=discord.TextStyle.long,
        placeholder='Type your feedback here...',
        required=False,
        max_length=300,
    )

    async def on_submit(self, interaction: discord.Interaction):
        await interaction.response.send_message(f'Thanks for your feedback, {self.name.value}!', ephemeral=True)

    async def on_error(self, interaction: discord.Interaction, error: Exception) -> None:
        await interaction.response.send_message('Oops! Something went wrong.', ephemeral=True)

        # Make sure we know what the error actually is
        traceback.print_exception(type(error), error, error.__traceback__)


client = MyClient()


@client.tree.command(guild=TEST_GUILD, description="Submit feedback")
async def feedback(interaction: discord.Interaction):
    # Send the modal with an instance of our `Feedback` class
    # Since modals require an interaction, they cannot be done as a response to a text command.
    # They can only be done as a response to either an application command or a button press.
    await interaction.response.send_modal(Feedback())
slate swan
#

Nice code, what's the point to send it

lyric sigil
#

you dont understand i think

#

unfortunately no

slate swan
lyric sigil
buoyant quail
#

xdd

lyric sigil
#

so

slate swan
#

Add the same for feeback what

lyric sigil
#

the command is for an game server to whitelist people

#

so i want them to wrote their IG name and some infos

#

then i want the bot to send all the info from the command that the guy used into a channel

#

so i can take the IG name and whitelist it

#

hold on gonna make an exemple

slate swan
#

My guy, there's no need... You already send the name. Now send the feedback as well

#

Then rename the TextInput data with whatever you want

#

If you want a username then set the label to something like "What's your in-game username?" instead

lyric sigil
#

but idk how to do that

#

thats the point

slate swan
#

All right, so you can't replace a string by another one?

#

Have you taken into consideration learning Python before making a bot? At least the most basics, and the advanced topics it requires to know, e.g. async and OOP

lyric sigil
#

but i figured out how to have the feedback

slate swan
#

So you haven't learned the advanced topics that discord.py requires you to have, which includes OOP

lyric sigil
#

now the thing i want to know is how do i can make the bot send all the modal infos into a specific channel

slate swan
#

Get a channel and send it

#

!d discord.ext.commands.Bot.get_channel

unkempt canyonBOT
slate swan
#

!d discord.TextChannel.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
lyric sigil
#

Done this

#
async def on_submit(self, interaction: discord.Interaction):
    await client.get_channel(1152966656314855484)
    await channel.send({self.name.value} , {self.feedback.value} )
    await interaction.response.send_message(f'Thanks for your feedback', ephemeral=True)
#

but it's not working

quick brook
lyric sigil
#

Good question that was i was going to ask

#

and also the purpose of this channel

quick brook
shrewd apex
#

lmao

lyric sigil
#

need to replace await with return ?

quick brook
#

probably also enable pyright bc if you have static type hinting enabled, vsc would already have detected the issue

quick brook
shrewd apex
#

get_channel get the channel for bot cache

#

if it dosent exist it returns None in which case you can make a request to discord api to fetch it

quick brook
lyric sigil
quick brook
lyric sigil
shrewd apex
#

what does that supposed to mean?

lyric sigil
lyric sigil
#

but thats weird i dont have any errors in vscode

shrewd apex
#

do u know how to handle or get errors in views ?

lyric sigil
#

No i guess ?

shrewd apex
#

view errors are under an on_error callback which u need to override

#

also use a fstring in channel.send

#

!d discord.TextChannel.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
lyric sigil
#

The modal says 'An error has occured'

#

but dont have any in vscode

#

and changed this also

#

``` await channel.send(f'{self.name.value} , {self.feedback.value}' )````

shrewd apex
lyric sigil
lyric sigil
#

NO

#

TRACEBACK

shrewd apex
#

SKILL ISSUE

lyric sigil
#
PS C:\Users\canai\Desktop\bots\Partins> & C:/Users/canai/AppData/Local/Programs/Python/Python311/python.exe c:/Users/canai/Desktop/bots/Partins/main_partins.py
2023-09-17 20:39:20 INFO     discord.client logging in using static token
2023-09-17 20:39:21 INFO     discord.gateway Shard ID None has connected to Gateway (Session ID: 6279143f8c844b87948f46755a064db9).
shrewd apex
#

read what i sent

shrewd apex
lyric sigil
#

and how do i override it ?

#
    async def on_error(self, interaction: discord.Interaction, error: Exception) -> None:
        await interaction.response.send_message('Oops! Something went wrong.', ephemeral=True)

        # Make sure we know what the error actually is
        traceback.print_exception(type(error), error, error.__traceback__)
nova badge
#

can you still make discord bots? I thought bots like groovy were banned?

slate swan
#

You can still make bots yes, why would it not be allowed

#

What you can't do are bots breaching terms of services, which groovy and other music bots were doing

#

And that's been the case since forever

#

hi

#

i get an 'interaction failed' error everytime i run my code. without any error in console ofc

here is my code;

@client.event
async def on_select(ctx, interaction):
    try:
        custom_id = interaction.custom_id
        selected_value = interaction.values[0]
        if custom_id == "crypto_select":

                if selected_value == "USDT":
                    embed = discord.Embed(
                        title="USDT Information",
                        color=0x00ff00
                    )
                    embed.add_field(name="Symbol", value="USDT", inline=True)
                    embed.add_field(name="Description", value="Tether (USDT) is a stablecoin.", inline=True)
                    embed.set_thumbnail(url="URL_TO_USDT_ICON_IMAGE")

                elif selected_value == "LTC":
                    embed = discord.Embed(
                        title="LTC Information",
                        color=0x0000ff
                    )
                    embed.add_field(name="Symbol", value="LTC", inline=True)
                    embed.add_field(name="Description", value="Litecoin (LTC) is a peer-to-peer cryptocurrency.", inline=True)
                    embed.set_thumbnail(url="URL_TO_LTC_ICON_IMAGE")

                elif selected_value == "ETH":
                    embed = discord.Embed(
                        title="ETH Information",
                        color=0xff0000
                    )
                    embed.add_field(name="Symbol", value="ETH", inline=True)
                    embed.add_field(name="Description", value="Ethereum (ETH) is a blockchain platform.", inline=True)
                    embed.set_thumbnail(url="URL_TO_ETH_ICON_IMAGE")

                await ctx.send(embed=embed)
    except Exception as e:
                print(f"An error occurred: {e}")```
quick brook
# nova badge can you still make discord bots? I thought bots like groovy were banned?

You still can. The story with the music bots is that Discord prohibits bots from using streaming services such as YT, Spotify and SoundCloud. Using those to stream music for your bot is considered a breach of TOS, and Discord has been enforcing and ramping up efforts to crack down on this. Thus, that's why the bots are slowly dying and being picked off one by one

to be also clear, streaming music illegally from YT, Spotify and SoundCloud also is illegal and results in copyright violations and a whole legal battle so...

quick brook
slate swan
#

??

#

what

#

why do you think im here nimrod

quick brook
# slate swan ??

dont think if i'm replying to someone else's question that i will automatically help you. no it doesn't work that way. I pick and choose

slate swan
#

there question had nothing to do with python

#

im making a help channel bruh so useless

quick brook
#

also insulting me like that proves to me that you are weak than anything else

glad cradle
static vine
#

I am trying to make my bot say the weather, but for some reason the code doesn't work. (I got the code from github)

slate swan
#

ah yes the average copy pasta 🍝 thisisfine

slate swan
slate swan
slate swan
glad cradle
#

mh? no on_select event in d.py though?

slate swan
glad cradle
#

!d discord.on_interaction

unkempt canyonBOT
#

discord.on_interaction(interaction)```
Called when an interaction happened.

This currently happens due to slash command invocations or components being used.

Warning

This is a low level function that is not generally meant to be used. If you are working with components, consider using the callbacks associated with the [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View) instead as it provides a nicer user experience.

New in version 2.0.
slate swan
#

do i replace this w/ on_select

quick brook
#

just read the examples here

silk plaza
#

hello, I have a question about aiohttp

quick gust
slate swan
silk plaza
#

the thing is that when i call a request that returns ~7k lines of json its goes very quickly, but when i try to call .json() or .text() on it it processed for a couple seconds (~30/45), can i somehow speed it up?

slate swan
silk plaza
slate swan
buoyant quail
#

on_interaction is the only event for interactions in dpy. for all types of them
there are no on_select, on_button_click or anything like that

slate swan
glad cradle
#

generally doesn't mean that should'nt ever be used

slate swan
#

Do your research smart

sick birch
sick birch
#

See the examples linked above for listening to select menus

slate swan
#

zlhawg ok

young dagger
#

How do I load the JSON one?

sick birch
young dagger
#
# JSON
channel_rules = {
    1067851901355430040: {
        'flex': 1067851927381090365,
        'duo': 1067851927381090365,
        'duoq': 1067851927381090365,
        'aram': 1067851927381090365,
    }
}

# Code
# Load channel_rules from JSON file
with open('channel_rules.json', 'r') as file:
    channel_rules = json.load(file)

@client.listen()
async def on_message(message):
    content = message.content.lower()

    for channel_id, keyword_mapping in channel_rules.items():
        for keyword, to_channel_id in keyword_mapping.items():
            if keyword in content:
                await message.channel.send(
                    f"Please use <#{to_channel_id}> for {keyword} related LFGs in order to keep this channel more clean.")```
sick birch
#

How can you tell it's opening the file every time?

young dagger
sick birch
#

Yeah, that just opens the file, reads the contents into channel_rules, and closes it

young dagger
sick birch
#

That's what you're doing

young dagger
sick birch
#

Correct

young dagger
#

Alright

sick birch
#

If you wanted to do that, you would probably bind channel_rules to your bot instance, and you'd have a command to re-load the file and update the state

nimble mirage
#

Can I get help with making shift logger system

nimble mirage
#

Mb

final iron
#

There's still more you can say...

harsh orbit
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range
what is that means?

glad cradle
#

that's Basic python

#

!e

x = [1]
x[2]
unkempt canyonBOT
#

@glad cradle :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 2, in <module>
003 |     x[2]
004 |     ~^^^
005 | IndexError: list index out of range
harsh orbit
#

also I have another question

#

how to get bot invite link from the tokens only?

harsh orbit
#

how to get bot invite link from the token?

desert kiln
#

hello peeps

desert kiln
final iron
harsh orbit
#

so how someone make this?

desert kiln
final iron
harsh orbit
#

get bot invite link from the token

#

actually I knew

#

just get the id

#

and set it in the link

#

nvm

final iron
#

Actually, the first bit before the dot can be decoded to base64, that's the string of the users id

#

It's possible if you know how to decode it

harsh orbit
# desert kiln You can't.
    print(f"https://discord.com/api/oauth2/authorize?client_id={str(bot.user.id)}&permissions=8&scope=bot")

so how I did it in one line?

harsh orbit
#

how did I get the bot.user.id ?
from the token, so I didnot need any info execpt the tokens

desert kiln
#

what

harsh orbit
#

?

desert kiln
#

you didn't get the invite from the token, you got it from the bots user ID

harsh orbit
#

🤦‍♂️

#

nvm nvm

final iron
#

Decode it, then you'll have your user ID

#

It's extremely easy as well

#

Just use base64

mighty pilot
#

Can you edit an embed? Or do you need to make a new one to change anything

final iron
#

You could just copy the embed though, and edit the fields you want

mighty pilot
#

Yea I'm gonna tinker with that lol

empty terrace
#

youtube_dl.utils.DownloadError: ERROR: oQAPiSBWvoE: YouTube said: Unable to extract video data - I can't fix this. Can someone explain it deeply

unkempt canyonBOT
#

5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.

desert kiln
#

I wonder, if the actual Python discord, codes there own bots in python pithink

desert kiln
#

oh noice

desert kiln
#

I need help, I'm trying to make stuff like, events, but I realise I need a handler, can someone help, I have cogs set up, I need my Event Handler and stuff for my @bot.event

#

Nevermind, figured it out

desert kiln
#

Nevermind, it didn't work 💀

quick gust
#

can u reframe that? Are you trying to add an event to a cog?

desert kiln
#

maybe 💀

desert kiln
naive briar
#

No? What have you tried?

quick gust
desert kiln
#
import discord
from discord.ext import commands, tasks
import os
import json

TOKEN = ""


class Solaris(commands.Bot):
    def __init__(self):
        super().__init__(
            command_prefix="s!",
            intents=discord.Intents.all()
        )
    async def setup_hook(self):
        for filename in os.listdir('./cogs'):
            if filename.endswith('.py'):
                try:
                    await self.load_extension(f'cogs.{filename[:-3]}')
                except Exception as e:
                    print(f'Failed to load {filename[:-3]} cog. Error: {str(e)}')
                    
Solaris().run(TOKEN)

This is my main bot.py file, where and how can I add a event handler pithink

quick brook
desert kiln
#

what's a subclass 💀

#

I feel light headed what's going on

quick brook
#

subclassed bot

desert kiln
#

so where do I put it....

quick brook
unkempt canyonBOT
#

bot.py line 387

async def on_guild_join(self, guild: discord.Guild) -> None:```
desert kiln
#

I do need a on_guild_join too

#

mane, I've been up for 7 hours straight coding

quick brook
#

get some rest

desert kiln
#

no

#

I must achieve my goals

#

of getting my event handler done

#

even then, I have college in 6 hours, so I can't sleep

quick brook
desert kiln
#

nahhhhhhhhhhh

desert kiln
#

damn

#

@quick brook

quick brook
#

you dont place it in setup_hook, but place it just like setup_hook

desert kiln
#

so, if not in the hook, where?

quick brook
#

ex:

class MyBot(commands.Bot):
    def __init__(self):
      super().__init__(
        command_prefix="s!",
        intents=discord.Intents.all()
      )

    async def setup_hook(self):
        for filename in os.listdir('./cogs'):
            if filename.endswith('.py'):
                try:
                    await self.load_extension(f'cogs.{filename[:-3]}')
                except Exception as e:
                    print(f'Failed to load {filename[:-3]} cog. Error: {str(e)}')
    
    # Override the event here. Essentially this allows the bot to listen to the event this way
    async def on_guild_join(self, guild: discord.Guild):
        print(f"Guild {guild.name} just joined!")
desert kiln
#

so I put it inline with the async def setup_hook?

#

and underneath it

quick brook
#

yes just llike the example

desert kiln
#

thanks so much

quick brook
#

Np

desert kiln
# quick brook Np

Hey uh, I wanna make the on_guild_join send an embed to the use who added the bot, how can I, I tried but it didn't send a message to me when I tried

#

And I accidentally pasted my code and got rid of it

#

bruh

quick brook
desert kiln
#

DM the user who added the bot

quick brook
desert kiln
#

Oh

quick brook
#

plus, DMing the user is purely annoying. Imagine every single time that you earned a new rank in an leveling system, and that notifcation gets DMed to you. You would quickly get annoyed with this. Your consumer satisfaction would decrease (or in economics, consumer utility), and you would want to get rid of the bot. To drive home the point, any bot that performs any sort of DMs is considered annoying and an invasion of privacy

desert kiln
#

Also, may I ask, as I don't know if this is ToS breaching, but is message logging, (like Dynos) ToS breaching and am I allowed to code my own? @quick brook

turbid condor
#

It shouldn't be against ToS but I don't think it's needed to log every message I'd say only log deleted messages or something similar

desert kiln
#

deleted messages

turbid condor
#

As u can just view every message in discord

naive briar
#

If a user deleted their message, it means that they don't want anyone to see it

turbid condor
desert kiln
slate swan
#

Meanwhile people using RPC

turbid condor
#

RPC?

desert kiln
#

Rich Presence

turbid condor
#

Where's the c?

desert kiln
#

idk

naive briar
#

Presence

slate swan
#

No - Remote Procedural Calls

naive briar
#

Right 😼

turbid condor
slate swan
#

And all Discord clients have an RPC server running you can interact with

desert kiln
slate swan
#

Which is often used by people to log any messages sent/deleted/whatever

#

As it sends similar events as the gateway

shrewd apex
slate swan
#

They do

shrewd apex
#

yeah

turbid condor
#

Welp sometimes deleted message are needed as proofs

slate swan
#

To be fair it's kind of normal to log deleted messages these days

naive briar
#

Does Discord even care about them? I wonder

turbid condor
#

Welp they have no way of detecting even if being logged

shrewd apex
#

its a event they send after all

#

u have to respond to the event data from the gateway no?

#

they can atleast be sure whether data is being received wether its stored they will prolly never know

desert kiln
#

real

#

Idk what else to do for my bot then

#

Does anyone know how to use Discords timeout feature for a bot command?

naive briar
#

!d discord.Member.timeout

unkempt canyonBOT
#

await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta).

You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members) to do this.

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit).
desert kiln
#

thanks

meager rock
shrewd apex
glad cradle
#

you don't respond to received events

#

usually

shrewd apex
#

i see

hushed galleon
# shrewd apex u do send some response right to the event? or is it not required

each heartbeat you send contains the last sequence number received by discord so i believe they can be reasonably sure on how up-to-date your client is on events (although i haven't tested how they handle outdated sequences)

edit: a quick check shows nothing special happens if the sequence is behind, at least by a bit ruby discord_ws.client.client ( DEBUG) => Received hello from gateway discord_ws.client.heartbeat ( DEBUG) => Waiting 42.16s for heartbeat discord_ws.client.client ( DEBUG) => Received READY event discord_ws.client.client ( DEBUG) => Received GUILD_CREATE event root ( WARNING) => Resetting sequence from 2 to 1 discord_ws.client.heartbeat ( DEBUG) => Sending heartbeat, last sequence: 1 discord_ws.client.client ( DEBUG) => Received heartbeat acknowledgement

plucky sun
#

how to make this bot?

turbid condor
#

Using python and a discord bot lib along with psutil and datetime module XD

#

Oh and u will need to use platform module too

plucky sun
#

@turbid condor

turbid condor
#

You can get the processor using platform module

#

As for the uptime u need to create a variable that stores the time when bot goes online and then use the current time (the time at which command is used) after that u can minus the variable u created earlier with current time to get the uptime

#

And for the disk usage and memory usage u need to use psutil module

#

!pip psutil

unkempt canyonBOT
#

Cross-platform lib for process and system monitoring in Python.

turbid condor
#

Check the docs on how to get the memory usage and disk usage

vale wing
visual island
#

you also need it when sending heartbeat

pliant jay
#

what would I change?

2023-09-18T15:15:00.641693433Z File "/home/user_535268127639076885/main.py", line 3, in <module>
2023-09-18T15:15:00.641706105Z from discord.ui import Button, ButtonStyle
2023-09-18T15:15:00.641746318Z ImportError: cannot import name 'ButtonStyle' from 'discord.ui' (/usr/local/lib/python3.11/site-packages/discord/ui/init.py)
2023-09-18T15:15:13.038967257Z Traceback (most recent call last):
2023-09-18T15:15:13.039025791Z File "/home/user_535268127639076885/main.py", line 3, in <module>
2023-09-18T15:15:13.039051238Z from discord.ui import Button, ButtonStyle
2023-09-18T15:15:13.039091115Z ImportError: cannot import name 'ButtonStyle' from 'discord.ui' (/usr/local/lib/python3.11/site-packages/discord/ui/init.py)

slate swan
#

!d discord.ButtonStyle

unkempt canyonBOT
#

class discord.ButtonStyle```
Represents the style of the button component.

New in version 2.0.
slate swan
#

its not in ui

pliant jay
#

okay thank you

slate swan
#

can someone tell me whas flipping wrong

cloud dawn
#

Uhm...

#

Well first of all you leaked your token.

#

Second, your indenting is wrong. It needs to be outside the command.

slate swan
#

its fine idc

#

but which indending

#

idk what u mean

naive briar
#

The bot.run(TOKEN) is indented inside the gen function

#

So the bot will never start

slate swan
#

how do i remove it from the function

naive briar
#

Move it down?

slate swan
#

wait

#

i did that before but didnt worked

naive briar
#
def func():
    something()
    inside()

def func():
    something()
outside()
slate swan
#

but i tried it again, but ye thanks

#

i also need to learn how to use the def

#

so yall are gonna fuck my token now abi

formal basin
#

How do anti swear bots not crash?

#

since they have to read every message sent

slate swan
#

idk

formal basin
#

and check if it is in a huge list

slate swan
#

bro

#

i wanna poo

pallid meadow
#

And that’s also why discord uses a websocket connection so it’s not super expensive compared to like a regular http request

#

As for how they handle it they most likely cache a config that has the word list

#

And then just reference that config

slate swan
#

yo

pallid meadow
#

It’s fairly inexpensive plus when you get really big you have separate applications aka shards

slate swan
#

how do i make a slash commands in python

pallid meadow
#

I mean any of the main python libs support slash commands

#

They have examples in their documentation

#

I personally use disnake which is a fork of discord.py lemme see if I can get you the examples for that

formal basin
#

I use an api

#

to detect bad words

pallid meadow
#

Yeah just look at their read me

pallid meadow
#

Or a SAAS api?

slate swan
pallid meadow
#

Yep

slate swan
#

so how do i use disnake

#

ion understand anything 💀

pallid meadow
#

Well I mean it has instructions in the readme

#

Like code you can literally copy and paste and it should get you up and running

slate swan
#

ah

pallid meadow
#

If you have ever used discord.py it’s the same thing

slate swan
#

ye i have

pallid meadow
#

then yeah for your case just treat this like discord.py

slate swan
#

alr cool

pallid meadow
#

You might eventually find some differences but that’s once you get farther

slate swan
#

ima restart coding then

quick brook
#

The only reason why you would want to use them is if you already have an existing codebase written during the hiatus period for dpy

#

and snipy please dont be a fork shill

glad cradle
#

what you are saying (repeatidly) has already been proved to be wrong, d.py does not "implements every single feature that the forks have"

"oftentimes contain poor code design" well even the forks had to rework d.py codebase

quick brook
glad cradle
#

stop saying lies like "d.py implements every single feature that the forks have" pls

quick brook
#

take a look for yourself

glad cradle
#

this lists only the features officially supported by the discord api

quick brook
#

dpy supports the features provided by discord. Internal features between the projects are not considered

formal basin
#

how can i stop the crashing

#

its not my api

glad cradle
quick brook
sick birch
#

I believe Discord works off of Action Rows, discord.py tries to abstract it further with a single "View" container

slate swan
#

.topic

lament depotBOT
#
**What feature would you be the most interested in making?**

Suggest more topics here!

slate swan
#

Interesting

glad cradle
quick brook
#

all of the forks are forked off of dpy 1.7.3. Views was not a concept introduced at that time

glad cradle
quick brook
glad cradle
#

i don't like some things like the interaction class

#

use subclasses for different interaction types is better for typing

faint dragon
#

thats dope, very useful for what im doing even if its not practical, ty

quick brook
slate swan
#

Isn't it all about preferences?

glad cradle
#

in the past i also listed why i reccomend it, in the end the user choose what he needs

quick brook
#

blasphemy

glad cradle
#

oke

#

btw i used d.py a lot before it was discontinued

empty terrace
#

Hi everyone. I have an problem with youtube_dl exactly this:
Unable to extract video data

#

Download error

unkempt canyonBOT
#
Our youtube-dl, or equivalents, policy

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
sick birch
#

We don't help with youtube_dl, sorry

slate swan
# sick birch We don't help with youtube_dl, sorry

hi again robin, u helped last time it worked but now i have another issue,

File "/workspaces/codespaces-blank/bot.py", line 172, in check
int(message.content)
ValueError: invalid literal for int() with base 10: ''

def check(message):
                return message.channel == interaction.channel and message.author == interaction.user
            try:
                # Wait for a response from the same user in the same channel
                response_message = await client.wait_for("message", check=check, timeout=600)  # Adjust the timeout as needed (in seconds)
                userid = int(response_message.content)
                guild = interaction.guild
                member = guild.get_member(userid)
                if response_message == interaction.user.id:
                      return await interaction.channel.send("You cannot add yourself to the ticket.")
                await interaction.channel.set_permissions(member, view_channel=True, send_messages=True)

                # Process the user's response, for example:
                await interaction.channel.send(f"Added @<{response_message.content}> to the ticket")

            except asyncio.TimeoutError:
                # Handle the case where the user did not respond within the specified timeout
                await interaction.channel.send("You did not respond in time. The conversation has ended.")```
sick birch
slate swan
sick birch
slate swan
#

one moment

#

excuse the light mode, its natural

#

i forget that lightmode is an irregularity on discord

sick birch
#

!paste Hmm. Can you pastebin your whole code? This is odd.

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

slate swan
#

oki

#

well actually, that's mainly it

#

unless you're asking for the embeds?

sick birch
#

All of your code, please

slate swan
#

ok

sick birch
#

It is easier to help when I have the full picture

sick birch
slate swan
sick birch
#

The file where you define your bot instance

slate swan
#
import discord
from discord.ui import Select
import asyncio
from discord.ui import View
from discord import SelectOption

intents = discord.Intents.default()
intents.typing = False
intents.presences = False

client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print(f'Logged in as {client.user.name}')```
sick birch
#

Yeah you're missing message content intents

slate swan
#

ehh

#

i thought it was discord.intents.defualt

sick birch
#

Default doesn't include message content, as it's a privledged intent

slate swan
#

whats the parameter

#

intents.all?

#

@sick birch

#

ill try

sick birch
slate swan
#

yes it worked

slate swan
sick birch
#

Enable only what you need

slate swan
#

oh ok

pliant jay
#

How do I disable / change this?

slate swan
#

oh wait @sick birch

#

raise ValueError('target parameter must be either Member or Role')
ValueError: target parameter must be either Member or Role

#
 if embed:
            await interaction.response.send_message(embed=embed)
            await asyncio.sleep(1)
            await interaction.channel.send(embed=idembed)
            def check(message):
                return message.channel == interaction.channel and message.author == interaction.user
            try:
                # Wait for a response from the same user in the same channel
                response_message = await client.wait_for("message", check=check, timeout=600)  # Adjust the timeout as needed (in seconds)
                userid = int(response_message.content)
                guild = interaction.guild
                member = guild.get_member(userid)
                if response_message == interaction.user.id:
                      return await interaction.channel.send("You cannot add yourself to the ticket.")
                await interaction.channel.set_permissions(member, view_channel=True, send_messages=True)

                # Process the user's response, for example:
                await interaction.channel.send(f"Added @<{response_message.content}> to the ticket")

            except asyncio.TimeoutError:
                # Handle the case where the user did not respond within the specified timeout
                await interaction.channel.send("You did not respond in time. The conversation has ended.")```
#

i thought it would work

sick birch
sick birch
slate swan
#

yes

sick birch
#

Can you re-upload please? It's very hard to help without having everything

slate swan
#

await interaction.channel.set_permissions(member, view_channel=True, send_messages=True)
File "/usr/local/python/3.10.8/lib/python3.10/site-packages/discord/abc.py", line 935, in set_permissions
raise ValueError('target parameter must be either Member or Role')
ValueError: target parameter must be either Member or Role

sick birch
slate swan
#

ok

#

how do i make it return not none

#

@sick birch

sick birch
#

Make sure your bot can "see" the user that ID is associated with

slate swan
#

ima try user=member

#

await interaction.channel.set_permissions(user=member, view_channel=True, send_messages=True)
TypeError: GuildChannel.set_permissions() missing 1 required positional argument: 'target'

#

@sick birch ^

sick birch
#

That's not going to change anything. discord.py is expecting a Member or Role object as the first positional argument

slate swan
#

yes, i did put the member object

#
userid = int(response_message.content)
                guild = interaction.guild
                member = guild.get_member(userid)```
#

@sick birch ^

sick birch
#

That's not a Member object. That's why the error is happening - it's None

#

Is the ID you input in the same guild?

slate swan
#

yes

sick birch
#

You might try enabling the members intent, then, to see if your cache is not being populated correctly

slate swan
#

okay let me c

onyx elk
#

after countless days, i have done it, i made an auth bot that can join servers for people

glad cradle
onyx elk
pallid meadow
#

I.e are you using aiohttp

#

Or the async client in httpx

pliant jay
merry cliff
#

show code

pallid meadow
merry cliff
#

then how did they get the ping variable to show?

slate swan
#

intresting

lusty wolf
#

When i use

await vc_channel.set_permissions(dueño, manage_channels=True, manage_permissions=True)

It doesn't do nothing
But if i use:

await vc_channel.set_permissions(dueño, manage_channels=True)
await asyncio.sleep(0.5)
await vc_channel.set_permissions(dueño, manage_permissions=True)

It does put the manage permissions but not the manage channels one, any help?

old vine
#

HEY

#

HELP

golden portal
#

but the top snippet, i tried that, and it works for me

formal basin
lusty wolf
#
@bot.command()
async def crearvc(ctx, dueño: discord.Member, nombre_canal):
    staff_role = ctx.guild.get_role(staff_role_id)
    if staff_role and staff_role in ctx.author.roles:
        category = ctx.guild.get_channel(categoria_personalizada_id)
        if category and isinstance(category, discord.CategoryChannel):
            # Crea el canal de voz en la categoría especificada
            vc_channel = await category.create_voice_channel(name=nombre_canal)

            await vc_channel.set_permissions(dueño, manage_channels=True, manage_permissions=True)

            session = Session()
            vc_personalizado = VCPersonalizado(
                nombre_canal=nombre_canal,
                id_canal=str(vc_channel.id),
                id_dueño=str(dueño.id),
                id_categoria=str(categoria_personalizada_id)
            )
            session.add(vc_personalizado)
            session.commit()
            session.close()

            embed = success_embed("Éxito", f'Se ha creado el canal de voz "{nombre_canal}" para {dueño.mention}.')
            await ctx.send(embed=embed)
        else:
            embed = error_embed("Error", 'No se encontró la categoría especificada.')
            await ctx.send(embed=embed)
    else:
        embed = error_embed("Error", 'No tienes permiso para ejecutar este comando o no tienes el rol de staff requerido.')
        await ctx.send(embed=embed)
#

It's on spanish btw, it just creates a voice channel and saves the info on the database.

desert kiln
#

I need help, I made a server backup bot, but upon restoring, the channels that didn't have a category, are getting put into a category, when I don't want them to be, can anyone help, I can provide code

desert kiln
strong latch
#
SnowflakeList('Q', [363328781022265344, 364822725467832321, 364846629175427073, 384173364849410048, 403953822441013248, 509682779571617801, 690298992474849292, 702584168525332580, 702584184052645930, 826152032071188491, 1045358666104193125, 1072364127491739679, 1105823156037496933, 1110851398159056967, 1112505356921339904, 1116526892191862816, 1117164006197690460, 1117164805367804044, 1148248251900907600, 1152675123678162997, 1152675562217812009])

What kind of list is this ? and how do you work with it?

turbid condor
#

can u tell what type of function it is?

tepid dagger
#

how do you set an embed's image to a file

turbid condor
#

and which lib are you using for that?

#

that's the prolem then

#

!blocking

unkempt canyonBOT
#
Asynchronous programming

Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.

What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:

import discord

# Bunch of bot code

async def ping(ctx):
    await ctx.send("Pong!")

What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.

async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!

tepid dagger
#

how do you check if the person running the command is_owner

#

i couldn't find anything for slash commands

slate swan
#

define your own check

tepid dagger
#

wdym

turbid condor
#

yes

slate swan
#

i need help with this i dont understand
Traceback (most recent call last): File "c:/Users/rivar/Desktop/Poll discord/main.py", line 4, in <module> client = commands.Bot(command_prefix = '!') TypeError: __init__() missing 1 required keyword-only argument: 'intents'

turbid condor
#

It says you haven't put intents inside you bot class

unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

stoic tusk
#

Anyone knows how to fix?

slate swan
#

define a log_channels varriable?

stoic tusk
slate swan
stoic tusk
final iron
#

Pretty self explanatory

young dagger
#

Will this function also be triggered when messages are edited by users?

@client.listen()
async def on_message(message):```
unkempt canyonBOT
#

discord.on_message_edit(before, after)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) receives an update event. If the message is not found in the internal message cache, then these events will not be called. Messages might not be in cache if the message is too old or the client is participating in high traffic guilds.

If this occurs increase the [`max_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) parameter or use the [`on_raw_message_edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_message_edit) event instead.

The following non-exhaustive cases trigger this event...
young dagger
# final iron No

So you can't create a function that works on both new and edited messages? You have to create a separate function for that?

final iron
#

Not really sure why you would want that though

young dagger
final iron
#

Why though

young dagger
#

Because it's a bad word filter 2_PeepoShrug

final iron
#

So just use 2 events, and create a function to filter it

#

Call the function in both events

young dagger
young dagger
young dagger
# final iron Call the function in both events

You mean something like this:

@client.listen
async def on_message(message):
    await handle_message(message)

@client.listen
async def on_message_edit(before, after):
    if before.content != after.content:
        await handle_message(after)```
final iron
#

Yeah

young dagger
# final iron Yeah

For some reason it's not working

@client.listen
async def on_message(message):
    await handle_message(message)

@client.listen
async def on_message_edit(before, after):
    if before.content != after.content:
        await handle_message(after)

async def handle_message(message):
    if not isinstance(message.author, discord.Member):
        return

# Code here```
#

Oh I'm missing parentheses

slate swan
#

How I can edit description in embed? (pycord)

buoyant quail
#

embed.description = ...

#

i don't think pycord has something special

slate swan
#

bruh

buoyant quail
#

that's different from what i suggested

#

it's just an attribute, yes

buoyant quail
slate swan
# buoyant quail .

I realized that it's easier for me to create a new embed rather than change the old one. Thanks!

tribal current
#

who good with excel? i got a question i can pay pm me right now

slate swan
#

!rule pay

unkempt canyonBOT
#

9. Do not offer or ask for paid work of any kind.

wet raft
#

sombody help me??

#

i cant figure out this error

shrewd apex
#

send a screen shot

#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

shrewd apex
#

or paste it there

unkempt mauve
#
2023-09-19 23:51:18 ERROR    discord.client Ignoring exception in on_guild_join
Traceback (most recent call last):
  File "FILE", line 441, in _run_event
    await coro(*args, **kwargs)
  File "FILE", line 70, in on_guild_join
    embed.set_author(icon_url=guild.owner.default_avatar, name=guild.owner, url=f'https://discord.com/users/{guild.owner_id}')
                              ^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'default_avatar'```

I dont get it, the guild that the bot is being added to has a valid owner, then why does it says guild.owner is None?
wet raft
#

its a big error

unkempt mauve
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

unkempt mauve
#

dude paste it there if its too big, dont flood the chat

wet raft
#

wha else then

unkempt mauve
wet raft
#

its an error btw

shrewd apex
unkempt mauve
shrewd apex
#

u need members iirc

unkempt mauve
#

but I am fetching the guild owner not member

wet raft
unkempt mauve
shrewd apex
#

try with server members intent i would say

shrewd apex
#

this is not your code is it?

wet raft
#

it is

#

i have it there

#

i put the the thang there so i remember for later

#

new discord bot coder thats why i put that there

unkempt mauve
shrewd apex
#

tbh idk it depends on the person verifying your bot

wet raft
#

i fixed it

slate swan
quick brook
#

this is hence why I plan on removing that intent from mine and just leaving message content since my bot is using hybrid commands. And for message content, i plan on creating an essay on why

glad cradle
#

why don't you fully migrate to slash commands? i mean discord enforced them to not give message content intent to bots for commands

quick brook
#

read the source code here. It's 12.8K lines of Python code

#

feel free to make a pr to convert all of them to slash commands once you understand how complex the bot is

glad cradle
#

i'm not here to go against you 😭 but i don't think that's a valid excuse for discord, even big bots were forced to migrate

quick brook
#

they have a team. I'm a solo developer. Migrating my bot would take too much effort and would not quantify the time spent

#

the goal is to create a module that depends on message_content that solves an issue that most people face

glad cradle
#

wdym?

meager rock
unkempt canyonBOT
#

Bot/kumikocore.py line 42

bot, interaction.user.id, bot.pool```
quick brook
#

most if not all of my helper coros follow this design of passing in the pool object directly, so it makes sense to implement it as so

meager rock
#

fair

unkempt canyonBOT
#

typing.TYPE_CHECKING```
A special constant that is assumed to be `True` by 3rd party static type checkers. It is `False` at runtime.

Usage:

```py
if TYPE_CHECKING:
    import expensive_mod

def fun(arg: 'expensive_mod.SomeType') -> None:
    local_var: expensive_mod.AnotherType = other_fun()
```  The first type annotation must be enclosed in quotes, making it a “forward reference”, to hide the `expensive_mod` reference from the interpreter runtime. Type annotations for local variables are not evaluated, so the second annotation does not need to be enclosed in quotes.
#

Bot/Libs/utils/blacklist.py line 41

# Circular import so bot is untyped```
quick brook
#

does not work in my case

#

unless you want to demostrate that in fact, you can make it work, feel free to make a pr and i'll test and code review it to ensure it will work

meager rock
#

bet I'll do that when I'm home

quick brook
meager rock
# quick brook ok i will be expecting to see a PR in a couple of hours

Just made 2 changes in the code ( on my cloud environment)

from __future__ import annotations

from typing import Dict, TYPE_CHECKING

if TYPE_CHECKING:
     from Bot.kumikocore import KumikoCore

# in function
async def get_or_fetch_blacklist(bot: KumikoCore, id: int, pool: asyncpg.Pool) -> bool:
``` worked like a charm for importing in a file
I couldn't test on a running bot since I don't have a dev environment rn but importing this way can have no issues \:)
quick brook
final iron
meager rock
glad cradle
quick brook
glad cradle
#

from typing import Dict, TYPE_CHECKING

if TYPE_CHECKING:
     from Bot.kumikocore import KumikoCore

# in function
async def get_or_fetch_blacklist(bot: "KumikoCore", id: int, pool: asyncpg.Pool) -> bool:
#

the future import does that for you

quick brook
meager rock
#

String annotations work with any version from 3.8 on

quick brook
#

hm ok

mighty pilot
#

Can I retrieve a message object with just it's ID?

#

Or do I need the channel as well

shrewd apex
#

channel as well

mighty pilot
#

Gross. Alright

snow coral
#

hey uh how would i add command cooldowns

desert kiln
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

desert kiln
true maple
#

Heyy! Is there any way I can make a Interaction.Modal appear when I press a button?

golden portal
dire mason
#

Does anyone know what this means?

(venv) PS C:\Users\boyle\PycharmProjects\NoteWizzard> py -3.10 -m pip install -U wavelink
No suitable Python runtime found
Pass --list (-0) to see all detected environments on your machine
or set environment variable PYLAUNCHER_ALLOW_INSTALL to use winget
or open the Microsoft Store to the requested version.
desert kiln
#

--list

dire mason
desert kiln
dire mason
# desert kiln yuh
At line:1 char:3
+ --list
+   ~
Missing expression after unary operator '--'.
At line:1 char:3
+ --list
+   ~~~~
Unexpected token 'list' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingExpressionAfterOperator

dire mason
final iron
#

Could you screenshot your interpreter settings?

final iron
#

Those are your libraries

dire mason
dire mason
final iron
#

And you have 3.11 installed

dire mason
final iron
#

You shouldn’t need to use the version at all

#

You’re in a venv, you should only have 1 interpreter

dire mason
#

Yeah

#

So how would install that then?

final iron
#

Normally

#

pip install …

dire mason
#

I got it...

#
discord.ext.commands.errors.ExtensionFailed: Extension 'Cog' raised an error: TypeError: module() takes at most 2 arguments (3 given)
#
import discord
from discord import app_commands
from discord.ext import commands
import wavelink
from typing import Any

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

class player(wavelink.player):

    def __init__(self, bot: discord.member, *args: Any, **kwargs: Any):
        super().__init__(*args, **kwargs)
        self.bot = bot

    @app_commands.command(name="play")
    async def connect(self, interaction: commands.Context, *, channel: discord.VoiceChannel | None = None):
        try:
            channel = channel or interaction.author.channel.voice
        except AttributeError:
            return await interaction.reply("User is not in voice channel.")

        vc: wavelink.player = await channel.connect(cls=wavelink.player)
        return vc

    @app_commands.command(name="sync")
    async def slash_sync(self, interaction):
        await interaction.response.send_message("Commands Successfully synced!")
        await self.bot.tree.sync()

    async def cog_load(self):
        print(f"{self.__class__.__name__} loaded!")

    async def cog_unload(self):
        print(f"{self.__class__.__name__} unloaded!")

async def setup(bot):

    await bot.add_cog(player(bot=bot))
final iron
#

What’s the full traceback

dire mason
final iron
#

Sure

dire mason
#
Traceback (most recent call last):
  File "C:\Users\boyle\PycharmProjects\NoteWizzard\main.py", line 16, in <module>
    NoteWizzard().run(TOKEN)
  File "C:\Users\boyle\PycharmProjects\NoteWizzard\venv\Lib\site-packages\discord\client.py", line 860, in run
    asyncio.run(runner())
  File "C:\Users\boyle\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "C:\Users\boyle\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\boyle\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "C:\Users\boyle\PycharmProjects\NoteWizzard\venv\Lib\site-packages\discord\client.py", line 849, in runner
    await self.start(token, reconnect=reconnect)
  File "C:\Users\boyle\PycharmProjects\NoteWizzard\venv\Lib\site-packages\discord\client.py", line 777, in start
    await self.login(token)
  File "C:\Users\boyle\PycharmProjects\NoteWizzard\venv\Lib\site-packages\discord\client.py", line 621, in login
    await self.setup_hook()
  File "C:\Users\boyle\PycharmProjects\NoteWizzard\main.py", line 14, in setup_hook
    await self.load_extension("Cog")
  File "C:\Users\boyle\PycharmProjects\NoteWizzard\venv\Lib\site-packages\discord\ext\commands\bot.py", line 1013, in load_extension
    await self._load_from_module_spec(spec, name)
  File "C:\Users\boyle\PycharmProjects\NoteWizzard\venv\Lib\site-packages\discord\ext\commands\bot.py", line 938, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'Cog' raised an error: TypeError: module() takes at most 2 arguments (3 given)

#

If you want to sent the solution or help me understand the errors, send them in my dms im heading off to bed

fervent shoal
#

heyyy so im makin a discord bot for a friend to troll somenoe, and im tryna make it have a toggle. so anyone with an admin role id would be able to toggle it on or off, and I cant figure out the toggle bit

#
Toggle = False  
@bot.command()
async def toggle(ctx):
    if is_admin(ctx):
        Toggle 
        await ctx.reply('Toggle is now ON')  
    else:
        await ctx.send('You dont have permission to use this command')  

@bot.event

async def on_message(message):
    vowels = "Uu"
    if Toggle:
        if is_snake(message):
            
            if any(v in vowels for v in message.content.lower()):
                await message.delete()
    else:
        await message.channel.send("Function disabled")

shrewd apex
#

looks gpt generated tbh

#

u would want the check has_role

fervent shoal
turbid condor
#

because the is admin condition isn't being satisfied

sick birch
#

Python scope doesn't really work like that

fervent shoal
#

so do i just slap the toggle bit under bot event or

sick birch
#

And yes use has_role

fervent shoal
#

idk im still new ish and i do python in small bursts, so most of the terminology is non existent in my head

sick birch
#

To toggle it on you'd do bot.toggle = True

#

In your on_message you would check if bot.toggle

fervent shoal
#

wait no that doesnt work

sick birch
#

!d discord.ext.commands.has_role

unkempt canyonBOT
#

@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

If the message is invoked in a private message context then the check will return `False`.

This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole) if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage) if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure).

Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole) or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage) instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure)...
sick birch
#

See documentation on how to use has role

#

You pass in either role ID or role name

fervent shoal
#

i got that, but regardless of the role its still spamming "function disabled"

naive briar
#

It sure will

#

You never change the variable's value from False to something else

#

So, the if Toggle statement will never be true

naive swan
#
def get_messages(sender, recipient, message):
    sender = sender.lower()
    sender_role = "assistant" if sender == "assistant" else "user"
    role = recipient.lower() if sender == "assistant" else sender

    user = get_user(role)
    personality = user['personality'] if user else config["global_personality"]

    bot_context=config["system_context"]

    system_role={"role": "system", "content": f"{bot_context}."}

    prefix='' if sender_role == 'assistant' else f"{personality}"
    add_message({"role": sender_role, "content": f"{prefix} {message}"})

    return [
      system_role,
      *[{"role": obj['role'], "content": obj['content']} for obj in history]
    ]

async def generate_response(message):
    try:
        if message.author == bot.user:
            return

        def call_openai_api():
            logger.info('Звоню на Апишник')
            return openai.ChatCompletion.create(
                model=config["model"],
                messages=get_messages(message.author.name, 'assistant', message.content),

temperature = 0.7
            )

        await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="a " + message.author.name))
        async with message.channel.typing():
            logger.info(message.author.name + ": " + message.content)
            response = await bot.loop.run_in_executor(None, call_openai_api)
            content = response['choices'][0]['message']['content']
            await message.reply(content)
            get_messages('assistant', message.author.name, content)
            logger.info("Assistant: " + content)
            logger.info("Токены: " + str(response["usage"]["total_tokens"]))

 #changing presence and error handling

So, the problem is, i need to have {message.author.name} at the end of system prompt/request, but im not sure i know where should i put it.

naive briar
#

Set the variable?

#

!e

toggle = False
print(toggle)

toggle = True
print(toggle)
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | False
002 | True
naive swan
sweet minnow
#

Code:

import discord
from discord_slash import SlashCommand

client = discord.Client(intents=discord.Intents.all())
slash = SlashCommand(client, sync_commands=True) # Declares slash commands through the client.

@client.event
async def on_ready():
    print("Ready!")

client.run("my_token_here")
#

but its already installed...

#

then how come it shows no module named 'discord_slash'?

naive briar
#

Because there's no module named discord_slash, not even in the screenshot

sweet minnow
#

?

#

Then what I'm I supposed to install?

naive briar
#

If you're using discord.py, none; discord.py already support slash commands

sweet minnow
#

Oh.

sweet minnow
#

What do I need to install?

naive briar
#

py-cord also support slash commands

sweet minnow
#

Oh.

quick brook
quick brook
# sweet minnow Oh.

Here is a short example of how to use discord.py's slash commands as well as general information on them:

https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f

This currently covers free commands and groups at the Bot level, as well as within Cog classes.
It also includes information and gotchas relating to syncing and whatnot.

NOTE: This will be migrating to https://about.abstractumbra.dev/ as soon as I can be bothered to finish it.

quick brook
#

Yes that's an actual story that happened a couple of weeks ago btw

sweet minnow
#

But, I have an already working bot (made 1-2 years ago)

#

but it has this error

#

and heres the python libaries installed

#

start of the code:

import discord
from discord.ext import tasks, commands
from discord.ext.commands import cooldown, BucketType

import sys, traceback

import os
import time
import random
import asyncio
import json
import os
import aiohttp
import mysql.connector
import numpy as np

from discord import Intents
from discord import default_permissions
from discord.ext import commands
from discord.commands import Option
#

the bot was originally hosted locally on my pc, and it still runs perfectly

#

but now i want to switch it to cloud hosting

#

this is what i put in requirements.txt

discord.py==2.3.0
aiohttp==3.8.4
async-generator==1.10
async-timeout==4.0.2
mysql-connector-python==8.0.33
numpy==1.24.2
py-cord==2.4.1
requests==2.28.2
quick brook
quick brook
sweet minnow
#

ok

#

discord.py
aiohttp
async-generator
async-timeout
mysql-connector-python
numpy
requests

#

Successfully installed aiohttp-3.8.5 aiosignal-1.3.1 async-generator-1.10 async-timeout-4.0.3 attrs-23.1.0 certifi-2023.7.22 charset-normalizer-3.2.0 discord.py-2.3.2 frozenlist-1.4.0 idna-3.4 multidict-6.0.4 mysql-connector-python-8.1.0 numpy-1.26.0 protobuf-4.21.12 requests-2.31.0 urllib3-2.0.5 yarl-1.9.2
Traceback (most recent call last):
File "/home/container/awwpika.py", line 18, in <module>
from discord import default_permissions
ImportError: cannot import name 'default_permissions' from 'discord' (/home/container/.local/lib/python3.11/site-packages/discord/init.py)
container@pterodactyl~ Server marked as offline...
[Bot-Hosting Daemon]: ---------- Detected server process in a crashed state! ----------
[Bot-Hosting Daemon]: Exit code: 1
[Bot-Hosting Daemon]: Out of memory: false
[Bot-Hosting Daemon]: Aborting automatic restart, last crash occurred less than 600 seconds ago.

buoyant quail
sweet minnow
#

It's pycord.

buoyant quail
#

ah

#

pycord also doesn't have it btw

#

it has discord.commands.default_permissions

#

but not discord.default_permissions

sweet minnow
#

then how does it work when i run locally

buoyant quail
#

then just don't install discord.py together with pycord

sweet minnow
#

so do i need to install pycord or no?

buoyant quail
#

if you use it - sure

#

pip uninstall discord.py
pip install -U py-cord

sweet minnow
#

okay

#

lemme try

#

omg it works :D

sweet minnow
quick gust
#

what's the best approach to keep looping a song in a vc for a particular period of time

naive swan
#
def get_messages(sender, recipient, message):
    sender = sender.lower()
    sender_role = "assistant" if sender == "assistant" else "user"
    role = recipient.lower() if sender == "assistant" else sender

    user = get_user(role)
    personality = user['personality'] if user else config["global_personality"]

    bot_context=config["system_context"]

    system_role={"role": "system", "content": f"{bot_context}."}

    prefix='' if sender_role == 'assistant' else f"{personality}"
    add_message({"role": sender_role, "content": f"{prefix} {message}"})

    return [
      system_role,
      *[{"role": obj['role'], "content": obj['content']} for obj in history]
    ]

async def generate_response(message):
    try:
        if message.author == bot.user:
            return

        def call_openai_api():
            logger.info('Звоню на Апишник')
            return openai.ChatCompletion.create(
                model=config["model"],
                messages=get_messages(message.author.name, 'assistant', message.content),

temperature = 0.7
            )

        await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="a " + message.author.name))
        async with message.channel.typing():
            logger.info(message.author.name + ": " + message.content)
            response = await bot.loop.run_in_executor(None, call_openai_api)
            content = response['choices'][0]['message']['content']
            await message.reply(content)
            get_messages('assistant', message.author.name, content)
            logger.info("Assistant: " + content)
            logger.info("Токены: " + str(response["usage"]["total_tokens"]))

 #changing presence and error handling

So, the problem is, i need to have {message.author.name} at the end of system prompt/request, but im not sure that iknow where should i put it.

slate swan
#

Hard to fall in the joke with such a bad quality picture

onyx elk
#

does anyone know why this doesnt edit permissions to do this

    await channel.set_permissions(ctx.guild.default_role, read_messages=True, send_messages=False)
#

its not even right colour

onyx elk
onyx elk
#

does anyone know why this doesnt edit permissions to do this

    await channel.set_permissions(ctx.guild.default_role, read_messages=True, send_messages=False)
slate swan
glad cradle
#

nah it can be used in guilds too

onyx elk
#

just you need attach file sperms

slate swan
onyx elk
hushed galleon
lament depotBOT
onyx elk
hushed galleon
#

oh oops, i dont edit channel permissions from my bot often so i wouldn't know

glad cradle
dire mason
#
Traceback (most recent call last):
  File "C:\Users\boyle\PycharmProjects\NoteWizzard\venv\Lib\site-packages\discord\ext\commands\bot.py", line 935, in _load_from_module_spec
    spec.loader.exec_module(lib)  # type: ignore
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap_external>", line 940, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "C:\Users\boyle\PycharmProjects\NoteWizzard\Cog.py", line 10, in <module>
    class player(wavelink.player):
TypeError: module() takes at most 2 arguments (3 given)

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

Traceback (most recent call last):
  File "C:\Users\boyle\PycharmProjects\NoteWizzard\main.py", line 16, in <module>
    NoteWizzard().run(TOKEN)
  File "C:\Users\boyle\PycharmProjects\NoteWizzard\venv\Lib\site-packages\discord\client.py", line 860, in run
    asyncio.run(runner())
  File "C:\Users\boyle\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "C:\Users\boyle\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\boyle\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "C:\Users\boyle\PycharmProjects\NoteWizzard\venv\Lib\site-packages\discord\client.py", line 849, in runner
    await self.start(token, reconnect=reconnect)
  File "C:\Users\boyle\PycharmProjects\NoteWizzard\venv\Lib\site-packages\discord\client.py", line 777, in start
    await self.login(token)
  File "C:\Users\boyle\PycharmProjects\NoteWizzard\venv\Lib\site-packages\discord\client.py", line 621, in login
    await self.setup_hook()
  File "C:\Users\boyle\PycharmProjects\NoteWizzard\main.py", line 14, in setup_hook
    await self.load_extension('Cog')
  File "C:\Users\boyle\PycharmProjects\NoteWizzard\venv\Lib\site-packages\discord\ext\commands\bot.py", line 1013, in load_extension
    await self._load_from_module_spec(spec, name)
  File "C:\Users\boyle\PycharmProjects\NoteWizzard\venv\Lib\site-packages\discord\ext\commands\bot.py", line 938, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'Cog' raised an error: TypeError: module() takes at most 2 arguments (3 given)

Getting this error, and I don't 100% undstand what it is trying to let me know is wrong. Can someone try to help me figure out that?

This is my orignal Code:

import discord
from discord import app_commands
from discord.ext import commands
import wavelink
from typing import Any

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

class player(wavelink.player):

    def __init__(self, bot: discord.member, *args: Any, **kwargs: Any):
        super().__init__(*args, **kwargs)
        self.bot = bot

    @app_commands.command(name="play")
    async def connect(self, interaction: commands.Context, *, channel: discord.VoiceChannel | None = None):
        try:
            channel = channel or interaction.author.channel.voice
        except AttributeError:
            return await interaction.reply("User is not in voice channel.")

        vc: wavelink.player = await channel.connect(cls=wavelink.player)
        return vc

    @app_commands.command(name="sync")
    async def slash_sync(self, interaction):
        await interaction.response.send_message("Commands Successfully synced!")
        await self.bot.tree.sync()

    async def cog_load(self):
        print(f"{self.__class__.__name__} loaded!")

    async def cog_unload(self):
        print(f"{self.__class__.__name__} unloaded!")

async def setup(bot):

    await bot.add_cog(player(bot=bot))
final iron
#

You need to subclass commands.Cog

#

You can't subclass wavelink.player and magically have the class turn into a cog

#

bot is also typehinted wrong

#

It's not discord.member, nor discord.Member

#

Your interaction typehint is also wrong

#

discord.Interaction.reply() doesn't exist as well

#

You're also loading a cog named Cog

dire mason
final iron
final iron
dire mason
final iron
#

No

#

Why are you trying to reply

dire mason
#

To let the user know the error

final iron
#

What's wrong with using send_message

dire mason
#

Can I not reply to the users interaction

final iron
#

Obviously not

#

!d discord.Interaction

unkempt canyonBOT
#

class discord.Interaction```
Represents a Discord interaction.

An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.

New in version 2.0.
final iron
#

Read the docs

dire mason
#
discord.ext.commands.errors.ExtensionFailed: Extension 'Cog' raised an error: TypeError: module() takes at most 2 arguments (3 given)

but like what is failing here

final iron
#

Already explained it.

dire mason
final iron
#

Cool

#

Is there a question anywhere?

dire mason
final iron
#

Sure

#

I dunno if it'll work

#

But it technically is what I said

dire mason
#

Same error

final iron
#

Yes, because doing that makes no sense

dire mason
#
    await bot.add_cog(Cog(bot=bot))

It is this?

final iron
#

You shouldn't be nesting classes

#

You should have 1 class, which inherits from commands.Cog

dire mason
#

I really dont understand.

#

I'm sorry, im really new to python

final iron
#

!lp

#

!tag lp

#

What's the learn python shit

#

!resources

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

final iron
#

OOP and async programming are the recommended bare essentials for discord.py

#

Inheriting is basic OOP

#

You need to inherit commands.Cog in your main class, not wavelink

dire mason
#

I just really want to make a music bot.

final iron
#

Okay, you've been given the solution

#

If you want to load a cog it has to inhert from commands.Cog

#

Not wavelink

final iron
dire mason
#

Because I want to design and improve and add features that preexisting ones do not have. Its also helps me to know what I can and not do. I want to also feel good about learning, and developing bots for my friends and others to enjoy,

final iron
#

@thorny tangle

#

<@&831776746206265384>

#

Spam/potential raid

#

I think it's a self-bot tbh

#

The reactions were added very quickly

#

Anyway, how should I go about testing functions/blocks of code for speed/efficiency

mighty pilot
final iron
#

There has to be a better way

#

I can’t imagine it’ll be all that accurate

pastel token
#

!e

prcnt = 50
print(f"[{'=' * prcnt}{' ' * (100 - prcnt)}]({prcnt}%)")
unkempt canyonBOT
#

@pastel token :white_check_mark: Your 3.11 eval job has completed with return code 0.

[==================================================                                                  ](50%)
pastel token
#

nice

#
prcnt = 25
print(f"[{'=' * prcnt}{' ' * (100 - prcnt)}]({prcnt}%)")
#

!e

prcnt = 25
print(f"[{'=' * prcnt}{' ' * (100 - prcnt)}]({prcnt}%)")
unkempt canyonBOT
#

@pastel token :white_check_mark: Your 3.11 eval job has completed with return code 0.

[=========================                                                                           ](25%)
pastel token
#

holy shit

#

wait what if i do the old command

#

!e
prcnt = 50
print('['+('=' * prcnt) + (" " * (100 - prcnt))']' + '(' + str(prcnt) + '%)')

unkempt canyonBOT
#

@pastel token :x: Your 3.11 eval job has completed with return code 1.

001 |   File "/home/main.py", line 2
002 |     print('['+('=' * prcnt) + (" " * (100 - prcnt))']' + '(' + str(prcnt) + '%)')
003 |           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
004 | SyntaxError: invalid syntax. Perhaps you forgot a comma?
pastel token
#

ok fstrings it is

final iron
pastel token
#

THAT EXISTS?!?

final iron
#

Yes…

#

Have you been using the commands in random channels all this time

pastel token
#

YES

#

oh my god im stupid

final iron
#

mighty pilot
mighty pilot
# final iron There has to be a better way

I wonder as well, but also I've ran it twice in the same command to run some tests and it seems to be fairly consistent with the short time spans between the beginning and end of commands. Like... 0.002 secs

feral timber
#

!docs discord.TextChannel.create_webhook

unkempt canyonBOT
#

await create_webhook(*, name, avatar=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a webhook for this channel.

You must have [`manage_webhooks`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_webhooks) to do this.

Changed in version 1.1: Added the `reason` keyword-only parameter.
feral timber
#

Looks like it

golden portal
#

if you only have the url though, there is a sync alternative such as SyncWebhook.from_url

#

!d discord.SyncWebhook.from_url

unkempt canyonBOT
#

classmethod from_url(url, *, session=..., bot_token=None)```
Creates a partial [`Webhook`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook) from a webhook URL.
feral timber
golden portal
#

i mean, you create it once, and that's it, after that you always reference the url

final iron
#

!d discord.Webhook.url

unkempt canyonBOT
final iron
#

create_webhook will return a discord.Webhook object

#

wdym

#

Like an error?

#

That's...not how you do that