#discord-bots
1 messages · Page 267 of 1
Whats transformer?
oh yeah did you sync your command after adding the autocomplete?
I did, i try to sync them periodically as i make small changes and want to make sure they go through
do you have any kind of error handler defined?
hm what shows up on discord when you start typing something to that option?
can you put print statements across your command (one at the start, before the cooldown check, etc.) to see how far it gets through your command?
Doesnt pop up with any options
doesnt look like the autocompleted is registered on discord's side at all
normally it would tell you "loading options failed" or similar if your bot couldnt respond to autocomplete requests
Yeah, i was thinking i was messing up somewhere
id try syncing that command again as dpy should know to tell the discord API that it's accepting autocompletion for that option
unless its actually syncing some other info command instead of the one in your earlier snippet
when i have the snippet above, it doesn't recognize it as a slash command at all
when i go back to the @bot.tree.command decorator, it pops up like it should
when i try to use the auto with the tree.command, it does what the pic shows
err yeah, @app_commands.command() defines a command without adding it to your bot
did you try using your tree command and autocomplete decorators together?
like @bot.tree.command.autocomplete?
no, i mean applying both decorators one after another: ```py
@app_commands.command(...)
@bot.tree.command(...)
@app_commands.autocomplete(...)
async def my_command(interaction, ...):```
i didn't try it like that, let me give it a go
so command is being invoked, but something is either blocking indefinitely or raised an error that got suppressed somehow
to rule out the error, can you put the entire body of your function in a try except like the following: py try: ... except Exception: import traceback traceback.print_exc() raise
give me a bit, when i try that, i'm getting another issue i've never seen before that i'm trying to figure out before i can say if it works or not
@hushed galleon you are awesome. i doubt i'm doing it the most efficient way, but that at least gets the list to pop up and is giving me actual errors to work on. I really appreciate your help and your time, tbh one of the few in a few servers that spent it to help.
@tough kernel if you aren't already, you should join the official discord.py discord server. It's the number one place for learning discord.py and asking questions from people (many of whom are active developers of the package)
I didnt realize there was one! I really appreciate and will look for it!
@tough kernel there's a link on the official rtd
TYVM!
It's in the channel's topic
Good afternoon!
The question is, is it possible to somehow make 2 responses in one interaction with the button
@discord.ui.button(label='📦', style=discord.ButtonStyle.blurple, custom_id='persistent_view:downloadsong')
async def btn_downloadsong_callback(self, interaction: discord.Interaction, button: discord.ui.Button):
button.disabled = True
await interaction.response.edit_message(view=self)
server = servers.get(interaction.guild)
...
button.disabled = False
await interaction.response.edit_message(view=self)
!d discord.Interaction.edit_original_response
await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
Thank you!
how can I make the text sent by bot into bold, italics, et cetera
same way you send them as a user on discord
I'll see
bold text, some underlines, italics etc
oh ok it works, thought it didn't last time. Thanks.
Also, any way to show text as embed?
!d discord.Embed you mean one of these?
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
I'll try it out
how do i make 1 file run 3 diff ones (not cogs)
i checked it ...its in 6 servers
do await ctx.send(str({g: len(g.members) for g in bot.guilds}))
if they are functions then you can import them to your main file set em up
how do i mention the user who called the command in a normal prefix command
cursed emote cut me off
ctx.author.mention?
#Slash Command Test
@bot.tree.command(name="hello")
async def hello(interaction: discord.Interaction):
await interaction.response.send_message(
f"Hi {interaction.user.mention}! This is a slash command")
This but in normal way. Without slash
yes works in commands
@bot.command()
async def hello(ctx):
await ctx.send("{} hi")
sum like that
@bot.command()
async def hello(ctx):
await ctx.send("f{ctx.author.mention} hi")```
@bot.command()
async def hello(ctx):
interaction = discord.Interaction()
await ctx.send(f"Hey {interaction.user.mention} :D")
I tried this but yea, error
oh ok
Why are you creating Interaction objects yourself
yhea ma bad
then can you tell me where are you setting up the activity?
to learn things?
sorry, not that sure how classes work here
like is it in on_ready or setup_hook?
i have on_ready in the code
then it might be because the activity is being setup before the bot caches the data
try using wait_until_ready
lemme try the one you sent first
got all the guilds ids and name
ok works. Thanks
gays can some one give me any tutoruial how to create a pagination with buttons ?
ohh its in a server with 47k members
idk how its surviving there and who added it?
good for u
what do u want to do ?
then?
not working with me
you lost
yp
ahh
i like do APIs and stuff
yp
im good at it
do u know how to create discord pagination with butttons ?
i made bot with minecraft API supercell API
nahh i never tried buttons
in discord.py
yet
man i love u i also create a bot for my website
mine craft
ya same as me
you own minecraft?
try using wait_until_ready if you are setting up presence in on_ready
no i lost my acount
mm i think it will work
since it might be due to your presence being setup before the bot cache
do u know how to create discord pagination with butttons ?@turbid condor
oh so sad!!
sadly no i tried messing with paginations but hardly managed to get them to work
yes i have many errors
ummm so?
why?
it makes my bot slow?
it's used like this py @bot.event async def on_ready(): await bot.wait_until_ready() #rest of the code
oh kayyyy
no u are just sending extra requests
and it may cause an error
class MyClient(discord.Client):
def __init__(self, *, intents: discord.Intents):
super().__init__(intents=intents)
self.tree = app_commands.CommandTree(self)
async def setup_hook(self):
self.tree.copy_global_to(guild=MY_GUILD)
await self.tree.sync()
this will work better for sync your commands
That's not any better
not needed just create a command
that's better
since you don't need to sync everytime the bot starts
only some special case
okay
Sync when you...
Basic
- Added/Removed a command
- Added/Removed autocomplete (decorator, transformer)
- Added/Removed an argument
- Added/Modified/Removed locale strings
- Converted the global/guild command to a guild/global command
Modify
Changed a command's... - name (name= kwarg, function name)
- description (description= kwarg, docstring)
Changed an argument's... - name (rename decorator, param name)
- choices (Literal, choices decorator, enum type)
- description (describe decorator, docstring)
- type (arg: str str is the type here)
Permissions
Added/Modified permissions: - default_permissions (decorator, kwarg)
- nsfw (kwarg)
Added/Modified contexts: - guild_only (decorator, kwarg)
Soon™️ ( App command contexts ): - allowed_contexts (kwarg)
- dm_only decorator, kwarg)
- private_channel_only decorator, kwarg)
Do not sync when you... - Changed anything in the command/autcomplete function's body (after the async def (): part)
Added/Modified/Removed library side checks: - (@)app_commands.checks...
- (@)commands...(.check)
- @app_commands.checks.(dynamic_)cooldown(...)
This is the same for hybrid app commands
These are the cases when you need to sync
what's the application command version of on_command_error?
Need a global error handler for application commands
or is it still on_command_error?
!d discord.app_commands.CommandTree.error
@error(coro)```
A decorator that registers a coroutine as a local error handler.
This must match the signature of the [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.on_error "discord.app_commands.CommandTree.on_error") callback.
The error passed will be derived from [`AppCommandError`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.AppCommandError "discord.app_commands.AppCommandError").
If you're using discord.py
the CommandTree is accessed via bot.tree if you're using commands.Bot
Using a client, and yeah -- discord.py
But anyway, thanks!
wait, isn't that just for a single command / local?
or am I confused
it's a handler for the whole tree
it will catch exceptions from any app command which is attached to it
@tree.error
async def on_app_command_error(interaction, exc):
...
npnp
@grim rock
here is the code it will work
@client.event
async def on_ready():
print(f'Logged in as {client.user} (ID: {client.user.id})')
await client.wait_until_ready()
total_members = 0
for guild in client.guilds:
total_members += guild.member_count
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f"{total_members}"))
instead of giving them the code just give them instructions that will help them learn
okay but it think its a litle thing dont need that much to learn
You should use len(bot.users) to get the unique user count
Calculating it with guild.member_count will include the same users in different guilds
oh thx
2023-07-09 13:14:44 ERROR discord.client Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\Users\avira\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "D:\Projects\discoord bot\bot.py", line 88, in on_ready
await client.wait_until_ready()
^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Resource' object has no attribute 'wait_until_ready'
how did you define client
@bot.command()
async def inspire(ctx):
quote = get_quote(0)
qauthor = get_quote(1)
embed = discord.Embed (
colour=discord.Colour.green(),
title="*Quotes*",
#discription=quote
)
embed.set_footer(text=qauthor)
await ctx.send("\n"+quote, embed=embed)
how can I get discription to print whatever text quote will have
discription=quote didn't work
what get_quote is?
weren't u using bot?
oh shit, sorry guys, didn't see the typo
that didnt work
wdym that didn't work?
just in case:
def get_quote(check):
response = requests.get("https://zenquotes.io/api/random")
json_data = json.loads(response.text)
quote = json_data[0]['q']
#quote = json_data[0]['q'] + "\n-" + json_data[0]['a']
qauthor = json_data[0]['a']
if check==0:
return (quote)
elif check==1:
return (qauthor)
- requests already has a method to load response from json using
.json()no need tojson.loads - dont use blocking libraries in discord bot
instead of requests use aiohttp
requests works fine

of command?
of how you set the status
the activity set
- dont set status in on_ready it can be called many times
- why you have
.wait_until_readyif you are already in an event that is called when this happens - why use
guild.member_count
wouldn't len(bot.users) be used instead?
you forgot to mention auto syncing
wait why is he incrementing total users by bot.users for each guild
i know but too hard to explain i belive
someone told me
so you just copy pasted something and dont even know how it works
here
just remove the for loop and instead of totalUsers put this
then don't use wait_until_ready as your bot will get stuck
i already said why even have that line
if the event is already called when this happens
sorry I didn't get point 1
async def get_quote(check):
response = requests.get("https://zenquotes.io/api/random")
json_data = json.loads(response.text)
quote = json_data[0]['q']
#quote = json_data[0]['q'] + "\n-" + json_data[0]['a']
qauthor = json_data[0]['a']
if check==0:
return (quote)
elif check==1:
return (qauthor)
also I found this on the site. Is this what you meant?
Yes to use aiohttp instead
Please don't use white theme. It kills eyes.
Is import asyncio not needed?
White theme is from the site, also I switch from dark to light on phone when I'm bored of seeing it
No, since you use aiohttp and not asyncio
its just the documentations seem to say that in order to use async & await we need to import asyncio but since nothing wrong has happened so far, I'm wondering if something's up
Because they use asyncio to sleep() and run()
where did I go wrong
async def get_quote2(check):
async with aiohttp.ClientSession() as session:
async with session.get("https://zenquotes.io/api/random") as response:
json_data = await response.json()
quote = json_data[0]['q']
#quote = json_data[0]['q'] + "\n-" + json_data[0]['a']
qauthor = json_data[0]['a']
if check==0:
return (quote)
elif check==1:
return (qauthor)
First, say what's wrong
this is how the original one looked
def get_quote(check):
response = requests.get("https://zenquotes.io/api/random")
json_data = json.loads(response.text)
quote = json_data[0]['q']
#quote = json_data[0]['q'] + "\n-" + json_data[0]['a']
qauthor = json_data[0]['a']
if check==0:
return (quote)
elif check==1:
return (qauthor)
json_data = await response.json() ?
What's wrong with it then
either improper usage of await or I have to put something in .json()...?
What?
I don't know if that was the right way to use .json()
!d aiohttp.ClientResponse.json
coroutine json(*, encoding=None, loads=json.loads, content_type='application/json')```
Read response’s body as *JSON*, return [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)") using specified *encoding* and *loader*. If data is not still available a `read` call will be done,
If *encoding* is `None` content encoding is autocalculated using [cchardet](https://aiohttp.readthedocs.io/en/stable/glossary.html#term-cchardet) or [charset-normalizer](https://aiohttp.readthedocs.io/en/stable/glossary.html#term-charset-normalizer) as fallback if *cchardet* is not available.
if response’s content-type does not match content\_type parameter [`aiohttp.ContentTypeError`](https://aiohttp.readthedocs.io/en/stable/client_reference.html#aiohttp.ContentTypeError "aiohttp.ContentTypeError") get raised. To disable content type check pass `None` value.
Why didn't you just try it and see, anyway
I got something like this
I'm starting to get 503 errors with this code. How can I change my code to avoid this kind of error?
@tasks.loop(seconds=60)
async def auto_delete_messages():
try:
# Get the channel
channel = client.get_channel(712074759453671494)
# Calculate the timestamp before which messages should be deleted
delete_before = discord.utils.utcnow() - datetime.timedelta(hours=4)
# Delete messages older than 4 hours and not pinned messages
await channel.purge(limit=100, check=lambda msg: not msg.pinned, before=delete_before, reason="Time-based message cleanup")
except discord.errors.DiscordServerError as e:
# Rest of the code```
503 errors!?!?!?!?!?!?
Unbelievable
I think he meant error 503
Yeah 😅 How can I avoid to print the entire HTML code for error messages?
except discord.errors.DiscordServerError as e:
# Handle the specific exception
if e.status == 503:
# Handle the 503 error
print("Service Unavailable error occurred. Retrying...")
else:
# Handle other DiscordServerError exceptions
print(f"An error occurred: {e}")
except Exception as e:
# Handle any other exceptions that might occur
print(f"An error occurred: {e}")```
Hard to believe that making just one API call every 60 seconds would be sufficient to override the rate limit
I remember seeing huge dumps from Cloudflare 🤷
U sure deleting 100 messages is one api call?
discord/abc.py line 128
async def _purge_helper(```
dosent seem to be one api call
https://github.com/Rapptz/discord.py/blob/270fa5f2e0d7eca396f9df0bcc9ad0e643c2fe9a/discord/abc.py#L123 it iterates over the messages calling delete method on it
discord/abc.py line 123
async def _single_delete_strategy(messages: Iterable[Message], *, reason: Optional[str] = None):```
That's ridiculous
If the bulk argument is True (it is by default), then discord.py will tell discord to delete in bulk
Which can require a single API call
If not always a single API call
!d discord.TextChannel.delete_messages
await delete_messages(messages, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes a list of messages. This is similar to [`Message.delete()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message.delete "discord.Message.delete") except it bulk deletes multiple messages.
As a special case, if the number of messages is 0, then nothing is done. If the number of messages is 1 then single message delete is done. If it’s more than two, then bulk delete is used.
You cannot bulk delete more than 100 messages or messages that are older than 14 days old.
You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") to do this...
discord/abc.py line 148
strategy = channel.delete_messages if bulk else _single_delete_strategy```
Data application: MySql
restore role when coming in
Does anyone know the error?
role = discord.utils.get(member.guild.roles, id=int(role_id))
if role:
await member.add_roles(role)
File "c:\Users\User\Desktop\XXXBOT\XXX.py", line 50, in on_member_join
await member.add_roles(role)
error
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "c:\Users\User\Desktop\XXXBOT\XXX.py", line 50, in on_member_join
await member.add_roles(role)
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\member.py", line 1051, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 741, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10011): Unknown Role```
It just says that the role you are trying to find is not being find
how do I add comments below the /hello
#Slash Command Test
@bot.tree.command(name="hello")
async def hello(interaction: discord.Interaction):
await interaction.response.send_message(
f"Hi {interaction.user.mention}! This is a slash command")
Docstring
!d discord.app_commands.CommandTree.comamnd
No documentation found for the requested symbol.
!d discord.app_commands.CommandTree.command
@command(*, name=..., description=..., nsfw=False, guild=..., guilds=..., auto_locale_strings=True, extras=...)```
A decorator that creates an application command from a regular function directly under this tree.
The description argument
thanks. also I figured out where to put await
SyntaxError
just an example i know i forgot to put ctx
no
the command doc is not indented
!E ```py
async def ping():
"""DESCRIPTION IS THIS"""
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | File "/home/main.py", line 2
002 | """DESCRIPTION IS THIS"""
003 | ^
004 | IndentationError: expected an indented block after function definition on line 1
but error is the same
i see
that is just codeblock issue i'm sure i indented it
!e print(IndentationError.mro)
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
(<class 'IndentationError'>, <class 'SyntaxError'>, <class 'Exception'>, <class 'BaseException'>, <class 'object'>)
yeah IndeantationError is subclass of SyntaxError
Any idea?
# Global var
last_game_start_time = None
if last_game_start_time is not None or (datetime.datetime.now() - last_game_start_time).total_seconds() > 180:```
Unexpected type(s):(None)Possible type(s):(timedelta)(_D)(datetime)(timedelta)
full traceback
You have an or there, which is why your linter is complaining
oh i see you cant subtract None from datetime.datetime possibly
How can I solve this?
i dont know what you are trying to achieve
just use and so the second part will never be evaluated if last_game_start_time is None
or perhaps the condition is meant to be is None or ...
You are right 🙂
But still getting the error:
Unexpected type(s):(None)Possible type(s):(timedelta)(_D)(datetime)(timedelta)
cause you have or
No
yes the second part is evaluated cause of this
Not really an error but a warning
did you write is None and ...?
Doesn't change it
i know, cause its wrong
think about what your if-statement is supposed to do, do you want it to proceed if your start time is not yet set?
No that is the point
can you show the full traceback in your console alongside how you defined /setlogchannel?
@bot.command()
@commands.has_permissions(administrator=True)
async def setlogchannel(ctx, channel: discord.TextChannel):
c.execute("INSERT OR REPLACE INTO settings (server_id, channel_id) VALUES (?, ?)", (ctx.guild.id, channel.id))
conn.commit()
bot.log_channel = channel
await ctx.send(f"Log channel set to {channel.mention}")
its prefixed command and you used slash command
so therefore the first part of your condition should be start_time is not None
do you understand why using or/and affects whether now() - start_time causes a TypeError?
no wait
i have one with slash
but i forgot to dlt this
@bot.tree.command(name="setlogchannel", description="configure log channel")
@commands.has_permissions(administrator=True)
@app_commands.describe(value = "Set Log channel for bot logs [Default = None]")
async def setlogchannel(interaction: discord.interactions, value: discord.TextChannel):
bot.log_channel = value
c.execute("INSERT OR REPLACE INTO settings (server_id, channel_id) VALUES (?, ?)", (interaction.guild.id, value))
conn.commit()
await interaction.response.send_message(f"Log channel set to {bot.log_channel}", ephemeral=True)
Yes, "or" checks the first condition, if it is true, it won't check the second condition. "and" will check both conditions
you annotate the interaction to discord.interactions whatever that is
also issue is possibly with that you cannot annotate parameter in slash command as TextChannel
right, so which one is the correct operator to join your conditions start_time is not None with now() - start_time?
also commands.has_permissions does not work on slash commands
!d discord.app_commands.checks.has_permissions use this instead
if last_game_start_time is None or (current_time - last_game_start_time).total_seconds() > 10:
@discord.app_commands.checks.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check") that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the permissions given by [`discord.Interaction.permissions`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.permissions "discord.Interaction.permissions").
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingPermissions "discord.app_commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure").
New in version 2.0...
then what works?
this
okayyyyyyyyyyy
you've declared value as a TextChannel object but passed it directly to your SQLite database, which doesn't understand what a TextChannel object is - perhaps you wanted to store the .id of that channel?
no server id with log channel id
oh earlier i thought you didnt want your statement to pass if start_time wasnt set
so yes you do want to store the channel id, in which case value.id is how you would get the ID from your TextChannel
The issue is that it cannot subtract None from datetime.datetime, and because of this, it's giving me a warning. The code will work as expected, but the warning is not nice right
btw this is the bottom half of the error, if you scrolled up a bit more you'd likely see sqlite3.ProgrammingError which makes it a bit more obvious what's causing the issue
your linter's not wrong though, by writing start_time is not None or now - start_time > 180s your first condition guarantees that start_time is None when its subtracted (same for the reverse, start_time is None and ...)
a fren sent this code
async def send_message(message, user_message,is_private):
try:
response=responses.handle_response(user_message)
await message.author.send(response) if is_private else await message.channel.send(response)
except Exception as e:
print(e)
I'm not sure what he's trying to achieve. Is it dm?
I haven't started exploring DMs and ephemeral messages yet
hmm, felt a bit of deja vu seeing that snippet #help-donut message (or #1068373735343652937 message)
2023-07-09 21:21:30 ERROR discord.app_commands.tree Ignoring exception in command 'setlogchannel'
Traceback (most recent call last):
File "C:\Users\avira\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\app_commands\commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Projects\discoord bot\bot.py", line 132, in setlogchannel
c.execute("INSERT OR REPLACE INTO settings (server_id, channel_id) VALUES (?, ?)", (interaction.guild.id, value))
sqlite3.ProgrammingError: Error binding parameter 2: type 'TextChannel' is not supported
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\avira\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\app_commands\tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\avira\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\avira\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\app_commands\commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'setlogchannel' raised an exception: ProgrammingError: Error binding parameter 2: type 'TextChannel' is not supported
So you mean that I should ignore the warning?
you cant pass TextChannel object directly to database
use id
its relatively simple, invoking the send() method on a User/Member object sends them a direct message, and if you're responding to an interaction with a message, i.e. interaction.response.send_message(), you have the option to specify ephemeral=True as an argument to send an ephemeral message
id like?
The channel ID.
quite the opposite, there are only two correct ways to write your condition
OKAY
you already did it in prefixed command
Well I can't use (current_time - last_game_start_time).total_seconds() if last_game_start_time = None
LIKE bot.log_channel = value.id
Because this is what is giving me the warning
no when saving to database save the channel id
think about it this way: ```py
x = None # or 1234
Which of the following does not cause a TypeError:
- x is None or x > 100
- x is None and x > 100
- x is not None or x > 100
- x is not None and x > 100``` two are always valid, two can cause an error (and your linter will tell you if it can cause an error)
How do I make custom Discord bots?
404 error...my internet problem?
idk maybe send the error
None of them removes the warning message
did you save after each change to make sure your linter checked again?
HOW I CAN MAKE DIFFRENT FILE FOR EVER COMMAND?? IS IT HELPFUL
you can create cogs to separate commands across many files
but i would separate it by some categories not one command per file
OH..
maybe one file is enough
one string is enough
do i need to turn the dm_channel_read on?
Go to your IDE and type this:
last_game_start_time = None
@client.command(name='remake')
async def remake_command(ctx):
current_time = datetime.datetime.now() # Get the current time
if last_game_start_time is None or (current_time - last_game_start_time).total_seconds() > 10:
embed = discord.Embed(
title='',
timestamp=datetime.datetime.now(),
description='Remake is no longer available. You can no longer start a new game.',
color=discord.Color.red()
)
await ctx.send(embed=embed)
else:
embed = discord.Embed(
title='',
timestamp=datetime.datetime.now(),
description='OKAY.',
color=discord.Color.green()
)
await ctx.send(embed=embed)```
maybe even thats too much
And tell me you're not getting any warning messages
oh yeah the missing typehint for start_time might be confusing your linter
How to remove response messages in 5 seconds
Do you know how to solve it?
@young dagger
add a typehint saying it could be a datetime or None
@hushed galleon
from typing import Optional
last_game_start_time: Optional[datetime.datetime] = None```
Type hinting 
for type checkers it does
Can you help me
Well that removed the warning, thank you
How to remove response messages in 5 seconds🤔🤔
delete_after kwarg when sending a message
await asyncio.sleep(5)
await message.delete()
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
There's a delete_after kwarg, use it.
with?
Not if you want to get rid of the warn message
Unexpected type(s):(None)Possible type(s):(timedelta)(_D)(datetime)(timedelta)
Grab some popcorn and read the conversation 👍
Well I could use last_game_start_time = 1974 as well. I don't know any other ways. But if you find any please let me know
yeah i didnt realize it was the inferred type being part of the problem, but tbf i dont think any language would do any better - what else could you say about the type of x = None other than None?
hence why inferring the type of None is usually pretty meaningless
but i guess your type checker already tells you that if you try assigning anything else to it
Okay. I found another solution:
if last_game_start_time is None:
return
elif isinstance(last_game_start_time, datetime.datetime) and (current_time - last_game_start_time).total_seconds() > 10:
return```
hmm i thought your linter didnt have the concept of a Never type though
#type-hinting would be a better place to talk further about this
if last_game_start_time is None or (isinstance(last_game_start_time, datetime.datetime) and (current_time - last_game_start_time).total_seconds() > 10)```
i meant this: ```py
if something:
return
if something_more:
return
return will already quit the function so second if wont be checked anyways
Why not just use or?
wasnt your first error being caused by the or
Nope
also this is more readable
what
show the code maybe
@bot.tree.command(name="setlogchannel", description="configure log channel")
@discord.app_commands.checks.has_permissions(administrator=True)
@app_commands.describe(value = "Set Log channel for bot logs [Default = None]")
async def setlogchannel(interaction: discord.interactions, value: discord.TextChannel):
bot.log_channel = value
c.execute("INSERT OR REPLACE INTO settings (server_id, channel_id) VALUES (?, ?)", (interaction.guild.id, value.id))
conn.commit()
embed=discord.Embed(title=f"DONE :thumbsup:", description=f"Log channel was set to {bot.log_channel}", colour=0xff0000)
await interaction.response.send_message(embed=embed, ephemeral=True)
..
Maybe don't add these weird empty spaces
you made it to post is in such big separation
nah i added spaces after that
Which leads to the result you have
why would you add it if it was not here when the issue was already
no spaces
2023-07-09 22:48:10 INFO discord.voice_client Connecting to voice...
2023-07-09 22:48:10 INFO discord.voice_client Starting voice handshake... (connection attempt 1)
2023-07-09 22:48:10 INFO discord.voice_client Voice handshake complete. Endpoint found india1813.discord.media
2023-07-09 22:48:57 INFO discord.voice_client The voice handshake is being terminated for Channel ID 930307747872903188 (Guild ID __________)
2023-07-09 22:48:57 INFO discord.voice_client Disconnecting from voice normally, close code 1000.
``` as it's connecting to voice channel but not playing music
anyone ?
can you share your code?
If you've set the after parameter of VoiceClient.play, are you handling the exception properly?
https://sourceb.in/m3z2x3FJWf here u go
track_url = track["external_urls"]["spotify"]
does this url actually point to an audio file
or does it point to some spotify track link
show json
i guess like if i add a url also its show me this
why would that work
you're searching the spotify api for a youtube link
anyways, doesn't look like your code is going to work at all
not like playing songs from youtube is against their tos
the api can only provide you with the preview you hear when you hit the play button on that embed iirc
you talking about this embed when you send spotify link?
when you hit play it plays preview of the song right
yep
any way to fix it ? like i can make changes ?
You shouldn't make a music bot, it goes against ToS of both spotify & youtube - we can't provide you help with it
im afraid we wont be able to help with it anyways
okay thanks so like i should re-code it whole ?
This interaction failed
@client.event
async def on_button_click(interaction: discord.Interaction):
if interaction.component.label == "Click me!":
await interaction.respond(content="Button clicked!")
@client.event
async def on_message(message):
if message.content.startswith('!button'):
embed = discord.Embed(
title='',
timestamp=datetime.datetime.now(),
description='Remake initiated. Click the button below to vote for a remake.',
color=discord.Color.green()
)
btn = Button(style=discord.ButtonStyle.green, label="Click me!")
view = View()
view.add_item(btn)
await message.channel.send(embed=embed, view=view)```
Which library is this?
no such event on_button_click
You should go through the buttons examples in the discord.py GitHub repo if that's what you are using
https://github.com/Rapptz/discord.py/blob/master/examples/views/counter.py here's a nice example
class SelfRoles(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="Valorant", style=discord.ButtonStyle.red)
async def blurple_color(self, interaction: discord.Interaction, Button: discord.ui.Button):
blurple_role = discord.utils.get(interaction.guild.roles, name="Valorant")
await interaction.user.add_roles(blurple_role)
await interaction.response.send_message('Success! Role has been added to your account', ephemeral=True)
@client.command(name="addrole")
async def self_role(ctx):
embed=discord.Embed(title="Select your favorite games for access to their channels!")
embed.set_image(url="https://cdn.wallpapersafari.com/91/23/unNTG4.jpg")
await ctx.send(embed=embed,
view=SelfRoles())```
This is how you do a button reaciton role,
Thanks Jimy
no problem!
you have commands imported right?
from discord.ext import commands
client=commands.Bot(prefix="prefix")```
Yes
kk just checken
@young dagger man i am so sorry but can you help me?
How to create a channel?
While
Man can you help me?
in what?
go on google try to find it...try it...struggle for it....modify it ..this is bets way to learn
if u still fail...then only come here
(heavy motivation)
simple as that
I can't find
you cant find what
Send me link
Bruh i can't find
type in what i did
You want to create a channel with the bot right?
While
While what?
!d discord.Guild.create_text_channel
await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") for the guild.
Note that you must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to create the channel.
The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.
Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
What's that mean 
Can you send me an example
What did you mean by "while" and "I create channel spam"?
you already have an example on stack
What is "I create channel spam" supposed to mean? I'm still not sure what question you're asking?
sounds like nuke bot kinda
Yes

💀💀💀💀
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
well then no example for you
We don't help with those here, sorry

why sorry though
Can I use this for my buttons? raise discord.DiscordException("You can only click the button once.")
I'm trying to be courteous.
I'm sure you could, but to accomplish what?
Do you want to send that message to the user?
Yeah
i wouldnt raise exception for that
If so, raising that exception is not going to get propagated to the user automatically (unless you've it set up that way, of course)
just send message or smth
Instead of the classic message This interaction failed
You can use the traditional interaction.response.send_message to tell the user they can only click it once
You can also disable the button
you can send any message informing why they cant use the button
Thanks 

apparently random docs does not exist
Can I make the message only visable for the user?
yeah you can
you just set the ephemeral to True
!d discord.InteractionResponse.send_message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
There's an ephemeral=True keyword argument in send_message
Something is wrong
https://paste.pythondiscord.com/vosisanafu
It doesn't allow others to vote
Yeah, your view doesn't take into account who clicked it 😛
It only takes into account if someone has clicked it
You are right. Should I keep it in a list?
self.clicked_users = []
if interaction.user.id not in self.clicked_users:
self.clicked_users.append(interaction.user.id)```
that is indeed one approach
hi guys can someone help me pls
Do you have any files or folders named discord?
as i know, no :/
Does import discord work?
Or, do you even have import discord?
You need to have that first before you can do from discord.ext import commands
import discord
from discord.ext import commands
The order here is important
yeah i know but that's not the problem :/
This traceback says from discord.ext import commands is on line 1 of your program
The yellow squiggly means you either don't have discord.py installed or your interpreter can't find it
but i use pycord
pip discord.....................
instead of discord.py :/
Ah, I can't help with pycord, sorry. I know they changed a lot of stuff's locations around so it might be that 
ah
mhm ?
can someone help me abt that ? (pycord)
Are you new to PY?
no
PY good place to install plugins
bruh
||Are you new to PY😂 ||
why are you using chatgpt to give you instructions how to install discord.py 😭
🤣
Teach her how to answer with ||chatgpt|| 😂
@fickle crown please don't use ChatGPT to provide answers, see rule #10
Also their problem is completely unrelated to what you gave them
Hi, you still have that problem?
pip install --upgrade discord-components
ERROR: Could not find a version that satisfies the requirement discord-components (from versions: none)
ERROR: No matching distribution found for discord-components
using python 3.10
discord-components was pulled from PyPI, if you've upgraded to discord.py 2.0 then check out their examples and docs on writing "views" to add buttons
https://github.com/Rapptz/discord.py/tree/master/examples/views
https://discordpy.readthedocs.io/en/stable/interactions/api.html#view

Isnt discord.py supporting buttons?
btw either import order is fine, python will always initialize the discord package first; pycord still uses the discord namespace as well https://github.com/Pycord-Development/pycord
yup, i was describing how to use them
gonna test, and thx for help
Thanks, didn't know that was a thing
discord.player ffmpeg process 1288 successfully terminated with return code of 1.
``` anyone i need it to be fixed
anyone ?
when ever i try to play music it terminaated it and it doesn't play the song but it give the now playing song in channel text
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
can someone help with this bot
What is this bot
ahh sorry
but how i violate it ?
@client.event
async def on_message(message):
if message.content.startswith('$hello'):
await message.channel.send('hello')
the message.content.startswith it doesnt work
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
Spotify tos does not allow playing their music public
and use commands instead
okay so which libary is better for music bot ?
You just cant use Spotify nor YouTube

Which means you cant really do music bot this days
okay
can someone share a good discord bot guide(updated one)
I have one that is in construction it does not have all features explained but you can check it out https://fallendeity.github.io/discord.py-masterclass/
A hands-on guide to Discord.py
its updated with the changes?
last bot i made was 2 yrs ago and it seems a lot has changed
Yes we are just doing it so Like i said it only has couple of guides currently
Check out in the future
ahh i see thankyou so much i'll check it out
I'd recommend looking at the official gist
What gist
the docs?
An API wrapper for Discord written in Python. Contribute to Rapptz/discord.py development by creating an account on GitHub.
this contains examples on how to use dpy in v2
alrr ty
and if you are migrating from v1 I recommend reading this
Can someone suggest a good service to host my discord bot for 24/7 and for free ?
welp there is nothing as good and free
these two words can't co-exist
if you want a good service you will have to pay for it
i used heroku earlier but not it has become paid
tho you can try aws it has a free tier but i forgot how long you can use it
alright, i'll check
and if you want a free hosting then u will have to use a shared ip
for free hosting you can check daki
okay, thanks 👍
1 year I believe
Hello, I've been trying to make a Verification bot and I've linked it to a MongoDB database and it keeps giving me the same error. Can someone help me?
we need more data, what error are you talking about?
Yes sir
im really sorry but i need help !!! i tryed to do a bot discord but he don't work i don't understand why the intercation didin't work .... somebody cna help me please ? i give the code and the error if u want ahah !
if somebody cna help me please
Then send them
ok
[2023-07-10 10:47:15] [ERROR ] discord.client: Ignoring exception in on_interaction
Traceback (most recent call last):
File "C:\Users\Ibibi\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Ibibi\Desktop\bot\index.py", line 135, in on_interaction
component = interaction.component
^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Interaction' object has no attribute 'component'
That's very obvious
Don't try to get an attribute that doesn't exist
if i give u my code can u fix it please it's like 2 weeks i try im a beginner and idk how fix it i just learn all of my code on the web
We don't spoon-feed here
and which library are you using?
can someone help me pls
try reinstalling pycord
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
What’s better pycord or discord.py
Hey, Im using discord.py, and want to spilt some commands off into different files to organise and clean up my code. I read that that should be done using extensions, but no matter which guide I follow I cant get it to work, any advice?
which ever you feel comfortable with
a basic cog example for discord.py v2. GitHub Gist: instantly share code, notes, and snippets.
Thanks, ill have a look
yes
are you sure this is the only place you are using prefix
cuz error message says this is not your prefix
uninstall it
this happened after uninstalling discord.py?
yeah
not the same error (a bit different)
try restarting your system
it's not the problem bcz i did that yesterday but nothing changed
Why using gist instead of repos ?
it contains additional notes not just codes and these contain links to repos too
Doesn't it become a mess if u use multiple kind of data storage ?
i'm not managing those or anything
so idk
k
which IDE are you using to run your bot?
try changing it
i run my script from cmd
try using an IDE like vsc since the issue might be because you are using cmd due to which it is unable to find the specified module
try using replit just to test if the same problem occurs or not
u sure u installed the packages using this terminal
and have the appropriate extension to run python installed
nah not this terminal
then install them from here too
run the file
Man help me
How to Fix?
what was the prefix you were using?
!
nothing :
and you will also need to enable intents in order for your bot to work
Can you send me?
try running your file
!intents
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
from cscode ?
this guy is doing nuke bot
vscode *
yes
who medra or the other one?
other one
ok thx for informing
i can't, when i click on the running button, i get no reaction
weird
may i know when does this error occur?
im not into conversation
cause looks like you misspelled the colorama
i tagged nobody 💀
so i cant help?
the error is not important 💀
so why you keep sending it
you can but i thought you won't bcz of this msg sorry
welp the colorama doesn't seem to be the problem since requirement is already satisfied
i sent it to let you see that the script is not executed
so you press the run button in vs code but nothing happens in console?
yes sirr
welp can't help as i got informed it's a nuke bot
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
Why is the slash command working?
wym ?
search in vscode settings for Interpreter
python interpreter most likely
and also check if you have the python extension installed
hello
please somebody for help me i stuck w my problem like since 2 weeks
hi
ok another way arround
all say it's obvious but no one now how to fix it 🙂
how are u bro : )
fine & u?
fineee
hm ?
thx
do this:
- ctrl shift p
- type in
interpreter - click
Python: Select Interpreter
and then from dropdown select python version you are using
okay
bruh ?
I'm really sorry for the ping, but you have to know that I'm at the end of it, it's a very simple problem but me, since I'm a beginner, nobody knows how to get to the end. I think you can do it you me I can't take it anymore I just want my bot's interactions to work can I provide the code and the error?
you have Python extension installed?
yes
yes just provide it and show whats not working
did you try relaunching the vs code?
lemme restart it
same problem after restarting
Ok thx a lot buyd
welp then no idea you can try asking in #editors-ides they might know the answer
there should be a play button on the top right use that to run file
wasnt he using it already?
don't know
:incoming_envelope: :ok_hand: applied timeout to @toxic mountain until <t:1688983524:f> (10 minutes) (reason: newlines spam - sent 117 newlines).
The <@&831776746206265384> have been alerted for review.
XD
!paste @toxic mountain for long code blocks use this
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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
btw @tall temple if u are still unable to run the file just use replit since we are only testing to check if the problem occured due to cmd not being able to fetch the modules
Module error or code mistake?
ERROR:
PS D:\Users\Jan\Desktop\Ekonomia 2.0> python .\main.py
Traceback (most recent call last):
File "D:\Users\Jan\Desktop\Ekonomia 2.0\main.py", line 1138, in <module>
@commands.has_role(1124753471082594415)
AttributeError: 'Command' object has no attribute 'has_role'
PS D:\Users\Jan\Desktop\Ekonomia 2.0>
CODE:
@bot.command()
@commands.has_role(1124753471082594415)
async def remove_deposit(ctx, amount: int, member: discord.Member):
data = load_data()
user_id = str(member.id)
if user_id not in data:
data[user_id] = {"wallet": 0, "deposit": 0}
deposit_balance = data[user_id]["deposit"]
if deposit_balance >= amount:
data[user_id]["deposit"] -= amount
save_data(data)
embed = discord.Embed(title="Usuwanie depozytu", color=discord.Color.green())
embed.add_field(name="Kwota", value=f"{amount} zł", inline=False)
embed.add_field(name="Status", value=f"Pomyślnie usunięto z depozytu użytkownika {member.name}", inline=False)
await ctx.send(embed=embed)
else:
await ctx.send("Użytkownik nie ma wystarczających środków na depozycie.")
Code mistake
Ugh

Maybe I'm wrong then. But I can't check docs rn cuz I'm on a beach :P
where is the definition of the commands
did you import it from somewhere
import discord
from discord import Embed
from discord.ext import commands
import json
import os
import random
import asyncio
what are the odds that you created a command named commands
cause looks like this is the problem
yup, I created command named "commands"
name the function something else and put the name kwarg in the decorator

for example ```py
@bot.command(name="commands")
async def my_super_cool_name(ctx):
...
for slash it works the same
super cool
thanks 
Ello, is message content intent required to read messages in DMs and public/private threads as well?
DMs I think no, for thread channels I don't know
my code :
https://paste.pythondiscord.com/umawusaqer
next my error :
I have no error in the console, but afterwards when I enter the !rank command which brings up the drop-down menu and I choose my rank, it puts me "interaction failure" even when looking at sites like github and similar cases I find nothing would someone modify the code for me to remedy this please?
its required for threads
thank you.
I already said it, we don't spoon-feed here
And the reason why Discord shows Interaction failed is because you never responded to the interaction
And there's no such events as on_select_option
thank you even if I do not understand that you are so unpleasant I hope it works because after 2 weeks toiling like crazy I just ask for an answer, I have done like 3 or 4 times the code in different ways I have never been able to solve ... hope you understand
What
u don't understand ?
Understand what
thank you even if I do not understand that you are so unpleasant I hope it works because after 2 weeks toiling like crazy I just ask for an answer, I have done like 3 or 4 times the code in different ways I have never been able to solve ... hope you understand
that brooo
The only thing I don't understand is, how is that relevant?
well, I'm asking what unlocks me and that the bot finally works, it's over, it's just missing that the interactions work...
why are you installing discord instead of pycord
and there should be a option called packages in side bar use that
i can't
wdym can't?
then just use the run button
💀
can u give me the code of your main file i'll try and check
import discord
from discord.ext import commands
from discord import default_permissions
from colorama import init
from colorama import Fore, Back, Style
import json
import os, glob
import shutil
import pathlib
config = json.load(open("config.json"))
init()
bot = commands.Bot(command_prefix="#", intents=discord.Intents.all())
@bot.command()
async def wlh(ctx):
await ctx.respond("wlh tg frr")
bot.run(config['bot_token'])
that's just a test script
no prob
How to make a self bot detect if a bot have edited a message and like detect it and respond
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
Ah ok -_-
14mins 😭
yeah its working for me
lemme see please
OH I GOT ITTTTT
wait have you installed pycord use
pip install py-cord```
i had to install py-cord module
yup
that is something else
lemme try on my pc 😉
okay
just watch a short tutorial on yt on how to run py files in vsc
that might help u run it
okok
for future its discord.py not discord
ok
pip install discord.py
why would the need discord.py when they are using py-cord?
i did not read it all i just saw them using discord which is not working
try running it from play button
the play button is not workinngggg
That did not explain why
Is discord.ext from pycord??
yeah i guess bcz it always works with my other projects
pycord used discord namespace
welp i'm out of ideas
Why
bruh ?
Ye
can't paste
!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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
use this
Nvm srry
np but don't think i'm that dumb 😹
Are nextcord and pycord the same thing?? Don’t think so
nextcord installed ?
they are different libs
yeah you got that too
Ye u have nextcord
oh
Thought so
uninstall it too
tho i'd suggest reinstalling all the packages after uninstalling them
it might be that you have some other packages that use discord namespace
pip freeze > packages.txt
use this to generate a txt file of all the installed packages
then uninstall them using
pip uninstall -y -r packages.txt
pip uninstall -y -r <(pip freeze) 1 liner
yeah this too wasn't sure of the syntax
@slate swan thanks babe
uninstalled all the sh*t and installed the packages i needed then the script finally worked !
thanks @turbid condor too
possibly you had installed other discord libraries
yeah my brother maybe 💀
go to #1035199133436354600 this does not look related to discord-bots
class DropButton(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="Click To Claim", custom_id="drop-button", style=discord.ButtonStyle.secondary)
async def button_callback(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.defer(ephemeral=True)
button.disabled = True
button.style = discord.ButtonStyle.success
button.label = "Claimed"
@client.command()
async def button(ctx):
await ctx.send("Press the button!", view=DropButton())```
Nothing is happening
what version of discord.py are you running?
cause they used to be inverted back in the lower versions
You didn't respond after deferring the interaction
oh so the Inteaction object has no attribute disabled is solved?
is there a website which provides examples for each things in discord.py
the github
there will be soon! currently in only has few features explained in depth but will have more over time
A hands-on guide to Discord.py
For now try looking at the gist for examples and if you don't get something ask here or create a forum post
Just a small and quick question
is PyCharm capable of using other languages too? or is it solely py?
try asking in #1035199133436354600 or elsewhere this is for questions related to discord bots
like if my bot directory has json files in it, PyCharm isn't gonna shit itself right?
no
json is not a programming language
gotcha
you can have text files or else
you could also edit other languages with it, but you won't get the tools and utilities that you would get for python
cool. thank you
Wait doesn't pycharm contains a lot of bugs?
hey could u help me
it is
how is it
cuz its. adiscord bto co,mand?
but the issue itself is not related to discord bots library ..
What's the issue tho?
.
def predict_next_numbers(sequence):
X, y = [], []
for i in range(len(sequence) - 5):
X.append(sequence[i:i+5])
y.append(sequence[i+5])
# Convert to array
X = np.array(X)
y = np.array(y)
# Reshape the input for CatBoost
X = X.reshape((X.shape[0], X.shape[1]))
# Create and train the CatBoost model
cat_model = cb.CatBoostRegressor(iterations=100, loss_function='RMSE')
cat_model.fit(X, y)
# Create and train the XGBoost model
xgb_model = xgb.XGBRegressor(n_estimators=100, learning_rate=0.1)
xgb_model.fit(X, y)
last_sequence = np.array(sequence[-5:]).reshape((1, 5))
predictions = []
for _ in range(4):
# Predict using CatBoost model
catboost_prediction = cat_model.predict(last_sequence)[0]
# Predict using XGBoost model
xgboost_prediction = xgb_model.predict(last_sequence)[0]
# Take the average of both predictions as the final prediction
next_number = (catboost_prediction + xgboost_prediction) / 2
predictions.append(round(next_number))
last_sequence = np.append(last_sequence[:, 1:], [[next_number]], axis=1)
return predictions
index error
!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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
I don't think so
I see
the pro version has some enhanced support for other files. The standard version has support for files other than .py, but it's a more basic range
ok
man idk if I wanna spend $100/yr lmao
there's a free version for students iirc
not a student 
not worth it then
I'm using the Community version tho
vscode might be nicer
they have great support, if not natively then with plugins
nice and lightweight too
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
Lmao... I can't believe this
I thought add_roles was gonna add roles to the server. Not to the menbers
it wouldnt be a method for Member object then
For that u need to create roles
But how do I specify a member for the role?
you need a Member object
If I remember correcly, an object is an class, isn't it? Or is it the same as an instance?
yeah in this case i meant instance
So, how do I do this? Is it like this?
member = discord.Member(_daneu)
member.add_roles(*roles[...])
nope
depends actually
what is your use case?
I want to get a list of <@membersIDS> passed to a slash command, and then I want to give a role for them
use the Member converter then
A hands-on guide to Discord.py
the example is using a prefixed command but works the same for slash
Thanks for showing me this SHould be very useful!
I'm gonna try here.
just show the errors
Bot connected to Discord.
Bot logged in as Krack
------
c:\Users\Admin\Desktop\Stuff\Coding Python\Python Projects\discord bot\command_handler.py:83: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
bot.add_cog(CommandHandler(bot))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Failed to load extensions: Extension 'command_handler' raised an error: TypeError: object NoneType can't be used in 'await' expression```
@slate swan
providing code pls wait ...
bot.add_cog(CommandHandler(bot))```
it tells you that bot.add_cog(CommandHandler(bot)) was not awaited
def setup(bot):
await bot.add_cog(CommandHandler(bot))```




