#discord-bots
1 messages · Page 335 of 1
Hey how could I register this slash command to this guild ID? I have no errors but it's been 15 minutes and the slash commands aren't there
code:
@bot.tree.command(name="reload", description="Reloads a cogs", guild=discord.Object(1175954196567183450))
@app_commands.checks.has_role('AN | Owner')
async def reload(interaction: discord.Interaction, cog: str):
time = datetime.datetime.now()
if not cog:
async with print("s"):
embed = discord.Embed(
title="Reload all cogs",
color= 0x00FF00,
timestamp=time
)
for ext in os.listdir("./cogs/"):
if ext.endswith(".py") and not ext.startswith("_"):
try:
await bot.reload_extension(f"cogs.{ext[:-3]}")
embed.add_field(
name=f'Reloaded: `{ext}` :white_check_mark: ',
value='\uFEFF',
inline=False)
except Exception as e:
embed.add_field(
name=f"failed to reload: `{ext}` :x:",
value=e,
inline=False
)
await asyncio.sleep(0.5)
await interaction.response.send_message(embed=embed)
return
else:
embed2 = discord.Embed(
title="Reloaded!",
color= 0x00FF00,
timestamp=time
)
ext = f"{cog.lower()}.py"
if not os.path.exists(f"./cogs/{ext}"):
embed2.add_field(
name=f"failed to reload {ext}",
value="This cog does not exist"
)
elif ext in os.listdir("./cogs"):
if ext.endswith(".py") and not ext.startswith("_"):
try:
await bot.unload_extension(f"cogs.{ext[:-3]}")
await bot.load_extension(f"cogs.{ext[:-3]}")
embed2.add_field(
name=f"Reloaded: `{ext}` :white_check_mark:",
value='\uFeFF',
inline=False
)
except Exception as failed:
trace = traceback.format_exc(limit=True)
embed2.add_field(
name=f"Failed to reload: {ext} :x:",
value=trace,
inline=False
)
await asyncio.sleep(0.5)
await interaction.response.send_message(embed=embed2)```
!paste for long code snippets
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.
regardless, how did you try to sync the command?
on an on_ready event
did you call sync() with the same guild= that you wanted to sync it to?
can you show us the code
@bot.event
async def on_ready():
changepresence.start()
bot.db = await aiosqlite.connect(database="Database/setup.db")
async with bot.db.cursor() as cursor:
await cursor.execute("CREATE TABLE IF NOT EXISTS setup (guild INTEGER, ps_channel INTEGER, pm_role INTEGER, ps_request INTEGER)")
await bot.db.commit()
bot.db2 = await aiosqlite.connect(database="Database/ad.db")
async with bot.db2.cursor() as cursor:
await cursor.execute("CREATE TABLE IF NOT EXISTS ad (guild INTEGER, ad STRING)")
await bot.db2.commit()
await bot.tree.sync()
print(f"{bot.user} is now online!")
you need to pass in guild=discord.Object(1175954196567183450) there as well
Okay thanks, make sense now
Does anyone have a good math lib to use that doesnt use eval?
I plan to make a calculator command
!d ast.literal_eval
ast.literal_eval(node_or_string)```
Evaluate an expression node or a string containing only a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, `None` and `Ellipsis`.
This can be used for evaluating strings containing Python values without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.
should be safe and is built in
Ok so I have a problem and I need help let me begin explaining
from .user import User
from .channel import Channel
# Message
class Message:
# Initialization
def __init__(self, message_data, http, client):
self.http = http
self.client = client
channel_data = await self.client.get_channel(message_data.get('channel_id')
self.channel = Channel(channel_data)
self.id = message_data.get('id')
self.pinned = message_data.get('pinned')
self.author = User(message_data.get('author'))
self.content = message_data.get('content')
self.guild_id = message_data.get('guild_id')
self.timestamp = message_data.get('timestamp')
self.channel_id = message_data.get('channel_id')
```
this is what I want to achieve but I cannot put async stuff in `__init__ `and if I make an async function I cannot await it in `__init__` so i need help.
you should accest channel_data as an argument and do the await stuff at the callsite
what If I dont wanna access channel_data as an argument? any alternatives?
why not?
well because I have a consistency in the code and i dont wanna break it by taking this 1 thing as an argument
self.client.get_channel is an async function
that doesn't really change consistency
idk but im looking for some better ways yk?
accepting the argument is the best way
hi i'am trying to make a bot that when u join a vc the time that u have spend will go to a google sheet but when i join a vc there is an error in the terminal that say {"error":"Bad data format"} and nothing appears in the gsheet as well
can someone help pls
code, and full error would be needed
also, consider using a database for this :) it's easier code-wise
although visually accessing the data may be a bit more tedious. but there are database browsing apps that make it look like excel
!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.
also, storing data in google sheets is against their terms of services and will get your google account terminated without prior warning. I've seen it happen
oh rlly?
lol yeah
its working
it aint meant for that lmao
oh lol
I mean as long as you dont hammer the API you should be fine
but I do recall that being not allowed. but if you want to be sure, you should consult the terms of service yourself. I ain't no lawyer lamo
ok thx lol
Hey! I'm currently having trouble with a discord and wordpress integration. The plan is simple: bot asks user for their order id and then proceeds to act on it accordingly.
The error as of now is stupidly frustrating. The bot is unable to read any messages at all. It will print user names, but never the contents of their messages. Here's the code https://paste.pythondiscord.com/B7UA
Looks like you're missing message content intents
intents = discord.Intents.default()
intents.messages = True
intents.guilds = True
+ intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)
Thankyou for such a fast response! I'll give it a go!
I'm baffeled. It reads contents now!! I appreachiate it. I guess chatgpt will only get you so far...
Intents are quite new, ChatGPT doesn't have this data so it won't help you on anything discord.py v2 related afaik
you would be better served asking here
Everything else was generated with the help of GPT so I'm guite suprised it missed this. Using GPT4. Will return here, when any seemingly impossible issues arise again 🥲
i run my code but it just says
ModuleNotFoundError: No module named 'pip._internal.utils.temp_dir
I havent had an issue until today
Are you using pip's internals in your code?
I dont know what that means to be honest. I just recently started coding discord bots
Hey, for some reason none of my other commands that are in a cog doesn't work except for slash commands that are synced to a specific guild. How can I fix this issue?
@bot.event
async def on_ready():
changepresence.start()
bot.db = await aiosqlite.connect(database="Database/setup.db")
async with bot.db.cursor() as cursor:
await cursor.execute("CREATE TABLE IF NOT EXISTS setup (guild INTEGER, ps_channel INTEGER, pm_role INTEGER, ps_request INTEGER)")
await bot.db.commit()
bot.db2 = await aiosqlite.connect(database="Database/ad.db")
async with bot.db2.cursor() as cursor:
await cursor.execute("CREATE TABLE IF NOT EXISTS ad (guild INTEGER, ad STRING)")
await bot.db2.commit()
await bot.tree.sync(guild=discord.Object(1175954196567183450))
await bot.load_extension("cogs.partner")
await bot.load_extension(f"cogs.setup")
await bot.tree.sync()
print(f"{bot.user} is now online!")
@bot.tree.command(name="sync", description="sync a command", guild=discord.Object(id=1175954196567183450))
@app_commands.checks.has_role('AN | Owner')
async def sync(interaction: discord.Interaction):
await bot.tree.sync()
they guild commands?
because you look to be
1- syncing
2- loading cogs
3- syincing global
Only 4 commands are guild and the rest is global
this is strange. show us your code please
regardless, you should always sync after loading the cogs
also, you shouldn't really do any of this within on_ready
since it can trigger many times during your bot's lifetime. Matter of fact, you should only sync manually through a sync command, rather than automatically
I synced my other commands manually but it didn’t synced at all
I fixed it just had to reinstall a different version of py
^ my responses: #python-discussion message #python-discussion message
mb forgot to delete it
@commands.Cog.listener()
async def on_message(self, message):
# Check if the message is from Sofi and contains the card drop indication
if self.sofi_id == message.author.id and "is dropping cards" in message.content:
user_id = message.author.id
if user_id not in self.drop_counts:
self.drop_counts[user_id] = 1
else:
self.drop_counts[user_id] += 1
user = self.bot.get_user(user_id)
if user:
await message.channel.send(f"Successfully counted a drop for {user.name}!")
await self.bot.process_commands(message)
this code doesnt work whats wrong?
any tracebacks?
no
well first you don't have to use self.bot.get_user, as that is same as message.author
though it is weird that no errors are shown
maybe your self.sofi_id is incorrect
well make sure you are sending messages in the channel that your bot is in and that your message actually contains "is dropping cards", it also has to be lowercase
yes its all correct
well I have no idea, you could use Counter though, it's a little safer than dict
from collections import Counter
...
self.drop_counts: Counter[int] = Counter()
...
self.drop_counts[user_id] += 1 # without checking if it's in or not
Kk i will read about that thx for tip
just realised Counter[int] will probably not work, it might though, you can always just try, if it doesn't, just remove it: self.drop_counts = Counter()
Alr
sofi id is int btw
steal?
like u wanna use a server emoji outside of discord?
whatsapp , telegram?
No, where you use a command from a bot, it sends a download link to that emoji.
where you can just download it
I added it to my bot either way, but if you still didn't understand, this is what it does basically.
I mean I doubt its against ToS because other bots do it, plus you can do it yourself so I highly doubt its against any rule.
oo yes u can
I don't believe so, no
good feature btw
ty
u can add thoes emoji to other platforms if u want
Yeah or to your own server if you wanted
And the bot doesn't even need to be in the server for the emoji.
it just goes off the url then sends the url, which you can copy the url of any emoji with your own acc. But some people don't know that some how lol
Want it?
that feature?
Ye
ill just send it here lol
oo ye u can
use pastbin
@commands.hybrid_command()
@commands.guild_only()
@app_commands.describe(emoji='Please give a discord Emoji.')
async def steal(self, ctx, emoji: discord.PartialEmoji):
embed = discord.Embed(title='Emoji Stealer', description=f'Download the emoji: [Download Emoji]({emoji.url})', timestamp=discord.utils.utcnow(), color=config.main_color)
embed.set_footer(text=config.footer_text, icon_url=self.bot.user.avatar.url)
embed.set_thumbnail(url=emoji.url)
await ctx.send(embed=embed)```
No need for pastebin lol
o lmao that just 4 lines code
wait we can just use hybrind_command to make it slash and prefix both
Yes
dam
hybrid is for prefix + slash
great
how to make a cmd dm only?
no i forgot alot of stuff trying to regain
@commands.dm_only()?
ah
Yeah, im a fan of hybrid
Only because I can do certain things slash commands can't do if that makes sense, like you can't reply to messages using a slash command, so I have certain prefix commands that require you to reply to someone
@commands.command(name='ratio')
async def ratio(self, ctx):
"""
Ratio another member's message by replying to it with the ratio command!
"""
if not ctx.message.reference:
await ctx.send("Please reply to a message with `ratio` to ratio it.")
return
target_message = await ctx.fetch_message(ctx.message.reference.message_id)
random.shuffle(emojis)
selected_emojis = emojis[:10]
for emoji in selected_emojis:
try:
await target_message.add_reaction(emoji)
except discord.errors.HTTPException as e:
if "Unknown Emoji" in str(e):
embed = discord.Embed(
title="Error",
description=f"An error occurred while adding an emoji to the message. Unknown Emoji: {emoji}\n\nPlease report this error to our [Support Server]({config.SUPPORT_SERVER})!",
color=config.error_color
)
await ctx.send(embed=embed)```
Which would be a ratio command, you could make it go off message id, but thats boring lol.
You would have to get the message ID yourself, but I rather do it the lazy way and make the bot do it, making it a prefix command only
config is a module?
I have a file called config
so i don't have to type certain things out every time
so I can just use the config file
main_color = 0x5865F2 # Main color for all EMBEDS, not Errors or Success usually...
error_color = 0xFF0000 # Error color for all errors
success_color = 0x00FF00 # Success color for all successful embeds
xp_per_message = random.randint(5, 15)
footer_text = "© UniBot 2023-2024"```
Like having stuff like this, so when I set a footer I can just do config.footer_text instead of typing it out again.
btw xp_per_message = random.randint(5, 15) only runs once
so you get the same xp per message across every mesasge
alr
Each message goes back to xp_per_message
so it pick random each time if im not wrong, but I didn't write the leveling system, the other dev did.
it does not run random.randint whenever you access it
so you should move that calculation in your handler
alr ty
hello!
does anyone know how i can instantly register slash commands in only one server using discord.py 2.0>?
I gave you a response, you can make a sync command.
just pass in the guild id when syncing
I don't think they have a sync command, so I gave them Umbras.
i saw it! thanks!
thanks
@iron sorrel which module for buttoms?
You need buttons?
any idea what might be wrong here?
def __init__(self):
super().__init__(title="Input")
self.add_item(discord.ui.TextInput(label='Input',
style=discord.TextStyle.long,
placeholder='Enter Input, one per line, in the format: HH:MM:SS:HH:MM:SS',
required=True))
async def callback(self, interaction: discord.Interaction):
# Defer the interaction to give us more time to respond
await interaction.response.defer()
# Try to process the input data and catch any exceptions
try:
input_data = self.children[0].value.split('\n')
# Create and write to file
filename = f"input_{datetime.now().strftime('%Y%m%d%H%M%S')}.txt"
with open(filename, 'w') as file:
file.write("StartingHour:StartingMinute:StartingSecond:EndingHour:EndingMinute:EndingSecond\n")
for line in input_data:
if line.strip(): # Ensure the line is not empty
file.write(line.strip() + '\n')
# Send confirmation after processing is done
await interaction.followup.send(f"File {filename} created successfully.")
except Exception as e:
# Log the exception
logging.error(f"An error occurred: {e}")
# Inform the user
await interaction.followup.send("An error occurred while processing your request.")
@bot.tree.command(name='create_modal', description='Create a modal')
async def create_modal(interaction: discord.Interaction):
# Show the modal to the user
modal = Modal()
await interaction.response.send_modal(modal)```
Issue?
Print the error
discord.ui
ye
do debugging
A gist which shows/tells you how to make buttons using discord.py v2(version 2.0.0a) - buttons.md
except Exception as e:
# Log the exception
logging.error(f"An error occurred: {e}")
but still nothing
oo
"do debugging"
print each step. So you can find out where it messes up at
ok
I don't mess with modal often, but no one else is here talking about it, so im just giving best advice by saying use prints to figure out the error
oo
2.0+
hm so nothing to import?
No
you only need to import discord
you need to learn interaction too
can u write a small code for me?
yes or no interaction
A gist which shows/tells you how to make buttons using discord.py v2(version 2.0.0a) - buttons.md
It shows examples here
there no example with yes or no
it is not calling the callback event
i have a reset cmd
i want the button confirmation
yes = clear
no = abort
sorry i m disturbing u
Well first
No one in here is going to write that for you, we aren't just gonna give code like that lol. Second, you gotta read what its saying, you can easily learn what its doing by reading them make the interactions yourself.
We are all here to help you, not write it for you, not to sound rude or anything, its just how it is, we are trying to help or help you with a problem, not write the code for you.
i thought thats a 3,4 line code mb
Depends on how you do it, but yes it could be. But we are here to help or let you learn if that makes sense? We don't wanna give code because then you don't learn if that makes sense, not trying to be rude either.
can u just get me a template?
ye i understood it
i didnt mean to write the whole code just a kindoff template helps
I can't just write a template lol
I mean, the github shows examples, so you can kinda go off what they are doing
it teaches you all.
there no example in discord.py
i m writing code with using it getting some error
!d discord.ui.View
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
import discord
from discord.ext import commands
class Errors(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
if isinstance(error, commands.CommandNotFound):
return
elif isinstance(error, commands.MissingPermissions):
missing_permissions = ', '.join(error.missing_perms) if hasattr(error, 'missing_perms') and error.missing_perms else "Unknown"
embed = discord.Embed(
title="",
description=f":mod_untick: You need certain Kryptex Permissions to use this command!\n:mod_arrow: You need one of those permissions:\n `{missing_permissions}`",
color=0x2f3136
)
embed.set_author(name="You can't use this command!",
icon_url=ctx.author.avatar.url)
await ctx.send(embed=embed)
async def setup(bot):
await bot.add_cog(Errors(bot))
@iron sorrel
what is this?
Everytime unknown error is showing
Ban permission kick permission
This is not showing
whaa
@iron sorrel bro can u check my code
whats not working with it?
AttributeError: 'Button' object has no attribute 'response'
interactions
check callback
Bro what is happening
do you need help?
thats what i m confused
i used the github way
i get attribute errors
code
AttributeError: 'Button' object has no attribute 'response'
interaction failed
Alright bro
you have to have interaction first
You have Button then interaction. It needs to be interaction then Button
just swap the order, then issue should be fixed maybe..?
oo
line number
dawg what 
nfirm
ye and i was finding that confirm where u get that from
i didnt knew it was your code
🗿 people usually dont respond with there codes
ye got it
did it work?
it did but another error
?
Traceback (most recent call last):
File "C:\Users\aksha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 430, in scheduled_task
await item.callback(interaction)
File "c:\Users\aksha\OneDrive\Documents\Code\Discord bots\Sofi utility\cogs\sofi.py", line 18, in no_button
await self.cog.confirmation_callback(False, interaction)
File "c:\Users\aksha\OneDrive\Documents\Code\Discord bots\Sofi utility\cogs\sofi.py", line 81, in confirmation_callback
await interaction.followup.send("Operation canceled.")
File "C:\Users\aksha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async.py", line 1817, in send
data = await adapter.execute_webhook(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\aksha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 220, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
Why are you using a webhook?
i m not
send updated code 😭
thats the same code
just send the updated code.
kk
async def no_button(self, interaction: discord.Interaction, button: discord.ui.Button):
try:
await interaction.message.edit(content="Operation canceled.")
await self.cog.confirmation_callback(False, interaction)
except discord.errors.NotFound as e:
print(f"Error: {e}")
Do this
to print error
Yes
with?
Error + code needed.
@sturdy fractal did you do this? Also if so, what error?
@client.command()
@commands.has_permissions(administrator=True)
async def testerror(ctx):
await ctx.send("error")
import discord
from discord.ext import commands
class Errors(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
if isinstance(error, commands.CommandNotFound):
return
elif isinstance(error, commands.MissingPermissions):
missing_permissions = ', '.join(error.missing_perms) if hasattr(error, 'missing_perms') and error.missing_perms else "Unknown"
embed = discord.Embed(
title="",
description=f":mod_untick: You need certain Kryptex Permissions to use this command!\n:mod_arrow: You need one of those permissions:\n `{missing_permissions}`",
color=0x2f3136
)
embed.set_author(name="You can't use this command!",
icon_url=ctx.author.avatar.url)
await ctx.send(embed=embed)
async def setup(bot):
await bot.add_cog(Errors(bot))
doing it
Issue?
testerror
Kryptex
BOT
— Today at 3:53 PM
You can't use this command!
:mod_untick: You need certain Kryptex Permissions to use this command!
:mod_arrow: You need one of those permissions:
Unknown
Unknown
is it cuz its doing Unknown?
?
what is the error 😭
wait it should be added below callback right
its your button........
why it is not showing
You need one of those permissions:
Ban Command
bro
or Administrator permisson
yes
I literally said that 
how to fix it
Bro
what is the command 
Because if the command has no perm on it, then its gonna be unknown
@client.command()
@commands.has_permissions(administrator=True)
async def testerror(ctx):
await ctx.send("error")
do you have admin?
no
are you owner of the server?
2024-01-14 16:00:03 ERROR discord.ui.view Ignoring exception in view <Buttons timeout=30 children=2> for item <Button style=<ButtonStyle.danger: 4> url=None disabled=False label='No' emoji=None row=None>
Traceback (most recent call last):
File "C:\Users\aksha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 430, in scheduled_task
await item.callback(interaction)
File "c:\Users\aksha\OneDrive\Documents\Code\Discord bots\Sofi utility\cogs\sofi.py", line 18, in no_button
await self.cog.confirmation_callback(False, interaction)
File "c:\Users\aksha\OneDrive\Documents\Code\Discord bots\Sofi utility\cogs\sofi.py", line 83, in confirmation_callback
await interaction.followup.send("Operation canceled.")
File "C:\Users\aksha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async.py", line 1817, in send
data = await adapter.execute_webhook(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\aksha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 220, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
idk dawg
?
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
if isinstance(error, commands.CommandNotFound):
return
elif isinstance(error, commands.MissingPermissions):
missing_permissions = ', '.join(getattr(error, 'missing_perms', [])) or "Unknown"
embed = discord.Embed(
title="",
description=f":mod_untick: You need certain Kryptex Permissions to use this command!\n:mod_arrow: You need one of those permissions:\n `{missing_permissions}`",
color=0x2f3136
)
embed.set_author(name="You can't use this command!",
icon_url=ctx.author.avatar.url)
await ctx.send(embed=embed)```
Try this, idk you are doing it weird tbh 
I have no clue, idk what this error is, never had this error with buttons
not working
got a suggestion from chatgpt
elif isinstance(error, commands.MissingPermissions):
missing_permissions = ', '.join(error.missing_permissions)
error_embed = discord.Embed(
title="Error",
description=f"You don't have the required permissions for this command, you need ``{missing_permissions}`` permission to use this command.",
timestamp=discord.utils.utcnow(),
color=config.error_color
)
error_embed.set_footer(text=config.footer_text, icon_url=self.bot.user.avatar.url)
await ctx.send(embed=error_embed, ephemeral=True)
This is how I do it, you can customize it how you want
Wouldn't recommend using gpt tbh
he knows some things, but half the time he is stupid
indeed
i use it as last option
I barely use him unless I know nothing

2024-01-14 16:03:49 ERROR discord.ui.view Ignoring exception in view <Buttons timeout=30 children=2> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Yes' emoji=None row=None>
Traceback (most recent call last):
File "C:\Users\aksha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 430, in _scheduled_task
await item.callback(interaction)
File "c:\Users\aksha\OneDrive\Documents\Code\Discord bots\Sofi utility\cogs\sofi.py", line 13, in yes_button
await self.cog.confirmation_callback(True, interaction)
File "c:\Users\aksha\OneDrive\Documents\Code\Discord bots\Sofi utility\cogs\sofi.py", line 81, in confirmation_callback
await interaction.response.send_message("Drop counts have been reset.", ephemeral=True)
File "C:\Users\aksha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 786, in send_message
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before
does this means i clicked the the button twice>
show code please, so I can help you,
@vapid parcel thnx bro its working
nah
Np.
code is same
Clearly not, cuz gpt fixed it 
async def confirmation_callback(self, confirmed: bool, interaction: discord.Interaction):
if confirmed:
self.drop_counts.clear()
await interaction.response.send_message("Drop counts have been reset.")
else:
await interaction.response.send_message("Operation canceled.",)
async def no_button(self, interaction: discord.Interaction, button: discord.ui.Button):
try:
await interaction.message.edit(content="Operation canceled.")
await self.cog.confirmation_callback(False, interaction)
except discord.errors.NotFound as e:
print(f"Error: {e}")
only 2 line lmao
and i want the button to be off
after being clicked
oh
I see
you are doing a callback. You don't need a call back when the buttons already do it for you I think
Wait
no
Kinda am atp 
removed followup and used response.send
you have it in a weird way....
well see, you are doing a followup... even tho idk hold on
🗿 this is kinda normal for me
when i get to code stuff i make myself and the helper confused
async def confirmation_callback(self, confirmed: bool, interaction: discord.Interaction):
if confirmed:
self.drop_counts.clear()
await interaction.response.defer()
async def no_button(self, interaction: discord.Interaction, button: discord.ui.Button):
try:
await interaction.message.edit(content="Operation canceled.")
await self.cog.confirmation_callback(False, interaction)
except discord.errors.NotFound as e:
print(f"Error: {e}")```
i removed it i m using response.send_message
use this code tho
Wait... Why are you using call back...?
defer?
Bro im so confused, im lost in the sauce atp 😭
to get interaction ig?
Buttons do that already...
Alright, we can do something like this I guess.. idk if it will work
hmm
async def confirmation_callback(self, confirmed: bool, interaction: discord.Interaction):
if confirmed:
await interaction.response.defer()
async def no_button(self, interaction: discord.Interaction, button: discord.ui.Button):
try:
await interaction.response.defer()
except discord.errors.NotFound as e:
print(f"Error: {e}")```
Do these, because your callback already does the rest
Unless im tripping, it is 5am 
what is defer ?
!tag defer
» mutable-default-args
» defaultdict

defer is to accept the interaction
without having a fail.
kk
Tell me if those buttons work
they are
they work?
i got it why we used to get error
when we alr responded
and tried to response 2nd time
Yeahhh
thats why we get the error
thats why i was confused on why we used call back
not we, YOU used callback
so I just made it accept interaction, then it shouldve worked
ye idk
Okay so the buttons are working? can you confirm?
ye
alr
lemme use again
Alright
await self.disable_buttons()
use this then do
await interaction.message.edit(view=self)
no it just edits the response
but doesnt actually clear the drop counts
then use await
its clearly accepting interaction tho
so that means you arent doing something right on your side, im doing my part tho 
ye but it doesnt clear the counts which he used to
BROO
ye
now this
it will just show for me i want it for every1
Bro
it will show for everyone 
an edit is an edit, no one can change how discord does edits 
self i thought only the user
.....................................
my brain is gonna explode 😭
do this
send updated code actually
so i can do this for you, then you can go on with your day 😭
i did it lemme test
kk
i even have to add storing counts in a file that gonna be a pain as well
this should work, if not then skill issue ig
hard to edit shit in a non IDE at 5am 
You shouldn't delete messages after you ping someone
??
Yeah I am currently helping them
Ultimate message logger lowkey 
sorry that issue was respolved
Android notifications history, best logger 
Real tho lol, ban him mods

@sturdy fractal did it work
i need you to like, confirm whats happening
so I can possibly go to sleep 
Breaking news: mods ban the android operating system
Meanwhile I just woke up
doing it
got really bored
wtf
XD
waiy bro
😭
nitro hacks
it doesnt take this long 😭
File "c:\Users\aksha\OneDrive\Documents\Code\Discord bots\Sofi utility\cogs\sofi.py", line 32, in no_button
await self.disable_buttons()
^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Buttons' object has no attribute 'disable_buttons'
dawg
idk the button loads for a while
😵💫
There 😭
@sturdy fractal does it work nowwwwwwwwwwwwwww
if not then i prolly forgot another thing 😭
@vapid parcel confirm doesnt work
ye its there
like what is the issue now...? idk why you are using call back atp 😭
alr gn
just make the buttons do it all 
and sorry for all the mental dmg i gave u
THE BUTTONS DONT WORK WITHOUT IT
...................................................................................................................................................................................................................................................
SO U still up for help? 💀
i feel pity for u
go to sleep ig
blow your house up atp 😭
joking obvi, don't report me 😭
So does disable work btw?
like what are the current issues you are HAVING
🗿 sorry
idk i m laughing
i will go to hell

for cancel yes
but it says interaction failed
and for confirm it doesnt
File "c:\Users\aksha\OneDrive\Documents\Code\Discord bots\Sofi utility\cogs\sofi.py", line 23, in yes_button
await self.cog.confirmation_callback(True, interaction)
File "c:\Users\aksha\OneDrive\Documents\Code\Discord bots\Sofi utility\cogs\sofi.py", line 115, in confirmation_callback
await interaction.response.defer()
File "C:\Users\aksha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 651, in defer
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before
this error
but i used !resetdrop 2nd time and it came
:/
Dawg, ive never used call back 
n im trying my best to like help you 😭
imma just sleep, just wait for another person to help ig 😭
ye better gn
thanks and sorry
imma go work on my bot tmr ig after I wake up XD
its fine
or you can just dm me n when I wake up I can rework it ig
to a way that i know works 
i m gonna be just here hit me when u fresh
hey can u help?
can u just dm me your bot button code any cmd code which involes button
like mine
ig
accept frq
WAIT WTF ARE U WATCHING PO*N
Sure
If you need my help, what's your latest code and like a quick explanation of your error?
so the error is
when i use cancel button i get interaction failed
but it does his work , the button gets disabled
while the confirm button doesnt work
Traceback (most recent call last):
File "C:\Users\aksha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 430, in _scheduled_task
await item.callback(interaction)
File "c:\Users\aksha\OneDrive\Documents\Code\Discord bots\Sofi utility\cogs\sofi.py", line 23, in yes_button
await self.cog.confirmation_callback(True, interaction)
File "c:\Users\aksha\OneDrive\Documents\Code\Discord bots\Sofi utility\cogs\sofi.py", line 115, in confirmation_callback
await interaction.response.defer()
File "C:\Users\aksha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 651, in defer
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before
I see
You can only do one interaction.response.xxxxx per each interaction object you receive
u mean per 10 sec? smh?
You here are first sending a message (line 22) then calling another function (line 23) and that function sends another response (line 115)
Sending a second response will always fail, you can only send one per each interaction object
i didnt send 2nd response
!resetdrop
and on 2nd !resetdrop it says interaction has alr been responded
o
Also I don't really see the reason for self.button_disabled
mb
Disables all buttons at the end
Since you set it to true then stop the view, meaning that it won't work anymore
idk too
its button.disabled = true i read in doc
lmao
so what to do here
An example of a confirmation prompt, from the official discord.py repository. Could be good to take a look
You need to remove one of the .response.x from your code, so you don't respond twice
Also, why not just do self.cog.drop_counts.clear() directly from the view? I see no point in having these callbacks on the Cog
What i said 😭
i want to clear them on click
Well it doesn't matter if you clear it from the cog callback, or the view button callback
Either way it'll get cleared on-click, since you're invoking the cog callback from the button one
alr lemme try
need to remove this line as welll
await self.cog.confirmation_callback
You either do it one way or the other, yes
if i removed it how will the button get interaction?
to clear counts
confused
Guys how do i set a bots about me
https://discord.com/developers/applications
Select your app -> description
either from code or u can use discord potral
Thanks
The buttons get interaction from the view
The view is a standalone thing that handles button stuff
oo
Your cog callbacks are something that you made
And that you are manually invoking from your button code
Them existing doesn't change the view's function
now if i even click cancell it will reset the drop counts
i just added what u said
and disabled callbacks
If you're calling .clear() from the no button callback
how can i use jishaku to run a function inside my cog?
I see a lot of duplicate and unnecessary code here. You're editing that message a bunch of times, when you really dont need to
once i fix this i will erase all comments
i m just keeping it till this gets fixed
No, by that I mean, for example, your no button, it could be reduced to the following:
#
@discord.ui.button(label="No", style=discord.ButtonStyle.red)
async def no_button(self,interaction: discord.Interaction, button: discord.ui.Button):
self.stop()
await self.disable_buttons()
await interaction.response.edit_message(content="Operation canceled.", view=self)
how can i use jishaku to run a function inside my cog?
oo ic
alr
and about the error?
lmao
u forgot the main thing
i clicked no
and it still reset the drop counts
Line 10 of the paste
You're clearing your leaderboard in the init lol
that what u said
Not in the init
^^
o wait
Yeah by directly on the view I mean within async def yes button
Aka It would replace that comment you have
@discord.ui.button(label="Yes", style=discord.ButtonStyle.green)
async def yes_button(self,interaction: discord.Interaction, button: discord.ui.Button):
self.stop()
await self.disable_buttons()
await interaction.response.edit_message(content="Drop counts have been reset.")
self.cog.drop_counts.clear()
bot.get_cog("name").func()
Yeah
And don't forget view=self when editing
im tryin to get bot cogs and im receiving an error:
C:/Users/Naseer/AppData/Local/Programs/Python/Python312/python.exe "c:/Users/Naseer/Desktop/That one server/GameLoop.py"
Traceback (most recent call last):
File "c:\Users\Naseer\Desktop\That one server\GameLoop.py", line 35, in <module>
bot.load_extentions(f"cogs{filename[:-3]}")
^^^^^^^^^^^^^^^^^^^
AttributeError: 'Client' object has no attribute 'load_extentions'
PS C:\Users\Naseer\Desktop\That one server>
show the code
All.?
no only this cogs part
u have your actually code in? main.py?
gameloop.py is your main.py here ig
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
bot.load_extentions(f"cogs{filename[:-3]}")
Token = "TOKEN?"
bot.run(config.Token)```
Because you already edit with interaction.response.edit_message
Ye
jsk py
await ctx.send("hey")
Error
value = await base.asend(self.send_value)
File "<repl>", line 1, in _repl_coroutine
await ctx.send("hey")
NameError: name 'ctx' is not defined
jishaku define context as _ctx by default so
All variables provided by Jishaku are prefixed with an underscore
_channel, _bot, _message, _ctx, _guild, _get, _find and so on
You can change it with an environment variable
okey thnx
jishaku support on pydis
JISHAKU_NO_UNDERSCORE="true" is the environment variable you need to set
now its working
import os
os.environ["JISHAKU_NO_UNDERSCORE"] = "true"
``` or
```py
import jishaku
jishaku.Flags.NO_UNDERSCORE = True
Nice 
Traceback (most recent call last):
File "C:\Users\Naseer\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "c:\Users\Naseer\Desktop\That one server\GameLoop.py", line 35, in on_message
await c.execute("SELECT * FROM status WHERE id = ? ", (message.author.id))
File "C:\Users\Naseer\AppData\Local\Programs\Python\Python312\Lib\site-packages\aiosqlite\cursor.py", line 48, in execute
await self._execute(self._cursor.execute, sql, parameters)
File "C:\Users\Naseer\AppData\Local\Programs\Python\Python312\Lib\site-packages\aiosqlite\cursor.py", line 40, in _execute
return await self._conn._execute(fn, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Naseer\AppData\Local\Programs\Python\Python312\Lib\site-packages\aiosqlite\core.py", line 133, in _execute
return await future
^^^^^^^^^^^^
File "C:\Users\Naseer\AppData\Local\Programs\Python\Python312\Lib\site-packages\aiosqlite\core.py", line 106, in run
result = function()
^^^^^^^^^^
sqlite3.ProgrammingError: parameters are of unsupported type
elif isinstance(error, commands.MissingRequiredArgument):
embed = discord.Embed(title="",
description=f":mod_untick: You need to provide a valid argument for this command!\n:mod_arrow: Usage:\n `{ctx.prefix}{ctx.command.name} {ctx.command.signature}`", color=0x2f3136)
await ctx.send(embed=embed)
The second parameter needs to be a tuple
(X) is not a tuple. Those are parentheses of order of operation stuff.
(X, ) is a tuple.
Command raised an exception: TypeError: Buttons.init() takes 2 positional arguments but 4 were given
`@client.event
async def on_member_join(member):
welcome_role_1 = member.guild.get_role(1158290739244048484)
if welcome_role_1:
await member.add_roles(welcome_role_1)
welcome_role_2 = member.guild.get_role(1159466928503533609)
if welcome_role_2:
await member.add_roles(welcome_role_2)
welcome_channel = client.get_channel(1158134371308540075)
if welcome_channel:
embed = discord.Embed(title=f"Herzlich willkommen {member.display_name}!",
description="Willkommen auf DevUnit, der ultimativen Coding & Tech-\nCommunity! 🎉",
color=discord.Color.blue())
embed.set_thumbnail(url=member.avatar_url)
embed.set_footer(text="DevUnit • DE")
await welcome_channel.send(embed=embed)`
Why doesnt this work?
Something is wrong with the avatar thing ig
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar)
Ahhh dawn
I forgot, thanks mate
`@client.event
async def on_member_join(member):
welcome_role_1 = member.guild.get_role(1158290739244048484)
if welcome_role_1:
await member.add_roles(welcome_role_1)
welcome_role_2 = member.guild.get_role(1159466928503533609)
if welcome_role_2:
await member.add_roles(welcome_role_2)
welcome_channel = client.get_channel(1158134371308540075)
if welcome_channel:
embed = discord.Embed(title=f"Herzlich willkommen {member.display_name}!",
description="Willkommen auf DevUnit, der ultimativen Coding & Tech-\nCommunity! 🎉",
color=discord.Color.blue())
embed.set_thumbnail(url=member.avatar.url)
embed.set_footer(text="DevUnit • DE")
await welcome_channel.send(embed=embed) `
Bot is still not starting...
Errors would be nice
(Also note how add_roles is plural. You can add_roles(as, many, roles, you, want) in one single call)
Just fixed it
`@client.tree.command()
async def comingsoon(ctx):
embed = discord.Embed(
title="Coming Soon!",
description="Dieses Feature ist in Entwicklung und\nwird bald verfügbar sein.\nWir freuen uns darauf,\nes mit euch zu teilen!",
color=discord.Color.blue()
)
embed.set_footer(text="DevUnit • DE")
embed.set_thumbnail(url=client.user.avatar_url)
await ctx.send(embed=embed)`
But there is a new thing that doesnt work, already searched for a resolution but didnt find any.
What is wrong there? :P
app commands don't take ctx
they take an interaction object. You use interaction.response.send_message() to send messages with it
here are some resources on app commands you may like
can anyone give good video tutorials to learn Discord bot dev?
All are bad. Reading documentation and looking at the examples is better
okay, thanks
thanks for this also
Is there a way to get all the users of all the servers the bot is in and check if those users are in a specific list of servers (via server ID) and if so, do something like apply a role, if not, then pass?
Solved, nevermind
Is it preferable to use decorators or subclass Client (discord.py)? Why?
That's an extremely broad question
So there's no general opinion, such as "subclassing is better, because oop and stuff"?
not for this
Would still love to hear some, any opinions on if there even is a difference (other than just visual style) 
I prefer subclassing because I often have extra attributes and methods bound to my client, and it lets me properly type hint the code, so that my editor can properly infer types of said variables
Plus I can create a single bot class and use it in many projects
(e.g. a friend taught me about git submodules and they are neato asf)
hi can u help me?
If you ask a question 😉
how do i paste the 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.
Oh, no I can't help since I've never worked with that. Sorry
ok thx
uhm how do i install it lol
As shown in that link
pip install git+THAT LINK
i don't evec know how to use it
You will need to learn som basic SQL. Which you can do here:
https://sqlbolt.com/
SQLBolt provides a set of interactive lessons and exercises to help you learn SQL
As stated:
A simple and easy to use async wrapper for sqlite3.
This is basically the same as sqlite3 except you use async with and await in front of most operations.
!d sqlite3
Source code: Lib/sqlite3/
SQLite is a C library that provides a lightweight disk-based database that doesn’t require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language. Some applications can use SQLite for internal data storage. It’s also possible to prototype an application using SQLite and then port the code to a larger database such as PostgreSQL or Oracle.
The sqlite3 module was written by Gerhard Häring. It provides an SQL interface compliant with the DB-API 2.0 specification described by PEP 249, and requires SQLite 3.7.15 or newer.
This document includes four main sections:
ok thx
One message removed from a suspended account.
One message removed from a suspended account.
then you can just send(embed=X, view=Y)
Question is unclear. Decorators are used to do stuff with a function (eg turn it into another function or some object) or a class, subclassing is OOP and is not directly related to decorators. Perhaps you forgot to specify the subject you are going to use decorators or subclassing for?
I specified discord.py. You can either create a client and then decorate your functions (coroutines) with decorators, or you can subclass Client. Specifically interested in the context of discord.py
I still can't understand the subject
I mean you typically would use decorators and subclassing for different subjects
Like subclassing for database, custom bot functions and other stuff; decorators ultimately for commands (in context of discord.py)
While you technically can use subclassing for commands (however that will be unholy af) I can't even think how you would implement additional functionality using dpy decorators
So there's no thing that is "better" to use, they are specific to the cases and solve different problems
I be direct:
client = discord.Client()
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
client.run(TOKEN)
vs
class CustomClient(discord.Client):
async def on_ready(self):
print(f'{self.user} has connected to Discord!')
client = CustomClient()
client.run(TOKEN)
This is probably the single case where decos and method overriding are interchangeable
Yeah for this one it doesn't matter much, I personally almost always subclass cause I have additional functionality. So if you subclass for something else, override this method as well. Subclassing solely for this method is ok too tho
I'm bored, someone please come here with a weird internal lib traceback issue that is actually caused by a typo
how to make it so people can only use a command in a specific channel
i had a friend recommending using Ruff and he gave me instructions to install poetry and all. But now since i lost his instructions i'm completely lost on what to do, i installed mypy, black and ruff for the configuration, but i'm still lost
.vscode:
settings.json
{
"python.analysis.extraPaths": [
"./database",
],
"[python]": {
"editor.defaultFormatter": "ms-python.black-formatter",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": "explicit"
},
},
"files.exclude": {
"**/__pycache__": true,
".mypy_cache": true
},
"ruff.organizeImports": false
}
extension.json
How do I create my own check deco again
{
"recommendations": [
"ms-python.python",
"zeshuaro.vscode-python-poetry",
"charliermarsh.ruff",
"matangover.mypy",
"ms-python.black-formatter"
]
}
I still receive erroers and my traceback seems to not being enabled
C:/Users/User/AppData/Local/pypoetry/Cache/virtualenvs/rp-utilities-2cgrnvKo-py3.11/Scripts/Activate.ps1
& : O arquivo C:\Users\User\AppData\Local\pypoetry\Cache\virtualenvs\rp-utilities-2cgrnvKo-py3.11\Scripts\Activate.ps1 não
about_Execution_Policies em https://go.microsoft.com/fwlink/?LinkID=135170.
No linha:1 caractere:3
+ & C:/Users/User/AppData/Local/pypoetry/Cache/virtualenvs/rp-utilities ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ErrodeSegurança: (:) [], PSSecurityException
+ FullyQualifiedErrorId : UnauthorizedAccess
okay guess the program is having issue with this:
Check the channel the command is being ran in and the desired channel
Mypy extension activated, version 0.3.0
Registering listener for interpreter changed event
Listener registered
[1] Check folder: c:\Users\User\Documents\GitHub\RP-Utilities
[1] Using extra arguments:
Activation complete
[1] Received Python path from Python extension: c:\Users\User\AppData\Local\pypoetry\Cache\virtualenvs\rp-utilities-2cgrnvKo-py3.11\Scripts\python.exe
[1] Running dmypy in folder c:\Users\User\Documents\GitHub\RP-Utilities
'C:\Users\User\AppData\Local\Programs\Python\Python311\Scripts\dmypy.EXE' --status-file 'c:\Users\User\AppData\Roaming\Code\User\workspaceStorage\7d9b54f5a8aa8c586d40915065449da4\matangover.mypy\dmypy-d26e67611339ec4bc1bc942196999aa8e80daf2d-4864.json' run --log-file 'c:\Users\User\AppData\Roaming\Code\User\workspaceStorage\7d9b54f5a8aa8c586d40915065449da4\matangover.mypy\dmypy-d26e67611339ec4bc1bc942196999aa8e80daf2d.log' -- --python-executable 'c:\Users\User\AppData\Local\pypoetry\Cache\virtualenvs\rp-utilities-2cgrnvKo-py3.11\Scripts\python.exe' . --show-error-end --no-error-summary --no-pretty --no-color-output
[1] stderr:
rp-utilities is not a valid Python package name
[1] Error running mypy in c:\Users\User\Documents\GitHub\RP-Utilities: mypy failed with error: "rp-utilities is not a valid Python package name
". See Output panel for details.
Solved
what did i did wrong i have no idea
how do i solve this mypy problem?
it's saying rp-utilities is not a valid Python package
this isn't a specific discord.py issue, I would just #1035199133436354600
Looks like mentions take up slightly more vertical space than plain text

Something wrong with this?
if rank == 1:
emoji = ":first_place:"
elif rank == 2:
emoji = ":second_place:"
elif rank == 3:
emoji = ":third_place:"
else:
emoji = ""
rank_display = f"{emoji}" if emoji else f"{rank}."
The ones with the emojis seem to be much closer together
It's just discord formatting
You'll have to find a way around it
Wtf
if you want to prevent the numbered list formatting, it seems like you can put a backslash in front of each period
Oh thanks
Why is it formatting anyway?
well, embed field values support markdown
i have this embed pinned for whenever i need to reference which parts of embeds support markdown
Cause it's an ordered list
No module found wavelink
search harder
Before we can help, please tell what you are using wavelink for
Music bot
Classic
I hope it does not download music from youtube-
No i'm using krypton open source code
Okay, but where do you get your music from
?
Well you don't AI generate it do you
No
I just added my bot token and run the code
, in <module>
async def on_wavelink_track_end(player: wavelink.Player, track: wavelink.Track, reason):
AttributeError: module 'wavelink' has no attribute 'Track'. Did you mean: 'tracks'?
Once again, where does the music come from
Are there local files that you own copyright for
how do you do set your bot's status to online from mobile
It's not possible. Not by regular means, you need to do some hacky shit
Wdym? Do you mean to run bot on mobile?
Should i send u full code
Oh
@pale zenith
Sorry, I do not know anything about wavelink
You should probably ask in their discord server:
https://discord.gg/RAKc3HF
Okay
i think he's asking where you got the music from, like where you downloaded the music/did you make it yourself
could be wrong
Precisely
data["embeds"] = [
{
"description" : "more text",
"title" : "This is a test",
"image" : [{"url": "htt p://a_cool_site.site" + file}]
}
]
{'content': 'message content', 'username': 'custom username', 'embeds': [{'description': 'more text', 'title': 'This is a test', 'image': [{'url': 'htt p://a_cool_site.site/uploads/Screenshot_2024-01-14_142626.png'}]}]}
400 Client Error: Bad Request for url: htt ps://discord.com/api/webhooks/the_id/secret_token
Someone who knows how to solve it?
first of all, there is obviously a space in the urls that doesn't belong there...
secondly, it's not even a valid api request url...
what is the_id and secret_token supposed to be?
Also, the code you pasted does not really seem to have anything to do with the error...
The ID and token of the webhook 🤷
Shocker 
well yeah, but it seems like they just copied a placeholder address without replacing the placeholders with actual values... Or am I reading it wrong?
like ofc you get an error, when trying to call that url...
interaction comes before button
(self, interaction, button) is the order. not (self, button, interaction)
you are probably following an old tutorial. OR just updated from a pre-release version of discord.py (older versions of the discord.py v2.0alpha used the latter order)
400 Bad Request typically means something about your payload is incorrectly structured
https://discord.com/developers/docs/resources/channel#embed-object
image? embed image object
https://discord.com/developers/docs/resources/channel#embed-object-embed-image-structure
url string source url of image (only supports http(s) and attachments)
following the documentation,embeds[].imageshould be given the object containing the url and not an array, or in other words it should look like:json [ { "description": "...", "image": {"url": "https://example.com/my_image.png"} } ]
How do I make a parameter optional?
@client.tree.command(name="map",description = "Display the current map.")
@app_commands.choices(mode=[discord.app_commands.Choice(name="Default",value=1),
discord.app_commands.Choice(name="Political",value=2),
discord.app_commands.Choice(name="Topography",value=3)])
async def map(interaction:discord.Interaction,mode: discord.app_commands.Choice[int]):
Such as mode?
you can wrap it in typing.Optional: ```py
from typing import Optional
@tree.command()
async def my_command(interaction, param: Optional[int]): ...
since Python 3.10, int | None is also equivalentor you can give the parameter a default value:py
@tree.command()
async def my_command(interaction, param: int = 0): ...```
thank you!
i dont think the Choice typehint is necessary though, what your command receives will always be one of the value= arguments from your choices decorator
It wont let me install discord on python because of a multidict error can any1 help?
the multidict dependency doesn't have any prebuilt wheels on python 3.12, so you should either:
- add
--extra-index-url https://abstractumbra.github.io/pip/to the end of yourpip installcommand which provides third-party 3.12 wheels for multidict - downgrade python to 3.11 and then reinstall discord.py
- follow the error message to install the C++ build tools before installing discord.py, though it requires about 6GB
for 1 should this work? C:\Users\Programs\Python\Python312/python.exe -m pip install --extra-index-url https://abstractumbra.github.io/pip/
don't forget to tell pip to install discord.py
C:\Users\Programs\Python\Python312/python.exe -m pip install discord.py --extra-index-url https://abstractumbra.github.io/pip/
this?
also that seems like an unusual place for your python installation to be placed at...
well assuming the python path is valid, sure
ye i had to move the folder cus my user folder was broken
eek, that doesn't sound good
Its because the name was my 1st and last name with a space inbetween so it didnt pick it up and i couldnt rename
oh, the normal way to work around that is to put quotes around the program you want to run, i.e. "C:\Users\My Name\AppData\Local\Programs\Python\Python312\python.exe" -m pip ... or in the case of python on windows, using the py launcher enabled by default in the python.org installer: py -m pip ... (assuming you didn't literally move the python installation files where it used to be, if so you'll need to move it back or repair it with the installer)
can i restrict discord.py slash command integer parameters to a certain range?
Like this
The above is from https://stackoverflow.com/questions/69561512/discord-js-v13-slashcommandbuilder-addintegeroption-set-range
ooo i found something
!d discord.app_commands.Range i assume?
class discord.app_commands.Range```
A type annotation that can be applied to a parameter to require a numeric or string type to fit within the range provided.
During type checking time this is equivalent to [`typing.Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated) so type checkers understand the intent of the code.
Some example ranges...
👍thanks
how do i create a dropdown with a bunch of options?
I'm seeing discord.ui.Select. Is it possible to have a dropdown in a slash command? That's what I'm after
For the user to select from a range of discrete choices
i think you probably want choices() or one of its alternative syntaxes
https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.app_commands.choices
note that they're hardcoded choices, if it needs to be unique to each user or otherwise generated dynamically, you'll need to use an @autocomplete() callback or a transformer that implements autocomplete()
https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.app_commands.Command.autocomplete
https://discordpy.readthedocs.io/en/stable/interactions/api.html#transformer
the latter might be nicer if you need to validate the user's input as autocomplete isn't allowed to restrict the user's input
Hm I'm getting TypeError: choices must all have the same inner option type as the parameter choice type
@app_commands.choices(voice=[
Choice(name='Sam', value=1),
Choice(name='Mike', value=2),
Choice(name='Mary', value=3),
Choice(name='BonziBUDDY', value=4),
])
async def say(self, ctx, text:str, voice:app_commands.Choice[str], pitch:app_commands.Range[int, 50, 400], speed:app_commands.Range[int, 50, 250]):
ah i changed the values
i think your command receives the value directly and not as a Choice instance, so im not sure if app_commands.Choice[str] is a valid typehint
besides than the inner type being different from the values that is
the inner type?
oh i mean str being a different type from your values 1, 2, etc.
ah I changed the values to strings now
that typehint I found on stack overflow. I'll try experimenting
status = Literal["online", 'idle', 'offline', 'dnd']
def _memberStatusStats(interaction: CommandInteraction) -> dict[status, int]:
statuses = groupby(interaction.guild.members, lambda m: m.status)
return dict(map(lambda k: (k[0], len(k[1])), dict(statuses)))
statuses = _memberStatusStats(interaction)
I didn't start up the bot for a while, seems like my command got outdated or something
Wait
could the error appear because there are no "IDLE" members?
What the fuck actually happened? 😂
2 different commands
But makes no sense to me, because i am using the same var in both commands
in guild members i am using lambda to distinguish humans from bots
@guild.sub_command()
async def members(self, interaction: CommandInteraction):
"""
List server members
"""
humans = len(list(filter(lambda m: not m.bot, interaction.guild.members)))
bots = len(list(filter(lambda m: m.bot, interaction.guild.members)))
statuses = _memberStatusStats(interaction)
em = Embed(
description=f"> {settings.emojis.members} Humans: `{humans}`\n"
f"> {settings.emojis.bots} Bots: `{bots}`\n"
f"> {settings.emojis.gd} Online: `{statuses['online']}`\n"
f"> {settings.emojis.wd} Offline: `{statuses['offline']}`\n"
f"> {settings.emojis.od} Idle: `{statuses['idle']}`\n"
f"> {settings.emojis.rd} DND: `{statuses['dnd']}`",
color=Color(settings.colors.embed),
)
em.set_author(name="Member Count")
await interaction.send(embed=em)
but i am using the same var
https://github.com/Rapptz/discord.py/blob/v2.3.2/discord/app_commands/transformers.py#L787-L789
judging from source code, voice: app_commands.Choice[str] technically works with discord.py as it creates a ChoiceTransformer for the typehint, but that transformer merely passes-through the value to your function so voice is actually just a str
it could be because there are no idle members, yes
Ok!
is _memberStatusStats a collections.Counter subclass? or something
you should be able to that_thing.setdefault('idle', 0)
I'm having a problem atm with discord registering my commands. Not sure what's up there. I've called self.bot.tree.sync() a few times. There doesn't seem to be an error
Well lambda should do detect all the members including bots statutes
It just randomly sends them, that makes it weird
you could also do x= {'idle': 0, ....}
x.update(dict(map(.....)))
mmmmm
so all have a default of 0 even if there aren't any
could it be syncing before your commands were added to the bot? especially if it came before loading your extension
though a few of us recently had our clients not see the new commands so you could try to ctrl+R and see if the commands show up
Alright it just started to work again. Not sure what I changed
Are you talking about the Literal?
nope, that function that uses groupby()
I've been syncing via command. I am guessing I misconfigured one of the slash command signatures or whatever and it didn't error out for me
https://docs.disnake.dev/en/stable/api/members.html#disnake.Member.status
i suspect the statuses are actually members of the disnake.Status enum rather than the strings you were expecting
so try indexing it with disnake.Status.idle instead
but you could also use a collections.Counter which returns 0 for empty keys
dang i didnt know counter had a key function
oh, it doesn't seem to
!d collections.Counter
class collections.Counter([iterable-or-mapping])```
A [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter) is a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) subclass for counting [hashable](https://docs.python.org/3/glossary.html#term-hashable) objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter) class is similar to bags or multisets in other languages.
Elements are counted from an *iterable* or initialized from another *mapping* (or counter):
```py
>>> c = Counter() # a new, empty counter
>>> c = Counter('gallahad') # a new counter from an iterable
>>> c = Counter({'red': 4, 'blue': 2}) # a new counter from a mapping
>>> c = Counter(cats=4, dogs=8) # a new counter from keyword args
I have never used collection, can you send me the package? Or is it part from disnake?
Oh nice
you're right, it doesnt haha
return collections.Counter([m.status for m in guild.members]) *would be appropriate
it would be soo nice if it had one, though
but I guess you accomplish the same with a listcomp/map so it doesn't really matter lol
mhm
Huh will return 0
omfg
counter[anything that's not counted] will give 0, rather than raising a KeyError
crap that's not what i need
My problem is that it also randomize the numbers, or i can't tell where they come from
could be this
🤔
Look at this
commands using the same variable
no members switched in that second
i have no idea what groupby() is or what it does. It could be that what messes it up
the numbers happen to be in the same order... were the emojis mixed up in the embed?
No
@guild.sub_command()
async def members(self, interaction: CommandInteraction):
"""
List server members
"""
humans = len(list(filter(lambda m: not m.bot, interaction.guild.members)))
bots = len(list(filter(lambda m: m.bot, interaction.guild.members)))
statuses = _memberStatusStats(interaction)
em = Embed(
description=f"> {settings.emojis.members} Humans: `{humans}`\n"
f"> {settings.emojis.bots} Bots: `{bots}`\n"
f"> {settings.emojis.gd} Online: `{statuses['online']}`\n"
f"> {settings.emojis.wd} Offline: `{statuses['offline']}`\n"
f"> {settings.emojis.od} Idle: `{statuses['idle']}`\n"
f"> {settings.emojis.rd} DND: `{statuses['dnd']}`",
color=Color(settings.colors.embed),
)
em.set_author(name="Member Count")
await interaction.send(embed=em)
.add_field(
name=f"{settings.emojis.activity} Status",
value=f"{settings.emojis.reply} {settings.emojis.gd} "
f"`{statuses['online']}`\n"
f"{settings.emojis.reply} {settings.emojis.od} "
f"`{statuses['offline']}`\n"
f"{settings.emojis.reply} {settings.emojis.rd} "
f"`{statuses['idle']}`\n"
f"{settings.emojis.reply} {settings.emojis.wd} "
f"`{statuses['dnd']}`\n",
)
this is inside guild info
wait i did mess them up
u smart dude i didn't even notice, i been coding all day didn't spend attention to small details
!pastebin
Hey how can I fix this error?
https://paste.pythondiscord.com/W2KA
Traceback (most recent call last):
File "C:\Users\berka\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\app_commands\commands.py", line 827, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\berka\Desktop\Partner Bot\cogs\setup.py", line 106, in setup
overwrite = pschannel.overwrites_for(self.bot.user.id)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\berka\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\abc.py", line 587, in overwrites_for
if overwrite.id == obj.id:
^^^^^^
AttributeError: 'int' object has no attribute 'id'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\berka\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\berka\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\berka\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\app_commands\commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'setup' raised an exception: AttributeError: 'int' object has no attribute 'id'```
that number has no attribute for id
noice an other spooky bot
my bot is also called spooky
overwrite = pschannel.overwrites_for(self.bot.user.id)
overwrites_for takes a Member or Role object. not an ID(int)
but it is created in js
Ohh, thanks
It's not the same one as that's currently being used
Updating does not work
It says that's not A command
Oh linux
Prefix it with whatever you prefix your install with instead of py
Oh I'm not even sure that commnad exists on Linux
Yeah it still says it's not a command
It also says the installation is satisfied for discord.py
No clue how to check the system interpreters on Linux
No idea but it's definitely installed
Well yes, but as previously mentioned you're using a different environment than you're installing into
This issue was solved in an update about a year ago
@sly hamlet are you on vps or just coding on linux
how do i can do music bot queue any tips?
how you do get that lines under players, games played and rank
Which part of it?
something like
'''
> member.mention
> member.mention
'''
using > before a sentence makes that sort of styling
thanks:)
async def beans(interaction:discord.Interaction, user:discord.Member):
await interaction.response.send_message("Succesfully sent Beans message", ephemeral=False)
await interaction.channel.send(f"Beans {user.mention}!") ```
its not showing up as a /command
does anyone know how to fix?
did you sync your CommandTree?
https://about.abstractumbra.dev/dpy
Check out the Application Commands Basics section 🙂
My site for random things and stuff. Including a custom pip index and walkthroughs, both for discord.py!
ok thanks
Does anyone know how to add tags when automating a forum post in discord.py. Found this documentation, but not sure how it works and how to get premade tags id https://discordpy.readthedocs.io/en/latest/api.html?highlight=thread#discord.ForumTag
!d discord.ForumChannel.available_tags is probably what you want
property available_tags```
Returns all the available tags for this forum.
New in version 2.1.
Thank you! I got the tags. As it seems now then automating post creation all i need to do is applied_tags=tag1,tag3 if im correct
inside a list yes, i.e. [tag1, tag3]
I Made a simple oauth callback it works and saves the discord user information but i want to give the user in my a role in my discord after completing the oauth2 how can i do this
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'avatar_url'
!D discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild).
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User).
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User) instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User) instances too.
hash(x) Returns the member’s hash.
str(x) Returns the member’s handle (e.g. `name` or `name#discriminator`).
Cheers boss
I Made a simple oauth callback it works and saves the discord user information but i want to give the user in my a role in my discord after completing the oauth2 how can i do this
Hello, I need some help. I'm trying to create a music bot in Python using ffmpeg and yt_dlp. However, when I use the command !play url, the bot joins the call, stays for about 5 seconds, and then disconnects. I can't figure out how to resolve this issue, please help.
Information appearing in the console after executing the !play command:
[2024-01-16 19:05:09] [INFO ] discord.voice_client: Starting voice handshake... (connection attempt 1)
[2024-01-16 19:05:10] [INFO ] discord.voice_client: Voice handshake complete. Endpoint found brazil9229.discord.media
[youtube] Extracting URL: https://www.youtube.com/watch?v=HJsv2IAYhkA
[youtube] HJsv2IAYhkA: Downloading webpage
[youtube] HJsv2IAYhkA: Downloading ios player API JSON
[youtube] HJsv2IAYhkA: Downloading android player API JSON
[youtube] HJsv2IAYhkA: Downloading m3u8 information
[2024-01-16 19:05:24] [INFO ] discord.player: ffmpeg process 13292 successfully terminated with a return code of 4294967274.
[2024-01-16 19:05:24] [INFO ] discord.voice_client: Disconnecting from voice normally, close code 1000.
[2024-01-16 19:05:24] [INFO ] discord.voice_client: The voice handshake is being terminated for Channel ID 1147392369130475633 (Guild ID 1147392368648126504)```
Code:
async def play(ctx, url):
# Verifica se o bot está em um canal de voz
if not ctx.author.voice or not ctx.author.voice.channel:
await ctx.send('Você precisa estar em um canal de voz para usar esse comando!')
return
# Obtém o canal de voz do autor da mensagem
channel = ctx.author.voice.channel
# Conecta ao canal de voz
vc = await channel.connect()
try:
# Cria uma instância do cliente yt_dlp
ydl = yt_dlp.YoutubeDL()
# Extrai informações do vídeo
info = ydl.extract_info(url, download=False)
url2 = info['formats'][0]['url']
# Adiciona opções para o FFmpeg
options = '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5'
# Inicia a reprodução de áudio no canal de voz
vc.play(discord.FFmpegPCMAudio(url2, options=options))
# Aguarda o término da reprodução antes de desconectar
while vc.is_playing():
await asyncio.sleep(1)
except Exception as e:
print(f"Erro ao reproduzir áudio: {e}")
finally:
# Desconecta do canal de voz
await vc.disconnect()```
@commands.Cog.listener()
async def on_raw_member_remove(self, payload):
guild_id = payload.guild.id
user_id = payload.user.id
await fun.approve_user(user_id=user_id, guildid=guild_id, approved=False)
``` why isnt this working? 🤔
depends on what "not working" means here
Traceback (most recent call last):
File "C:\Program Files\Python310\lib\site-packages\discord\client.py", line 375, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Gnome\Desktop\adminmaster\cogs\private_commands.py", line 109, in on_raw_member_remove
guild_id = payload.guild.id
AttributeError: 'RawMemberRemoveEvent' object has no attribute 'guild'
``` ;-;
!d discord.RawMemberRemoveEvent.guild_id
The ID of the guild the user left.
guild.id would imply there's a fully discord.Guild instance attached to the raw payload
which is unfortunately not the case
well it's a trade off
on_member_remove gives you nice objects but only if they're cached
lies I tell you, random member uncached leaves and it all breaks
the matrix is broken
Hey, how can I fix this error?
File "C:\Users\berka\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\bot.py", line 935, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Cooldown.init() takes 3 positional arguments but 4 were given
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\berka\Desktop\Partner Bot\main.py", line 392, in load
await bot.load_extension(f"cogs.{ext[:-3]}")
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.partner' raised an error: TypeError: Cooldown.init() takes 3 positional arguments but 4 were given
I'm trying to make my custom cooldown
Code:
async def is_premium(self, guild_id):
self.bot.db4 = await aiosqlite.connect(database="Database/premium.db")
async with self.bot.db4.cursor() as cursor:
await cursor.execute("SELECT guild FROM premium WHERE guild = ?", (guild_id,))
guild = await cursor.fetchone()
return guild is not None
class PremiumBypassCooldown(commands.Cooldown):
def __init__(self, rate, per, premium_check):
super().__init__(rate, per, commands.BucketType.guild)
self.premium_check = premium_check
async def update_rate_limit(self, current=None):
guild_id = self._bucket_key
if await self.premium_check(guild_id):
return None
return super().update_rate_limit(current)
@app_commands.commands.command(name="partner", description="Partner with this guild to another guild")
@app_commands.checks.cooldown(1, 120, type=PremiumBypassCooldown(per=1, rate=120, premium_check=is_premium))
@app_commands.checks.bot_has_permissions(send_messages=True)
async def partner(self, interaction: discord.Interaction, guild_id: str):```
dpy 2.0 changed how cooldowns were implemented so now commands.Cooldown is an alias of app_commands.Cooldown, and it no longer handles bucket keys
https://github.com/Rapptz/discord.py/blob/v2.3.2/discord/app_commands/checks.py#L91
discord/app_commands/checks.py line 91
def __init__(self, rate: float, per: float) -> None:```
the cooldown check for app commands also only takes a key= function, what you want instead is the dynamic cooldown decorator
!d discord.app_commands.checks.dynamic_cooldown
@discord.app_commands.checks.dynamic_cooldown(factory, *, key=...)```
A decorator that adds a dynamic cooldown to a command.
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns are based off of the `key` function provided. If a `key` is not provided then it defaults to a user-level cooldown. The `key` function must take a single parameter, the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) and return a value that is used as a key to the internal cooldown mapping.
If a `factory` function is given, it must be a function that accepts a single parameter of type [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Cooldown) or `None`. If `None` is returned then that cooldown is effectively bypassed.
Both `key` and `factory` can optionally be coroutines.
Quick question
Nvm'
Thanks for the help though
Update: I got the gist on how to make dynamic cooldowns but I have a different problem and the problem is filling in the arguments that I made for the dynamic_cooldown function that I made
@app_commands.commands.command(name="partner", description="Partner with this guild to another guild")
@app_commands.checks.dynamic_cooldown(lambda interaction, self: self.is_premium(interaction=interaction, self=self))
@app_commands.checks.bot_has_permissions(send_messages=True)```
```py
async def is_premium(self, interaction: discord.Interaction) -> [app_commands.Cooldown]:
self.bot.db4 = await aiosqlite.connect(database="Database/premium.db")
async with self.bot.db4.cursor() as cursor:
await cursor.execute("SELECT guild FROM premium WHERE guild = ?", (interaction.guild.id,))
guild = await cursor.fetchone()
if guild:
return None
else:
return app_commands.Cooldown(1, 180)
!pastebin
Error^
that only happens when they don't collaborate/don't put in some effort
