#discord-bots

1 messages · Page 267 of 1

tough kernel
#

@hushed galleon

tough kernel
#

Whats transformer?

hushed galleon
#

oh yeah did you sync your command after adding the autocomplete?

tough kernel
hushed galleon
#

do you have any kind of error handler defined?

hushed galleon
#

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?

tough kernel
#

Doesnt pop up with any options

hushed galleon
#

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

tough kernel
#

Yeah, i was thinking i was messing up somewhere

hushed galleon
#

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

tough kernel
#

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

hushed galleon
#

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?

tough kernel
#

like @bot.tree.command.autocomplete?

hushed galleon
tough kernel
hushed galleon
#

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

tough kernel
#

@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.

hexed oyster
#

@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)

tough kernel
hexed oyster
#

@tough kernel there's a link on the official rtd

tough kernel
#

TYVM!

hexed oyster
#

Np

#

I'm really surprised it's not in pins here lmao

naive briar
#

It's in the channel's topic

tribal pivot
#

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)
naive briar
#

!d discord.Interaction.edit_original_response

unkempt canyonBOT
#

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.
tribal pivot
grand moss
#

how can I make the text sent by bot into bold, italics, et cetera

sick birch
grand moss
#

I'll see

sick birch
#

bold text, some underlines, italics etc

grand moss
#

oh ok it works, thought it didn't last time. Thanks.
Also, any way to show text as embed?

slate swan
unkempt canyonBOT
#

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...
grand moss
#

I'll try it out

grim rock
#

yo total no. of members decreases... its 47309 from 47317

#

this means its legit?

slate swan
#

how do i make 1 file run 3 diff ones (not cogs)

grim rock
#

i checked it ...its in 6 servers

shrewd apex
turbid condor
grand moss
#

how do i mention the user who called the command in a normal prefix command
cursed emote cut me off

turbid condor
grand moss
#
#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

grim rock
slate swan
#

sum like that

turbid condor
#
@bot.command()
async def hello(ctx):
      await ctx.send("f{ctx.author.mention} hi")```
grand moss
#
@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

turbid condor
#

and he's asking for a prefix command

#

not slash

slate swan
#

Why are you creating Interaction objects yourself

grim rock
#

yhea ma bad

turbid condor
grim rock
grand moss
#

sorry, not that sure how classes work here

turbid condor
#

like is it in on_ready or setup_hook?

grand moss
#

i have on_ready in the code

turbid condor
#

try using wait_until_ready

grand moss
#

lemme try the one you sent first

grim rock
grand moss
#

ok works. Thanks

slate swan
#

gays can some one give me any tutoruial how to create a pagination with buttons ?

grim rock
#

ohh its in a server with 47k members

#

idk how its surviving there and who added it?

slate swan
grim rock
#

still im unable to do what i want

slate swan
grim rock
#

all the members in all the guilds on activity status

slate swan
#

ahhh

#

i give up with it

#

i tryed to do it once

grim rock
#

then?

slate swan
#

not working with me

grim rock
#

you lost

slate swan
#

yp

grim rock
#

ahh

slate swan
#

i allredy dont code discord bots so

#

i dont give much effort

grim rock
#

i like do APIs and stuff

slate swan
#

yp

grim rock
#

im good at it

slate swan
#

do u know how to create discord pagination with butttons ?

grim rock
#

i made bot with minecraft API supercell API

#

nahh i never tried buttons

#

yet

slate swan
#

mine craft

slate swan
grim rock
#

you own minecraft?

grim rock
#

will*

turbid condor
slate swan
turbid condor
#

since it might be due to your presence being setup before the bot cache

slate swan
#

do u know how to create discord pagination with butttons ?@turbid condor

grim rock
turbid condor
turbid condor
grim rock
turbid condor
# grim rock

and one more thing you should not sync your commands in on_ready

grim rock
#

it makes my bot slow?

turbid condor
# grim rock ummm so?

it's used like this py @bot.event async def on_ready(): await bot.wait_until_ready() #rest of the code

grim rock
#

oh kayyyy

turbid condor
naive briar
#

Not defined

#

It's a method

turbid condor
#

and it may cause an error

slate swan
# grim rock

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

naive briar
#

That's not any better

turbid condor
#

that's better

#

since you don't need to sync everytime the bot starts

#

only some special case

slate swan
#

okay

turbid condor
#

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

GitHub

Summary
Adds @dm_only and @private_only decorators to allow specifying the new contexts field in app commands, as specified here, as well as the relevant init args.
The docs mention that if this fi...

#

These are the cases when you need to sync

pulsar bridge
#

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?

turbid condor
#

on_app_command_error

#

if i am right

vocal snow
#

!d discord.app_commands.CommandTree.error

unkempt canyonBOT
#

@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").
vocal snow
#

the CommandTree is accessed via bot.tree if you're using commands.Bot

pulsar bridge
#

But anyway, thanks!

#

wait, isn't that just for a single command / local?

#

or am I confused

vocal snow
#

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):
    ...
pulsar bridge
#

Oh! Right Face_Palm

#

Apologies, and thanks again

vocal snow
#

npnp

slate swan
#

@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}"))

turbid condor
#

instead of giving them the code just give them instructions that will help them learn

slate swan
vocal snow
#

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

grim rock
# slate swan <@722621005054476319> here is the code it will work ```py @client.event async ...
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'
slate swan
#

how did you define client

grand moss
#
@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

slate swan
#

what get_quote is?

grand moss
#

oh shit, sorry guys, didn't see the typo

grim rock
turbid condor
#

wdym that didn't work?

grand moss
# slate swan what `get_quote` is?

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)
grim rock
#

it isbut

slate swan
grim rock
turbid condor
turbid condor
grim rock
#

requests works fine

slate swan
#

..

#

no cause its blocking

turbid condor
grim rock
slate swan
#

of how you set the status

turbid condor
grim rock
slate swan
#
  1. dont set status in on_ready it can be called many times
  2. why you have .wait_until_ready if you are already in an event that is called when this happens
  3. why use guild.member_count
turbid condor
#

wouldn't len(bot.users) be used instead?

turbid condor
slate swan
#

wait why is he incrementing total users by bot.users for each guild

slate swan
grim rock
#

someone told me

slate swan
#

so you just copy pasted something and dont even know how it works

turbid condor
slate swan
#

and move it to setup_hook

#

dont keep it in on_ready

turbid condor
slate swan
#

i already said why even have that line

#

if the event is already called when this happens

grand moss
#

also I found this on the site. Is this what you meant?

slate swan
#

Yes to use aiohttp instead

quaint obsidian
#

Please don't use white theme. It kills eyes.

grand moss
#

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

slate swan
grand moss
#

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

slate swan
#

Because they use asyncio to sleep() and run()

grand moss
#

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)
naive briar
#

First, say what's wrong

grand moss
#

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)
grand moss
naive briar
#

What's wrong with it then

grand moss
#

either improper usage of await or I have to put something in .json()...?

naive briar
#

What?

grand moss
#

I don't know if that was the right way to use .json()

naive briar
#

!d aiohttp.ClientResponse.json

unkempt canyonBOT
#

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.
naive briar
#

Why didn't you just try it and see, anyway

grand moss
#

I got something like this

naive briar
#

Await your get_quote function

#

Or, more correctly, your coroutine

young dagger
#

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```
naive briar
#

Unbelievable

turbid condor
#

I think he meant error 503

young dagger
# naive briar Unbelievable

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 🤷

turbid condor
unkempt canyonBOT
#

discord/abc.py line 128

async def _purge_helper(```
shrewd apex
#

dosent seem to be one api call

unkempt canyonBOT
#

discord/abc.py line 123

async def _single_delete_strategy(messages: Iterable[Message], *, reason: Optional[str] = None):```
turbid condor
#

Yeah that's around 100+ calls

#

That's why he getting rate limited

naive briar
#

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

unkempt canyonBOT
#

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...
unkempt canyonBOT
#

discord/abc.py line 148

strategy = channel.delete_messages if bulk else _single_delete_strategy```
naive briar
#

Don't think so

#

But maybe

fickle crown
#

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```
naive briar
#

Stop reposting

#

Just wait for someone to answer

turbid condor
#

It just says that the role you are trying to find is not being find

grand moss
#

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")
turbid condor
#

Docstring

naive briar
unkempt canyonBOT
#
Naw.

No documentation found for the requested symbol.

naive briar
#

!d discord.app_commands.CommandTree.command

unkempt canyonBOT
#

@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.
naive briar
#

The description argument

turbid condor
#
async def ping():
"""DESCRIPTION IS THIS"""```
#

This works too

grand moss
#

thanks. also I figured out where to put await

turbid condor
slate swan
#

the command doc is not indented

#

!E ```py
async def ping():
"""DESCRIPTION IS THIS"""

unkempt canyonBOT
#

@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
slate swan
#

why here its IndentationError

#

but in my IDLE its Syntax

turbid condor
#

but error is the same

slate swan
#

i see

turbid condor
#

that is just codeblock issue i'm sure i indented it

slate swan
#

!e print(IndentationError.mro)

unkempt canyonBOT
#

@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'>)
slate swan
#

yeah IndeantationError is subclass of SyntaxError

young dagger
#

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)
vocal snow
#

You have an or there, which is why your linter is complaining

slate swan
#

oh i see you cant subtract None from datetime.datetime possibly

young dagger
slate swan
vocal snow
hushed galleon
#

or perhaps the condition is meant to be is None or ...

young dagger
young dagger
slate swan
#

cause you have or

young dagger
#

No

slate swan
#

yes the second part is evaluated cause of this

young dagger
hushed galleon
#

did you write is None and ...?

young dagger
hushed galleon
#

i know, cause its wrong

young dagger
#

It's because of last_game_start_time = None

#

as global variable

hushed galleon
#

think about what your if-statement is supposed to do, do you want it to proceed if your start time is not yet set?

young dagger
#

No that is the point

grim rock
#

its saying application didnt respond but in actual the command did its job

hushed galleon
#

can you show the full traceback in your console alongside how you defined /setlogchannel?

slate swan
grim rock
# slate swan code?
@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}")
slate swan
#

its prefixed command and you used slash command

grim rock
#

ohhhhkayyy

#

got itgot it

#

i copied from old cmd and forgot to change

hushed galleon
# young dagger No that is the point

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?

grim rock
#

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)
young dagger
slate swan
#

also issue is possibly with that you cannot annotate parameter in slash command as TextChannel

hushed galleon
slate swan
#

!d discord.app_commands.checks.has_permissions use this instead

young dagger
unkempt canyonBOT
#

@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...
slate swan
grim rock
#

okayyyyyyyyyyy

hushed galleon
hushed galleon
hushed galleon
young dagger
hushed galleon
# grim rock

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

hushed galleon
grand moss
#

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

grim rock
# hushed galleon btw this is the bottom half of the error, if you scrolled up a bit more you'd li...
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
young dagger
slate swan
#

use id

hushed galleon
# grand moss I haven't started exploring DMs and ephemeral messages yet

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

grim rock
slate swan
unkempt canyonBOT
hushed galleon
grim rock
#

OKAY

slate swan
#

you already did it in prefixed command

young dagger
grim rock
#

LIKE bot.log_channel = value.id

young dagger
#

Because this is what is giving me the warning

slate swan
grim rock
#

here value is TextChannel

#

okayy but it will be same thing ig?

hushed galleon
slate swan
#

How do I make custom Discord bots?

grim rock
slate swan
grim rock
#

THANKS FOR THE HELP!!

young dagger
hushed galleon
grim rock
#

HOW I CAN MAKE DIFFRENT FILE FOR EVER COMMAND?? IS IT HELPFUL

slate swan
#

you can create cogs to separate commands across many files

#

but i would separate it by some categories not one command per file

grim rock
#

maybe one file is enough

woven dew
grand moss
young dagger
# hushed galleon did you save after each change to make sure your linter checked again?

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)```
grim rock
young dagger
#

And tell me you're not getting any warning messages

hushed galleon
ember mango
#

How to remove response messages in 5 seconds

young dagger
ember mango
hushed galleon
ember mango
young dagger
slate swan
#

Do you even need the Optional

#

Adding a default being None already makes it optional

naive briar
#

Type hinting yert

slate swan
#

for type checkers it does

ember mango
young dagger
ember mango
#

How to remove response messages in 5 seconds🤔🤔

slate swan
#

delete_after kwarg when sending a message

young dagger
slate swan
#

Absolutely useless

#

!d discord.TextChannel.send

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

Sends a message to the destination with the content given.

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

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "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**.
slate swan
#

There's a delete_after kwarg, use it.

slate swan
young dagger
#

Grab some popcorn and read the conversation 👍

slate swan
#

Wacky type checkers

#

Type hinting in python always sucked either way

young dagger
#

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

hushed galleon
slate swan
#

x: datetime.datetime = None

#

x: datetime.datetime | None = None

hushed galleon
#

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

young dagger
slate swan
#

no need to use elif tho

#

just if

hushed galleon
#

hmm i thought your linter didnt have the concept of a Never type though

young dagger
# slate swan just `if`
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)```
slate swan
#

return will already quit the function so second if wont be checked anyways

young dagger
slate swan
#

wasnt your first error being caused by the or

young dagger
#

Nope

slate swan
grim rock
#

why the emoji is like that

#

can i emojies/imgs from my files?

slate swan
#

what

slate swan
grim rock
#
@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)
    
slate swan
#

..

#

Maybe don't add these weird empty spaces

#

you made it to post is in such big separation

grim rock
#

nah i added spaces after that

slate swan
#

Which leads to the result you have

grim rock
#

they are same

slate swan
grim rock
#

no spaces

dapper summit
#
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 ?

vocal snow
#

can you share your code?

#

If you've set the after parameter of VoiceClient.play, are you handling the exception properly?

dapper summit
vocal snow
#

track_url = track["external_urls"]["spotify"]

#

does this url actually point to an audio file

#

or does it point to some spotify track link

grim rock
dapper summit
vocal snow
#

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

dapper summit
#

if i add spotify link it give me same

vocal snow
#

the spotify web api doesn't expose the actual audio

#

for obvious reasons

slate swan
#

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

slate swan
#

when you hit play it plays preview of the song right

dapper summit
#

any way to fix it ? like i can make changes ?

slate swan
#

You shouldn't make a music bot, it goes against ToS of both spotify & youtube - we can't provide you help with it

slate swan
dapper summit
young dagger
#

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)```
meager chasm
#

Which library is this?

meager chasm
#

You should go through the buttons examples in the discord.py GitHub repo if that's what you are using

sick birch
grim rock
#

can I do edit my discord bot code from html website in same dir

#

using py script

ornate sapphire
# young dagger This interaction failed ```py @client.event async def on_button_click(interacti...
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,
ornate sapphire
#

no problem!

ornate sapphire
#
from discord.ext import commands

client=commands.Bot(prefix="prefix")```
young dagger
#

Yes

ornate sapphire
#

kk just checken

ember mango
#

@young dagger man i am so sorry but can you help me?

#

How to create a channel?

#

While

ember mango
grim rock
#

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)

slate swan
ember mango
slate swan
#

you cant find what

ember mango
slate swan
#

no whats so hard in typing

#

i already closed it anyways

ember mango
slate swan
#

type in what i did

young dagger
young dagger
#

While what?

ember mango
#

I create channel soam

#

Spam*

sick birch
unkempt canyonBOT
#
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...
sick birch
ember mango
sick birch
#

What did you mean by "while" and "I create channel spam"?

slate swan
sick birch
#

What is "I create channel spam" supposed to mean? I'm still not sure what question you're asking?

slate swan
#

sounds like nuke bot kinda

ember mango
slate swan
ember mango
sick birch
unkempt canyonBOT
#

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

slate swan
#

well then no example for you

sick birch
#

We don't help with those here, sorry

slate swan
slate swan
young dagger
#

Can I use this for my buttons? raise discord.DiscordException("You can only click the button once.")

sick birch
#

I'm trying to be courteous.

sick birch
#

Do you want to send that message to the user?

young dagger
#

Yeah

slate swan
sick birch
#

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)

slate swan
#

just send message or smth

young dagger
#

Instead of the classic message This interaction failed

sick birch
#

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

slate swan
young dagger
#

Thanks hattip

ember mango
slate swan
#

apparently random docs does not exist

young dagger
slate swan
#

you just set the ephemeral to True

#

!d discord.InteractionResponse.send_message

unkempt canyonBOT
#

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.
sick birch
young dagger
#

It doesn't allow others to vote

sick birch
#

It only takes into account if someone has clicked it

young dagger
sick birch
#

that is indeed one approach

tall temple
#

hi guys can someone help me pls

sick birch
tall temple
sick birch
#

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

tall temple
sick birch
tall temple
#

yeah i changed

#

but i retested

sick birch
#

The yellow squiggly means you either don't have discord.py installed or your interpreter can't find it

tall temple
fickle crown
tall temple
sick birch
#

Ah, I can't help with pycord, sorry. I know they changed a lot of stuff's locations around so it might be that shrug

tall temple
#

ah

tall temple
#

can someone help me abt that ? (pycord)

fickle crown
#

Are you new to PY?

tall temple
fickle crown
#

PY good place to install plugins

tall temple
#

bruh

fickle crown
tall temple
#

i USE PYCORD

#

damn is that difficult to understand ?

twilit grotto
tall temple
#

🤣

fickle crown
sick birch
#

@fickle crown please don't use ChatGPT to provide answers, see rule #10
Also their problem is completely unrelated to what you gave them

slate swan
gritty tree
#
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

hushed galleon
hushed galleon
hushed galleon
gritty tree
sick birch
dapper summit
#
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

hasty pike
unkempt canyonBOT
#

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

fiery jetty
#

can someone help with this bot

naive briar
#

What is this bot

fiery jetty
#

ahh sorry

dapper summit
fiery jetty
#


@client.event
async def on_message(message):
    if message.content.startswith('$hello'):
        await message.channel.send('hello')
#

the message.content.startswith it doesnt work

unkempt canyonBOT
#
Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

slate swan
#

and use commands instead

dapper summit
slate swan
dapper summit
slate swan
#

Which means you cant really do music bot this days

dapper summit
#

okay

fiery jetty
#

can someone share a good discord bot guide(updated one)

slate swan
fiery jetty
#

last bot i made was 2 yrs ago and it seems a lot has changed

slate swan
#

Check out in the future

fiery jetty
turbid condor
naive briar
#

What gist

fiery jetty
turbid condor
#

this contains examples on how to use dpy in v2

fiery jetty
#

alrr ty

turbid condor
dry pelican
#

Can someone suggest a good service to host my discord bot for 24/7 and for free ?

turbid condor
#

these two words can't co-exist

#

if you want a good service you will have to pay for it

dry pelican
turbid condor
#

tho you can try aws it has a free tier but i forgot how long you can use it

dry pelican
#

alright, i'll check

turbid condor
#

and if you want a free hosting then u will have to use a shared ip

#

for free hosting you can check daki

dry pelican
#

okay, thanks 👍

turbid condor
#

and yeah discloud too

#

they also have a free tier

slate swan
#

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?

rugged shadow
#

we need more data, what error are you talking about?

tall temple
toxic mountain
#

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

toxic mountain
#

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'

naive briar
#

That's very obvious

toxic mountain
#

yeah but i didn't now how to fix it

#

can u help me please ?

naive briar
#

Don't try to get an attribute that doesn't exist

toxic mountain
#

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

naive briar
#

We don't spoon-feed here

dapper vapor
#

Guys

#

How do you do application / commands

turbid condor
tall temple
turbid condor
turbid condor
dapper vapor
barren shard
#

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?

turbid condor
barren shard
#

Thanks, ill have a look

tall temple
ember mango
#

Hello, Can Anyone Help me!

#

@turbid condor

turbid condor
tall temple
#

yes

turbid condor
#

cuz error message says this is not your prefix

turbid condor
tall temple
turbid condor
tall temple
#

not the same error (a bit different)

turbid condor
#

try restarting your system

tall temple
#

it's not the problem bcz i did that yesterday but nothing changed

gloomy hound
turbid condor
#

it contains additional notes not just codes and these contain links to repos too

gloomy hound
turbid condor
#

so idk

gloomy hound
#

k

turbid condor
#

try changing it

tall temple
turbid condor
#

try using replit just to test if the same problem occurs or not

tall temple
#

i try to run with vsc but nothing ...

turbid condor
#

and have the appropriate extension to run python installed

tall temple
#

nah not this terminal

turbid condor
tall temple
#

after that ?? :D

turbid condor
#

run the file

ember mango
#

How to Fix?

turbid condor
ember mango
tall temple
turbid condor
#

and you will also need to enable intents in order for your bot to work

turbid condor
turbid condor
unkempt canyonBOT
#
Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

tall temple
slate swan
tall temple
#

vscode *

turbid condor
turbid condor
slate swan
turbid condor
#

ok thx for informing

tall temple
turbid condor
#

weird

slate swan
#

im not into conversation

#

cause looks like you misspelled the colorama

tall temple
slate swan
tall temple
slate swan
#

so why you keep sending it

tall temple
turbid condor
#

welp the colorama doesn't seem to be the problem since requirement is already satisfied

tall temple
slate swan
ember mango
turbid condor
slate swan
#

in vscode settings

turbid condor
#

!rule 5

unkempt canyonBOT
#

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

ember mango
tall temple
slate swan
#

python interpreter most likely

turbid condor
#

and also check if you have the python extension installed

toxic mountain
#

hello

toxic mountain
#

please somebody for help me i stuck w my problem like since 2 weeks

tall temple
slate swan
toxic mountain
#

all say it's obvious but no one now how to fix it 🙂

toxic mountain
tall temple
toxic mountain
tall temple
toxic mountain
#

thx

slate swan
#

do this:

  • ctrl shift p
  • type in interpreter
  • click Python: Select Interpreter
#

and then from dropdown select python version you are using

tall temple
#

okay

toxic mountain
slate swan
tall temple
slate swan
slate swan
tall temple
#

same problem after restarting

toxic mountain
slate swan
turbid condor
#

there should be a play button on the top right use that to run file

slate swan
turbid condor
unkempt canyonBOT
#

: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.

turbid condor
#

XD

slate swan
#

!paste @toxic mountain for long code blocks use this

unkempt canyonBOT
#
Pasting large amounts of code

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

After pasting your code, save it by clicking the 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.

turbid condor
#

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

gritty tree
#

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.")
gritty tree
slate swan
#

Maybe I'm wrong then. But I can't check docs rn cuz I'm on a beach :P

slate swan
#

did you import it from somewhere

gritty tree
#

import discord
from discord import Embed
from discord.ext import commands
import json
import os
import random
import asyncio

slate swan
#

what are the odds that you created a command named commands

#

cause looks like this is the problem

gritty tree
slate swan
gritty tree
slate swan
#

for example ```py
@bot.command(name="commands")
async def my_super_cool_name(ctx):
...

#

for slash it works the same

turbid condor
#

super cool

slate swan
#

thanks sunglasses_1

gritty tree
#

Now works fine

plucky knoll
#

Ello, is message content intent required to read messages in DMs and public/private threads as well?

brazen raft
#

DMs I think no, for thread channels I don't know

toxic mountain
#

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?

plucky knoll
#

thank you.

naive briar
#

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

toxic mountain
# naive briar I already said it, we don't spoon-feed here

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

naive briar
#

What

toxic mountain
#

u don't understand ?

naive briar
#

Understand what

toxic mountain
#

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

naive briar
#

The only thing I don't understand is, how is that relevant?

toxic mountain
turbid condor
#

why are you installing discord instead of pycord

#

and there should be a option called packages in side bar use that

turbid condor
#

and instead of doing python main.py use the run button

tall temple
#

okok

#

@turbid condor it's not appearing with installed modules

turbid condor
#

remove that discord package

#

and then run using the run button

tall temple
turbid condor
#

wdym can't?

tall temple
turbid condor
#

then just use the run button

tall temple
turbid condor
#

can u give me the code of your main file i'll try and check

tall temple
#
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

turbid condor
#

ok

#

give me 5 min

tall temple
#

no prob

plush cargo
#

How to make a self bot detect if a bot have edited a message and like detect it and respond

unkempt canyonBOT
#

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

plush cargo
#

Ah ok -_-

tall temple
turbid condor
tall temple
#

lemme see please

turbid condor
#

wait a min

#

i'll inv u to the repl

tall temple
#

ok

#

alr

turbid condor
#

try running it using the python main.py command

tall temple
#

damn

turbid condor
#

XD

tall temple
#

OH I GOT ITTTTT

turbid condor
# tall temple

wait have you installed pycord use

pip install py-cord```
tall temple
#

i had to install py-cord module

turbid condor
#

yup

tall temple
#

i install pycord like pip install pycord

#

dumb ass 😭

turbid condor
#

that is something else

tall temple
#

lemme try on my pc 😉

tall temple
#

💀

turbid condor
#

welp its a cmd issue

#

try using vsc

tall temple
#

okay

turbid condor
#

just watch a short tutorial on yt on how to run py files in vsc

#

that might help u run it

tall temple
#

okok

slate swan
tall temple
#

ok

slate swan
#

pip install discord.py

turbid condor
slate swan
turbid condor
tall temple
naive briar
#

That did not explain why

vocal laurel
#

Is discord.ext from pycord??

tall temple
slate swan
#

pycord used discord namespace

turbid condor
#

welp i'm out of ideas

vocal laurel
#

Just put in pip install discord.ext

#

Idk

naive briar
#

Why

tall temple
#

bruh ?

naive briar
#

See what it prints

vocal laurel
tall temple
#

can't paste

vocal laurel
#

Oof

#

Ok select them and right click and press copy

#

Then Paste the text

tall temple
#

BRO ?

#

i can't paste which means there is too much caracters wtf

turbid condor
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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

After pasting your code, save it by clicking the 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.

turbid condor
#

use this

tall temple
vocal laurel
#

Nvm srry

tall temple
tall temple
vocal laurel
#

Are nextcord and pycord the same thing?? Don’t think so

tall temple
#

nextcord installed ?

turbid condor
turbid condor
vocal laurel
tall temple
#

oh

vocal laurel
turbid condor
#

uninstall it too

tall temple
turbid condor
#

tho i'd suggest reinstalling all the packages after uninstalling them

tall temple
#

a

#

too late 😹

slate swan
#

it might be that you have some other packages that use discord namespace

tall temple
#

mhm

#

how can i uninstall all packages ?

#

@slate swan

turbid condor
#

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

slate swan
#

pip uninstall -y -r <(pip freeze) 1 liner

turbid condor
tall temple
#

@slate swan thanks babe

#

uninstalled all the sh*t and installed the packages i needed then the script finally worked !

#

thanks @turbid condor too

slate swan
tall temple
slate swan
#

you are in a class right

#

what every method in class must have?

hasty pike
#

Bruh

#

Sorry

spring fable
#

yo can someone help ke i get tuple index

#

erorr

slate swan
#

show full code

#

looks like you have changed the order of the arguments

slate swan
young dagger
#
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

slate swan
#

cause they used to be inverted back in the lower versions

naive briar
slate swan
#

oh so the Inteaction object has no attribute disabled is solved?

versed zodiac
#

is there a website which provides examples for each things in discord.py

thin raft
#

the github

slate swan
turbid condor
rapid hedge
#

Just a small and quick question
is PyCharm capable of using other languages too? or is it solely py?

slate swan
rapid hedge
#

like if my bot directory has json files in it, PyCharm isn't gonna shit itself right?

vocal snow
#

no

slate swan
rapid hedge
#

gotcha

slate swan
#

you can have text files or else

vocal snow
#

you could also edit other languages with it, but you won't get the tools and utilities that you would get for python

rapid hedge
#

cool. thank you

turbid condor
#

Wait doesn't pycharm contains a lot of bugs?

spring fable
spring fable
#

it is

slate swan
#

how is it

spring fable
#

cuz its. adiscord bto co,mand?

slate swan
#

but the issue itself is not related to discord bots library ..

turbid condor
#

What's the issue tho?

spring fable
#

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

slate swan
unkempt canyonBOT
#
Pasting large amounts of code

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

After pasting your code, save it by clicking the 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.

turbid condor
#

Or u can create a forum post

full lily
turbid condor
#

I see

full lily
rapid hedge
full lily
rapid hedge
#

not a student FingerGuns

full lily
#

not worth it then

rapid hedge
#

I'm using the Community version tho

full lily
#

vscode might be nicer

#

they have great support, if not natively then with plugins

#

nice and lightweight too

slate swan
#

How do I add or remove roles?

#

!d discord.Member.add_roles

unkempt canyonBOT
#

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.
slate swan
#

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

turbid condor
#

For that u need to create roles

slate swan
#

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

#

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.

versed zodiac
#

cause i am getting errors

slate swan
#

just show the errors

versed zodiac
#
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 ...

slate swan
#

it tells you that bot.add_cog(CommandHandler(bot)) was not awaited

versed zodiac