#discord-bots

1 messages · Page 314 of 1

robust fulcrum
#

But there are some colors i guess

still spade
#

alright ik that tho are they predefined name or any of the choice we can think

like for red is it red ?

still spade
#

alright thnx

hot sparrow
#

edit: resolved

async def embed_cat(interaction: discord.Interaction, link: str):
...
...
    await interaction.response.send_message(embeds=embed_list, view=None)
Traceback (most recent call last):
  in embed_cat
    await interaction.response.send_message(embeds=embed_list, view=None) #TODO: make working save button
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 801, in send_message
    await adapter.create_interaction_response(
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 219, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```

got this funny behaviour today
#

was working last week

#

i also noticed that this stderr shows up 10 seconds after discord reports that the application did not respond

#

there was also this funny warning message, so im thinking is it because im downloading like a very big zip file on the host at the same time

[2023-10-18 23:23:35] [WARNING ] discord.gateway: Can't keep up, shard ID None websocket is 23.4s behind.```
#
[2023-10-18 23:54:35] [INFO    ] discord.gateway: Shard ID None has successfully RESUMED session 81ece34c46850679f301fe64a3343349.
#

ok thats not normal

shrewd vapor
#

Its normal

hot sparrow
strong sage
final iron
#

Seems like more of a discord issue

turbid condor
#

It's cuz of connection issue

#

And that's too many disconnects and reconnects

#

It's almost happening every hour

cinder tulip
#
@client.tree.command(name="rps", description="Play Rock, Paper, Scissors with another member.")
async def rps(interaction: discord.Interaction, challenge: discord.Member, stats: str = "") -> None:
    if challenge and not stats:

        class RPSView(discord.ui.View):
            def __init__(self, challenged_user: discord.Member, challenger_user: discord.Member):
                super().__init__()
                self.challenged_user = challenged_user
                self.challenger_user = challenger_user

            @discord.ui.button(label="Accept", custom_id="accept", style=discord.ButtonStyle.green)
            async def accept_button(self, button: discord.ui.Button, interaction: discord.Interaction):
                if interaction.user == self.challenged_user:

                    move_view = MoveView(challenged_user=self.challenged_user, challenger_user=self.challenger_user)
                await interaction.response.send_message("Make your move:", view=move_view, ephemeral=True)

            @discord.ui.button(label="Refuse", custom_id="refuse", style=discord.ButtonStyle.red)
            async def refuse_button(self, button: discord.ui.Button,interaction: discord.Interaction):
                if interaction.user == self.challenged_user:
                        embed = discord.Embed(title=f"{self.challenged_user.display_name} refused the game", color=discord.Color.red())
                        await interaction.response.send_message(embed=embed)
                else:
                     await interaction.response.send_message("You can't refuse a challenge you didn't initiate!", ephemeral=True)
                
        await interaction.response.send_message(f"{challenge.mention}\n{interaction.user.mention} has challenged you to a game of rock, paper, scissors!", view=RPSView(challenged_user=challenge, challenger_user=interaction.user))

anyone knows why it doesn't work? it tells me "AttributeError: 'Button' object has no attribute 'user'" but i got no idea of what to do (this happens when i click on the refuse button)

shrewd vapor
turbid condor
#

Welp your host

shrewd vapor
#

Its connection from the hoster lol

#

They say 300mbps

cinder tulip
#

Imma tell you that it happends to me sometimes too, and i host straight from my pc so idk

#

but that happends like two or three times every idk when

turbid condor
turbid condor
shrewd vapor
#

Its the life 🤷‍♂️

turbid condor
#

Even i also host bot but i get that rarely once or twice a day

cinder tulip
#

i've been tryna fix this thing from like 2 hours

#

i owe you my house

turbid condor
cinder tulip
turbid condor
#

Welp that was in old version

#

Now interaction comes first then button

cinder tulip
#

alright man, thanks alot for your support :D

shrewd vapor
#

You know why my bot get this error every hours ?

2023-10-18 18:11:36 INFO     discord.player ffmpeg process 9098 successfully terminated with return code of 0.
2023-10-18 18:16:49 INFO     discord.player ffmpeg process 9103 successfully terminated with return code of 0.
2023-10-18 18:18:50 ERROR    discord.voice_client Disconnected from voice... Reconnecting in 1.70s.
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/voice_client.py", line 461, in poll_voice_ws
    await self.ws.poll_event()
  File "/home/container/.local/lib/python3.11/site-packages/discord/gateway.py", line 1011, in poll_event
    raise ConnectionClosed(self.ws, shard_id=None, code=self._close_code)
discord.errors.ConnectionClosed: Shard ID None WebSocket closed with 1006
2023-10-18 18:18:52 INFO     discord.voice_client The voice handshake is being terminated for Channel ID 1154257710301323344 (Guild ID 1077639717497090171)
2023-10-18 18:18:52 INFO     discord.voice_client Connecting to voice...
2023-10-18 18:18:52 INFO     discord.voice_client Starting voice handshake... (connection attempt 27)
2023-10-18 18:18:52 INFO     discord.voice_client Voice handshake complete. Endpoint found rotterdam6138.discord.media```
#

He just read .mp3 everytime and he play in a vc

cinder tulip
turbid condor
#

I don't know much about voice module

#

Haven't gotten into it yet

cinder tulip
shrewd vapor
cinder tulip
turbid condor
shrewd vapor
#

He play music since 5 days without stop except with this error

cinder tulip
#

ffmpeg doesnt work at all with me

turbid condor
#

As shard id non is closing

shrewd vapor
#

ffmpeg work

cinder tulip
#

i tried with wavelink but i sukc

cinder tulip
shrewd vapor
#

You just need to add to PATH

cinder tulip
shrewd vapor
#

Have you the error ?

turbid condor
#

Wavelink is actually pretty easy for dpy users

cinder tulip
cinder tulip
turbid condor
#

Welp if you know OOPS then I don't think it should be hard

shrewd vapor
#

I use ffmpeg and PyNaCl

turbid condor
#

And you will need to read the docs as the yt tutorials are old and outdated

#

Just like discord

shrewd vapor
#

I have stop to try to use youtube and i download all mp3 i want for give in folder for the bot

shrewd vapor
#

Youtube have blocked all api for play in streaming

cinder tulip
shrewd vapor
#

You can play 2 minutes and after he stop

turbid condor
#

It's against their ToS

cinder tulip
shrewd vapor
#

Its why i use mp3 now lol

turbid condor
#

SoundCloud allows you to play but their api is closed i heard

shrewd vapor
#

I just use that

current_song = None

async def play(connect):
    global current_song
    songs_dir = "song"
    last_song = None
    while True:
        mp3_files = [f for f in os.listdir(songs_dir) if f.endswith(".mp3")]
        if mp3_files:
            random_song = random.choice(mp3_files)
            while random_song == last_song:
                random_song = random.choice(mp3_files)
            last_song = random_song
            current_song = random_song
            random_song_path = os.path.join(songs_dir, random_song)
            connect.play(discord.FFmpegPCMAudio(random_song_path))
            while connect.is_playing():
                await asyncio.sleep(1)```
#

In the on_ready i just connect the bot to the special vc

turbid condor
#

Well i stay away from music

hot sparrow
turbid condor
#

Only breaking ToS if I'm not bot owner and getting paid for it

shrewd vapor
#

My music bot is only for me in my private vc

turbid condor
#

Well if it's for you then just use an audio player

shrewd vapor
#

I already have spotify but we listen my bot with my friend

#

My bot play only song from Taylor Swift

turbid condor
#

Ahh

cinder tulip
turbid condor
#

Dedicated to swift

#

Liked Love Story

shrewd vapor
#

My favorite is Enchanted

cinder tulip
#

nah you all are chatting while im having errors on errors 😭

shrewd vapor
#

I'm so excited about i go see Taylor Swift in may 2024 for The Eras Tour

turbid condor
cinder tulip
turbid condor
shrewd vapor
#

I see

turbid condor
#

I only listen the ones that feel good to the ears no matter the singer

#

Heck I don't even know names of singers except only a few which i heard from the peeps around me

#

But still don't know which song they sang

shrewd vapor
#

I have link all image in the db and is linked with the name of the song

turbid condor
#

Well filtering out a specific singer is easy

cinder tulip
#
class MoveView(discord.ui.View):
    def __init__(self, challenged_user: discord.Member, challenger_user: discord.Member):
        super().__init__(timeout=None)
        self.challenged_user = challenged_user
        self.challenger_user = challenger_user

    @discord.ui.button(label="🪨", custom_id="rock", style=discord.ButtonStyle.gray)
    async def rock_button(self, button, interaction):
        await self.process_move("rock", interaction)

    @discord.ui.button(label="📃", custom_id="paper", style=discord.ButtonStyle.gray)
    async def paper_button(self, button, interaction):
        await self.process_move("paper", interaction)

    @discord.ui.button(label="✂️", custom_id="scissors", style=discord.ButtonStyle.gray)
    async def scissors_button(self, button, interaction):
        await self.process_move("scissors", interaction)

    async def process_move(self, move: str, interaction: discord.Interaction):
        # Check if the interacting user is one of the players
        if interaction.user == self.challenged_user or interaction.user == self.challenger_user:
            # You can add more sophisticated game logic here
            result = self.calculate_result(move)

            embed = discord.Embed(title=f"Game Result", color=discord.Color.blue())
            embed.add_field(name=f"{self.challenger_user.display_name}'s Move", value=move, inline=True)
            embed.add_field(name=f"{self.challenged_user.display_name}'s Move", value=result, inline=True)
            await interaction.response.send_message(embed=embed)

ok so i think the error should be in here, basically once i click the "accept" button it should send an ephimeral embed to both of the players of rock paper and scissors, the fact is that it sends it to only the player that had to click the "accept" button, which is indeed, the challenged player. so yeah, once with my alt i click one of the three buttons it just says:

  File "C:\Users\-\AppData\Roaming\Python\Python310\site-packages\discord\ui\view.py", line 427, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\-\Desktop\-\Scripts\Pepsi_Fish\main.py", line 1197, in rock_button
    await self.process_move("rock", interaction)
  File "c:\Users\-\Desktop\-\Scripts\Pepsi_Fish\main.py", line 1209, in process_move
    if interaction.user == self.challenged_user or interaction.user == self.challenger_user:
AttributeError: 'Button' object has no attribute 'user'```
So yeah what i need to do is realize how i could send the embed with the three rps buttons to both the challenged user and the one who challenged and make the button work
slate swan
#

intreraction comes before button argument

cinder tulip
#

i tried helping myself with chatgpt but mannn life is hard

shrewd vapor
#

You can try Bard

cinder tulip
shrewd vapor
#

Freedom Gpt

#

Llava 2

#

Llama

cinder tulip
#

bro is an AI expert

shrewd vapor
#

I love the ai

slate swan
shrewd vapor
#

I try to made my own ai

slate swan
#

@button

cinder tulip
#

even "nobody" told me that before but mannn

turbid condor
#

Yeah i told this to u before

cinder tulip
#

life sure is idk

turbid condor
#

Not coding with it

cinder tulip
#

oh well

#

now that i got the same thing but with 'str' object has no attribute 'user' XD

#

and i cant find it

turbid condor
#

str object has no attribute user?

cinder tulip
#

yeahh

turbid condor
#

Show the relevant code

cinder tulip
#
Traceback (most recent call last):
  File "C:\Users\-\AppData\Roaming\Python\Python310\site-packages\discord\ui\view.py", line 427, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\-\Desktop\-\Scripts\Pepsi_Fish\main.py", line 1197, in rock_button
    await self.process_move("rock", interaction)
  File "c:\Users\-\Desktop\-\Scripts\Pepsi_Fish\main.py", line 1209, in process_move
    if interaction.user == self.challenged_user or interaction.user == self.challenger_user:
AttributeError: 'str' object has no attribute 'user'
class MoveView(discord.ui.View):
    def __init__(self, challenged_user: discord.Member, challenger_user: discord.Member):
        super().__init__(timeout=None)
        self.challenged_user = challenged_user
        self.challenger_user = challenger_user

    @discord.ui.button(label="🪨", custom_id="rock", style=discord.ButtonStyle.gray)
    async def rock_button(self, interaction: discord.Interaction,button: discord.ui.Button):
        await self.process_move("rock", interaction)

    @discord.ui.button(label="📃", custom_id="paper", style=discord.ButtonStyle.gray)
    async def paper_button(self, interaction: discord.Interaction,button: discord.ui.Button):
        await self.process_move("paper", interaction)

    @discord.ui.button(label="✂️", custom_id="scissors", style=discord.ButtonStyle.gray)
    async def scissors_button(self, interaction: discord.Interaction,button: discord.ui.Button):
        await self.process_move("scissors", interaction)

    async def process_move(self,interaction: discord.Interaction, move: str):
        # Check if the interacting user is one of the players
        if interaction.user == self.challenged_user or interaction.user == self.challenger_user:
            # You can add more sophisticated game logic here
            result = self.calculate_result(move)

            embed = discord.Embed(title=f"Game Result", color=discord.Color.blue())
            embed.add_field(name=f"{self.challenger_user.display_name}'s Move", value=move, inline=True)
            embed.add_field(name=f"{self.challenged_user.display_name}'s Move", value=result, inline=True)
            await interaction.response.send_message(embed=embed)

i think it's always in this part

turbid condor
#

And whole traceback

shrewd vapor
#

How can i get the server link after that ?

await bot.create_guild(name = f"{interaction.guild.name}", region = None, icon = None, code = records[0])```
cinder tulip
turbid condor
shrewd vapor
#

Yes

cinder tulip
#

and i cant find it in readthedocs

shrewd vapor
#

For he send me after the new server is created

cinder tulip
#

oh damn

cinder tulip
#

or i need to move interaction above self

#

man i feel so stupid right now lol

slate swan
#

!E ```py
def f(arg_1: str, arg_2: int):
print(arg_1, arg_2)

f("some text", 123)
f(123, "some text")

unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | some text 123
002 | 123 some text
slate swan
#

i mean the interpreter doesnt really care

naive briar
#

That's why we have Mypy 👍

cinder tulip
#

i see

shrewd vapor
#

!d discord.abc.GuildChannel.create_invite

unkempt canyonBOT
#

await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates an instant invite from a text or voice channel.

You must have [`create_instant_invite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_instant_invite) to do this.
cinder tulip
turbid condor
shrewd vapor
#

Idk how to make this

#

I have never use that

turbid condor
#

Use that variable to get the channels of the server

#

!d discord.Guild.channels

unkempt canyonBOT
turbid condor
# unkempt canyon

After that you can index the first channel or use a for loop and create an invite using this function

#

Just break the loop on first turn if you use that

cinder tulip
#

guys i got good news

#

now, the ephimeral embed to choose the moves works, but the problem is that the one who got challenged recieves it only, and if they click on of the 3 moves they just wins

#

okay im starting to realize that maybe that is impossible for the bot

quick gust
#

no its not

#

show your command code

cinder tulip
#
        class RPSView(discord.ui.View):
            def __init__(self, challenged_user: discord.Member, challenger_user: discord.Member):
                super().__init__()
                self.challenged_user = challenged_user
                self.challenger_user = challenger_user

            @discord.ui.button(label="Accept", custom_id="accept", style=discord.ButtonStyle.green)
            async def accept_button(self, interaction: discord.Interaction, button: discord.ui.Button):
                if interaction.user == self.challenged_user:
                    move_view = MoveView(challenged_user=self.challenged_user, challenger_user=self.challenger_user)
                    await interaction.response.send_message("Make your move:", view=move_view, ephemeral=True)
                elif interaction.user == self.challenger_user:
                    move_view = MoveView(challenged_user=self.challenged_user, challenger_user=self.challenger_user)
                    await interaction.response.send_message(f"{interaction.user.mention}, make your move:", view=move_view, ephemeral=True)

            @discord.ui.button(label="Refuse", custom_id="refuse", style=discord.ButtonStyle.red)
            async def refuse_button(self, interaction: discord.Interaction, button: discord.ui.Button):
                if interaction.user == self.challenged_user:
                    embed = discord.Embed(title=f"{self.challenged_user.display_name} refused the game", color=discord.Color.red())
                    await interaction.response.send_message(embed=embed)
                else:
                    await interaction.response.send_message("You can't refuse a challenge you didn't initiate!", ephemeral=True)

        await interaction.response.send_message(f"{challenge.mention}\n{interaction.user.mention} has challenged you to a game of rock, paper, scissors!", view=RPSView(challenged_user=challenge, challenger_user=interaction.user))

# New MoveView class
class MoveView(discord.ui.View):
    def __init__(self, challenged_user: discord.Member, challenger_user: discord.Member):
        super().__init__(timeout=None)
        self.challenged_user = challenged_user
        self.challenger_user = challenger_user

    @discord.ui.button(label="🪨", custom_id="rock", style=discord.ButtonStyle.gray)
    async def rock_button(self, interaction: discord.Interaction,button: discord.ui.Button):
        await self.process_move(interaction, "rock")

    @discord.ui.button(label="📃", custom_id="paper", style=discord.ButtonStyle.gray)
    async def paper_button(self, interaction: discord.Interaction,button: discord.ui.Button):
        await self.process_move(interaction, "paper")

    @discord.ui.button(label="✂️", custom_id="scissors", style=discord.ButtonStyle.gray)
    async def scissors_button(self, interaction: discord.Interaction,button: discord.ui.Button):
        await self.process_move(interaction, "scissors")

    async def process_move(self, interaction: discord.Interaction, move: str):
    # Check if the interacting user is one of the players
        if interaction.user == self.challenged_user or interaction.user == self.challenger_user:
        # Send an ephemeral message with the chosen move to both players
            await interaction.response.send_message(f"You chose {move}!",ephemeral=True)
        result = self.calculate_result(move)

        embed = discord.Embed(title=f"Game Result", color=discord.Color.blue())
        embed.add_field(name=f"{self.challenger_user.display_name}'s Move", value=move, inline=True)
        embed.add_field(name=f"{self.challenged_user.display_name}'s Move", value=result, inline=True)
        await interaction.response.send_message(embed=embed)
#

bruh why is the thing off

quick gust
#

shouldnt u show both their moves?

quick gust
#

also that wont fix anything

cinder tulip
#

yeah i know but

quick gust
#

you need to send the ephemeral message to the challenger too

#

or whoever does not receive it

#

challenger ig yeah

cinder tulip
#

yeah but in that case how do i do that

#

is it because i put an elif

#

I can remove that, tho, would still not know how to send it to both people

#

like "send_message" to both the challenger and the one who got challenged

quick gust
#

you know you dont have to make it ephemeral

pulsar lance
#

Can someone help me how to make music bot

cinder tulip
quick gust
#

yeah if u dont make it ephemeral, itll be fine

#

everyone will be able to see it, but only the challenger and challenged will be able to interact iwth the buttons

cinder tulip
#

exactly exactly

quick gust
#

assuming you code it in of course

cinder tulip
#

im working on it

#

now i just need to make the bot wait for both's moves and send the embed result

quick gust
#

yeah

shrewd vapor
#
2023-10-18 19:24:45 ERROR    discord.app_commands.tree Ignoring exception in command 'deploy-backup'
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 842, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/bot.py", line 221, in deploybackup
    new_guild = await bot.create_guild(name = f"{interaction.guild.name}", region = "Europe", icon = None, code = records[0])
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Client.create_guild() got an unexpected keyword argument 'region'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 856, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'deploy-backup' raised an exception: TypeError: Client.create_guild() got an unexpected keyword argument 'region'```
#
@bot.tree.command(name = "deploy-backup", description = "Deploy a backup")
async def deploybackup(interaction : discord.Interaction, server : str):
    connection = mysql.connector.connect(host = '', database = '', user = '', password = '')
    cursor = connection.cursor()
    query = "SELECT code FROM backup WHERE server = %s"
    val = (server,)
    cursor.execute(query, val)
    records = cursor.fetchall()
    if records is None:
        await interaction.response.send_message(f"Backup not found")
        cursor.close()
        connection.close()
        return
    else:
        new_guild = await bot.create_guild(name = f"{interaction.guild.name}", region = "Europe", icon = None, code = records[0])
        link = await new_guild.text_channels[0].create_invite()
        await interaction.response.send_message(f"Backup deployed\n{link}")
        cursor.close()
        connection.close()```
slate swan
#

!d discord.ext.commands.Bot.create_guild

unkempt canyonBOT
#

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

Creates a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild).

Bot accounts in more than 10 guilds are not allowed to create guilds.

Changed in version 2.0: `name` and `icon` parameters are now keyword-only. The `region` parameter has been removed.

Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
slate swan
#

i dont see region in here too

shrewd vapor
#

Ok i try without

slate swan
#

Changed in version 2.0: name and icon parameters are now keyword-only. The region parameter has been removed.

shrewd vapor
#
2023-10-18 19:28:04 ERROR    discord.app_commands.tree Ignoring exception in command 'deploy-backup'
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 842, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/bot.py", line 221, in deploybackup
    new_guild = await bot.create_guild(name = f"{interaction.guild.name}", icon = None, code = records[0])
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 2295, in create_guild
    icon_base64 = utils._bytes_to_base64_data(icon)
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/discord/utils.py", line 626, in _bytes_to_base64_data
    mime = _get_mime_type_for_image(data)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/discord/utils.py", line 612, in _get_mime_type_for_image
    if data.startswith(b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A'):
       ^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'startswith'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 860, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'deploy-backup' raised an exception: AttributeError: 'NoneType' object has no attribute 'startswith'```
cinder tulip
#

nah y'all i dont think i can finish my command

#

it's been more than 3 hours and my braincells are cooked

#

im almost at the end but man this sucks

spark nimbus
#

|| File "d:\program\python\discord\bot\main.py", line 155, in <module>
@client.event()
^^^^^^^^^^^^^^
TypeError: Client.event() missing 1 required positional argument: 'coro' ||

and I set client as the bot commands:
|| client = commands.Bot(command_prefix='.', intents=intents)||

brazen raft
#

Terrible name choices aside, it's just @client.event without the () at the end

lunar vine
#

no, amt is the response message,

#

when it asks for the amt, it waits for a response with a number, that number is defined as {amt} and since ive moved that code to the button callback, its no longer supporting the other code

cinder tulip
#
Traceback (most recent call last):
  File "C:\Users\-\AppData\Roaming\Python\Python310\site-packages\discord\ui\view.py", line 427, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\-\Desktop\-\Scripts\Pepsi_Fish\main.py", line 1198, in rock_button
    await self.process_move(interaction, "rock")
  File "c:\Users\-\Desktop\-\Scripts\Pepsi_Fish\main.py", line 1217, in process_move
    await interaction.response.send_message(embed=embed)
  File "C:\Users\-\AppData\Roaming\Python\Python310\site-packages\discord\interactions.py", line 774, in send_message
    raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before

how would i be able to fix this

slate swan
#

Don't respond twice to the same interaction

cinder tulip
lunar vine
#

make like a handler

slate swan
#

You can send a new message in the channel or edit the original message

cinder tulip
#

wouldnt that make it harder tho

lunar vine
#
await interaction.response.send_message("You've already pressed!", ephemeral=True)```
#

idk for ur code, but for mine im using it for else:

cinder tulip
slate swan
#

More complicated or not doesn't matter, you just can't respond twice

lunar vine
obsidian fable
#
        track_json = track_json["data"][0]["attributes"]
        artist_json = artist_json["data"][0]["attributes"]

        audio_traits = track_json["audioTraits"]
        print(audio_traits)
        traits_mapping = {"atmos": ":AMDolby:", "lossless": ":AMLossless:", "spatial": ":AMAirPodsPro:"}
        traits = ' '.join(traits_mapping.get(trait) for trait in audio_traits if trait in traits_mapping)

why am I getting a KeyError on audioTraits even though its present in the json?

white citrus
#
class TicketMain_One(nc.ui.View):
    def __init__(self, header, textbox, button_one):
        super().__init__()

        self.header = header
        self.textbox = textbox
        self.button_one = button_one
        print("--------")
        print(button_one)
        print(self.button_one)
        print("---------")
        self.b_one = nc.ui.button(style=nc.ButtonStyle.blurple, label=button_one)

    #@nc.ui.button(style=nc.ButtonStyle.blurple, label=button_one)
    async def b_one(self, button: nc.ui.Button, inter: nc.Interaction):
        inter.response.send_message("HI")```

Why i dont get a button
lunar vine
#

@turbid condor

lunar vine
#

i fixed it by making amt a global thing

lunar vine
#

unless ur debugging

lunar vine
white citrus
#

I would like to use button_one as label

lunar vine
#

then define it was button_one and not b_one

white citrus
#

button_one is given by a other class

white citrus
#

@lunar vine you see?

lunar vine
#

oh

#

yeah i completly ignored the comment, its just natural for me to skip over them ig

lunar vine
white citrus
patent lark
#

is there a way to have the bot logout and log itself back in? when i think about, it seems not possible. But you guys are smarter

patent lark
#

Essentially re running the bot via command

white citrus
#

@lunar vine ?

patent lark
#

I assume there’s no way to log the bot back in once it has been logged out. (at least not manually)

lunar vine
#

xD, u mean like rehosting it?

patent lark
#

yes

lunar vine
#

u could prolly make a macro of some sort to type the cmd every 5 mins

#

or just buy hosting

patent lark
#

I see

#

But i think you’ve got my intentions a little wrong

#

It’s not that the bot has an issue being online, but say i have a reason to re run the bot, and i would like to do this via command

#

I remember touching around on this topic a while back, i don’t think i really found a solution

slate swan
#

and consider using dict.get method

white citrus
shrewd apex
#

altho if u want to use a modal result as a button label you would be better if creating the button and adding it to the view dynamically

white citrus
# shrewd apex show button_one code
class SetupTicket(nc.ui.Modal):
    def __init__(self):
        super().__init__(f"Create new Ticketsystem")
        self.header = nc.ui.TextInput(label="Header", style=nc.TextInputStyle.short, max_length=50, required=True, placeholder="Exp: Support Ticket")
        self.textbox = nc.ui.TextInput(label="Textbox", style=nc.TextInputStyle.paragraph, max_length=2500, required=True)
        self.button_one_label = nc.ui.TextInput(label="Button 1 (Blue)", style=nc.TextInputStyle.short, max_length=50, required=True)
        self.button_two_label = nc.ui.TextInput(label="Button 2 (Red)", style=nc.TextInputStyle.short, max_length=50, required=False, placeholder="Report Member")
        self.button_three_label = nc.ui.TextInput(label="Button 3 (Grey)", style=nc.TextInputStyle.short, max_length=50, required=False, placeholder="Other")

        self.add_item(self.header)
        self.add_item(self.textbox)
        self.add_item(self.button_one_label)
        self.add_item(self.button_two_label)
        self.add_item(self.button_three_label)

    async def callback(self, inter: Interaction):
        if self.button_one_label.value:
            if not self.button_two_label.value and not self.button_three_label.value:
                view = TicketMain_One(self.header, self.textbox, self.button_one_label)
            elif self.button_two_label.value:
                if not self.button_three_label.value:
                    view = TicketMain_Two(self.header, self.textbox, self.button_one_label, self.button_two_label)
                else:
                    view = TicketMain_Three(self.header, self.textbox, self.button_one_label, self.button_two_label, self.button_three_label)
            elif self.button_three_label.value:
                view = TicketMain_Two(self.header, self.textbox, self.button_one_label, self.button_three_label)

        print(view)
        await inter.response.send_message(content="Hi", view=view)```
shrewd apex
#

!code

unkempt canyonBOT
#
Formatting code on discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

white citrus
verbal drift
#

kinda off topic: where can i get a free proxy for my web scraper made in python?

shrewd apex
white citrus
shrewd apex
#

yeah ik it should be label for the button for that u need to dynamically create the button

you first need to create the modal get the label string

create the view object and then create a button using the label string

assign a callback to the button and then add it to the view

async def foo(inter): ...
view = View()
button = ui.Button(label=....)
button.callback = foo
view.add_item(button)
shrewd apex
#

create a function seperately for it

#

just assign it later in python functions are first class citizens

#

u can have a function in the view subclass itself like a callback but dont decorate it with the button decorator

#

instead assign it when ur making the button

white citrus
glad cradle
verbal drift
#

which scrapes the one and only website..

slate swan
brazen raft
#

Is helping you a violation of rule 5

final iron
#

Not inherently

#

It depends how the content is created

patent lark
#
await message.author.timeout(until=datetime.timedelta(days=1), reason="Hard R")```
```TypeError: Member.timeout() got some positional-only arguments passed as keyword arguments: 'until'```
Im using it as the doc explains, why am i getting this error
wicked atlas
#

positional only means you cannot specify it as a keyword argument, meaning you cannot supply it with 'until='

#

!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).
wicked atlas
#

Looks like you can just remove the 'until=' and you'll be all set

patent lark
#

AH, how stupid can i be

#

Thank you

wicked atlas
#

👍

stone forge
#

if role:
# remove all author roles first
await message.author.add_roles(role)

#

how would one achieve this?

turbid condor
stone forge
turbid condor
#

If yes then you can use a for loop to check for all_roles and if any role matches a one in the list then remove it

#

Using remove_role

final iron
unkempt canyonBOT
#

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

Removes [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)s from this member.

You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles) to use this, and the removed [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)s must appear lower in the list of roles than the highest role of the member.
turbid condor
#

!d discord.Member.roles

unkempt canyonBOT
#

property roles```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role) that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.

These roles are sorted by their position in the role hierarchy.
turbid condor
void whale
#

can anyone help me start making discord bots kind confused how to even start?

turbid condor
# void whale can anyone help me start making discord bots kind confused how to even start?
- Primitive data types
- Operators
- Data structures
- Importing
- Variables, namespace and scope
- String formatting
- OOP
- Control flow
- Exception handling
- Function definitions
- Classes, objects, attributes and methods
- Console usage, interpreters and environments
- Decorators

Useful to know:
- Asyncio basics
- What is blocking?
- Logging
- knowing how to read docs properly
``` for more details see <https://gist.github.com/scragly/095b5278a354d46e86f02d643fc3d64b#required-knowledge>
#

You need to know about these first

final iron
#

Could probably learn it relatively quickly

void whale
#

hey anyone know why i cant install it

turbid condor
void whale
#

yes

turbid condor
#

This too but the python from official website

void whale
turbid condor
#

You need this too

void whale
turbid condor
#

Download from here

#

And install python 3.11

#

Not 3.12 or later

slate swan
# void whale

For your knowledge, that's just intellisense and not python itself - same for all other extensions in VSC

turbid condor
void whale
slate swan
#

Still worth knowing

turbid condor
#

?

void whale
#

nothing 3.11

#

that i can see

turbid condor
#

Scroll down and there download according to your os

hallow kernel
#

Can embed have a background?

turbid condor
#

No

#

They depend on the users theme

hallow kernel
#

Ok, another question same goal.
How to add image to embed like python logo in that embed #discord-bots message

lost cradle
#

Hey, I was trying to run pip install discord in the terminal and im getting this, im super new to python and I was following a tutorial so I don't know what to do.

hallow kernel
#

why someone needs msvcpp tools to use discord py??

Ah maybe because it conpiles when installing...

Are not there precompiled versions?

lost cradle
hallow kernel
turbid condor
lost cradle
turbid condor
unkempt canyonBOT
#
I'm sorry Dave, I'm afraid I can't do that.

No documentation found for the requested symbol.

turbid condor
#

!d discord.Embed.set_thumbnail

unkempt canyonBOT
#

set_thumbnail(*, url)```
Sets the thumbnail for the embed content.

This function returns the class instance to allow for fluent-style chaining.

Changed in version 1.4: Passing `None` removes the thumbnail.
turbid condor
#

Use 3.11 or earlier

hallow kernel
#

Or should i check docs and not ask

turbid condor
hallow kernel
#

Url means image, ok

turbid condor
#

Or a local image file

turbid condor
turbid condor
lost cradle
naive briar
turbid condor
#

Welp yeah but we can't skip it

lost cradle
#

has it just not updated yet?

turbid condor
lost cradle
#

oh ok

lost cradle
turbid condor
#

Yeah

lost cradle
#

alright

turbid condor
#

Just not 3.12 or above

lost cradle
#

thank you

lost cradle
#

when I try to change to 3.11 virtualenv it gives me this

turbid condor
#

I think you will need to create a new venv

#

I never used pycharm so i don't know much

#

You can try searching the web

lost cradle
#

ok

turbid condor
#

Try selecting existing

#

Or change location of your venv

vale wing
#

The venv one

#

And create again

lost cradle
vale wing
#

Sorry but what's unclear

lost cradle
vale wing
#

Delete directory in displayed location

#

You delete parent dir of this

#

Whole venv

#

Not objects inside

lost cradle
#

yeah so this right

vale wing
#

Yes

lost cradle
#

thank you

lost cradle
# vale wing Yes

okay so I managed to get the bot online, but when I try to run some commands I get this

'Message' object is not callable

#

I get this for every message

vale wing
#

Send full traceback

lost cradle
#

can I just send the code, its pretty simplistic

vale wing
#

Well you don't get only that line in error do you

#

Unless you made a bad error handler

lost cradle
vale wing
#

Ok send code

#

Bad error handler for sure

lost cradle
#

responses.py

import random
def handle_response(message: str) -> str:
    p_message = message()

    if p_message == 'i love terraria' :
        return 'Based'

    if p_message == 'i hate terraria' :
        return 'Cringe'

    if p_message == '!roll' :
        return str(random.randint(1, 6))

    if p_message == '!help' :
        return ("# List of my commands "
                "!help - Get the list of commands"
                "!roll - Roll a number between 1 and 6")

vale wing
#

Yeah and wtf is message()

#

And why is it typehinted as str

#

You get content via message.content

#

Also this is a bad way of writing commands

#

Lemme fetch you a tutorial

lost cradle
#

That would be helpful

lost cradle
vale wing
#

String is not callable either

lost cradle
#

uh

#

okay, what changes would you make just to get the bot to function

lost cradle
vale wing
#

Great opportunity to learn

lost cradle
#

I just know the very basics

vale wing
#

Well that tutorial is pretty simple

#

Just need some OOP and functional

lost cradle
#

The b in basics then

turbid condor
lost cradle
#

what else do I use?

naive briar
#

discord.py already support buttons, drop-downs, ...

mystic marsh
#

Im pretty sure its possible but not sure how its done. How can I have specific values in a dropdown pre-selected.

mystic marsh
golden portal
mystic marsh
#

also hru milady

golden portal
#

I'm doin fine

mystic marsh
#

dw im just sleepey lol

mystic marsh
golden portal
#

what's your curernt code

mystic marsh
# golden portal so which one do you want it to default value then?
class ConfigDropdown(discord.ui.Select):
    def __init__(self, guildconfig):
        self.guildconfig = guildconfig
        starter_pokemon = [
            'Pin Shinies', 'Level Up Messages'
        ]   
        options = [
            discord.SelectOption(label=starters, description=starters, default=True)
            for starters in starter_pokemon
        ]
        
        super().__init__(
            placeholder='Toggle the server settings!', min_values=1, max_values=len(options), options=options,
        )

So if pin-shinies is equal to 1, it'll be set to true.

#

otherwise it'll be 0

#

self.guildconfig is a list of the data. i could maybe create an idx and use its value in the loop.

golden portal
#

couldn't you just do ```py
options = [
discord.SelectOption(label=starters, description=starters, default=starters == 'Pin Shinies')
for starters in starter_pokemon
]

mystic marsh
#

No like, thats only 2 in my list, lets say I have 10 configs, and 5 of them are true (equal to 1) and the rest arent.

#

those 5 would be set as default.

golden portal
#

what makes them set to True?

mystic marsh
#

like thats the database for now. im not sure if I should use booleans or not but

mystic marsh
#

why do i sense chat gpt

golden portal
mystic marsh
#

Like, these are the current rows for now

golden portal
#

how are you fetching this value

mystic marsh
#

so either one.

golden portal
mystic marsh
#

Wdym like I did for starter_pokemon

#

also yea i should change that to guild_config or something.

mystic marsh
mystic marsh
#
def __init__(self, guildconfig):
        self.guildconfig = guildconfig
        starter_pokemon = [
            'Pin Shinies', 'Level Up Messages'
        ]  
        guildata = self.guildconfig
        guildata = guildata[2:]
        options = [
            discord.SelectOption(
                label=starters,
                description=f"{starters}",
                default=(guildata[idx] == 1)
            )
            for idx, starters in enumerate(starter_pokemon)
        ]
#

so if its == 1 it'll set as default

golden portal
#

could've just call bool

#

but that works

slate swan
#

Hello guys, please help me run this discord bot code i have
Basically what it does it it checks all members in a server and if they have a certain role it will kick them u can call it a role kicker but its just lots of files that idk what to do with it is a zip file please help me run it

mystic marsh
#

yea ig

mystic marsh
# golden portal but that works

one last thing, sorry I dont know much about views really. lets say the user selects, 3 things, how can 1 get those three values? Does self.values[0] return first one only? Also how would I differentiate it if it was deselected or selected?

golden portal
#

do you know what [0] does

mystic marsh
#

does it not return an selected value? so the first.

golden portal
#

[0] takes the first element of a list, self.values is a list of selected options

#

also, self.values will only contain selected values

mystic marsh
golden portal
#

!e ```py
a = ['first', 'second', 'third']
print('first element', a[0])
print('amount', len(a))
print('what is this', a)
print('first two elements', a[:2])

unkempt canyonBOT
#

@golden portal :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | first element first
002 | amount 3
003 | what is this ['first', 'second', 'third']
004 | first two elements ['first', 'second']
mystic marsh
#

you cant really loop it.

#

oh hmm

golden portal
#

me when discovering data structures

mystic marsh
#

so 0, 1 or 2

golden portal
#

[:2] doesnt raise any index error, it's just slicing

#

also it returns up to 2 elements, 0, 1

harsh orbit
#

How to check if an argument is a user mention

mystic marsh
mystic marsh
#

is it possible finding that out.

final iron
#

values returns the selected options

mystic marsh
# final iron values returns the selected options

I mean in the context of what its actually doing. because lets say in my example above pin shinies is already selected my default, since its value is 1 in the database, but lets say I deselect it from the dropdown, and select level up messages. How would I know if the selected value has been selected or deselected? So I can update the database accordingly.

final iron
slate swan
final iron
mystic marsh
slate swan
#

ooo

mystic marsh
mystic marsh
#

boring as.

slate swan
#

idk its fun to play with tensorflow

mystic marsh
#

lol

mystic marsh
slate swan
#

yeah

#

recognizes poketwo spawns

oak abyss
#

!e

print("This is a test")```
unkempt canyonBOT
#

@oak abyss :white_check_mark: Your 3.12 eval job has completed with return code 0.

This is a test
oak abyss
#

!e

import discord```
unkempt canyonBOT
#

@oak abyss :x: Your 3.12 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     import discord
004 | ModuleNotFoundError: No module named 'discord'
shrewd fjord
slate swan
unkempt canyonBOT
#
Microsoft Visual C++ Build Tools

When you install a library through pip on Windows, sometimes you may encounter this error:

error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/

This means the library you're installing has code written in other languages and needs additional tools to install. To install these tools, follow the following steps: (Requires 6GB+ disk space)

1. Open https://visualstudio.microsoft.com/visual-cpp-build-tools/.
2. Click Download Build Tools >. A file named vs_BuildTools or vs_BuildTools.exe should start downloading. If no downloads start after a few seconds, click click here to retry.
3. Run the downloaded file. Click Continue to proceed.
4. Choose C++ build tools and press Install. You may need a reboot after the installation.
5. Try installing the library via pip again.

slate swan
#

can someone help with this command? I ran "pip install discord" and i installed the c++ build toolos

hallow kernel
#

Can i somehow take part of chat and move it to thread? I have owner permissions, and using bots, and I don't actually need messages, simulating users by "integration" is ok.

Is there tool or should i make it up?....

slate swan
fiery girder
slate swan
slate swan
fiery girder
#

damn i didnt download that i dont thing its neccesary but ok

slate swan
slate swan
fiery girder
#

just install the c++ manually

#

instead of download one of the most memory hogging software to get it

slate swan
#

I dont get why pip install discord.py needs c++ libaries

fiery girder
#

same

#

just get python latest version

#

then open powershell and do pip install

#

dont use freaking command prompt

#

use powershell

#

lol @void whale

void whale
#

im new to this how do i do that?

fiery girder
#

just search powershell

#

on windows

brazen raft
#

Do py -m pip install discord.py

#

Instead of pip install discord.py

slate swan
#

!dashm

unkempt canyonBOT
#
Install packages with `python -m pip`

When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.

Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.

Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.

fiery girder
#

use powershe;;

#

powershell

void whale
fiery girder
#

just search it in the windows

#

windows powershell its a default app

hushed galleon
#

how did you install python?

fiery girder
#

use only pip install

void whale
fiery girder
slate swan
fiery girder
#

vscode is an extension you need to install the interpreter

slate swan
#

you need to install actual interpreter and not just vscode extension

void whale
#

do i download 3.12

fiery girder
#

yes

#

latest

hushed galleon
#

dont download 3.12 right now, it's a headache for compiled third party packages

fiery girder
#

or you can do 3.11 its prob more stable

slate swan
#

use 3.11

void whale
#

i only see 3.12 not 3.11

slate swan
#

most libraries are not converted to 3.12 yet

fiery girder
#

go to downloads

slate swan
hushed galleon
slate swan
#

scroll to bottom then you can see installers

#

choose one for your system

void whale
slate swan
#

run it

fiery girder
#

just install it normal

void whale
fiery girder
#

now run the command in powershell

void whale
#

what one? py -m pip install discord .py pip install discord.py

fiery girder
#

any

hushed galleon
#

if you kept all the default settings, py -m pip ..., but you'll need to restart your terminal before you can use it (pip install ... requires checking "Add Python to PATH"/"Add Python to environment variables" in the installer, but it's not particularly important for working with discord.py)

fiery girder
#

for me pip install discord.py works maybe it dont for you

void whale
fiery girder
#

yes

void whale
# fiery girder yes

so can i start doing the code or is there anything else i need to download before starting

fiery girder
#

if you want any external libraries you can install them later but for discord you are good to go

slate swan
#

i have a feeling there is an missing command

#

idk why

fiery girder
# slate swan

instead of using command prefix / use app commands or hybrid commands with ! prefix

#

its all up to you but its a good suggestion

naive briar
#

No point

slate swan
#

it like pops up

fiery girder
#

it dont

#

you need app commands for that

slate swan
fiery girder
#

not the command prefix to be /

slate swan
naive briar
fiery girder
naive briar
#

The only flaw in the code you sent is that you aren't running the bot

fiery girder
#
@bot.hybrid_command(name="clear", description="Clears Specified Amount oF Messages")
@commands.has_role(admin_id)
async def clear(ctx, amount):
    await ctx.channel.purge(limit=int(amount))
    await ctx.reply(
        embed=Embed(title="Cleared", description=f"{amount} Messages Cleared")
    )

like this simple command if i press / now it will pop up the thing because it has hybrid command and app_commands connected

#

but what you are doing with just not work with the popups you want

#

@slate swan you need to use the app command if you want the popup thing that works not the normal commands with / as prefix

#

you will need to sync in the tree

slate swan
fiery girder
#

no

#

i keep forgetting the command lol

#

it just with the / thing instead of using the prefix use the app command

#

or hybrid if you want ! and / together

#

i like using hybrid cause it can have both app and normal commands @slate swan

slate swan
fiery girder
#

yes

slate swan
#

then from config import TOKEN

fiery girder
#

you need to set the bot to app commands

fiery girder
fiery girder
#

i can give you the class for hooking it up if you want you just need to do the same thing as normal just need to write bot.hybridcommand instead of bot.app_command

oak abyss
#

@fiery girder remember my league bot suggestions? started one, its already in 1200 servers

slate swan
#

`import discord
from discord import app_commands
from discord.ext import commands
from config import TOKEN

bot - commands,Bot(command_prefix="!" , intents - discord.Intents.all()))`

slate swan
#

then I need to sync right?

fiery girder
oak abyss
#

yes

slate swan
oak abyss
spark nimbus
#

how do i get thee message time

slate swan
#

`import discord
from discord import app_commands
from discord.ext import commands
from config import TOKEN

bot - commands.Bot(command_prefix="!" , intents - discord.Intents.all())`

#

this ig?

oak abyss
slate swan
#

`import discord
from discord import app_commands
from discord.ext import commands
from config import TOKEN

bot = commands.Bot(command_prefix="!" , intents - discord.Intents.all())`

#

now I need to sync it to the tree

fiery girder
oak abyss
#

i hate slash commands

fiery girder
#

you can use the app_command for slash command bot.command for ! command and hybrid command for both

oak abyss
#

prefixes were so good, slashes eat my brain

fiery girder
oak abyss
fiery girder
#

u sure?

oak abyss
#

yh

slate swan
#

`import discord
from discord import app_commands
from discord.ext import commands
from config import TOKEN

bot = commands.Bot(command_prefix="!" , intents - discord.Intents.all())

@bot.event
async def on_ready():
print("Logged into Host")`

slate swan
#

i still didnt finish it yet

oak abyss
#

print(f"Logged into {bot.user}")

fiery girder
#

yup

slate swan
#

`import discord
from discord import app_commands
from discord.ext import commands
from config import TOKEN

bot = commands.Bot(command_prefix="!" , intents - discord.Intents.all())

@bot.event
async def on_ready():
print(f"Logged into {bot.user}")`

oak abyss
#

@fiery girder hows ur bot

fiery girder
#

good

#

am working on a profile system to make custom profiles

oak abyss
# slate swan `import discord from discord import app_commands from discord.ext import command...
import discord
from discord import app_commands
from discord.ext import commands
from config import TOKEN

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

@bot.event
async def on_ready():
    print(f"Logged into {bot.user.name} (ID: {bot.user.id})")

@bot.command()
async def hello(ctx):
    await ctx.send("Hello, I'm your friendly bot!")

bot.run(TOKEN)```
#

feel free to use this

fiery girder
oak abyss
#

he literally has a prefix setup if you can read his code

fiery girder
#

it should be bot.app_command or bot.hybrid command

fiery girder
oak abyss
#
import discord
from discord.ext import commands
from config import TOKEN

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

@bot.event
async def on_ready():
    print(f"Logged into {bot.user.name} (ID: {bot.user.id})")

@bot.command()
async def hello(ctx):
    await ctx.send("Hello, I'm your friendly bot!")

@bot.slash_command()
async def greet(ctx):
    await ctx.send("Hello, I'm your friendly bot!")

bot.run(TOKEN)
#

there u go then @slate swan

fiery girder
#

name="hello",description="says hello"

#

ion the bot.slashcommand

slate swan
#

`import discord
from discord import app_commands
from discord.ext import commands
from config import TOKEN

bot = commands.Bot(command_prefix="!" , intents - discord.Intents.all())

@bot.event
async def on_ready():
print(f"Logged into {bot.user}")
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)")`

oak abyss
# slate swan `import discord from discord import app_commands from discord.ext import command...
import discord
from discord.ext import commands
from config import TOKEN

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

@bot.event
async def on_ready():
    print(f"Logged into {bot.user.name} (ID: {bot.user.id})")

@bot.slash_command(
    name="hello",
    description="Says hello."
)
async def hello(ctx):
    await ctx.respond("Hello, I'm your friendly bot!")

bot.run(TOKEN)
fiery girder
#

ctx.reply not respond

oak abyss
#

it can

fiery girder
#

can it?

oak abyss
#

im sure it can

slate swan
#

import discord
from discord.ext import commands
from config import TOKEN

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

@bot.event
async def on_ready():
    print(f"Logged into {bot.user.name} (ID: {bot.user.id})")

@bot.slash_command(
    name="hello",
    description="Says hello."
)
async def hello(ctx):
    await ctx.reply("Hello, I'm your friendly bot!")

bot.run(TOKEN)```
#

ima change it and make it .set embed

oak abyss
#

@slate swan heres a free code, feel free to use this instead.

import discord
from discord.ext import commands
from config import TOKEN

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

@bot.event
async def on_ready():
    print(f"Logged into {bot.user.name} (ID: {bot.user.id})")

@bot.slash_command(
    name="ping",
    description="Check the bot's ping."
)
async def ping(ctx):
    latency = round(bot.latency * 1000)  
    embed = discord.Embed(
        title="Pong!",
        description=f"Latency: {latency}ms",
        color=discord.Color.blue()
    )

    await ctx.reply(embed=embed)

bot.run(TOKEN)
oak abyss
#

for?

fiery girder
#

getting it right the first ite

oak abyss
#

@slate swan do u need a bot stats command? ill code it for u

still spade
still spade
#

like the button

still spade
oak abyss
still spade
#

umm so i m facing problem is that when the user is going from 3rd page to the 2nd page so like how can we do it ?
do i need to create for every page an embed and use an loop so like when the user is 3rd its current page would be 3 and if he going to 2nd current page become 2 and the data of 2nd get fetch @oak abyss

oak abyss
# slate swan Yes please,
import discord
from discord.ext import commands
from config import TOKEN
from datetime import datetime

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

@bot.event
async def on_ready():
    print(f"Logged into {bot.user.name} (ID: {bot.user.id})")

@bot.slash_command(
    name="botstats",
    description="View bot statistics.",
    guild_ids=None
)
async def botstats(ctx):
    latency = round(bot.latency * 1000)

    server_count = len(bot.guilds)
    member_count = sum(guild.member_count for guild in bot.guilds)

    uptime = datetime.now() - bot.user.created_at

    owner_username = bot.get_user(bot.owner_id).name

    embed = discord.Embed(
        title="Bot Statistics",
        color=discord.Color.blue()
    )
    
    embed.add_field(name="Bot Ping", value=f":ping_pong: {latency}ms")
    embed.add_field(name="Bot Servers", value=f":blue_circle: {server_count}")
    embed.add_field(name="Bot Members", value=f":busts_in_silhouette: {member_count}")
    embed.add_field(name="Bot Uptime", value=f":clock1: {uptime}")
    embed.add_field(name="Bot Owner", value=f":crown: {owner_username}")

    await ctx.reply(embed=embed)

bot.run(TOKEN)
still spade
oak abyss
still spade
slate swan
oak abyss
#

completely up to you!

slate swan
#

Or does it read it off somewhere else ?

oak abyss
#

bot.run("tokenhere")

example:
bot.run("11414u1nddmbdwliryairuhba5m2h5j2rqdwafkw5jw4b")

fringe ember
#

The problem is just i dont found app_command

slate swan
slate swan
#

Same source as the one you provided me.

#

I think it’s not reading the “token”

oak abyss
#
import discord
from discord.ext import commands
from datetime import datetime

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

@bot.event
async def on_ready():
    print(f"Logged into {bot.user.name} (ID: {bot.user.id})")

@bot.slash_command(
    name="botstats",
    description="View bot statistics.",
    guild_ids=None
)
async def botstats(ctx):
    latency = round(bot.latency * 1000)

    server_count = len(bot.guilds)
    member_count = sum(guild.member_count for guild in bot.guilds)

    uptime = datetime.now() - bot.user.created_at

    owner_username = bot.get_user(bot.owner_id).name

    embed = discord.Embed(
        title="Bot Statistics",
        color=discord.Color.blue()
    )
    
    embed.add_field(name="Bot Ping", value=f":ping_pong: {latency}ms")
    embed.add_field(name="Bot Servers", value=f":blue_circle: {server_count}")
    embed.add_field(name="Bot Members", value=f":busts_in_silhouette: {member_count}")
    embed.add_field(name="Bot Uptime", value=f":clock1: {uptime}")
    embed.add_field(name="Bot Owner", value=f":crown: {owner_username}")

    await ctx.reply(embed=embed)

bot.run("put ur token here")  ```
oak abyss
#

not secrets bar

slate swan
#

Why did you post the bot token….

oak abyss
#

also add " " around the bot token

void whale
oak abyss
#

ur bot is missing intents

slate swan
#

How do I make it import the token from secret?

oak abyss
#

add this
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="!", intents=intents)

oak abyss
#

replace it with line 3 and 4

#

if it still doesnt work, go into developer portal, click on 'bot' scroll down and enable the message intents and stuff

still spade
#

hey viva can u also help me in the button

oak abyss
#

then go into developer portal, click on 'bot' scroll down and enable the message intents and stuff

oak abyss
slate swan
oak abyss
oak abyss
# still spade hey viva can u also help me in the button
import discord
from discord.ext import commands
from discord_slash import SlashCommand
from discord_slash.utils.manage_commands import create_option, create_choice

bot = commands.Bot(command_prefix='!')
slash = SlashCommand(bot, sync_commands=True)

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name}')

@slash.slash(
    name="hello",
    description="Say hello with a button",
)
async def hello(ctx):
    # Create a message with a button
    await ctx.send(
        content="Click the button to say hello!",
        components=[
            discord.ui.Button(style=discord.ButtonStyle.primary, label="Hello", custom_id="hello_button")
        ]
    )

@bot.event
async def on_button(ctx):
    # Check if the button was clicked by the bot's user
    if ctx.author.id == bot.user.id:
        return

    if ctx.custom_id == "hello_button":
        await ctx.send("Hello, world!", ephemeral=True)  # Sends a hidden response only visible to the user who clicked the button

bot.run('YOUR_BOT_TOKEN')
#

did it work @void whale

quick gust
#

@vale wing someone is taking ur position

oak abyss
#

wbu @slate swan

slate swan
slate swan
#

Got this error 🙃

oak abyss
#

just change it to app_commands or wtv

#

yeah wherever that is, u can still find it

#

its like under the token area

slate swan
quick gust
oak abyss
slate swan
#

you mind sharing it?

oak abyss
#

plus the wifi in my house is horrible rn, shutting down every second

oak abyss
oak abyss
slate swan
#

this 20 lines that you just shared?

oak abyss
oak abyss
#

r u ok?

quick gust
#

u had a hello command in ur league bot?

oak abyss
#

i deleted the unnecessary stuff

oak abyss
#

it was the first command since i was nwe to python bots

slate swan
oak abyss
#

ive made discord bots that are in 1200+ servers within a week

quick gust
#

weird flex butok

slate swan
oak abyss
#

ur framing me of using gpt

#

for no reason at all

slate swan
#

i literally have a reason

#

you are giving someone code that is literally depreciated and has comments that state obvious

#

typically like AI tools do

oak abyss
#

i was helping mocha so i just gave ali an old code

slate swan
#

then if its from 2021 why are you giving it to someone when its depreciated

oak abyss
#

hes planning on dming me later

#

if u can read the fucking full chat without beefing on random reasons

slate swan
#

you are making a fool out of you

oak abyss
slate swan
#

xd

#

i see no reason why someone would want a code that literally doesnt work

slate swan
unkempt canyonBOT
#

10. Do not copy and paste answers from ChatGPT or similar AI tools.

oak abyss
#

@slate swan @void whale where did yall reach

slate swan
#

cause its not really help

oak abyss
#

oh my days if only my wifi wasnt shit rn

#

its taking years to send msgs

void whale
oak abyss
#

@void whale

#

see the buttons on the left? click on "Bot" then scroll down and enable intents and run ur code

void whale
#

or do i have it already done

oak abyss
slate swan
oak abyss
#

now run ur bot code

slate swan
oak abyss
#

@slate swan hows ur progress

#

@slate swan can we go to dms?

shrewd fjord
#

🛐

lost cradle
#

Hey, how can I make this simple bot work? Im hosting it locally


import discord
import random
from discord.ext import commands

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

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


@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name}')


@bot.command(name='roll')
async def roll(ctx):
    dice_roll = random.randint(1, 6)
    await ctx.send(f':game_die: You rolled: {dice_roll}')

TOKEN = 'placeholder'
bot.run(TOKEN)

for now it doesn't respond

shrewd fjord
#

Big fan :3

oak abyss
oak abyss
unkempt canyonBOT
#
Discord Message Content Intent

The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."

The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.

Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:

intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents

bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor

For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.

void whale
shrewd fjord
void whale
shrewd fjord
#

Wdym by "does not turn on"

naive briar
#

😳

shrewd fjord
#

Cattyyy uwu_blush

oak abyss
void whale
shrewd fjord
void whale
oak abyss
#

@shrewd fjord do u own any bots?

shrewd fjord
oak abyss
#

why did u add bot prefix code 2 times

slate swan
# void whale

you are overriding first bot instance with second without intents

shrewd fjord
oak abyss
#

im curious

snow breach
#

Hi, I'm new and I would like some help with my projects in py. Can anyone help me?

still spade
shrewd fjord
oak abyss
shrewd fjord
#

??

meager chasm
snow breach
#

my project is about a discord bot

meager chasm
snow breach
#

I have a problem with the function to create an embed and I don't understand the problem, everything is fine but in the final function where I have to send the result with the color it doesn't send it

meager chasm
#

!code

unkempt canyonBOT
#
Formatting code on discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

snow breach
#

!code

#

how?

meager chasm
#

Like the error says, you need to pass an argument to the intents parameter

#

check the !intents tag for an example

snow breach
#

how send my code?

meager chasm
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.

lost cradle
snow breach
#

i don t understead

slate swan
meager chasm
snow breach
#

ohhh

#

ok thanks

velvet compass
#

Don't include any tokens or api keys please

snow breach
#

i italian

meager chasm
#
embed = discord.Embed(title=risposta.content, description=risposta1.content, color=color.content)
``` is this the embed which doesn't get sent?
snow breach
#

yes

slate swan
#
import os
from discord.ext import commands
from datetime import datetime

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

@bot.event
async def on_ready():
    print(f"Logged into {bot.user.name} (ID: {bot.user.id})")

@bot.slash_command(
    name="botstats",
    description="View bot statistics.",
    guild_ids=None
)
async def botstats(ctx):
    latency = round(bot.latency * 1000)

    server_count = len(bot.guilds)
    member_count = sum(guild.member_count for guild in bot.guilds)

    uptime = datetime.now() - bot.user.created_at

    owner_username = bot.get_user(bot.owner_id).name

    embed = discord.Embed(
        title="Bot Statistics",
        color=discord.Color.blue()
    )

    embed.add_field(name="Bot Ping", value=f":ping_pong: {latency}ms")
    embed.add_field(name="Bot Servers", value=f":blue_circle: {server_count}")
    embed.add_field(name="Bot Members", value=f":busts_in_silhouette: {member_count}")
    embed.add_field(name="Bot Uptime", value=f":clock1: {uptime}")
    embed.add_field(name="Bot Owner", value=f":crown: {owner_username}")

    await ctx.reply(embed=embed)```
meager chasm
# snow breach yes

await ctx.send(embed=emb) you're sending emb here, but your embed is called embed

velvet compass
#
                    embed = discord.Embed(title=risposta.content, description=risposta1.content, color=color.content)
                    await ctx.send(embed=emb)

Is that last line a typo

slate swan
meager chasm
snow breach
#

it doesn't work anyway

meager chasm
snow breach
#

i write await ctx.send(embed=embed)

meager chasm
meager chasm
slate swan
#

Not too sure, I think it might be the Latest one

snow breach
slate swan
#

Since I did: pip install -U discord

slate swan
meager chasm
#

you will need something like ```py
@bot.tree.slash_command(...)

slate swan
#

its @bot.tree.command()

slate swan
meager chasm
#

yes

#

you will also need to sync the commandtree, do you have code for that?

meager chasm
snow breach
#

no

slate swan
#

hi

#

how do i decompile pyc file

snow breach
vale wing
#

Face me in spoonfeeding I bet my spoon is larger

cold sonnet
slate swan
#
import discord
import os
from discord.ext import commands
from datetime import datetime

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

@bot.event
async def on_ready():
    print(f"Logged into {bot.user.name} (ID: {bot.user.id})")

@bot.slash_command(
    name="botstats",
    description="View bot statistics.",
    guild_ids=None
)
async def botstats(ctx):
    latency = round(bot.latency * 1000)

    server_count = len(bot.guilds)
    member_count = sum(guild.member_count for guild in bot.guilds)

    uptime = datetime.now() - bot.user.created_at

    owner_username = bot.get_user(bot.owner_id).name

    embed = discord.Embed(
        title="Bot Statistics",
        color=discord.Color.blue()
    )

    embed.add_field(name="Bot Ping", value=f":ping_pong: {latency}ms")
    embed.add_field(name="Bot Servers", value=f":blue_circle: {server_count}")
    embed.add_field(name="Bot Members", value=f":busts_in_silhouette: {member_count}")
    embed.add_field(name="Bot Uptime", value=f":clock1: {uptime}")
    embed.add_field(name="Bot Owner", value=f":crown: {owner_username}")

    await ctx.reply(embed=embed)```
#

Somehow a trace back to line 14

glad cradle
#

send it

slate swan
white citrus
#

Can someone help

slate swan
glad cradle
glad cradle
glad cradle
#

note that you need to manually sync Slash commands

glad cradle
# slate swan 08?

yes but you can look to everything in that page, it's related to what you want to do, command syncing for example

slate swan
#

how can i learn how to code discord bots??

slate swan
#

And w3school

harsh orbit
#
Traceback (most recent call last):
  File "C:\Users\Hadi\PycharmProjects\Balance system\venv\Lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
    await item.callback(interaction)
  File "C:\Users\Hadi\PycharmProjects\Balance system\main.py", line 176, in check_s
    await interaction.response.send_modal(check(title= "فحص السيرفر ."))
                                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Command.__call__() missing 1 required positional argument: 'context'

Why this happening here

    @discord.ui.button(label="فحص السيرفر", style=discord.ButtonStyle.grey, custom_id="closs")
    async def check_s(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_modal(check(title= "فحص السيرفر ."))
#

I didnot understand the error

slate swan
#

what is check

#

LINK : fatal error LNK1158: cannot run 'rc.exe'
error: command 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\link.exe' failed with exit code 1158
[end of output]

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

harsh orbit
# slate swan what is `check`
class check(discord.ui.Modal):
    server_id = discord.ui.TextInput(label="ايدي السيرفر (server_id)", placeholder="مثال : 1130898038639054940 ")
    async def on_submit(self, interaction: discord.Interaction):
        try:
            int(self.server_id.value)
        except:
            await interaction.response.send_message("يرجى إدخال ايدي السيرفر بشكل صحيح", ephemeral=True)
            return
        server = bot.get_guild(int(self.server_id.value))
        if server is None:
            view = discord.ui.View()
            view.add_item(discord.ui.Button(label="إضافة البوت", style=discord.ButtonStyle.link,
                                            url=bot_link))
            await interaction.response.send_message("يرجى إضافة البوت الى السيرفر المراد فحصه اولا ", view=view, ephemeral=True)
            return
        else:
            NOT = 0
            ALREADY = 0
            data = json.load(open(DATABASE_FILENAME, "r"))
            keys = list(data.keys())
            for i in range(len(keys)):
                id = keys[i]
                if int(id) in [member.id for member in server.members]:
                    ALREADY += 1
                else:
                    NOT += 1
            await interaction.response.send_message(f"تم العثور على {ALREADY} أعضاء موجودين مسبقا في `{server.name}`\n يمكنك إضافة {NOT} أعضاء \n - {interaction.user.mention}")
slate swan
#

should I downgrade?

#

if so how do i uninstall py 3.12

glad cradle
glad cradle
slate swan
glad cradle
#

you could install 3.11 and use py

#

py -3.11 -m pip install ...

#

if you have py installed

glad cradle
slate swan
glad cradle
#

that's not the command to remove python 3.12

glad cradle
slate swan
#

uninstalled

#

from programs and features

glad cradle
#

btw unrelated to this channel

slate swan
glad cradle
#

yes you was, now the question changed

slate swan
final iron
vague junco
#

Someone knows, how to do a modal form in discord.py?

 async def button_app_callback(interaction):
            select = discord.ui.Select(
                placeholder="Выберите роль",
                options=[
                    discord.SelectOption(label="Анкета на модератора Discord-сервера", value="0x1",
                                         emoji="![mod](https://cdn.discordapp.com/emojis/1163874068571897886.webp?size=128 "mod")"),
                    discord.SelectOption(label="Анкета на сотрудника техотдела", value="0x2",
                                         emoji="![developer](https://cdn.discordapp.com/emojis/1163873684931493938.webp?size=128 "developer") "),
                ]
            )

            view = discord.ui.View(timeout=None)
            view.add_item(select)
            await interaction.response.send_message(view=view, ephemeral=True)

            async def select_callback(interaction: discord.Interaction):
                selected_role = interaction.data['values'][0]
                category_id = channels_config['tickets_category_id']
                category = discord.utils.get(interaction.guild.categories, id=category_id)

                if selected_role == "0x1":
                    channel_name = f'{interaction.user.name}'
                    ticket_channel = await category.create_text_channel(channel_name)
mystic marsh
vague junco
#

I need to create a modal after selecting in select

mystic marsh
#

well, you can simply create a seperate class inherited from discord.ui.Modal. theres an example on github

vague junco
#

Ok

mystic marsh
#

Under rapptz git for discor.dpy

sick coyote
#

when im selecting my select menu, it doesnt reset the choice it will stay applied, how can i reset the choices?

slate swan
#

`py
import discord
import os
from discord import app_commands
from discord.ext import commands

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

@bot.event
async def on_ready():
print("Logged Onto GlacierUTIL")
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print(e)

@bot.tree.command(name="read_tos")
async def read_tos(interaction: discord.Interaction):
await interaction.response.send_message("fuck kyxn"
ephmeral=True)

bot.run(TOKEN)`

frank nacelle
#

but its a simple fix

#
import discord
from discord.ext import commands
from api import *

intents = discord.Intents.all()
bot = commands.Bot(command_prefix="!", intents=intents)```
slate swan
frank nacelle
#

ye app_commands does not exist

slate swan
#

synced is not defined weird

frank nacelle
frank nacelle
#

this is what i have for my on_event or what ever ```py
@bot.event
async def on_ready():
print(f"Logged in as {bot.user.name}")

synced_commands = await bot.tree.sync()
print(f"Synced {len(synced_commands)} slash commands")

for cmd in synced_commands:
    print("These Commands have been synced: " + str(cmd))```
slate swan
frank nacelle
slate swan
frank nacelle
#

but i just have one problem and thats a /ping_role: @Role.name :message_link http.smth

#

i have 3 at the moment but the ping_role is the one that is not working properly

slate swan
#
import discord
from discord.ext import commands
from api import *

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

@bot.event
async def on_ready():
    print(f"Logged in as {bot.user.name}")

    synced_commands = await bot.tree.sync()
    print(f"Synced {len(synced_commands)} slash commands")

    for cmd in synced_commands:
        print("These Commands have been synced: " + str(cmd))

@bot.tree.command(name="read_tos")
async def read_tos(interaction: discord.Interaction):
    await interaction.response.send_message("fuck kyxn"
    ephmeral=True)```
#

would this be correct?

frank nacelle
#

u will need a description remember

slate swan
slate swan
frank nacelle
slate swan
frank nacelle
# slate swan wait can you show me your code?
@bot.tree.command(name="get_ping_role", description="Gets the id of a Role")
async def get_ping_role(inter: discord.Interaction, role_name: str):
    role = discord.utils.get(inter.guild.roles, name=role_name)
    if role:
        await inter.response.send_message(f"The ID of {role_name} is {role.id}")
    else:
        await inter.response.send_message(f"Role '{role_name}' not found.")```
#

all u have to do is like
/ping get_ping_role :RoleName Help

#

he RoleName part will not exist in the :

#

it just shows

slate swan
#
@bot.tree.command(name="read_tos")
async def read_tos(interaction: discord.Interaction):
    await interaction.response.send_message("fuck kyxn"
    ephmeral=True)```
#

isnt this correct aswell?

slate swan
#

it says unexpected indent

#

for my bot

hushed galleon
slate swan
#
import discord
from discord.ext import commands
from api import *

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

@bot.event
async def on_ready():
    print(f"Logged in as {bot.user.name}")

    synced_commands = await bot.tree.sync()
    print(f"Synced {len(synced_commands)} slash commands")

    for cmd in synced_commands:
        print("These Commands have been synced: " + str(cmd))

@bot.tree.command(name="read_tos")
async def read_tos(interaction: discord.Interaction):
    await interaction.response.send_message("fuck kyxn"
    ephmeral=True)

    bot.run(TOKEN)```
slate swan
hushed galleon
#

you're missing a comma after the first argument to your send_message()

slate swan
#
import discord
from discord.ext import commands
from api import *

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

@bot.event
async def on_ready():
    print(f"Logged in as {bot.user.name}")

    synced_commands = await bot.tree.sync()
    print(f"Synced {len(synced_commands)} slash commands")

    for cmd in synced_commands:
        print("These Commands have been synced: " + str(cmd))

@bot.tree.command(name="read_tos")
async def read_tos(interaction: discord.Interaction):
    await interaction.response.send_message, ("fuck kyxn"
    ephmeral=True)

    bot.run(TOKEN)```
slate swan
#

now its back to the same traceback: Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'bot' is not defined

hushed galleon
#
def add(x, y):
    return x + y

add(1, y=2)``` `1` is the first argument and `y=2` is the second argument, the comma goes between them
hushed galleon
slate swan
hushed galleon
#

like the actual visual studio, or vs code?

slate swan
#

explains

#

very much of the problem\

#

but on replit the imports have some typa issue

hushed galleon
#

well however you tried running it was not correct, because it's trying to open an interactive session and run a snippet of your code rather than whatever file you saved your bot to

slate swan
#
import discord
from discord.ext import commands
from api import *

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

@bot.event
async def on_ready():
    print(f"Logged in as {bot.user.name}")

    synced_commands = await bot.tree.sync()
    print(f"Synced {len(synced_commands)} slash commands")

    for cmd in synced_commands:
        print("These Commands have been synced: " + str(cmd))

@bot.tree.command(name="read_tos")
async def read_tos(interaction: discord.Interaction):
    await interaction.response.send_message,("fuck kyxn"
    ephmeral=True)

    bot.run(TOKEN)```
#

it says im missinc a comma

#

in line 20

frank nacelle
slate swan
#

oh there is a typo in ephemeral

#
import discord
from discord.ext import commands
from api import *

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

@bot.event
async def on_ready():
    print(f"Logged in as {bot.user.name}")

    synced_commands = await bot.tree.sync()
    print(f"Synced {len(synced_commands)} slash commands")

    for cmd in synced_commands:
        print("These Commands have been synced: " + str(cmd))

@bot.command(name="read_tos")
async def read_tos(ctx):
    await ctx.send("fuck kyxn", ephemeral=True)

bot.run(TOKEN)```
slate swan
#
import discord
from discord.ext import commands
import os

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

@bot.event
async def on_ready():
    print(f"Logged in as {bot.user.name}")

    synced_commands = await bot.tree.sync()
    print(f"Synced {len(synced_commands)} slash commands")

    for cmd in synced_commands:
        print("These Commands have been synced: " + str(cmd)

@bot.command(name="read_tos")
async def read_tos(ctx):
    await ctx.send("fuck kyxn", ephemeral=True)

TOKEN = os.environ.get("TOKEN")
bot.run(TOKEN)```
frank nacelle
slate swan
cunning shell
#

I need help on coding a discord bot

final iron
slate swan
final iron
#

Legitimately tells you the issue

slate swan
#

done

slate swan
#

i finished and updated the code

#

why is it syncing 0 slash commands

final iron
#

Show how you’re syncing them

slate swan
# final iron Show how you’re syncing them
import discord
from discord.ext import commands
import os

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

@bot.event
async def on_ready():
    print(f"Logged in as {bot.user.name}")

    synced_commands = await bot.tree.sync()
    print(f"Synced {len(synced_commands)} slash commands")

    for cmd in synced_commands:
      print("These Commands have been synced: " + str(cmd))

@bot.command(name="read_tos")
async def read_tos(ctx):
    await ctx.send("fuck kyxn", ephemeral=True)

TOKEN = os.environ.get("TOKEN")
bot.run(TOKEN)```
final iron
#

First of all, you shouldn’t be syncing in your on_ready

#

Either subclass commands.Bot, overwrite the setup_hook function and sync your commands there, or create a prefixed command for it

slate swan
#

cant find nothing really.

final iron
#

The first solution is pretty straightforward

#

It’s just subclassing which is basic OOP

#

The 2nd solution is also simple, you’re basically just creating a command and running your await bot.tree…

slate swan
slate parrot
#

yay i helped 😎

slate swan
#

the only command you have is a prefix command, whereas CommandTree is a container for app commands

slate swan
#

was wondering how I would make it an embed

#

!d discord.InteractionResponse.send_message Check the embed and embeds keyword arguments