#discord-bots
1 messages · Page 314 of 1
alright ik that tho are they predefined name or any of the choice we can think
like for red is it red ?
Maybe this could help you
https://gist.github.com/lykn/bac99b06d45ff8eed34c2220d86b6bf4
A gist which shows/tells you how to make buttons using discord.py v2(version 2.0.0a) - buttons.md
alright thnx
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
Its normal
Nope
It's cuz of connection issue
And that's too many disconnects and reconnects
It's almost happening every hour
@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)
Its not my connection 
Welp your host
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
Interchange interaction and buttons
Welp having it occasionally is ok but every hour I won't call that a good connectivity
Its the life 🤷♂️
Even i also host bot but i get that rarely once or twice a day
dude i owe you 50 bucks
i've been tryna fix this thing from like 2 hours
i owe you my house
It's white money right?
👁️
Only cash accepted
Welp that was in old version
Now interaction comes first then button
alright man, thanks alot for your support :D
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
maybe always connection?
this gives me ptsd of trying to make a music bot
Maybe idk
yeah cause it disconnects and tries to reconnect again so maybeee
But yeah looking at traceback it looks like a connection issue
He play music since 5 days without stop except with this error
what are you even using to make music
ffmpeg doesnt work at all with me
As shard id non is closing
ffmpeg work
i tried with wavelink but i sukc
i guess i suck anyways
You just need to add to PATH
I did but when i play the command there's some weird stuff on my terminal and just doesnt play
Have you the error ?
Wavelink is actually pretty easy for dpy users
not for mava
i dunno, just know that like last year, ill try the next year LMAO
Welp if you know OOPS then I don't think it should be hard
I use ffmpeg and PyNaCl
And you will need to read the docs as the yt tutorials are old and outdated
Just like discord
I have stop to try to use youtube and i download all mp3 i want for give in folder for the bot
yeah that's right mann
Youtube have blocked all api for play in streaming
yeah that's probably why
You can play 2 minutes and after he stop
It's against their ToS

Its why i use mp3 now lol
SoundCloud allows you to play but their api is closed i heard
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
Well i stay away from music
ok download finished and my bot is working again thank goodness
that's smart
Only breaking ToS if I'm not bot owner and getting paid for it
My music bot is only for me in my private vc
Well if it's for you then just use an audio player
I already have spotify but we listen my bot with my friend
My bot play only song from Taylor Swift
Ahh
orrr both get spotify premium and listen in remote sessions 
My favorite is Enchanted
nah you all are chatting while im having errors on errors 😭
I'm so excited about i go see Taylor Swift in may 2024 for The Eras Tour
noiceee
You can send the errors we can look at those too
oh alright alright
Well I'm not a music fan in general so i rarely listen to songs
I see
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
Well filtering out a specific singer is easy
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
intreraction comes before button argument
i tried helping myself with chatgpt but mannn life is hard
You can try Bard
literally for everything?
bro is an AI expert
I love the ai
for every decorated function with
I try to made my own ai
@button
just changed ill try to see if it works
even "nobody" told me that before but mannn
Yeah i told this to u before
life sure is idk
Ai is only good if it's used for the purpose of learning
Not coding with it
oh well
now that i got the same thing but with 'str' object has no attribute 'user' XD
and i cant find it
str object has no attribute user?
yeahh
Show the relevant code
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
And whole traceback
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])```
wow that's something i never tried to do myself
The created servers invite link?
Yes
and i cant find it in readthedocs
For he send me after the new server is created
Check your argument order
oh damn
would that mean that i have to move scissors
or i need to move interaction above self
man i feel so stupid right now lol
!E ```py
def f(arg_1: str, arg_2: int):
print(arg_1, arg_2)
f("some text", 123)
f(123, "some text")
@slate swan :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | some text 123
002 | 123 some text
i mean the interpreter doesnt really care
That's why we have Mypy 👍
!d discord.abc.GuildChannel.create_invite
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.
gg
You need use the channels attribute on the created guild
Assign this function a variable it returns a guild object
Use that variable to get the channels of the server
!d discord.Guild.channels
property channels```
A list of channels that belongs to this guild.
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
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
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
why are u showing 1 person's move in 1 field and the result in another person's move
shouldnt u show both their moves?
oh my god
misstype
also that wont fix anything
yeah i know but
you need to send the ephemeral message to the challenger too
or whoever does not receive it
challenger ig yeah
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
you know you dont have to make it ephemeral
Can someone help me how to make music bot
Yeah you're right now that im thinking about it
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
exactly exactly
assuming you code it in of course
im working on it
now i just need to make the bot wait for both's moves and send the embed result
yeah
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()```
!d discord.ext.commands.Bot.create_guild
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`.
i dont see region in here too
Ok i try without
Changed in version 2.0: name and icon parameters are now keyword-only. The region parameter has been removed.
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'```
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
|| 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)||
Terrible name choices aside, it's just @client.event without the () at the end
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
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
Don't respond twice to the same interaction
yeah but im making a rock paper scissors game
make like a handler
You can send a new message in the channel or edit the original message
wouldnt that make it harder tho
await interaction.response.send_message("You've already pressed!", ephemeral=True)```
idk for ur code, but for mine im using it for else:
i guess that's fair
More complicated or not doesn't matter, you just can't respond twice
hmm
ok
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?
oh 💀
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
@turbid condor
why ui button is commented
i fixed it by making amt a global thing
remove da hasttag before nc
unless ur debugging
he might just be removing it to see if it fixes the error; rather than yk removing the whole line to use later
I would like to use button_one as label
button_one is given by a other class
oh
yeah i completly ignored the comment, its just natural for me to skip over them ig
what is the label name its giving you
Its given by a modal
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
wha
Essentially re running the bot via command
@lunar vine ?
I assume there’s no way to log the bot back in once it has been logged out. (at least not manually)
ig a macro?
xD, u mean like rehosting it?
yes
u could prolly make a macro of some sort to type the cmd every 5 mins
or just buy hosting
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
print it in your python script to verify
and consider using dict.get method
Can someone help?
show button_one code
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
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)```
!code
Yeah sry
kinda off topic: where can i get a free proxy for my web scraper made in python?
but what is button_one assigned to?
web scraper for?
It should be the label for the Button
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)
But the callback is huge
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
And what is if i have a view with 2 buttons?
create 2 callbacks?
so sorry for the late reply, i was busy but i’m making an nsfw bot for a friend of mine
which scrapes the one and only website..
Ur making one for you, Don’t lie!
Is helping you a violation of rule 5
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
positional only means you cannot specify it as a keyword argument, meaning you cannot supply it with 'until='
!d discord.Member.timeout
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).
Looks like you can just remove the 'until=' and you'll be all set
👍
if role:
# remove all author roles first
await message.author.add_roles(role)
how would one achieve this?
Is author roles a list of roles?
no but i need it to read the users active roles at the time this event is called
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
!d discord.Member.remove_roles
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.
!d discord.Member.roles
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.
Use
to check for all roles
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
Might seem like a lot, but most of it is just basic stuff
Could probably learn it relatively quickly
hey anyone know why i cant install it
Have you installed python?
This too but the python from official website
so then should i download it from here insted?
You need this too
what else do i need?
For your knowledge, that's just intellisense and not python itself - same for all other extensions in VSC
I assume they are a complete beginner to programming
I cant download 3.11 or 3.12
Still worth knowing
when i click it it only shows 3.12
nothing 3.11
that i can see
Can embed have a background?
Ok, another question same goal.
How to add image to embed like python logo in that embed #discord-bots message
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.
why someone needs msvcpp tools to use discord py??
Ah maybe because it conpiles when installing...
Are not there precompiled versions?
I did download that and it still doesn't work
Did you install them?
What python version are you using??
3.12
!d discord.Embed.set_thmbnail
No documentation found for the requested symbol.
!d discord.Embed.set_thumbnail
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.
That's the issue
3.12 isn't supported by discord.py
Use 3.11 or earlier
Can it have only image or could you use text/emoji?
Or should i check docs and not ask
Only a url
Url means image, ok
Or a local image file
Yeas a url to an image
You can't add text but for emoji if it's a png file or a link then yes
oh
More like yarl 🫠
Welp yeah but we can't skip it
also uh why
has it just not updated yet?
Well it has a dependency which is needed for it to work
oh ok
3.11.6 works?
Yeah
alright
Just not 3.12 or above
thank you
okay, I installed 3.11, but pycharm is still using 3.12
when I try to change to 3.11 virtualenv it gives me this
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
?
Sorry but what's unclear
do i just delete these?
Delete directory in displayed location
You delete parent dir of this
Whole venv
Not objects inside
yeah so this right
Yes
thank you
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
Code issues
Send full traceback
uhh how
can I just send the code, its pretty simplistic
only that
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")
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
That would be helpful
so I know that its supposed to be a string
Well that's not a string
String is not callable either
I don't really understand this
Well you probably lack basic python knowledge then
Great opportunity to learn
I do
I just know the very basics
The b in basics then
Time to learn some O in OOP
discord.py already support buttons, drop-downs, ...
Im pretty sure its possible but not sure how its done. How can I have specific values in a dropdown pre-selected.
Use discord.ui.View etc, theres a pretty cool gist on it too by rapptz.
Set SelectOption.default to true
O i see, and its still recognized in callback through self.values[0] right.
also hru milady
I'm doin fine
what
ion understand
dw im just sleepey lol
Umm another problem is if its in a loop. I have a set of values which is returned from a postgres table, 0 or 1. I'm creating the options in a loop, but if I do it individually it'll be easy.
so which one do you want it to default value then?
what's your curernt code
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.
couldn't you just do ```py
options = [
discord.SelectOption(label=starters, description=starters, default=starters == 'Pin Shinies')
for starters in starter_pokemon
]
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.
what makes them set to True?
like thats the database for now. im not sure if I should use booleans or not but
the guilds owner.
why do i sense chat gpt
and these state are stored in a table row?
yea.
Like, these are the current rows for now
how are you fetching this value
I saved the result as guildconfig or I can use this
async def get_guild_config(guildid):
pool = await get_pool()
async with pool.acquire() as conn:
guilddata = await conn.fetch("SELECT * FROM guilds WHERE guildid = $1", guildid)
return guilddata[0]
so either one.
so just loop through the columns and check if they are set like what you did for starter_pokemon? I dont see what's the issue
Wdym like I did for starter_pokemon
also yea i should change that to guild_config or something.
I mean yea hang on I got an idea
yea this worked
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
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
yea ig
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?
do you know what [0] does
does it not return an selected value? so the first.
[0] takes the first element of a list, self.values is a list of selected options
also, self.values will only contain selected values
yea alr, but again. how will ik how many have been selected or not?
!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])
@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']
me when discovering data structures
yea but what if like only 1 is selected, or 3 are. it could return index errors? or would a[:2] return all values up to 2
so 0, 1 or 2
[:2] doesnt raise any index error, it's just slicing
also it returns up to 2 elements, 0, 1
How to check if an argument is a user mention
Oh i see
how about my second question, determining whether it was selected or deselcted?
is it possible finding that out.
Wdym
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.
It would be triggered in the callback
are you making a poketwo namer bot?
The callback would be triggered, and you could just use some simple list logic to see what changed
no its my own pokemon bot lol
ooo
alr i'll test it out tomorrow morning, ty for your time.
idk its fun to play with tensorflow
lol
never tried, can it really make one?
!e
print("This is a test")```
@oak abyss :white_check_mark: Your 3.12 eval job has completed with return code 0.
This is a test
!e
import discord```
@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'
#bot-commands
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.
can someone help with this command? I ran "pip install discord" and i installed the c++ build toolos
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?....
its pip install discord.py
why you need c++ and discord together
I need the builds.
.
damn i didnt download that i dont thing its neccesary but ok
i still get the same error with c++ build
just install the c++ manually
instead of download one of the most memory hogging software to get it
I dont get why pip install discord.py needs c++ libaries
same
just get python latest version
then open powershell and do pip install
dont use freaking command prompt
use powershell
lol @void whale
im new to this how do i do that?
!dashm
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.
and were is that
discord.py doesnt but its dependencies do, and i assume you have python 3.12 installed as the listed packages don't have prebuilt wheels for 3.12, requiring you to compile them - the easiest solution is downgrading to 3.11 so you don't need any compilation
how did you install python?
use only pip install
threw visual studio code
bruh
how so can I do that
vscode is an extension you need to install the interpreter
you need to install actual interpreter and not just vscode extension
do i download 3.12
dont download 3.12 right now, it's a headache for compiled third party packages
or you can do 3.11 its prob more stable
use 3.11
i only see 3.12 not 3.11
most libraries are not converted to 3.12 yet
go to downloads
https://www.python.org/downloads/release/python-3116/
you probably want to uninstall 3.12 first, then use the recommended 64-bit windows installer from the above link
ok i download one and its in my files manager now what should i do from there
run it
just install it normal
ok i installed it
now run the command in powershell
what one? py -m pip install discord .py pip install discord.py
any
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)
for me pip install discord.py works maybe it dont for you
have i done it?
yes
so can i start doing the code or is there anything else i need to download before starting
if you want any external libraries you can install them later but for discord you are good to go
Thank you!
instead of using command prefix / use app commands or hybrid commands with ! prefix
its all up to you but its a good suggestion
No point
arent / commands better?
it like pops up
how so?
not the command prefix to be /
oh to import them
What missing command?
to use them and put the bot to that or to hybrid commands
The only flaw in the code you sent is that you aren't running the bot
@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
using async?
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
import discord
from discord import app commands
yes
then from config import TOKEN
you need to set the bot to app commands
idk abt that cause idk ur code mine i just wrote the token on top
id recommend hybrid commands
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
@fiery girder remember my league bot suggestions? started one, its already in 1200 servers
`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()))`
nice
then I need to sync right?
commands.bot
you cant use bot - commands.bot with the app_commands if you dont go the hybrid command bot
yes
oh shi yea lmao
also theres an extra bracket at the end
how do i get thee message time
`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?
yeah, almost 200k users
yeah thats perfect for a start
`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
async def setup_hook(self):
await self.tree.sync()
print(f"Synced slash commands for {self.user}.")
i hate slash commands
you can use the app_command for slash command bot.command for ! command and hybrid command for both
prefixes were so good, slashes eat my brain
you have it?
yes
u sure?
yh
`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")`
no
i still didnt finish it yet
print(f"Logged into {bot.user}")
yup
`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}")`
@fiery girder hows ur bot
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
that dont work with app command
he literally has a prefix setup if you can read his code
it should be bot.app_command or bot.hybrid command
read the chat above
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
still wrong
name="hello",description="says hello"
ion the bot.slashcommand
`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)")`
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)
ctx.reply not respond
it can
can it?
im sure it can
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
@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)
i am proud of u
for?
getting it right the first ite
ah ok
@slate swan do u need a bot stats command? ill code it for u
are u done with the page navigation thing i need help in it kinda
like the button
^
yeah what do u need help with in it
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
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)
also do u have written the like button interaction cmd
ill help later im busy at the moment
can i dm u ?
Thank you ! And question, I put “TOKEN” as a key secret right ?
its highly suggested you do that, if you don't want to do it then dont
completely up to you!
The source you just provided, does it read the secret ?
Or does it read it off somewhere else ?
no it is like
bot.run("tokenhere")
example:
bot.run("11414u1nddmbdwliryairuhba5m2h5j2rqdwafkw5jw4b")
I go to line 4 then change it to what exactly ?
Same source as the one you provided me.
I think it’s not reading the “token”
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") ```
ur supposed to put ur token in the script
not secrets bar
I think it’s ADD_COMMAND ?
Why did you post the bot token….
il change after
How do I make it import the token from secret?
add this
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="!", intents=intents)
import os
(rest of the code here)
bot.run(os.getenv('BOT_TOKEN'))
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
hey viva can u also help me in the button
then go into developer portal, click on 'bot' scroll down and enable the message intents and stuff
working?
Would this be correct ?
yes
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
@vale wing someone is taking ur position
wbu @slate swan
Got this error 🙃
just change the wordings to what the error did
just change it to app_commands or wtv
yeah wherever that is, u can still find it
its like under the token area
not to mention discord_slash is depreciated and this is most likely from gpt
that too incorrectly
its a code i had from 2021 replit
you mind sharing it?
plus the wifi in my house is horrible rn, shutting down every second
opening gpt at this point would be world destruction
no? its a league bot that i spent hours on
this is a league bot?
this 20 lines that you just shared?
leave hours, i spent days
i literally deleted all other lines
r u ok?
u had a hello command in ur league bot?
i deleted the unnecessary stuff
yes 💀
it was the first command since i was nwe to python bots
xd yea and you kindly added those comments
i was literally watching youtube tutorials adding those
ive made discord bots that are in 1200+ servers within a week
weird flex butok
how does that change anything xd
?
ur framing me of using gpt
for no reason at all
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
maybe because its from fucking 2021??? why the hell would i make a new ass code to give these people
i was helping mocha so i just gave ali an old code
then if its from 2021 why are you giving it to someone when its depreciated
i never said its finished
hes planning on dming me later
if u can read the fucking full chat without beefing on random reasons
you are making a fool out of you
yeah okay down
!rule 10 just so you know you cant use AI tools to help here
@slate swan @void whale where did yall reach
cause its not really help
it isnt even ai tools
oh my days if only my wifi wasnt shit rn
its taking years to send msgs
mine still does not turn on stil
@void whale
see the buttons on the left? click on "Bot" then scroll down and enable intents and run ur code
A hands-on guide to Discord.py
enable message content intent on the bottom
message intent is needed for prefix commands
now run ur bot code
this has it all explained
Whoa brooo
🛐
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
Big fan :3
acc nvm
lmao
!mcintent
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.
still does not turn on
@void whale read
yes and still my bot does not turn on
Wdym by "does not turn on"
😳
Cattyyy 
he wants his bot to get flirty
the bot does not come online
Whats your code?
@shrewd fjord do u own any bots?
Remove 2nd bot = ...
why did u add bot prefix code 2 times
you are overriding first bot instance with second without intents
Why do you want to know? 
Hi, I'm new and I would like some help with my projects in py. Can anyone help me?
umm u didnt get the point i m saying i m able to create the button tho there is an thing i m not able to and like i share above
;-; lets keep it secret
dms?
??
Hi, this channel is for discord bots specifically; you might want to create your own help channel instead: #❓|how-to-get-help
my project is about a discord bot
Ask away!
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
Paste the code here please
!code
Like the error says, you need to pass an argument to the intents parameter
check the !intents tag for an example
how send my code?
!paste
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.
ty
i don t understead
did you actually read the embed
- Go to this link: https://paste.pythondiscord.com/
- Paste your code
- Press
Ctrl + S(to save) - Send the link here
Don't include any tokens or api keys please
embed = discord.Embed(title=risposta.content, description=risposta1.content, color=color.content)
``` is this the embed which doesn't get sent?
yes
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)```
await ctx.send(embed=emb) you're sending emb here, but your embed is called embed
embed = discord.Embed(title=risposta.content, description=risposta1.content, color=color.content)
await ctx.send(embed=emb)
Is that last line a typo
Is there an error with this, there is a trace back in line 14 saying “do you mean add_commands”
1 second
Could you send the full traceback please?
it doesn't work anyway
await ctx.send('Ecco a te il tuo embed') does it send this?
i write await ctx.send(embed=embed)
What version of discord.py are you using?
color=color.content I think this is incorrect; just color=color
and this
Let me check
Not too sure, I think it might be the Latest one
it doesn't work anyway
Since I did: pip install -U discord
What do you think the issue is?
I just remembered that discord.py uses a CommandTree class for app commands
you will need something like ```py
@bot.tree.slash_command(...)
its @bot.tree.command()
So where would I replace it ? In line 14 where the trace back is?
Do you get any errors?
no
it doesn't give me any errors
Ong
Face me in spoonfeeding I bet my spoon is larger
what in the 3rd party
use discord.py ❌
use discord.py + other libs that specifically have some stuff discord.py has ✅
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
send it
There
you're using Discord.py right? that's not how you create Slash commands there
Fr?
here there are some examples https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f#file-08-free_function_commands-py
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
08?
note that you need to manually sync Slash commands
yes but you can look to everything in that page, it's related to what you want to do, command syncing for example
how can i learn how to code discord bots??
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
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
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}")
python 3.12?
yes
are you on Windows?
yep[
you could install 3.11 and use py
py -3.11 -m pip install ...
if you have py installed
from the control panel
'py' is not recognized as an internal or external command,
operable program or batch file.
that's not the command to remove python 3.12
search control panel in cortana
cortana doesnt work
uninstalled
from programs and features
btw unrelated to this channel
I was using discord.py
yes you was, now the question changed
cant find 3.11 for some reason
Are you using a venv
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=""),
discord.SelectOption(label="Анкета на сотрудника техотдела", value="0x2",
emoji=" "),
]
)
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)
Thats not a modal? its select options.
I need to create a modal after selecting in select
well, you can simply create a seperate class inherited from discord.ui.Modal. theres an example on github
Ok
Under rapptz git for discor.dpy
when im selecting my select menu, it doesnt reset the choice it will stay applied, how can i reset the choices?
`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)`
name 'bot' is not defined
lol
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)```
Oh my god, sorry for being a complete dumbass
ye app_commands does not exist
synced is not defined weird
when doing a /command u need 2 things python @bot.tree.commands(name="Name_", description=" Smth to call") async def ping_name(interaction: discord.Interaction):
well it is until u call it inside your on_run() event
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))```
im pretty new to python So i figured learning discord.py
same i started 2 hrs ago
no way hahaha
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
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?
u will need a description remember
thats cool af im trying to make a slash command with 2 buttons agree to tos or dont, if you agree it sends an embed via webhook
yep I still have it look
like this since u can get the Id of a Role so u can import it to your core.py to make a list of Roles that can either use it or use the slash
but i have not got that far since im still new
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
@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?
bot.tree.sync() should be defined if you've installed discord.py 2.0+, though it's easier to help debug if you send the full traceback of the error
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)```
ephmeral=True)File "<stdin>", line 1
ephmeral=True)
IndentationError: unexpected indentephmeral=True)File "<stdin>", line 1
ephmeral=True)
IndentationError: unexpected indent
you're missing a comma after the first argument to your send_message()
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)```
would this be correct?
now its back to the same traceback: Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'bot' is not defined
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
err how are you running your bot?
visual studio lmao
like the actual visual studio, or vs code?
vs code
explains
very much of the problem\
but on replit the imports have some typa issue
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
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
wait is it possible to make it sleep after this much time with out a Hosting Server or no?
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)```
How can I make the code run the token from the secrets
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)```
just make a Private Channel but i dont know how but u can make it only be used by a certain role to use
done, but there is a problem with line 16
I need help on coding a discord bot
Read the error
print("These Commands have been synced: " + str(cmd))
Legitimately tells you the issue
done
I know, im just stoned rn
i finished and updated the code
why is it syncing 0 slash commands
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)```
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
Im a bit new and ive checked discord.py documentation
cant find nothing really.
For which
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…
Appreciate you for trying to help… I’m just to stupid to comprehend what you just said.
u missed a comma next to the quotation on "f** kyxn"
yay i helped 😎
well you're not adding commands to your tree so why would you expect it to be any number other than 0
the only command you have is a prefix command, whereas CommandTree is a container for app commands
i finished it already but thank you
was wondering how I would make it an embed
!d discord.InteractionResponse.send_message Check the embed and embeds keyword arguments

