#discord-bots

1 messages · Page 130 of 1

hushed galleon
#

but i dont think id need those methods, dpy can just do the http requests with their objects

torn sail
#

yeah you dont

hushed galleon
#

might as well learn a bit of fast api in the process

#

but ill come back to it tomorrow

brazen skiff
#

hii I'm using the new discord.py for slash commands I'm not sure how to set up cogs

#

is there any reference for using cogs?

slate swan
brazen skiff
#

but how do you ink the cog with main file

#

so when the main script runs it calls this cog

naive briar
#

!d discord.ext.commands.Bot.load_extension

unkempt canyonBOT
#

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

Loads an extension.

An extension is a python module that contains commands, cogs, or listeners.

An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.

Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine "(in Python v3.11)").
slate swan
#

is this normal?

#
            await interaction.guild.ban(user,reason=reason)
rustic edge
#

!slashcommands

rustic edge
#

How do I use args with the / commands?

#

When I do, I get this error: TypeError: parameter 'arg' is missing a type annotation in callback 'feedpeasant'

Code:


@client.tree.command(name = "feedpeasant", description = "Feed the peasants")
async def feedpeasant(interaction: discord.Interaction, arg='None') -> None:
    role = discord.utils.find(lambda r: r.name == 'mod', interaction.message.author.roles)
    if role in interaction.author.roles:
        if arg == 'None':
          await interaction.response.send_message('You must specify a peasant to feed')
        else:
         if arg == 'all':
            await interaction.response.send_message('Feeding all peasants :bread:')
            with open('log.txt', "a") as f:
                f.write("\nA mod has fed all peasants \n Command has been run at: " + time.ctime())
                f.close()
         elif arg == interaction.message.author.mention:
            await interaction.response.send_message('You cannot feed yourself goofy')
            with open('log.txt', "a") as f:
                f.write("\nA mod has tried to feed themselves \n Command has been run at: " + time.ctime())
                f.close()
        if arg != 'all' and arg != interaction.message.author.mention:
            await interaction.response.send_message(f'Feeding {arg} :bread:')
            with open('log.txt', "a") as f:
                f.write("\nA mod has fed {arg} \n Command has been run at: " + time.ctime())
                f.close()
    else:
        await interaction.response.send_message('You are not a mod, you peasant. Get back to bread farming.')
        with open('log.txt', "a") as f:
            f.write("\nA peasant tried to feed someone \n Command has been run at: " + time.ctime())
            f.close()
paper sluice
#

you need to type-annotate the args

#

just like you did for your interaction

rustic edge
#

so interaction.args?

paper sluice
#

no

rustic edge
#

ohhh, args: discord.Args

paper sluice
#

like arg: <the type you want the arg to be>

rustic edge
#

type meaning string?

paper sluice
#

yea

rustic edge
#

It gets underlined

paper sluice
#

the class, not a string literal

#

like arg: str

rustic edge
#

ooh

#

im very silly, ty

rustic edge
# paper sluice like `arg: str`

For most of my code, that works. Although for one part I'm not sure why it doesn't, it's the exact same layout as the others.

#

nvm got it

#

ty for ur help

slate swan
#

How do i add slash command to cogs?

rustic edge
slate swan
#

ty

rustic edge
#

How can I use CTX with / commands since I don't know how else to check a user's roles.

proud apex
#

I'm making my Rpg game. I want to know, for example, you want to build a plant, it will take an hour to build, for example, there are workers, and they must somehow influence the time, 1 worker takes 2 minutes. How to take time from building? (discord.py, db - postgre)

slate swan
#
@commands.cooldown(1, 60*60*24, commands.BucketType.user)

is there any way to store the cooldown somewhere so after the bot restarts it will continue your time

rare echo
#

cant seem to find it in docs but is there a way to add the role icon images through a cmd?

#

nvm i found it FacePalm

pulsar bridge
#

I got an issue connecting to Mongo, and I have no idea what's going wrong as it was working perfectly yesterday.
I'm using it for a discord bot.

  File "C:\Users\main\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\main\Downloads\Personal Stuff\Christmasbot\cbot.py", line 558, in on_message
    if (cb_cdata.count_documents(query_one) == 0):
  File "C:\Users\main\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pymongo\collection.py", line 1835, in count_documents
    return self._retryable_non_cursor_read(_cmd, session)

I believe this is where the issue is, but the error is quite long. I can attach a .txt if needed. Any ideas?

rustic edge
#

How can I send a message multiple times, and not just have it reply to the user?

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.

vale wing
#

Rate bot pfp

rustic edge
#

6/10

#

too many sqaures

shrewd apex
shrewd apex
#

and edit the message

rustic edge
#

And I want it to be separate messages

upbeat gust
shrewd apex
upbeat gust
#

You can't just defer

rustic edge
shrewd apex
#

make a check

upbeat gust
unkempt canyonBOT
#

@discord.app_commands.default_permissions(**perms)```
A decorator that sets the default permissions needed to execute this command.

When this decorator is used, by default users must have these permissions to execute the command. However, an administrator can change the permissions needed to execute this command using the official client. Therefore, this only serves as a hint.

Setting an empty permissions field, including via calling this with no arguments, will disallow anyone except server administrators from using the command in a guild.

This is sent to Discord server side, and is not a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check"). Therefore, error handlers are not called.

Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
rustic edge
#

ty

#

what if I want it to only work with certain roles though?

upbeat gust
unkempt canyonBOT
#

@discord.app_commands.checks.has_role(item, /)```
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 invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingRole "discord.app_commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.NoPrivateMessage "discord.app_commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure").

New in version 2.0...
rustic edge
#

ty

rustic edge
naive briar
#

No

rustic edge
#

what do I replace it with then?

#

is it like
@discord.app_commands.checks.has_role(mod, /)?

naive briar
#

No

shrewd apex
#

/ indicates positional arguments

upbeat gust
#

https://docs.python.org/3/glossary.html#term-parameter
These functions will be used for example:

def basic(pos_only, /, pos_or_kw, *, kw_only): ...
def var(*args, **kwargs): ...
```Python has 5 types of parameters:

• Positional-only, all parameters before `/` or `*args`
This can only be passed with `basic(1, ...)`, not `basic(pos_only=1, ...)`

• Positional-or-keyword, "normal" parameters
This can be passed with either `basic(..., 2, ...)` or `basic(..., pos_or_kw=2, ...)`

• Keyword-only, all parameters after `*,` or `*args`
This can only be passed with `basic(..., kw_only=3)`, not `basic(..., 3)`

• Var-positional, `*args`, inside the function this will be a `tuple`.
This takes as many positional args as you want to give it. This is used by `print`.
`var(1, 2, 3, 4, 5, ...)`

• Var-keyword, `**kwargs`, inside the function this will be a `dict`.
This takes as many keyword args as you want to give it. This is used by `dict`.
`var(foo=1, bar=2, baz=3, ...)`
rustic edge
#

so @discord.app_commands.checks.has_role(item, /mod?)

#

sorry, im not very smart

upbeat gust
#

it just means everything before it must be positional

rustic edge
#

yes

#

but it makes no sense

#

got it

shrewd apex
rustic edge
#

yes, i got it

shrewd apex
#

just be async and takes interaction as first positional

#

no other args iirc

vale wing
#

I'm good at coding but bad at design 💀

rustic edge
shrewd apex
rustic edge
#

lol

rustic edge
# unkempt canyon

is it possible to respond to the user if they don't have the correct role?

shrewd apex
#

make the centre line discord nitro and add some sparkles on side ig

vale wing
rustic edge
#

include wumpus in it

vale wing
#

If he uses the has_role and not the custom check there's no predicate

rustic edge
naive briar
#

!d discord.ext.commands.Command.error pithink

unkempt canyonBOT
#

@error```
A decorator that registers a coroutine as a local error handler.

A local error handler is an [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event limited to a single command. However, the [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") is still invoked afterwards as the catch-all.

Changed in version 2.0: `coro` parameter is now positional-only.
vale wing
#

Screw local error handlers, get global

#

!d discord.ext.commands.Bot.on_command_error

shrewd apex
unkempt canyonBOT
#

await on_command_error(context, exception, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

The default command error handler provided by the bot.

By default this logs to the library logger, however it could be overridden to have a different implementation.

This only fires if you do not specify any listeners for command error.

Changed in version 2.0: `context` and `exception` parameters are now positional-only. Instead of writing to `sys.stderr` this now uses the library logger.
rustic edge
#

lol

upbeat gust
#

guys this is a slash command

shrewd apex
#

^^

#

use the app_command_error

upbeat gust
#
from discord import Interaction
from discord.app_commands import AppCommandError

bot = commands.Bot(...)
# Bot has a built-in tree
# but this is the same for a
# CommandTree you define.
tree = bot.tree

@tree.error
async def on_app_command_error(
    interaction: Interaction,
    error: AppCommandError
):
    ...```
vale wing
#

I forgor 🤗

shrewd apex
vale wing
#

!d disnake.ext.commands.Bot.on_slash_command_error 🦶

unkempt canyonBOT
#

await on_slash_command_error(interaction, exception)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

The default slash command error handler provided by the bot.

By default this prints to [`sys.stderr`](https://docs.python.org/3/library/sys.html#sys.stderr "(in Python v3.11)") however it could be overridden to have a different implementation.

This only fires if you do not specify any listeners for slash command error.
vale wing
#

Disnaek gud 👍

rustic edge
#

cause im not very smart

upbeat gust
rustic edge
#

where do I put that in my code?

upbeat gust
#

anywhere

rustic edge
#

k

#

it gets underlined

shrewd apex
upbeat gust
rustic edge
#

idk

upbeat gust
#

well hover over it then-

rustic edge
slate swan
#

What is the best way to have a cooldown on a command?

naive briar
#

!d discord.ext.commands.cooldown

unkempt canyonBOT
#

@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.

A command can only have a single cooldown.
slate swan
#
@app_commands.has_permission(ban_members=True)

how can I make the user need perms to do a slash command?

slate swan
#

@naive briar is there a way to reset the cooldown using a command?

naive briar
#

🤨

slate swan
naive briar
#

Not with the cooldown

#

!d discord.ext.commands.dynamic_cooldown

unkempt canyonBOT
#

@discord.ext.commands.dynamic_cooldown(cooldown, type)```
A decorator that adds a dynamic cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")

This differs from [`cooldown()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.cooldown "discord.ext.commands.cooldown") in that it takes a function that accepts a single parameter of type [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Cooldown "discord.app_commands.Cooldown") or `None`. If `None` is returned then that cooldown is effectively bypassed.

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.

A command can only have a single cooldown.

New in version 2.0.
slate swan
#
User: Zio Economy#3124
Prefix: z
Failed to upload commands to Discord (HTTP status 400, error code 50035)
In command 'purge' defined in function 'ban'
  In parameter 'amount'
    description._errors: [{'code': 'BASE_TYPE_REQUIRED', 'message': 'This field is required'}]

naive briar
#

You have to store the cooldown somewhere in a database

slate swan
# slate swan ```py User: Zio Economy#3124 Prefix: z Failed to upload commands to Discord (HTT...
@client.tree.command(name='purge', description='Deletes messages.')
@app_commands.describe(amount = '')
async def ban(interaction: discord.Interaction, amount: str):
  if amount == '':
    await interaction.response.send_message('Please provide an integer to purge.', ephemeral=True)
  amount = int(amount)
  if amount <= 0:
    await interaction.response.send_message(f'Cannot purge {amount} mesages!.', ephemeral=True)
  if amount >= 201:
    await interaction.response.send_message(f'Cannot purge more than 200 mesages!.', ephemeral=True)
  if amount <= 200 and amount >= 1:
    purge = discord.Embed(title='purged', description=f'**Purged**: {amount} message')
    await interaction.channel.purge(limit=amount)
    await interaction.response.send_message(embed=purge, ephemeral=True)
slate swan
naive briar
#

!d discord.app_commands.Cooldown.reset

unkempt canyonBOT
bright wedge
#

guild not defined

slate swan
#

@bright wedge like how do i do that then

#

do i do in the async def guild?

#

@bot.command()
@commands.has_permissions(administrator=True)
async def changeprefix(ctx, prefix):

with open("prefix.json", "r") as f:
    prefix = json.load(f)
prefix[str(guild.id)] = prefix

with open("prefix.json", "w") as f:
    json.dump(prefix, f)
bright wedge
#

you write this pert?

slate swan
#

yes

#

is it wrong?

bright wedge
#

ctx.guild

naive briar
#

!d discord.ext.commands.Context.guild

unkempt canyonBOT
slate swan
#

oh thanks

#
Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\client.py", line 502, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 1422, in on_message
    await self.process_commands(message)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 1418, in process_commands
    ctx = await self.get_context(message)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 1324, in get_context
    prefix = await self.get_prefix(message)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 1266, in get_prefix
    ret = await nextcord.utils.maybe_coroutine(prefix, self, message)  # type: ignore
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\utils.py", line 548, in maybe_coroutine
    value = f(*args, **kwargs)
  File "c:\Users\PC\Desktop\Appelsy Bot\main.py", line 23, in get_prefix
    prefix = json.load(f)
  File "C:\Program Files\Python39\lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
  File "C:\Program Files\Python39\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Program Files\Python39\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Program Files\Python39\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)```
#



def get_prefix(bot, message):

    with open("prefix.json", "r") as f:
        prefix = json.load(f)
    return prefix[str(message.guild.id)]

bot = commands.Bot(command_prefix= get_prefix , help_command=None, intents=nextcord.Intents.all())

@bot.event
async def on_guild_join(guild):

    with open("prefix.json", "r") as f:
        prefix = json.load(f)
    prefix[str(guild.id)] = "!"

    with open("prefix.json", "w") as f:
        json.dump(prefix, f)

   



@bot.command()
@commands.has_permissions(administrator=True)
async def changeprefix(ctx, prefix):

    with open("prefix.json", "r") as f:
        prefix = json.load(f)
    prefix[str(ctx.guild.id)] = prefix

    with open("prefix.json", "w") as f:
        json.dump(prefix, f)
bright wedge
#

Brackets in your js file

slate swan
#

OH WHY DID I FORGOT

#

thanks

bright wedge
#

👍

naive briar
#

What do you mean

bright wedge
#

Must use custom function

slate swan
#

File "c:\Users\PC\Desktop\Appelsy Bot\main.py", line 24, in get_prefix
return prefix[str(message.guild.id)]
KeyError: '1036249066193047562'

#

do i use int

shrewd apex
#

whats prefix

bright wedge
#

Yes

slate swan
#

File "c:\Users\PC\Desktop\Appelsy Bot\main.py", line 24, in get_prefix
return prefix[int(message.guild.id)]
KeyError: 1036249066193047562

shrewd apex
#

just put a try except

bright wedge
#

You need to create it, there is no ready function for that.

#

It's easy if you think it

naive briar
#

And JSON isn't a database

shrewd apex
#

when u edit some sort of exception is raised use that

#

idk which exception

bright wedge
#

You can use asyncio sleep

#

Or you can go deeper,but play with asyncio for first

slate swan
smoky patrol
#

How can i build in a simple rich presence

unkempt canyonBOT
#

Hey @prisma crystal!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

prisma crystal
radiant parrot
#

How would I go about removing a title from an embed when done embed_to_dic

prisma crystal
naive briar
radiant parrot
slate swan
#

how do you delete a channel with discord py

loud junco
#
      embed.set_image('https://static.wikia.nocookie.net/monopoly/images/a/a5/Monopoly_Board_Game_%28UK%29.jpg/revision/latest/scale-to-width-down/1000?cb=20220120173735')
```this is not how u use it?? (2 argument is given but 1 is only needed)
naive briar
#

!d discord.TextChannel.delete

unkempt canyonBOT
#

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

Deletes the channel.

You must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to do this.
naive briar
slate swan
radiant parrot
slate swan
#

i want my channel deleted by a button press

slate swan
#

await interaction.channel.delete()?

slate swan
#

a

#

thank you

#

how do i make my bot only listen to user?

naive briar
#

A specific user or all users that isn't a bot

slate swan
naive briar
#

!d discord.User.bot - check if this is True or not

unkempt canyonBOT
slate swan
#

wait

#

that embed looks similar

#

it aint workign

slate swan
#

why u deleting ur messages now

#

and y u aint responding

#

can you leave me alone

#

.

brazen skiff
#

how to add cogs to the new discord.py slash command version?

naive briar
#

!d discord.ext.commands.Bot.add_cog

unkempt canyonBOT
#

await add_cog(cog, /, *, override=False, guild=..., guilds=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Adds a “cog” to the bot.

A cog is a class that has its own event listeners and commands.

If the cog is a [`app_commands.Group`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group "discord.app_commands.Group") then it is added to the bot’s [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") as well.

Note

Exceptions raised inside a [`Cog`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog "discord.ext.commands.Cog")’s [`cog_load()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.cog_load "discord.ext.commands.Cog.cog_load") method will be propagated to the caller...
shrewd apex
slate swan
#

👍

brazen skiff
#

like in github ?

slate swan
brazen skiff
#

ok 👍

shrewd apex
#

bro just add cog as u do normally

brazen skiff
#

wait I confused with you both guys 🤣

brazen skiff
brazen skiff
# shrewd apex https://discord.com/channels/267624335836053506/343944376055103488/9899685983972...
import discord
from discord import app_commands
from discord.ext import commands

class test(commands.Cog):
    def __init__(self, bot: commands.Bot) -> None:
        self.bot = bot

    @app_commands.command(
        name="ping",description="whatever"
    )

    async def ping(
        self,
        interaction: discord.Interaction,
    ):
        await interaction.response.send_message(f"Pong! {round(app_commands.latency * 1000)}ms")
    

async def setup(bot: commands.Bot) -> None:
    await bot.add_cog(test(bot), guilds=[discord.Object(id=456)])
``` this is in my cogs/test.py
#

is there any mistakes?

slate swan
#

how do you make the bot delete 2 messages instead of only 1?

shrewd apex
#

seems fine yes

brazen skiff
brazen skiff
# shrewd apex seems fine yes
for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        bot.load_extension(f'cogs.{filename[:-3]}')
``` is in my main.py
naive briar
#

load_extension is a coroutine

#

You need to await it

brazen skiff
#

oh lemme try

brazen skiff
naive briar
#

It only works in a async function

brazen skiff
shrewd apex
#

have u synced?

#

oh yeah await it

#

and call this function in setup_hook

brazen skiff
#

ok

#
@bot.event
async def on_ready():
    print('Bot is up and ready')
    async def setup_hook(self):
        for filename in os.listdir('./cogs'):
            if filename.endswith('.py'):
                await bot.load_extension(f'cogs.{filename[:-3]}')

    try:
        synced = await bot.tree.sync()
        print(f'Synced {len(synced)} command(s)')

    except Exception as e:
        print(e)
``` the main func
naive briar
#

Reading the walkthrough would have told you that

#

!d discord.ext.commands.Bot.setup_hook

unkempt canyonBOT
#

await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

A coroutine to be called to setup the bot, by default this is blank.

To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.

This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login "discord.ext.commands.Bot.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") event.

Warning

Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_for "discord.ext.commands.Bot.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_until_ready "discord.ext.commands.Bot.wait_until_ready")...
brazen skiff
naive briar
#

setup_hook is an event

slate swan
#

this isnt working

brazen skiff
slate swan
shrewd apex
#

bro learn basic python first

#

discord.User.bot == True 💀
its if message.author.bot:

slate swan
#

nothing is happening

brazen skiff
#

@shrewd apex the cog is not syncing 🤦‍♂️

shrewd apex
vocal snow
slate swan
#

i changed

vocal snow
vocal snow
#

this still makes no sense

#

what is that supposed to do

slate swan
#

dude

slate swan
#

i need my bot only respond to discord people not bots

cold oyster
#

Hey so I have a modal, How do I send the modal embed to another channel, A channel with it's ID

vocal snow
slate swan
vocal snow
#

anyways it wont matter

#

your first if statement checks the user id

#

it's only going to execute the rest of the code if the message author's id is that

vocal snow
slate swan
#

i cant send much im on phone

cold oyster
slate swan
cold oyster
#

ok

#
    async def callback(self, interaction) -> None:
        embed = disnake.Embed(title="Apply for Pilot")
        for key, value in interaction.text_values.items():
            embed.add_field(name=key, value=value, inline=False)
        await interaction.response.send_message(embed=embed)


@client.slash_command() 
async def apply_pilot(inter: disnake.ApplicationCommandInteraction):
    await inter.response.send_modal(modal=MyModal())
slate swan
#

ah ill have to look at it on pc @cold oyster srry

bright wedge
#

how i can make a slash command works in all guilds?

#
@tree.command(name = "test", description = "My first application Command")
async def first_command(interaction):
    await interaction.response.send_message("Hello!")
vocal snow
#

sync the tree globally

bright wedge
vocal snow
#

you can just await tree.sync()

slate swan
# cold oyster alr

in ur callback try do channel = interaction.guild.get_channel() and put your channel id in the parenthesis then under just type await channel.send(embed=embed) this is what i think ur tryna achieveme btw

bright wedge
brazen skiff
mystic birch
#

hey, when I launch my bot it says process with exited code 1 do you have an idea please?

cold oyster
#
    async def callback(self, interaction) -> None:
        embed = disnake.Embed(title="Apply for Pilot")
        channel = interaction.guild.get_channel(1037373141460193350)
        for key, value in interaction.text_values.items():
            embed.add_field(name=key, value=value, inline=False)
        await channel.send_message(embed=embed)


@client.slash_command() 
async def apply_pilot(inter: disnake.ApplicationCommandInteraction):
    await inter.response.send_modal(modal=MyModal())```
#

My code

cold oyster
slate swan
#

not send_message

#

just send

cold oyster
#

oh ok

mystic birch
#

hey, when I launch my bot it says process with exited code 1 do you have an idea please?

cold oyster
cold oyster
#

It still send the image

#

@slate swan

slate swan
sharp sky
#

Hmm

slate swan
#

@slate swan ur an alt of a scammer

#

lmfao

unkempt canyonBOT
#

Hey @mystic birch!

It looks like you tried to attach file type(s) that we do not allow (.js). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.

Feel free to ask in #community-meta if you think this is a mistake.

slate swan
#

modal*

#

i cant look at it on phone srry

naive briar
mystic birch
slate swan
mystic birch
#

py

slate swan
#

@mystic birch

naive briar
#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

mystic birch
#

are these aphostrophes?

slate swan
slate swan
slate swan
# slate swan no?

you are dont lie as soon as i saw that embed from your message i knew instantly you had contact with my friend and now hes told me that ur an alt of a scammer who makes scam roblox servers

mystic birch
#

thanks

slate swan
#

I’m not a alt either 💀

#

You got no proof either

mystic birch
#

suddenly I can't launch my bot you know why? I put the token lower

slate swan
#

And you know nothing abt what I do and my story so yeah

mystic birch
#

thanks

slate swan
#

anyways keep ur story in my dms and dont talk here

#

Nah I don’t feel like wasting time on you anyways

slate swan
#

this channel lol

vocal snow
#

🍵

primal token
little peak
#

Hello i want to make a discord bot that outputs the newest video of a channel with a slash command i managed to get the video id with yt api now how do i form the link i want to add
(data["items"][0]["id"]["videoId"])
infront of
https://www.youtube.com/watch?v=

slate swan
#

!fstring

unkempt canyonBOT
#

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

mighty yarrow
#

@slate swan

little peak
#

nvm

slate swan
slate swan
little peak
#

i now get this

little peak
# slate swan ?

print(f"https://www.youtube.com/watch?v= {data["items"][0]["id"]["videoId"]}") ^ SyntaxError: f-string: unmatched '['

primal token
#

use single quotes in your f string

slate swan
#

toggle one of them

little peak
#

oh

#

like remove the "

primal token
#

!e

print(f'{"lol"}')
unkempt canyonBOT
#

@primal token :white_check_mark: Your 3.11 eval job has completed with return code 0.

lol
little peak
#

from items etc?

#

oh okay

mighty yarrow
unkempt canyonBOT
#

Custom Command Checks in discord.py

Often you may find the need to use checks that don't exist by default in discord.py. Fortunately, discord.py provides discord.ext.commands.check which allows you to create you own checks like this:

from discord.ext.commands import check, Context

def in_any_channel(*channels):
  async def predicate(ctx: Context):
    return ctx.channel.id in channels
  return check(predicate)

This check is to check whether the invoked command is in a given set of channels. The inner function, named predicate here, is used to perform the actual check on the command, and check logic should go in this function. It must be an async function, and always provides a single commands.Context argument which you can use to create check logic. This check function should return a boolean value indicating whether the check passed (return True) or failed (return False).

The check can now be used like any other commands check as a decorator of a command, such as this:

@bot.command(name="ping")
@in_any_channel(728343273562701984)
async def ping(ctx: Context):
  ...

This would lock the ping command to only be used in the channel 728343273562701984. If this check function fails it will raise a CheckFailure exception, which can be handled in your error handler.

little peak
#

thank you very much

primal token
#

Havent really seen it or remember it

slate swan
#

*than a

primal token
#

Guess i just cant remember

slate swan
#

How do i get message.content in a variable from a slash command?

slate swan
#
@client.tree.command()
async def test(interaction: Interaction):
#

im using this

#

what do i change here

#

to get user input

primal token
#

join is an int

#

What?

#

sorry join is an int lmao

#

voice[1] returns an int and you're trying to use in to the variable that has its value which would be join

#

!e

1 in 1
unkempt canyonBOT
#

@primal token :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | TypeError: argument of type 'int' is not iterable
slate swan
#

HOW DO I GET USER INPUT FROM SLASH COMMAND

#

OMG

primal token
#

I'm pretty sure most libraries use arguments, but how do you set them up? I'm not sure, you would need to find out

primal token
#

?

upbeat otter
#

(OMG)

slate swan
#
@client.tree.command()
async def test(interaction: Interaction):
#

what do i change here

upbeat otter
#
async def uwu(inter: discord.Interaction, argument: str) -> None:
  ...

# Usage: /uwu yes
shrewd apex
upbeat otter
#

,

slate swan
#

uwu ;-;

slate swan
#

ashley moment

upbeat otter
#

ahem

shrewd apex
#

sarth got bad memories

slate swan
shrewd apex
upbeat otter
slate swan
little peak
#

When i try to do this command the Bot does not anwser i want the bot to send the link and the person who uses the command to be able to put in some text that comes after the link

`#Send message "video" when user sends /video
@slash.slash(name="video", description="Sends newest video", options =
[manage_commands.create_option( #create an arg
name = "text", #Name the arg as "text"
description = "....", #Describe arg
option_type = 3, #option_type 3 is string
required = false #Make arg required
)])
async def _space(ctx: SlashContext, sentence):
newword = "" #define new sentence
for char in sentence: #For each character in given sentence
newword = newword + char + " " #Add to new sentence with space
await ctx.send(content=newword) #send mew sentence

async def _help(ctx: SlashContext):
await ctx.send(content=f'https://www.youtube.com/watch?v={(data["items"][0]["id"]["videoId"])}')`

mighty yarrow
#

like this?

sacred oyster
#

i got an error my code is ```py
import discord
from discord import app_commands

class aclient(discord.Client):
def innit(self):
super().innit(intents=discord.Intents.default())
self.synced = False
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
await tree.sync(guild = discord.Object(id = 990534020880277514))
self.synced = True
print(f"We have logged in as {self.user}")

client = aclient()
tree = app_commands.CommandTree(client)

@tree.command(name = Hello, description = "Hello user", guild = discord.Object(id = 990534020880277514))
async def self(interaction: discord.Interaction, name: str):
await interaction.response.send_message(f"Hello {name}! I was made by me!")
client.run('xxxxx')```

#

what is it?

#

ping when anyone is ready

primal token
unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot 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

intents = Intents.default()
intents.members = True

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

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

naive briar
#

Which library are you using

slate swan
#

this is a dm command that sends a message to a specific user but for some reason it only sends the the first word of what I want to send.
e,g If I wanted the bot to send hello world it would only send hello

sacred oyster
little peak
sacred oyster
slate swan
#

fixed?

stark zenith
#

how do i make my bot automatically delete a embed it sends after a few seconds

naive briar
#

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

Set the delete_after

little peak
#

When i try to do this command the Bot does not anwser i want the bot to send the link and the person who uses the command to be able to put in some text that comes after the link

`#Send message "video" when user sends /video
@slash.slash(name="video", description="Sends newest video", options =
[manage_commands.create_option( #create an arg
name = "text", #Name the arg as "text"
description = "....", #Describe arg
option_type = 3, #option_type 3 is string
required = false #Make arg required
)])
async def _space(ctx: SlashContext, sentence):
newword = "" #define new sentence
for char in sentence: #For each character in given sentence
newword = newword + char + " " #Add to new sentence with space
await ctx.send(content=newword) #send mew sentence

async def _help(ctx: SlashContext):
await ctx.send(content=f'https://www.youtube.com/watch?v={(data["items"][0]["id"]["videoId"])}')`

stark zenith
little peak
naive briar
#

That doesn't help me understand why

#

And I've never seen manage_commands in discord.py before

little peak
#

i can use /video [text: test]
but when i send it it wont respont

naive briar
#

Do you get any errors in the console

little peak
# naive briar Do you get any errors in the console

wait

An exception has occurred while executing command video:
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\client.py", line 744, in invoke_command
await coro
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\model.py", line 145, in invoke
return await self.func(*args, **kwargs)
TypeError: _space() got an unexpected keyword argument 'text'

naive briar
#

It seems like the library is calling the slash command's callback with the option names as kwargs. Try changing the option name to sentence or changing the sentence argument to text

little peak
#

thanks

little peak
naive briar
#

!e

text = "Hello, world!"
new_text = ""

for char in text:
    new_text += (char + " ")

print(new_text)
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

H e l l o ,   w o r l d ! 
little peak
#

oh

#

but it wont send the link

#

oh wait

#

i think i know how

mighty yarrow
little peak
unkempt canyonBOT
#

Joining Iterables

If you want to display a list (or some other iterable), you can write:

colors = ['red', 'green', 'blue', 'yellow']
output = ""
separator = ", "
for color in colors:
    output += color + separator
print(output)
# Prints 'red, green, blue, yellow, '

However, the separator is still added to the last element, and it is relatively slow.

A better solution is to use str.join.

colors = ['red', 'green', 'blue', 'yellow']
separator = ", "
print(separator.join(colors))
# Prints 'red, green, blue, yellow'

An important thing to note is that you can only str.join strings. For a list of ints,
you must convert each element to a string before joining.

integers = [1, 3, 6, 10, 15]
print(", ".join(str(e) for e in integers))
# Prints '1, 3, 6, 10, 15'
naive briar
maiden fable
#

Ah okay

stark zenith
#

why wont it delete the embed after sleeping for 4 seconds??

upbeat otter
stark zenith
#

thats where embed came from

upbeat otter
stark zenith
naive briar
#

Store that in a variable then delete it

stark zenith
#

alright

naive briar
#

!d discord.Message.delete

unkempt canyonBOT
#

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

Deletes the message.

Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages").

Changed in version 1.1: Added the new `delay` keyword-only parameter.
naive briar
#

Or just set the delete_after argument

slate swan
#
Traceback (most recent call last):
  File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 851, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "main.py", line 37, in sync
    await interaction.response.send_message(f"synced {len(synced)} commands in this guild!", ephemeral=True)
  File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/interactions.py", line 718, in send_message
    await adapter.create_interaction_response(
  File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/webhook/async_.py", line 219, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1240, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 876, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 869, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'sync' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
#
@client.tree.command(name='sync', description='If commands arent working or there oudated, use this.')
async def sync(interaction: discord.Interaction):
 synced = await client.tree.sync(guild=interaction.guild)
 await interaction.response.send_message(f"synced {len(synced)} commands in this guild!", ephemeral=True)
               ```
naive briar
#

It took too long to respond

cloud dawn
#

Register globally instead.

stark zenith
naive briar
#

What's the error then

slate swan
cloud dawn
#

use the delete_after lol

slate swan
#

Or that

mighty yarrow
#

Why replit is faster than my vscode

#

Wtf

slate swan
cloud dawn
#

lmao

#

repl.it is 512mb ram and like 1.5ghz zo doubt

slate swan
#

Is that an arg?

cloud dawn
stark zenith
#

can u give me example on where to put that

#

cant find anything online

slate swan
stark zenith
#

like that?

slate swan
cloud dawn
stark zenith
#

i got this error

slate swan
#
c = await interaction.guild.create_text_channel(
        f"Ticket {interaction.user.id}", overwrites=overwrites)
      await c.send(
        f"{interaction.user.mention} **Please wait for staff**, Your **next** ticket can be open in **5m**. **Staff members** do **{prefix}close** to **close this ticket**. **(#{client.ticketnumber})**"
slate swan
stark zenith
#

im not using buttons @slate swan

slate swan
# stark zenith

Why don't you make message send in channel using the button it's easier and more convenient

#

yea^

#

and you can check if they have a ticket

#

Using an event is very excessive

#
ticket = utils.get(interaction.guild.text_channels,
                       name=f"ticket-{interaction.user.id}")
    if ticket is not None:
      await interaction.response.send_message(
        f"{interaction.user.mention} you already have a ticket open here {ticket.mention}.",
stark zenith
#

because i need my bot to send a message as soon as a ticket is made via ticket tool then to delete itself after a few seconds

slate swan
#

yea

slate swan
#

here @winter coral

stark zenith
#

but i cant have buttons

slate swan
stark zenith
#

i dont want buttons

#

at all

slate swan
#

its better

stark zenith
#

i js want a quick message saying "waiting for a sessiosn" then it deletes itself after a few seconds

stark zenith
slate swan
#
c = await ctx.guild.create_text_channel(f"Ticket {ctx.author.id}")
      message = await c.send(
        f"{ctx.author.mention} waiting for sesson"
      await asyncio.sleep(5)
      await message.delete()
slate swan
# stark zenith at all

Fair enough, but put the channel create from command into variable for example
chnanel_created = guild.Chanel.create or whatever

msgg = chnanel_created.send("hi")
time.sleep(5)
msgg.delete()

#

A lot more efficient

slate swan
#

yea lol

#

just took it from mine 😎

#

Lol I have done the same thing with mine too

#

I mean it's most convenient way so I'm not surprised

#

yea

#

i love making slash commands]

#

Ngl i use to use discord py but now I use nextcord due to the fact of discord py devs randomly quiting the project

#

What database

#

json

#

ik its not the best but

#

What?

#

idk

#

json isn't a database

#

it is now

#

💀

alpine cove
slate swan
#

Why not just use mongo db

#

idk how

alpine cove
#

or psql if ur a beginner

open yoke
#

Why is pip install discord working with 3.10 but not 3.11?

sick birch
#

After all it only released a few weeks ago

alpine cove
slate swan
mighty pilot
#

I haven't used mongodb myself but how is it easier? You literally write what you want done in sql and it does it Sussott

slate swan
sick birch
#

But for something like Discord a relational database is more fitting due to the relational nature of its data

mighty pilot
#

I need structure in my life Norow

sick birch
#

same friend

slate swan
teal glade
slate swan
#

Whatever you prefer

#

Some people prefer SQLite I personally prefer mongo

teal glade
#

hmm yea i've seen many use mongo

open yoke
slate swan
#

Fun fact: when discord was first released it used mongo db but they had to migrate to Casandra due to a lot of issues

#

i prefer pickle

stark zenith
#

@slate swan this wont work see anything wrong i could fix?

alpine cove
slate swan
#

msgg = await channel.send(embed=embedVar)

stark zenith
#

ah alr ty

mighty pilot
#

it was never awaited so what do you think needs to be done

slate swan
stark zenith
#

oh im dumb 💀

alpine cove
mighty pilot
#

Woo learning 📈

stark zenith
#

alright i think i got lemme run it

#

yeah learning py i think im doing good so far

#

started 3 days ago so yeah

alpine cove
stark zenith
#

works 👍 thanks guys

mighty pilot
slate swan
#
@client.tree.command(name='sell', description='Sell your items here!')
@app_commands.describe(amount='How much to sell?')
@app_commands.describe(choices='Choose an item!')
@app_commands.choices(choices=[
  discord.app_commands.Choice(name='Clownfish', value=1),
  discord.app_commands.Choice(name='Sunfish', value=2),
  discord.app_commands.Choice(name='Nametag', value=3)
])
async def sell(interaction: discord.Interaction, choices: discord.app_commands.Choice[int] ,amount: int):
  if choices == 1:
#

how can I see what the user put for the choice?

slate swan
mighty pilot
#

What do you mean by see what they put

alpine cove
#

-_-

slate swan
slate swan
slate swan
alpine cove
slate swan
#

i dont understand the docs?

mighty pilot
#

I don't even understand the question

#

What exactly are you trying to see

slate swan
#

im trying to run a command based off the user input

mighty pilot
#

So what's the problem? If choices == sunfish: do a thing

slate swan
#

yea basically

mighty pilot
#

So what's the question

slate swan
#

got it

#

if choice.value == 1:

slate swan
mighty pilot
sick birch
#

It uses a tree as a container for application commands

slate swan
#

Also the tree gives more control over what you can do with app commands

slate swan
#

i tried here but i get this error

mighty pilot
#

I didn't know there were any differences tbh I just thought it made more sense to use the tree

slate swan
#

🗿 read the source code and you'll find much more interesting stuff there

mighty pilot
slate swan
#

imagine syncing a command to sync a command that syncs commands

visual trellis
#

can someone help me why my command isnt working

alpine cove
slate swan
#

the color is suppose to be a integer and you gave it a string

alpine cove
#

did u put smth like: discord.Color("red")

visual trellis
alpine cove
#

bruh

#

just dont pass color

#

or do color=None

mighty pilot
#

That's a good one

slate swan
#
@client.tree.command(name='sync', description='If commands arent working or there oudated, use this!')
async def sync(interaction: discord.Interaction):
 synccmds = await client.tree.sync(guild=interaction.guild)
 await interaction.response.send_message(f"synced {len(synccmds)} commands in this guild!", ephemeral=True)
 return

can someone please help me fix this?

visual trellis
alpine cove
visual trellis
#

@client.command()
async def update(ctx):
embed = discord.Embed(
title = 'title',
description = 'desc',
colour = None
)
embed.set_footer(text = 'this is a footer')
embed.set_image(url='')
embed.set_thumbnail(url='')
embed.set_author(name='Jordan', icon_url='')
embed.add_field(name='field name', value='field value', inline=False)
embed.add_field(name='field name', value='field value', inline=True)
embed.add_field(name='field name', value='field value', inline=False)
embed.add_field(name='field name', value='field value', inline=True)
await client.say(embed=embed)

alpine cove
visual trellis
alpine cove
open yoke
#

any idea when discord.py will start working with 3.11?

visual trellis
#

your helping now anyone can help but your choosing too

alpine cove
slate swan
visual trellis
slate swan
#

@visual trellis he doesnt have to help...

visual trellis
#

hence why i said hes choosing too

open yoke
#

when I try to do pip install discord it gives me an error

slate swan
#

and its pip install discord.py, not pip install discord

stark zenith
#

anyone know how i can 2 embeds together like this? cant find any resources online helping me with it

open yoke
slate swan
warped mirage
#

Can someone help me make a on message event, so basically if someone says a word, lets put "free" as an example, It says don't beg for free stuff, then deletes the users message, which in my case is free

slate swan
#
def get_prefix(bot, message):

    with open("prefix.json", "r") as f:
        prefix = json.load(f)
    return prefix[int(message.guild.id)]

bot = commands.Bot(command_prefix= get_prefix , help_command=None, intents=nextcord.Intents.all())
@bot.event
async def on_guild_join(guild):

    with open("prefix.json", "r") as f:
        prefix = json.load(f)
    prefix[int(guild.id)] = "!"

    with open("prefix.json", "w") as f:
        json.dump(prefix, f)
@bot.command()
@commands.has_permissions(administrator=True)
async def changeprefix(ctx, prefix):

    with open("prefix.json", "r") as f:
        prefix = json.load(f)
    prefix[int(ctx.guild.id)] = prefix

    with open("prefix.json", "w") as f:
        json.dump(prefix, f)

error:

Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\client.py", line 502, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 1422, in on_message
    await self.process_commands(message)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 1418, in process_commands
    ctx = await self.get_context(message)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 1324, in get_context
    prefix = await self.get_prefix(message)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 1266, in get_prefix
    ret = await nextcord.utils.maybe_coroutine(prefix, self, message)  # type: ignore
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\utils.py", line 548, in maybe_coroutine
    value = f(*args, **kwargs)
  File "c:\Users\PC\Desktop\Appelsy Bot\main.py", line 24, in get_prefix
    return prefix[int(message.guild.id)]
KeyError: 1036249066193047562```
#

jsons don't have integer Keys
you meant to use str(message.guild.id) there maybe
and stop using json as a database!

#

i dont know database so i am using json for now

warped mirage
#

Can someone help me with this py @client.event async def on_message(message, inter: discord.Interaction, user: discord.User): message = "free"

warped mirage
#

How can i do so if someone says that word, in any channel, bot deletes the users message and Pings it and says: This word is blacklisted

warped mirage
#

message: message.content?

slate swan
warped mirage
#

All I need is a small event

slate swan
#

in here

warped mirage
#
@client.event
async def on_message(message, inter: discord.Interaction, user: discord.Member):
    message.content = "free"```
#

I have this now

slate swan
#

u should use if statment

warped mirage
#

yea

#

And i need to it sees what user

#

So it pings ig

slate swan
#

if message.content == “free”:
await message.delete()
await message.author.send(f“{message.author.mention} this is a blacklisted word”

something like that i think so hard on mobile

#

embed.colour=int("0x" + colour, 16)
so thats what i did how do i do that if they put a color like red it will be red and not w hex

warped mirage
#
@client.event
async def on_message(message, inter: discord.Interaction, user: discord.Member):
    message.content = "free"
    if message.content == "free":
        await message.delete()
        await message.author.send(f"{message.author.mention} this is a blacklisted word");```
#

so this?

slate swan
#

cuz u already did it

warped mirage
#
@client.event
async def on_message(message, inter: discord.Interaction, user: discord.Member):
    if message.content == "free":
        await message.delete()
        await message.author.send(f"{message.author.mention} this is a blacklisted word");```?
slate swan
#

u do
[str(join)]: i think

#

try that maybe it wont work

naive briar
#

What are you even trying to do

mighty pilot
feral frost
#

how can i make it so that when i input a number and another one that it becomes 1 for example 2 and 1 it becomes 21

warped mirage
mighty pilot
open yoke
#

I've downloaded the thing it told me to

#

doesn't work still

naive briar
warped mirage
#
@client.event
async def on_message(message, member: discord.Member):
    if message.content == "free":
        await message.delete()
        await message.channel.send(f"{member.mention},\nDon't beg for free stuff...\nUse [#95138054399863123](/guild/267624335836053506/channel/95138054399863123/) to beg!", after_delete = 10)```

err: TypeError: on_message() missing 1 required positional argument: 'member'
#

How can i fix?

feral frost
slate swan
#

embed.colour=int("0x" + colour, 16)
so thats what i did how do i do that if they put a color like red it will be red and not w hex

naive briar
warped mirage
#

member isnt defined now.

naive briar
#

Then get the member from the message

warped mirage
#

How?

naive briar
#

!d discord.Message.author

unkempt canyonBOT
warped mirage
#
@client.event
async def on_message(message):
    if message.content == "free":
        await message.delete()
        await message.channel.send(f"{member.mention},\nDon't beg for free stuff...\nUse [#951380543998663123](/guild/267624335836053506/channel/951380543998663123/) to beg!", after_delete = 10)```
#

this is what I have

slate swan
warped mirage
warped mirage
#

And either way, it starts with "member"

naive briar
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

019
warped mirage
#

Can someone please help?

feral frost
#

ok

slate swan
#

embed.colour=int("0x" + colour, 16)
so thats what i did how do i do that if they put a color like red it will be red and not w hex

slate swan
warped mirage
#

So how do i fix?

slate swan
#

bring member syntax in on_message

naive briar
#

Don't

primal token
#

You cant

#

on_message is a namespace which only takes 1 argument upon calling

slate swan
#

message.author?

primal token
#

!d discord.Message.mentions

unkempt canyonBOT
#

A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.

Warning

The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.

warped mirage
#

So i showed what i have atm, can someone help me fix?

slate swan
#

whats the problem tho

warped mirage
slate swan
#
embed.colour=int("0x" + colour, 16)```
so thats what i did how do i do that if they put a color like red it will be red and not w hex i made that members can make an embed and they need to choose color
slate swan
warped mirage
#

I want so it pings the member

slate swan
#

wait so message.author.mention doesnt work?

warped mirage
#

It deleted message but

#
 await message.author.mention(f"Don't beg for free stuff...\nUse [#951380543998668810](/guild/267624335836053506/channel/951380543998668810/) to beg!", after_delete = 10)
TypeError: 'str' object is not callable```
slate swan
#

bro

#

in the f string

warped mirage
#

?

cloud dawn
mighty pilot
warped mirage
#

How do i fix?

feral frost
slate swan
naive briar
#

They told you like 5+ times

warped mirage
#

thats what i did

slate swan
#

bro

#

!e

#

u did this

unkempt canyonBOT
#
Missing required argument

code

#
Command Help

!eval [python_version] <code, ...>
Can also use: e

Run Python code and get the results.

This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.

If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside of them.

By default your code is run on Python's 3.11 beta release, to assist with testing. If you run into issues related to this Python version, you can request the bot to use Python 3.10 by specifying the python_version arg and setting it to 3.10.

We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!

slate swan
cloud dawn
slate swan
cloud dawn
#

And why would you f string a single variable

cloud dawn
slate swan
cloud dawn
#
await message.channel.send(message.author.mention)
slate swan
#

im just saying to put it in the f string cos he wanted to say something else with it

#
@client.event
async def on_message(message, ctx, member:discord.Member):
    if message.content == "free":
        await message.delete()
        await ctx.send(f"{ctx.author.mention} Don't beg for free stuff...\nUse [#951380543998663123](/guild/267624335836053506/channel/951380543998663123/) to beg!", after_delete = 10)```
slate swan
#

@warped mirage just copy what he sent at this point tbh ^

feral frost
#

just like a calc like this

@bot.command(aliases=["calc"])
async def calculator(ctx, *, expression:str):
    calculation = eval(expression)
    embed = discord.Embed(title="Calculator:", color=color)
    embed.add_field(name="Input:", value=f"{expression}", inline=False)
    embed.add_field(name="Result:", value=f"{calculation}", inline=False)
    await ctx.send(embed=embed)
naive briar
feral frost
#

ill explain

feral frost
naive briar
#

And someone can do some naughty things if you're using eval for the calculator

feral frost
naive briar
feral frost
#

how can i make it more ?

slate swan
naive briar
feral frost
#

but like i want infinite numberos

slate swan
#

i believe, or im wrong

feral frost
slate swan
#

Yes, but if you keep assigning it, you can have more.

feral frost
#

what does os.system('clear') do ?

naive briar
#

Clear the console

unkempt canyonBOT
#

examples/basic_bot.py lines 45 to 47

async def choose(ctx, *choices: str):
    """Chooses between multiple choices."""
    await ctx.send(random.choice(choices))```
cloud dawn
slate swan
feral frost
slate swan
cloud dawn
feral frost
naive briar
#

What do you mean

feral frost
#

look

naive briar
#

What does your code look like

smoky patrol
#

hey guys
i worked on my discord bot and i want to use like a restart command do you know how to code it

feral frost
# naive briar What does your code look like

@bot.command(description='For when you wanna settle the score some other way')
async def choose(ctx, *choices: str):
"""Chooses between multiple choices."""
await ctx.send(random.choice(choices))

naive briar
#

You're choosing random element from it

cloud dawn
#

it has to be a list

feral frost
pearl inlet
#
@bot.event
async def on_raw_reaction_add(payload):
    print(payload.member.id)
    channel = bot.get_channel(payload.channel_id)
    user = bot.get_user(id=payload.user_id)
    print(str(user.name))
    print("reaction added")
    if (payload.member != bot.user):
        await channel.send((user.id, "just reacted to a message!"))

The goal is to send a message when someone adds a reaction to a message for some reason user is returning "none"

naive briar
unkempt canyonBOT
#

get_user(id, /)```
Returns a user with the given ID.

Changed in version 2.0: `id` parameter is now positional-only.
naive briar
#

And you must have members intent enabled

cloud dawn
smoky patrol
slate swan
honest shoal
naive briar
#

!d discord.Client.close

unkempt canyonBOT
#

await close()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Closes the connection to Discord.
naive briar
#

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

smoky patrol
#

dont know where to implement it

honest shoal
#

use brackets

smoky patrol
#

can u show me how i should do it?

slate swan
smoky patrol
slate swan
#

can someone give me a spicy layout for a help embed 🙏 (@)

honest shoal
slate swan
slate swan
slate swan
#

but I can edit it if it is one

open yoke
#

guess what, didnt work

slate swan
honest shoal
smoky patrol
#

ok let me try

slate swan
#

yeah it works for hundreds of people but not you, cool

slate swan
#

yea

honest shoal
#

hmmm use slash commands in this modern era

open yoke
honest shoal
#

they are well descriptive

slate swan
#

like this

smoky patrol
slate swan
naive briar
honest shoal
slate swan
unkempt canyonBOT
#

await start(token, *, reconnect=True, ignore_session_start_limit=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

A shorthand coroutine for [`login()`](https://docs.disnake.dev/en/latest/api.html#disnake.Client.login "disnake.Client.login") + [`connect()`](https://docs.disnake.dev/en/latest/api.html#disnake.Client.connect "disnake.Client.connect").
slate swan
#

disssssss 🐍

#

i suck at making embeds fr

naive briar
#

Their docs pages looks beautiful

honest shoal
# slate swan ?

I mean, you don't really need help menus for slash commands

slate swan
slate swan
slate swan
#

if i were to rate discord libs it would be like
hikari
disnake
dpy
nextcord

smoky patrol
slate swan
#

i mean if you make each cmd like this then you dont need it

#

pycord doesnt exist ;-;

mighty pilot
cloud dawn
slate swan
cloud dawn
#

what is pycord?

slate swan
#

Pycord is super underdeveloped

#

how can I add a cooldown to slash cmds...

#

ffmpeg wrapper sun_glass

#

!pip pycord

unkempt canyonBOT
smoky patrol
open yoke
#

i had some dude trying to help me yesterday

#

i did it in front of him and even he was confused

honest shoal
mighty pilot
naive briar
unkempt canyonBOT
honest shoal
naive briar
#

!d disnake.ext.commands.Cooldown

unkempt canyonBOT
honest shoal
#

so it's same for slash and prefix based cmds

slate swan
open yoke
#

do you know when it'll be fixed or nah?

slate swan
#

that's upto those libraries' maintainers, i can;t say anythin

#
@client.tree.command(name="beg", description="Beg for money!")
@commands.cooldown(1, 10, commands.BucketType.user)
@client.event
async def on_application_command_error(ctx, error):
  if isinstance(error, commands.CommandOnCooldown):
    await ctx.send(error)
  else: 
    raise error
#

why doesnt this work

cloud dawn
naive briar
#

There's no on_application_command_error event

slate swan
#

app_commands.CommandOnCooldown

naive briar
slate swan
slate swan
#

there's something called on_app_command_error but idk what class it belongs to

cloud dawn
slate swan
#

@discord.app_commands.Cooldown(1, 10)

cloud dawn
#

Not that easy

slate swan
#

@client.tree.command(name="beg", description="Beg for money!")
@app_commands.checks.cooldown(1, 15, key=lamdba i: (i.user.id))

#

what about this

cloud dawn
#

Yup

#

I've made a function if you're interested.

slate swan
#

im interested

smoky patrol
#

How can i build in a simple rich presence, my friends told me it does not work

cloud dawn
#
from typing import Callable, TypeVar
from enum import Enum

from discord.app_commands import Cooldown

# noinspection PyProtectedMember
from discord.app_commands.checks import _create_cooldown_decorator

T = TypeVar('T')


class Btypes(Enum):
    guild = lambda i: (i.guild_id, i.guild_id)
    channel = lambda i: (i.guild_id, i.channel_id)
    user = lambda i: (i.guild_id, i.user.id)


def koeldown(rate: float | int, per: float | int, btype: Btypes) -> Callable[[T], T]:
    return _create_cooldown_decorator(btype, lambda interaction: Cooldown(rate, per))

# Usage
from utils.cooldowns import Btypes, koeldown

@koeldown(1, 150, Btypes.user)
async def...

smoky patrol
#

this right?

slate swan
#

..```py
@client.tree.error
async def on_app_command_error(error: app_commands.AppCommandError, interaction: discord.Interaction):
if isinstance(error, app_commands.CommandOnCooldown):
await interaction.response.send_message(error, ephemeral=True)
else: raise error

#
Task exception was never retrieved
future: <Task finished name='CommandTree-invoker' coro=<CommandTree._from_interaction.<locals>.wrapper() done, defined at /home/runner/game-bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py:1087> exception=TypeError('exceptions must derive from BaseException')>
Traceback (most recent call last):
  File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1240, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 872, in _invoke_with_namespace
    if not await self._check_can_run(interaction):
  File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 1010, in _check_can_run
    return await async_all(f(interaction) for f in predicates)
  File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/utils.py", line 662, in async_all
    elem = await elem
  File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/app_commands/checks.py", line 407, in predicate
    raise CommandOnCooldown(bucket, retry_after)
discord.app_commands.errors.CommandOnCooldown: You are on cooldown. Try again in 12.99s

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1089, in wrapper
    await self._call(interaction)
  File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1244, in _call
    await self.on_error(interaction, e)
  File "main.py", line 129, in on_app_command_error
    raise error
TypeError: exceptions must derive from BaseException
cloud dawn
#

I suggest building the error on the base of the tree

slate swan
#

?

cloud dawn
#

I've made it in my own bot as well, example: ```py
class CmdTree(CommandTree):
"""A subclass of CommandTree to override on_error"""

async def on_error(self, interaction: Interaction, error: AppCommandError) -> None:
    # Per usual, getting the original error
    error = getattr(error, 'original', error)

    log.debug("Reached error_handler")

    if isinstance(error, (NotFound, HTTPException, Forbidden)):
        log.warn(f"'{interaction.command.name}' command raised {error.status} {error.__class__}")
        raise error
    elif isinstance(error, CommandOnCooldown):
        await interaction.response.send_message(
            f"This command is on cooldown! Time left: {time_fmt(error.retry_after)}", ephemeral=True)
    else:
        raise error
#

@slate swan A lot on slash isn't easy, many work arounds and things need to be taken into account.

slate swan
#

im watching a yt vid and it works for him ._.

cloud dawn
glad cradle
#

Isn't the purpose of a global error handler to handle errors? So why do you raise the error

slate swan
#

5 months ago

slate swan
#

what if there's some error that's totally random, it will just be silenced

cloud dawn
#

!d discord.User.mention

unkempt canyonBOT
slate swan
#

that mentions the command author

cloud dawn
#

That's it.

glad cradle
vivid cipher
#

Help please!!!

@bot.command()
async def repeat(ctx, *args, amount = 1):
    await ctx.channel.purge(limit = amount)
    embed = discord.Embed(color = 0x177121, description = args) 
    await ctx.send(embed = embed)

If I write a command, for example, >repeat hi hello, then I get parentheses in the message (clearly visible on the screenshot). How to remove brackets?

cloud dawn
#

Because I don't have any more errors to handle.

slate swan
#

can somone help me fix my slash command cooldown

cloud dawn
#

Also this is called an echo not repeat, I'd be confused lol

#

Also just do ctx.message.delete()

unkempt canyonBOT
#

str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") will be raised if there are any non-string values in *iterable*, including [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. The separator between elements is the string providing this method.
cloud dawn
primal token
#

I was just answering his question?

#

In this case, yes args should be a kwarg, but if he wants to convert the tuple into a string he would use that, i may be incorrect in this context but i answered his question

sick birch
#

Did you import discord?

#

no worries

exotic totem
#

Can anyone tell me why it only returns the name of the author of the message, and not the message as well

#
import discord
from discord.ext import commands

class Myclient(discord.Client):
    async def on_ready(self):
        print('Logged on as {0}'.format(self.user))
    
    async def on_message(self, message):
        print('Message from {0.author}: {0.content}'.format(message))

client = Myclient(intents=discord.Intents.default())
client.run('token')
#

I already tried to change the intend to 'all'

#

Didn't work

slate swan
#
class View(discord.ui.View):

  def __init__(self, *, timeout: float = 3600.0):
    super().__init__(timeout=timeout)
    self.value = 0
    self.cd = commands.CooldownMapping.from_cooldown(1.0, 2.0, key)

  async def interaction_check(self, interaction: discord.Interaction):
    retry_after = self.cd.update_rate_limit(interaction)
    if retry_after:
      raise ButtonOnCooldown(retry_after)

how can I stop my button from intefering with my test menu

@client.command()
async def test(ctx):
  select = Select(options=[
    
  discord.SelectOption(label="Cloudy", emoji=':cloud:', description='cloudy weather'),
  discord.SelectOption(label="Rainy", description='rainy weather')
  ])
  view = View()
  view.add_item(select)
  await ctx.send("test menus", view=view)
sick birch
#

color=0xFFFF00

#

Hm?

sick birch
#

Could you show the new code with all intents?

exotic totem
#

It's basically the same thing, what changes is that the bot doesn't even run

exotic totem
#

That one

sick birch
#

Are all 3 of the privledged intents enabled?

exotic totem
#

Just the last one

sick birch
#

Make sure to enable all 3, then run your bot again with discord.Intents.all()

exotic totem
#

It worked!

#

Thanks

stark zenith
#

when a ticket is opened via ticket tool i want my bot to copy the id i send so i can add the person to the ticket, this is how far i came anything i can fix?

potent spear
#

that's not the whole error traceback

potent spear
potent spear
#

never said it was not
read the WHOLE error traceback

potent spear
cloud dawn
mighty pilot
slate swan
#

😩

slate swan
#

instead of just the menu

mighty pilot
slate swan
#

yea

#

but how can I make it so it only sends the menu

mighty pilot
#

The view is the buttons

slate swan
#

ok

#

but how can i make it only send the menu....

mighty pilot
#

Don't send the buttons with view=view Norow

slate swan
#

then what do I do?!!?!??!?!

mighty pilot
#

Create the menu in the interaction instead of the button view? Remove the items from the view before sending it?

slate swan
#

what

mighty pilot
#

Show me what it does currently in discord

slate swan
#

i dont want the button

#
  view = View()
  view.remove_item(View)
  view.add_item(select)

  await ctx.send("test menus", view=select)

i tried this but it doesnt work

#

wait

#
  view = View()
  view.remove_item(view)
  view.add_item(select)

  await ctx.send("test menus", view=view)

does the same thing

mighty pilot
#

Show the entirety of your view code now

slate swan
#
@client.command()
async def test(ctx):
  select = Select(options=[
    
  discord.SelectOption(label="Cloudy", emoji='☁️', description='cloudy weather'),
  discord.SelectOption(label="Rainy", description='rainy weather')
  ])
  view = View()
  view.remove_item(view)
  view.add_item(select)

  await ctx.send("test menus", view=view)


mighty pilot
#

That's not your view

faint mural
#
Traceback (most recent call last):
  File "/home/--/--/--/venv/lib/python3.10/site-packages/discord/client.py", line 627, in connect
    await self.ws.poll_event()
  File "/home/--/--/--/venv/lib/python3.10/site-packages/discord/gateway.py", line 645, in poll_event
    raise ConnectionClosed(self.socket, shard_id=self.shard_id, code=code) from None
discord.errors.ConnectionClosed: Shard ID None WebSocket closed with 1000
``` Any idea what could cause this?

Docs link for reference: https://discord.com/developers/docs/topics/gateway#heartbeat-interval-example-heartbeat-ack
Discord Developer Portal

Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.

slate swan
#
class View(discord.ui.View):

  def __init__(self, *, timeout: float = 3600.0):
    super().__init__(timeout=timeout)
    self.value = 0
    self.cd = commands.CooldownMapping.from_cooldown(1.0, 2.0, key)

  async def interaction_check(self, interaction: discord.Interaction):
    retry_after = self.cd.update_rate_limit(interaction)
    if retry_after:
      raise ButtonOnCooldown(retry_after)

    return True

  async def on_error(self, interaction: discord.Interaction, error: Exception,
                     item: discord.ui.Item):
    if isinstance(error, ButtonOnCooldown):
      seconds = int(error.retry_after)
      unit = 'second' if seconds == 1 else 'seconds'
      await interaction.response.send_message(f"Please wait {seconds} {unit}.",
                                              ephmeral=True)
  else:
      await super().on_error(interaction, error, item)

  @discord.ui.button(label='Create Support Channel Here',
                     style=discord.ButtonStyle.green)
  async def count(self, interaction: discord.Interaction,
                  button: discord.ui.Button):
    ticket = utils.get(interaction.guild.text_channels,
                       name=f"ticket-{interaction.user.id}")
    if ticket is not None:
      await interaction.response.send_message(
        f"{interaction.user.mention} you already have a ticket open here {ticket.mention}.",
        ephemeral=True)
faint mural
sick birch
#

1000 is an unkown error, is it persisting?

mighty pilot
faint mural
#

It sometimes happens, I am unsure why that is

slate swan
#

  select = Select(options=[
    
  discord.SelectOption(label="Cloudy", emoji='☁️', description='cloudy weather'),
  discord.SelectOption(label="Rainy", description='rainy weather')
  ])
sick birch
#

Is it local?

faint mural
#

Yes it is local (linux)

sick birch
#

Hm. It might just be on Discord's end then

faint mural
#

Maybe i have to open another issue then :sight:

mighty pilot
#

Instead of view

slate swan
#

alr alr

#
Traceback (most recent call last):
  File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 190, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 1629, in test
    view.remove_item(count)
NameError: name 'count' is not defined

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1347, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 986, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 199, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'count' is not defined

#
  view = View()
  view.remove_item(count)
  view.add_item(select)