#General Help

1 messages ยท Page 8 of 1

slender lintel
#

just wanna make sure before i start doing something else

#

ight

#

no

crimson coral
#

how did you add that ping command

slender lintel
#

different cog mm

crimson coral
#

and that cog would load a new command fine?

slender lintel
#

there's only 1 command there and I didn't touch that cog for like 4 months mm

crimson coral
#

might as well try

slender lintel
#

didn't work

stiff dagger
#

Is there something I need to do for the values to not stay 'selected' after I select them. I select orange and everything runs fine but the orange value just stays there. It's more of a visual thing, but also since the orange value remains selected there, I have to select another value before I can reselect Orange.

stiff dagger
#

Also I don't specify max_values only min_values=1 but it automatically takes it as my selection not letting me select more as if I had also set max_values as 1

crimson coral
earnest sail
#

so when I defer inside a modal's callback, it sends a response message:

async def callback(self, interaction: Interaction):
    await interaction.response.defer()

if I don't defer, I get an "this interaction failed". What can I do about it? I don't want to send a message when I defer()

frigid lark
#

you still need
interaction.response.send_message(message)

earnest sail
#

that's a discord design?

frigid lark
#

thats how you send messages with it

earnest sail
#

but I don't want to send any message after that

#

but if I don't, I get "interaction failed"

#

that's the issue

frigid lark
#

yep

#

you have to send something

earnest sail
#

that sucks

#

thanks anyway

frigid lark
#

its the same with slash commands

#

you need ctx.respond

earnest sail
#

nope

#

with slash commands when I do defer() it doesn't send a message

#

that's happening only with modals

crimson coral
#

defer is only used for extending the response time

#

even if you defer in a slash command, you still have to respond

#

the same goes for all interactions on discord

earnest sail
#

but why on modals it sends a message automatically?

crimson coral
#

it doesn't, that's the response body

#

the same happens when you type a slash command

#

you'll see a little "thinking" prompt

earnest sail
#

I don't get it.. i've been using defer on all my slash and that's not happening

#

there is no "thinking" prompt

#

and theres no "interaction failed"

crimson coral
#

because your commands are executing very quickly

earnest sail
#

maybe "interaction failed" comes after a while, but stil no thinking prompty

earnest sail
crimson coral
#

oh not thinking, it'll be sending command

earnest sail
#

theres no "thinking" prompt

crimson coral
#

that may be considered a response

earnest sail
#

but there is a thinking prompt

#

couldn't it be a bug with pycord?

crimson coral
#

i just tested and you can submit fine without it

#

do interaction.response.edit_message

#

regardless, every interaction on discord; slash commands, user commands, buttons, dropdowns, modal submissions, etc. requires a response that's either sending a new message via response or editing the message that triggered it

earnest sail
#

yeah, that worked, thank you

crimson coral
#

all good

earnest sail
#

still weird that defer() is working differently when used on modal's callbacks

crimson coral
#

i mean

#

for your usage you literally don't need defer

earnest sail
#

well, I did defer because even using interaction.message.editI was getting "interaction failed"

#

so I guess it wasn't counting as a response

crimson coral
#

defer is only needed if your response takes more than 3 seconds

earnest sail
#

anyways, may I ask you another thing?

crimson coral
#

sure

earnest sail
#

whenever I send a modal after another modal has been submitted, the placeholder value is the value from the previous modal

#

is that a discord design?

crimson coral
#

uhhhh

#

i don't think so

#

pretty sure you have full control over it

earnest sail
#

now that's weird

crimson coral
#

sounds like you're crossing variables somewhere

earnest sail
#

well I'll re read my code later

upbeat hill
#

what does this code do?

def __init__(self, channel):
        super().__init__()
        self.channel = channel
idle wagon
#

Hi. How do more than 1 dropdown, to one message? Can I do this?

upbeat hill
#

after a button has been used how do you disable thee other buttons in that view for that channel

sudden path
#

You can use the disable_all_items method

#

b!rtfm pyc disable_all_items

open bearBOT
sudden path
upbeat hill
#

thanks

upbeat hill
fresh brook
#

Any slash command in a cog examples?

obsidian goblet
#

How do i convert Users to Member objects ?

sudden path
obsidian goblet
#

yes

sudden path
#

b!rtfm pyc get_member

sudden path
#

Or

discord.utils.get(ctx.guild.members, id=124558)```
obsidian goblet
#

ive been trying to get get_member to work and it keeps giving errors

sudden path
#

ctx.guild.get_member()

upbeat hill
obsidian goblet
sudden path
#

Then the user is not a server member

obsidian goblet
#

its my id tho ?

obsidian goblet
#

thats also retuning none

glad saffron
#

Hi guys, I'm trying to use embeds, but I'm running into this issue

#

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: Embed.add_field() got an unexpected keyword argument 'title'

#

This is my code

#
embed = discord.Embed(
        title="My Amazing Embed",
        description="Embeds are super easy, barely an inconvenience.",
        color=discord.Colour.blurple(), # Pycord provides a class with default colors you can choose from
    )
    embed.add_field(title="A Normal Field", value="A really nice field with some information. **The description as well as the fields support markdown!**")

    embed.add_field(title="Inline Field 1", value="Inline Field 1", inline=True)
    embed.add_field(title="Inline Field 2", value="Inline Field 2", inline=True)
    embed.add_field(title="Inline Field 3", value="Inline Field 3", inline=True)
 
    embed.set_footer(text="Footer! No markdown here.") # footers can have icons too
    embed.set_author(name="Pycord Team", icon="https://example.com/link-to-my-image.png")
    embed.set_thumbnail(url="https://example.com/link-to-my-thumbnail.png")
    embed.set_image(url="https://example.com/link-to-my-banner.png")
 
    await ctx.respond("Hello! Here's a cool embed.", embed=embed, ephemeral=True) # Send the embed with some text
#

It's from a Pycord guide and I think either the syntax got updated and this guide is outdated or I am doing something wrong

sudden path
obsidian goblet
#

i didnt

#

thank you for the help

steep snow
glad saffron
steep snow
#

Nope, it has always been like this as far as I know.

glad saffron
#

Is this guide outdated ๐Ÿ˜…

#

Huhhh ok i see

hoary birch
#

Uh so i have been trying to update my ban command and it works fine as a slash command but when I try to use it as a prefix command it fails.
I have narrowed the error down to banning a member outside the server.

This does not work with either users in the server or outside:

@commands.command()
 @commands.has_permissions(ban_members=True)
    async def ban(self, ctx, member: discord.Member, *, reason=None):
        user = await self.bot.get_or_fetch_user(member.id)
await ctx.guild.ban(user=user, delete_message_days=0, reason=reason)

This works with both users inside and outside the server but does not work with @mentions:

@commands.command()
 @commands.has_permissions(ban_members=True)
    async def ban(self, ctx, member, *, reason=None):
        user = await self.bot.get_or_fetch_user(member)
await ctx.guild.ban(user=user, delete_message_days=0, reason=reason)

Working slash command for reference:

@moderator.command(description='Ban a member from this server!')
    async def ban(self, ctx, member: Option(discord.Member, description="@mention or user id of the member you wantto ban", required=True), *, reason=None):
await ctx.guild.ban(user=user, delete_message_days=0, reason=reason)
     ```
ancient gazelle
#

I need to get the data of the message my pycord bot has been called in form of a reaction.
Earlier, this used to work ctx.channel.fetch_message(ctx.message.reference.message_id) but cant find its replacement in pycord. Any help here.

sudden path
hoary birch
sudden path
#

Mhm.

ancient gazelle
sudden path
#

It still is message.reference

#

b!rtfm pyc message.reference

ancient gazelle
#

Can anyone help me in making a slash command that works as a response to a message?

crimson coral
ancient gazelle
crimson coral
#

not... really?

#

a slash command response is technically a reply to yourself

#

well not technically, it just looks like it

ancient gazelle
#

Oh-

#

Makes lot more sense.

#

Thanks.

crimson coral
#

all good

queen nacelle
#

how would I send a modal on button_callback (when button is clicked)

frank moon
#

how to set a value and description for each auto complete option?

ornate spade
#

I believe you can return a list of OptionChoice objects which have these attrs

warped bear
#

I used on_interaction to grant the role when the button is pressed, is there any other better way?
I don't want to change the message after restarting.

stable tiger
#

yes, persistent view with your giving roles function in its button callback

warped bear
#

It is exactly what I was looking for! Thank you.

wraith finch
#

has anybody worked with mongo here?

distant stag
#

my bot is catching events like on_message but its not responding to commands

#

could there any possible reasons for that ?

celest moth
#

what's wrong with getting a variable like this?

wide cloak
#

Whats the max time for the delete_after arg?

frank moon
ornate spade
#

if you mean an autocomplete description just use the option description

frank moon
#

Wdym option description?

ornate spade
#

Option(description="...")

frank moon
#

Oh

#

The discord.Option

ornate spade
#

I didnt think you would ask this

frank moon
#

So like ```py
return [discord.Option(name=thing, etx)]

frank moon
ornate spade
#

you can return OptionChoices

frank moon
#

Kinda confuse

ornate spade
#

and those dont have descriptions

frank moon
ornate spade
#

where should it be written

frank moon
#

Nvm forgotten how autocomplete works

#

Ok

#

So return discord.OptionChoices

#

For auto complete

ornate spade
#

yes you can return a list of those

#

OptionChoice

frank moon
#

Ok

frank moon
slender lintel
#
Traceback (most recent call last):
  File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\cog.py", line 723, in _load_from_module_spec
    setup(self)
  File "C:\Users\zReaxrYT\PycharmProjects\Discord\extensions\Verify.py", line 95, in setup
    bot.add_command(verify(bot))
AttributeError: 'Bot' object has no attribute 'add_command'

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

Traceback (most recent call last):
  File "C:\Users\zReaxrYT\PycharmProjects\Discord\main.py", line 19, in <module>
    bot.load_extension(f"extensions.{filename[:-3]}")
  File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\cog.py", line 783, in load_extension
    self._load_from_module_spec(spec, name)
  File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\cog.py", line 728, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'extensions.Verify' raised an error: AttributeError: 'Bot' object has no attribute 'add_command'

Why can i not use normal commands in cog?

celest moth
#

anyone understand this error?

crimson gale
#

reinstall package

inner iris
#

The default_permissions decorator isn't working on my bot. It doesn't matter if I set it or not, the command can always be invoked by all members.
This is my code:

    @message_group.command(
        usage="<channel> <message>",
        description="Sends a message in the given channel.",
    )
    @commands.guild_only()
    @discord.default_permissions(embed_links=True)
    async def send(
        self,
        ctx: discord.ApplicationContext,
        channel: discord.TextChannel,
        *,
        message: str,
    ):
        await channel.send(message)
        await ctx.respond(
            f"Successfully sent the message into {channel.mention}.",
            ephemeral=True,
        )

Am I doing something wrong? Well, probably yes, but what?

inland acorn
#

how to just delete the message with button if the button was not clicked under 7 seconds

inner iris
#

just delete the message after 7 seconds using the delete_after argument

inland acorn
#

coz editted message will also then deleted after 7 secs

inner iris
#

hm

slender lintel
#

my bot isn't reading message.content is there a reason for this? its only reading when i @ my bot

crimson coral
#

?tag intents

hearty rainBOT
#
import discord
from discord.ext import commands

# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True  # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content 
intents = discord.Intents.default()

# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True  # Required for prefix commands >= 2.0.0b5

# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()

# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
inner iris
#

chill, i'm thinking

crimson coral
inland acorn
#

after 7 sec of pressing

crimson coral
#

then just check if the button was pressed inside on_timeout

slender lintel
crimson coral
#

i mean it can't be that hard to think of how to check that

inland acorn
crimson coral
#

yes, timeout is always called when the view times out

#

pressing the button doesn't stop the view

inland acorn
#

uhmm should i just do view.stop in callback function?

crimson coral
#

well you can but that'll still call on_timeout

inland acorn
#

brrr

crimson coral
#

just make another variable that checks if the button was pressed

inland acorn
#

coz i am suffering with similar issue, see this #976001050110726245

crimson coral
#

it shouldn't mix, but if you're worried about that then map to an ID inside a dict or something

inland acorn
#

so just rewritting whole part of this

surreal nimbus
#

can the discord.commands.Option be subclassed and have a some sort of Context?

ornate spade
#

what's the use case?

surreal nimbus
#

I also need to get the discord.Bot instance

#

but I think I can access it, because the subclassed Option is in a cog

#

so I only need the user's id

#

wait, how do I get the discord.Bot instance if it's a class inside a class?

celest moth
#

is it necessary to close a file after i open it in python?

crimson gale
#

not necessarily but closing them frees memory for python to use

#

generally you should use context managers to handle opening files and such

obsidian garnet
#

One message removed from a suspended account.

native gulch
#

Hi, do message.content still usable in the 2.0.0rc1 version?

native gulch
clever lava
#

hey

#

i want the bot pick up one random option of the list below

#
random = ["option1","option2","option3"]
#

this is the list

#

help

#

i forgor

crimson coral
slender lintel
#
Ignoring exception in modal <extensions.Verify.verfiy_modal object at 0x000001BDB87CE550>:
Traceback (most recent call last):
  File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\ui\modal.py", line 217, in dispatch
    await value.callback(interaction)
  File "C:\Users\zReaxrYT\PycharmProjects\Discord\extensions\Verify.py", line 71, in callback
    await channel.send("Test")
AttributeError: 'NoneType' object has no attribute 'send'
crimson coral
#

your get_channel returned none

slender lintel
clever lava
slender lintel
#

self.bot.get_channel() have i tried but not working..

crimson coral
slender lintel
#

when yeah is dont working

terse kiln
#

hi why is that when i install pycord with python3 -m pip install -U py-cord --pre and start my bot it says no module named 'discord_components'?

I wrote my bot using pycord and it's been running great for the past months. Now that I moved the bot to another server it's not working.

clever lava
ocean timber
#

Can someone explain this traceback to me? Its happening after exactly one command execution.

Ignoring exception in command settings music:
Traceback (most recent call last):
  File "C:\Users\J\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 113, in wrapped
    ret = await coro(arg)
  File "C:\Users\J\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 762, in _invoke
    await self.callback(self.cog, ctx, **kwargs)
  File "C:\Workspaces\tornado-bot\cogs\settings.py", line 33, in music
    await ctx.defer(ephemeral=True)
  File "C:\Users\J\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\interactions.py", line 494, in defer
    await adapter.create_interaction_response(
  File "C:\Users\J\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\webhook\async_.py", line 211, 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 "C:\Users\J\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\bot.py", line 755, in process_application_commands
    await ctx.command.invoke(ctx)
  File "C:\Users\J\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 312, in invoke
    await injected(ctx)
  File "C:\Users\J\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 113, in wrapped
    ret = await coro(arg)
  File "C:\Users\J\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 1020, in _invoke
    await command.invoke(ctx)
  File "C:\Users\J\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 312, in invoke
    await injected(ctx)
  File "C:\Users\J\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 119, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.commands.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
hushed dove
#

It is possible to do some task like closing connection to a db when the bot is stopped?

ocean timber
# slow dome do you want to show your code?
    settings = SlashCommandGroup("settings", "Change the bots settings on this server.",
                                 permissions=[CommandPermission("manage_guild", 2, True)])

    @settings.command()
    async def music(self, ctx: ApplicationContext,
                    option: Option(str, "Select an option.", choices=["embed size: [Small | Medium | Large]",
                                                                      "delete embed when finished: [True | False]"],
                                   required=True), value: Option(str, "Select a value.", required=True)):
        """Configure the music player."""
        # await ctx.defer(ephemeral=True)

        if not values_valid(option, value.lower()):
            await ctx.respond(f"โŒ **{value} is not valid** for {option.split(': ')[0]}.\n"
                              "๐Ÿ‘‰ **Valid options are** shown **in the brackets** behind the option.", ephemeral=True)
            return

        options = {"embed size": """UPDATE settings SET MusicEmbedSize = (?) WHERE GuildID = ?""",
                   "delete embed when finished": """UPDATE settings SET MusicDeleteEmbedAfterSong = (?) 
                                                    WHERE GuildID = ?"""}
        values = {"embed size": {"large": 2, "medium": 1, "small": 0},
                  "delete embed when finished": {"true": 1, "false": 0}}
        value = value.lower()
        option = option.split(": ")[0]

        cur = database.cursor()
        cur.execute(options[option], (values[option][value], ctx.guild_id))
        await ctx.respond(f"โœ… **{option}** has been **set to {value}**.")
#

The command works perfect the first time, the second time it does not

#

and raises the error in the traceback

slow dome
#

and what does it say from the client side

ocean timber
#

what do you mean?

ocean timber
sudden path
slender lintel
#

I haven't received any replyI haven't received any reply

upbeat hill
#

how would you use disable_all_items for a interaction?

sudden path
#

I'd do py discord.utils.get(ctx.guild.channels, id=idHere)

clever lava
#
Ignoring exception in on_connect
Traceback (most recent call last):
  File "/home/runner/Hauter-Bot/venv/lib/python3.8/site-packages/discord/client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "/home/runner/Hauter-Bot/venv/lib/python3.8/site-packages/discord/bot.py", line 1147, in on_connect
    await self.sync_commands()
  File "/home/runner/Hauter-Bot/venv/lib/python3.8/site-packages/discord/bot.py", line 643, in sync_commands
Traceback (most recent call last):
  File "main.py", line 2, in <module>
Ignoring exception in on_connect
Traceback (most recent call last):
  File "/home/runner/Hauter-Bot/venv/lib/python3.8/site-packages/discord/client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "/home/runner/Hauter-Bot/venv/lib/python3.8/site-packages/discord/bot.py", line 1147, in on_connect
    await self.sync_commands()
  File "/home/runner/Hauter-Bot/venv/lib/python3.8/site-packages/discord/bot.py", line 643, in sync_commands
    registered_guild_commands[guild_id] = await self.register_commands(
  File "/home/runner/Hauter-Bot/venv/lib/python3.8/site-packages/discord/bot.py", line 473, in register_commands
    prefetched_commands = await self.http.get_guild_commands(self.user.id, guild_id)
  File "/home/runner/Hauter-Bot/venv/lib/python3.8/site-packages/discord/http.py", line 353, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
#

why am i getting this error every time i run the bot?

crimson gale
#

because some server hasnt granted the bot access to the applications.commands scope

clever lava
#

umm

clever lava
#

i toggled it on when i made the invite link

crimson gale
#

servers have to reinvite with the appropriate scopes turned on

plain rover
#

Hi, I am trying to add a command with custom permissions. For this I am using this line:

@self.slash_command(name='test2', permissions=[discord.CommandPermission(id=ROLES['Slash'], type=1, permission=True, guild_id=GUILDS['Bot Development'])])``` however the permissions don't get set correctly. What am I doing wrong?
crimson coral
#

you can no longer set user/role discord-level permissions via the bot, you can only do that via the server's integrations tab now

crimson gale
#

if you still need to limits commands to bot owner, you can just use checks instead

plain rover
#

Huh, that's sad. But thanks for the answer!

crimson gale
#

youre not out of hope

plain rover
#

I mean, I was looking for elegant solutions, I don't think checks will do the job? (Although I don't quite know how they work yet, so I will see)

crimson gale
#

they will

#

some basic checks can be found in the commands extension

#

they raise errors if the check doesnt pass for your error handler to handle

plain rover
#

But the commands would still show up if users type '/' in the chat, which is what I wanted to avoid in the first place.

placid field
#

rq, before i obliterate my bot, do i need to call await interaction.original_message() before accessing interaction.message.id, or do i have to do message = await interaction.original_message()

crimson gale
#

if the users cant use a command then i call it good enough

crimson coral
#

if you really want no one else to see your command, either manage it yourself via the integrations menu or limit it to your own guild if that isn't an option

crimson coral
#

in my experience interaction.message has worked pretty reliably but it might depend on other factors

placid field
#

thanks

gilded widget
#

Not directly related to pycord but more of a general question. I currently have the following code:

async def request(self,
                  *,
                  method: callable | str,
                  endpoint: str,
                  data: dict = None
                  ) -> dict:

I'm currently getting the following error in relation to the method argument: TypeError: unsupported operand type(s) for |: 'builtin_function_or_method' and 'type'
Anyone know of a good way to get around this? For reference, the method param should either take in a string like "get" or take in a callable such as aiohttp.ClientSession.get.

crimson gale
gilded widget
#

3.10.1

crimson gale
#

huh, that should work then

#

if not then the workaround is to import Union from typing and use that instead

gilded widget
#

yeah, weirdly enough that fixed it. isn't the | operator in type hinting in python 3.10 meant to replace typing.Union?

crimson gale
#

yep, but its the simplest work around i see right now

agile estuary
#

So idk if i understand that correctly. If i run my bot then change a cog (while the bot runs) then reload that cog with reload_extension, the changes i made should update right? So the next time when i use a slash command it should have the updated behavior. Or did i missunderstand the use of reload_extension?

crimson gale
#

its intended use is to change functionality while the bot is running

crimson coral
#

that's meant to be the case but slash callbacks are weird with reloading so idk if it works

agile estuary
#

Oh ok. Bcs i reload my cog and the slash command has the old behavior.

crimson coral
#

iirc it was meant to be implemented properly but it hasn't worked in my experience

crimson gale
weak fog
#

hey, somehow nothing works for me anymore, I uninstalled everything and then couldn't install anything in the terminal, do you know what's going on there?

agile estuary
crimson gale
#

yes

gilded widget
agile estuary
# crimson gale yes

mh so i tried using sync_commands after the reload already, same results no error.

agile estuary
crimson coral
#

just tried and on rc1 it looks like reload_extension alone works for me now

#

which is nice to know

agile estuary
crimson coral
#

jesus

#

uhh i recommend updating to rc1

#

though do note if you specified the messages intent, you need to change that to message_content

agile estuary
crimson gale
sudden path
#

Can I fetch a user by their username and discrim?

inner iris
#

global is not possible as far as I know

idle wagon
#

Hi whether it is possible to transfer arguments to model?

sudden path
sudden path
inner iris
#

I just see, that would actually be a command

sudden path
#

Ah. Thanks.

inner iris
#

actually this is far simpler I think
member = discord.utils.get(message.guild.members, name='Foo', discriminator='1234')

sudden path
#

Yeah haha.

winged pagoda
#

I'm trying to have a group of commands that any user can use, but I would like them not to be used at the same time.

Is there any way to set a "shared" cooldown or what should i look into start/stopping users from using commands

inner iris
#

@commands.cooldown(rate, per, commands.BucketType.<type>)
<type> can be channel, guild, user/member, category, role

winged pagoda
steep verge
#

How do I fix this error with mongodb?

inner iris
steep verge
gilded widget
#

or maybe people just havent responded yet ๐Ÿคจ

inner iris
#

that's not true

#

bad order of messages xD

gilded widget
#

lmao

fresh brook
#

Is it possible to get the value of each row of a long modal text input?

celest moth
#

what arguments are available in await respond? i tried ephemeral=True and got an error

gilded widget
#

using the ephemeral parameter shouldn't be an issue with the function itself.

celest moth
gilded widget
#

like having an interaction object?

celest moth
#

yup

gilded widget
#

slash commands have ApplicationContext which has a property of interaction

celest moth
#

I see, thank you very much

sudden path
#

What @commands. Checks hide/grey-out the slash command?

celest moth
#

How do i get the user that invoked the command? is there something like ctx.author?

gilded widget
#

yes

slender lintel
#

Hey i have two questions, i have a code for online members i have len(user) used for count but dont working.
Code:

    for user in ctx.guild.members:
        if user.status != discord.Status.offline:
            print(user)

So my next question is, how i can see record of server boosts?

gilded widget
#

p.tag idw

supple ravineBOT
# gilded widget p.tag idw

Saying it doesn't work or asking what's wrong with this code? is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.

gilded widget
#

second question, don't believe you can see a record

gilded widget
#

what

slender lintel
#

can i see the record of server boosts, yes or no?

slender lintel
gilded widget
#

I said no, I don't think you can see server boosts

#

i lost power so you'll need to check for yourself tbh

#

and I can't help you with your first issue if you don't tell me what the actual issue is with the code

#

saying it doesn't work doesn't tell me anything

slender lintel
gilded widget
#

what exactly are you trying to accomplish. are you wanting to count the amount of online members?

slender lintel
#

yes

#

i have len(user) tried but i dont know is not working

gilded widget
#

just increment an int every time a member isn't offline?

#
count = 0
for user in ctx.guild.members:
    if user.status != discord.Status.offline:
        count += 1
#

should work if I'm understanding what you want

slender lintel
gilded widget
#

not sure why you would print the user if you're just trying to count how many are online

slender lintel
#

wait

slender lintel
gilded widget
#

still not entirely sure what you want, but if you just wanna print the amount of users online then place a print(count) after and outside of the for loop

slender lintel
#

I am i know what i want

slender lintel
#

so direct expamle 23

slender lintel
#

so basically this atmo bot i gave him founder everything with admin permission but he dosent even reply in the server and in dm he replies

ornate spade
#

enable message_content intent

slender lintel
slender lintel
coarse axle
#

How would I be able to get the user on who a UserCommand is used? For example I want to kick someone, I can right click them to get a user context menu, but how would I know who has been clicked?

#

For dislash it used to be ctx.target_author

desert dagger
#

Any ideas why the "get" seems to fail roleID ends up equaling the name=role value

async def create(ctx, role: Option(str, "role", required=True), colors: Option(str, "color", required=False)):

                await ctx.guild.create_role(name=role, color=colors, reason=f'created by {ctx.author.name}')
                roleID = discord.utils.get(ctx.guild.roles, name=role)
                print('role id', roleID)

If i try to use Int(roleID) i get an error like
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'Role'

coarse axle
#

roleID returns a Role object, so you'll have to use roleID.id to get its ID (which would already be an integer then)

desert dagger
#

ahh

#

thanks

coarse axle
#

๐Ÿ‘

desert dagger
#

code was working fine a bit ago then it went ๐Ÿ’ฉ lmao

slender lintel
#

@ornate spade please help

ornate spade
#

I told you the idea I had

wraith finch
#

Is there a way to see the errors after adding cogs?

Like before adding cogs I could see errors in my terminal to do with commands and it was so much easier to fix them but now after adding cogs there are no errors in my terminal. So is there a way I can see them?

crimson gale
slender lintel
#

done

plain rover
#

Can I somehow respond to a Modal interaction without sending a message? My code right now looks something like this

class TestModal(discord.ui.Modal):
    def __init__(self, title):
        super().__init__(title)
        self.add_item(discord.ui.InputText(label='Input', placeholder='Placeholder'))

    async def callback(self, interaction: discord.Interaction):
        await interaction.response.send_message('HI')```  however I do wish to respond there without the "HI" appearing.
crimson gale
#

you could try your luck with response.pong()

#

some people have had success with it

#

@plain rover

plain rover
#

I tried

async def callback(self, interaction: discord.Interaction):
    await interaction.response.pong() ```
However that doesn't seem to do anything.
stable tiger
#

my suggestion would be make that 'Hi' message into .send_message('Hi', ephemeral=True) so only Modal user sees it

plain rover
#

Ooh, I didn't know this existed. Thanks!

frank moon
#

why is the @discord.default_permissions(moderate_members=True) not working in my slash command? the user literally has no role/permissions to run the cmd

jolly belfry
#

Hey i have this error when i run the .bal command
I excepted it to make me a new balance account but i have this error
The code:
@bot.command()
async def bal(ctx,user):
await open_account(ctx.author)
users = get_bank_data()
user = ctx.author
wallet_amt = users[str(user.id)["wallet"]]
bank_amt = users[str(user.id)["bank"]]

em = discord.Embed(title = f"{ctx.author.name}'s balance'",color = discord.Color.red())
em.addfield(name = "Wallet Balance",value = wallet_amt)
em.addfield(name = "Bank Balance",value = bank_amt)
await ctx.reply(embed = em)

async def open_account(user):
users = await get_bank_data()

if str(user.id) in users:
return False
else:
users[str(user.id)["wallet"]] = 0
users[str(user.id)["bank"]] = 0

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

async def get_bank_data():
with open("wallets.json","r") as f:
users = json.load(f)

return users

The error message:
Ignoring exception in command bal:
Traceback (most recent call last):
File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 855, in invoke
await self.prepare(ctx)
File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 697, in _parse_arguments
transformed = await self.transform(ctx, param)
File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 542, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: user is a required argument that is missing.

When i run the .bal command it does nothing

crimson gale
#

self explanatory

#

user error

jolly belfry
#

wdym?

crimson gale
#

discord.ext.commands.errors.MissingRequiredArgument: user is a required argument that is missing.

jolly belfry
#

what do i need to do?

crimson gale
#

provide input

jolly belfry
#

soo

#

i do .bal <what_do_i_put_in_here??>

#

what do i need to put there?

crimson gale
#

well you made the command

#

you should know

jolly belfry
#

i have the code provided above

#

@bot.command()
async def bal(ctx,user):
await open_account(ctx.author)
users = get_bank_data()
user = ctx.author
wallet_amt = users[str(user.id)["wallet"]]
bank_amt = users[str(user.id)["bank"]]

em = discord.Embed(title = f"{ctx.author.name}'s balance'",color = discord.Color.red())
em.addfield(name = "Wallet Balance",value = wallet_amt)
em.addfield(name = "Bank Balance",value = bank_amt)
await ctx.reply(embed = em)

async def open_account(user):
users = await get_bank_data()

if str(user.id) in users:
return False
else:
users[str(user.id)["wallet"]] = 0
users[str(user.id)["bank"]] = 0

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

async def get_bank_data():
with open("wallets.json","r") as f:
users = json.load(f)

return users

#

thats the code

crimson gale
#

?tag codeblock

hearty rainBOT
#

dynoError No tag codeblocks found.

jolly belfry
#

oops

crimson gale
#

?tag codeblock

hearty rainBOT
#

Please put your code in a code block:
```py
Here is your Code
```

That makes reading code in Discord a lot easier:

print("This is an example.")
jolly belfry
#
@bot.command()
async def bal(ctx,user):
  await open_account(ctx.author)
  users = get_bank_data()
  user = ctx.author
  wallet_amt = users[str(user.id)["wallet"]]
  bank_amt = users[str(user.id)["bank"]]

  em = discord.Embed(title = f"{ctx.author.name}'s balance'",color = discord.Color.red())
  em.addfield(name = "Wallet Balance",value = wallet_amt)
  em.addfield(name = "Bank Balance",value = bank_amt)
  await ctx.reply(embed = em)

async def open_account(user):
  users = await get_bank_data()

  if str(user.id) in users:
    return False
  else:
    users[str(user.id)["wallet"]] = 0
    users[str(user.id)["bank"]] = 0

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

async def get_bank_data():
  with open("wallets.json","r") as f:
    users = json.load(f)

  return users
crimson gale
#

so based on this

#

you want user to be an optional arg right?

jolly belfry
#

i just want to do .bal and when you dont have account it creates one and when you have an account to show your bank and wallet balance

crimson gale
#

so user is supposed to be an optional arg

jolly belfry
#

i think so

crimson gale
#

user = None in function definition

jolly belfry
#

what function?

crimson gale
#

then you need to set user to ctx.author if user is None

crimson gale
crimson gale
#

fyi dont use json as permanent database solution

jolly belfry
#

so dont just do user = ctx.author

#

do if user = None:

#

user = ctx.author

crimson gale
#

yes but you might wanna use a different comparison operator in the condition

#

infact you shouldnt be using a comparison operator in there

jolly belfry
#

what?

crimson gale
#

is None is what you need

jolly belfry
#

if not user?

#

oh

distant mesa
jolly belfry
#

if user is None?

crimson gale
jolly belfry
#

ok

#

lemme try that

agile roost
#

Why this code send the cooldown embed(message) 10 times or more ?

class Cog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self._cd = commands.CooldownMapping.from_cooldown(1, 6.0, commands.BucketType.user)

    def get_ratelimit(self, message: discord.Message) -> typing.Optional[int]:
        bucket = self._cd.get_bucket(message)
        return bucket.update_rate_limit()

    @commands.Cog.listener()
    async def on_message(self, msg: discord.Message):
        if isinstance(msg.channel, discord.DMChannel):
            ratelimit = self.get_ratelimit(msg)
            if ratelimit is None:
                # not ratelimited (No Cooldown)
            else:
                # is ratelimited (Cooldown) embed```
crimson gale
jolly belfry
#
File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 855, in invoke
    await self.prepare(ctx)
  File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 789, in prepare
    await self._parse_arguments(ctx)
  File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 697, in _parse_arguments
    transformed = await self.transform(ctx, param)
  File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 542, in transform
    raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: user is a required argument that is missing.
#

got this error

distant mesa
#

user=None

crimson gale
#

you didnt make the argument optional

distant mesa
#

in function params

agile roost
#

ohso and how do I prevent this

jolly belfry
#

after doing user = user or ctx.author

crimson gale
#

in function params

#

the place where you have ctx as well

jolly belfry
#

oh

#

ok

agile roost
#

Do I have to do ctx there ?

crimson gale
#

has nothing to do with your issue probably

jolly belfry
crimson gale
#

right there

jolly belfry
#

at the bal or open account

#

?

crimson gale
#

you want the user argument to be optional for the command to work

distant mesa
#

because bot is looping on its own messages

jolly belfry
crimson gale
#

if you make user optional on the latter, it still wouldnt work without it

distant mesa
#

async def bal(ctx, user=None)

agile roost
#

How do I optional write there in the parameter?

distant mesa
distant mesa
#

@agile roost

agile roost
distant mesa
crimson gale
agile roost
#

Ah ok sry

jolly belfry
#

different error this time

crimson gale
#

show

jolly belfry
#

wait

agile roost
#

But my code didn't still work

jolly belfry
#
Ignoring exception in command bal:
Traceback (most recent call last):
  File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 98, in bal
    await open_account(user)
  File "main.py", line 112, in open_account
    if str(user.id) in users:
AttributeError: 'NoneType' object has no attribute 'id'

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

Traceback (most recent call last):
  File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'id'
crimson gale
distant mesa
jolly belfry
#

oh

#

so do user = None before the bal function?

distant mesa
agile roost
jolly belfry
crimson gale
distant mesa
jolly belfry
#
@bot.command()
async def bal(ctx,user=None):
  await open_account(user)
  users = get_bank_data()
  user = ctx.author
  wallet_amt = users[str(user.id)["wallet"]]
  bank_amt = users[str(user.id)["bank"]]
  
  em = discord.Embed(title = f"{ctx.author.name}'s balance'",color = discord.Color.red())
  em.addfield(name = "Wallet Balance",value = wallet_amt)
  em.addfield(name = "Bank Balance",value = bank_amt)
  await ctx.reply(embed = em)

async def open_account(user):
  users = await get_bank_data()

  if str(user.id) in users:
    return False
  else:
    users[str(user.id)["wallet"]] = 0
    users[str(user.id)["bank"]] = 0

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

async def get_bank_data():
  with open("wallets.json","r") as f:
    users = json.load(f)

  return users
jolly belfry
crimson gale
#

just put it there

#

before you call open_account

jolly belfry
#

lemme do that

agile roost
#

It works thanks

distant mesa
#

np

jolly belfry
#

error again

#
File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 100, in bal
    await open_account(user)
  File "main.py", line 117, in open_account
    users[str(user.id)["wallet"]] = 0
TypeError: string indices must be integers

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

Traceback (most recent call last):
  File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/runner/DiscordPotatoBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: string indices must be integers
frank moon
#

why is the @discord.default_permissions(moderate_members=True) not working in my slash command? the user literally has no role/permissions to run the cmd

crimson gale
#

move the ["wallet"] to the right outside of the square brackets

inland acorn
#

true

crimson gale
#

^ not as a permanent solution

jolly belfry
crimson gale
#

sqlite, mongodb

#

youve got choices

inland acorn
#

i feel data loss

jolly belfry
#

i followed code with swastik tutorial

distant mesa
inland acorn
#

json is not recommended but

#

i use mongodb altas

crimson gale
#

mongodb is better compared to just plain json files

jolly belfry
#

i ggt

#

gtg

distant mesa
jolly belfry
#

cya later

frank moon
#

why is the @discord.default_permissions(moderate_members=True) not working in my slash command? the user literally has no role/permissions to run the cmd

hushed basalt
#

hello, one question, theres anyway to limit @bridge.bridge_command() to a guild?

wraith finch
# inland acorn i use mongodb altas

you use mongodb? I have this bug where like after I insert something into the database anything after that line doesn't get executed the command just stops, its so weird is it the same for u?

atomic thistle
#

If I have same commands.Cog.listener() in two different cog files, will both of then run or only one of them will run?

sudden path
atomic thistle
#

thanks

wraith finch
sudden path
#

Mind sharing your command.

wraith finch
#

ok

#
    @commands.command(name = 'createfaction')
    async def create_faction_command(self, ctx, *, faction = None):
        print('ok')
        user = ctx.author.id
        if faction == None:

            em = discord.Embed(
                title = "Help ๐Ÿ› ๏ธ",
                description = '**d.createfaction [faction name]**\nCreate your Faction',
                colour = discord.Colour.yellow()
            )
            await ctx.send(embed = em)
        
        else:
            faction_name = faction.capitalize()

            if self.collection.count_documents({ "leader": user }, limit = 1):
                await ctx.send(f"{ctx.author} You already own a Faction!")
            
            elif self.collection.count_documents({ "_id": faction_name }, limit = 1):
                await ctx.send(f"This Faction already exists!")

            else:
                await self.collection.insert_one({"_id": faction_name, "leader": user})
                await ctx.send (f'{faction_name} Created!')
#

the command works

#

await self.collection.insert_one({"_id": faction_name, "leader": user})
await ctx.send (f'{faction_name} Created!')

In this scenario the bot wont send a message but if I write

            await ctx.send (f'{faction_name} Created!')
            await self.collection.insert_one({"_id": faction_name, "leader": user})

It will send a message

sudden path
#

Does it insert the document?

wraith finch
#

But just wont execute the command after that

#

so uh I just tested something I removed the await before self.collection and now it works

#

huh

#

so much time wasted over 1 small thing

reef iron
#

PyMongo isn't async. Try Motor, the async lib for Mongo.

#

@wraith finch ^

wraith finch
reef iron
#

I should note that if your DB queries are well optimised, you don't need Motor. PyMongo works perfectly.

wraith finch
#

okay ty

reef iron
#

No worries

slender lintel
#

Hey, how i can create a count? Not 1, 2, 3, 4.. count only one number example: 23 User. i hope to understand this

    for user in ctx.guild.members:
        if user.status != discord.Status.offline:
            print(user)
crimson gale
#

variables

slender lintel
ornate spade
#

make a list and use len()

crimson gale
#

or that

slender lintel
sudden path
#

Yeah that's not how it works

slender lintel
#

i have see it

slender lintel
sudden path
#

I'm pretty sure for loops, lists and variables are basic python

crimson gale
#

^

#

simple solution

#

learn more python

#

and improve your problem solving skills

slender lintel
#

and then i am a superhero? pepehmm

slender lintel
sudden path
#

What

slender lintel
#

How what?

crimson gale
#

your sentence is confusing

slender lintel
#

why?

slender lintel
sudden path
#

Use the translator then

slender lintel
#

Ok

slender lintel
ornate spade
#

[item for item in list if condition]

#

like [n for n in range(11) if n != 5]

jolly belfry
#

HEY

#

oops

#

why do i need to unistall discord.py to install pycord?

crimson gale
#

because they both use the same namespace and having both installed breaks everything

jolly belfry
#

oh ok

rose shard
#

well I'm continuing my bot and gotta make a battle system
So before that i gotta make an inventory so can ya help me and give some pointers of how should i proceed

sudden path
#

Its like. You first try doing something and ask here if you encounter any issues.

rose shard
#

alrighty

pulsar flint
#

any ideas why i get this error?

  File "c:\Users\alexj\Desktop\EpicGiant Bot\main.py", line 3, in <module>
    bot = discord.Bot()
AttributeError: module 'discord' has no attribute 'Bot'
slender lintel
crimson gale
#

pip show py-cord

pulsar flint
#

yes

#
(venv) PS C:\Users\alexj\Desktop\EpicGiant Bot> pip show py-cord
Name: py-cord
Version: 1.7.3
Summary: A Python wrapper for the Discord API
Home-page: https://github.com/Pycord-Development/pycord
Author: Pycord Development
Author-email:
License: MIT
Location: c:\users\alexj\desktop\epicgiant bot\venv\lib\site-packages
Requires: aiohttp
Required-by:
crimson gale
#

theres your answer

pulsar flint
#

oh yeah

crimson gale
#

upgrade to py-cord==2.0.0rc1

pulsar flint
#

alr

slender lintel
#

How do i make pressing a button edit an embed which has been sent in a previous command? I get the error:
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook

class join_ticket(discord.ui.View):
  def __init__(self):
    super().__init__(timeout=None)
  @discord.ui.button(row=0, label="Join Request", emoji=':no_entry:', style=discord.ButtonStyle.grey, custom_id="delete_ticket", disabled=False)
  async def button_callback2(ctx, message, interaction: discord.Interaction):
    guild = bot.get_guild(901481491337465928)

    req_embed = discord.Embed(title="Request!", description=f" is looking for a !\nOther Trader: {interaction.user.mention}\n\n**Trade:**\n\n> {interaction.user.mention} has joined the ticket!", color=0x40C96B)
    req_embed.set_footer(text=f"Request")
    req_embed.set_thumbnail(url=guild.icon)

    await interaction.edit_original_message(embed=req_embed)```
frank moon
#

why is the @discord.default_permissions(moderate_members=True) not working in my slash command? the user literally has no role/permissions to run the cmd

analog elk
#

How do I get a bot to return a message like this, where only the user can see it and they get the opportunity to dismiss it? I googled around, and looked in the documentation and couldnt find anything on it, although I might have just missed it.

slow dome
analog elk
#

thank you!!

ancient gazelle
sudden path
ancient gazelle
#

If it is set to false, everyone with perms will be able to see right?

gilded widget
#

everyone who can view messages in that channel will be able to see it, yes

ancient gazelle
gilded widget
#

await ctx.respond(embed=discord.Embed(title="test", description="test"))

inland acorn
#

its the same from inside but can be used with await

#

it works perf fine and my bot is verified

solar berry
#

Is there a way to fetch a ton of random users from discord (tryna make a discriminator collector cuz dyno's stopped working)

idle linden
#

AttributeError: module 'discord.commands' has no attribute 'group'

#

I call bs

#

should I not be using the alpha/master right now?

idle linden
#

or is something screwed up in my venv

inner iris
humble marsh
#

Question, what does AppInfo Module do? and how does it work?

storm burrow
#

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'tuple' object is not callable

Using discord.TextChannel in slash command and fetching channel name with it throws this error. Anyone knows why?

frank moon
#

why is the @discord.default_permissions(moderate_members=True) not working in my slash command? the user literally has no role/permissions to run the cmd

rose shard
#

How can i get the time on which my embed was created at

crimson isle
#

how to install pycord on vps without any error?

#

py-cord==2.0.0b5

upbeat hill
#

how can you keep buttons working after a restart of the bot?

crimson coral
#

and even then they said it was unreliable and removed it (though i wouldn't be surprised if there were other reasons)

#

the chances of you generating a random number and it being a real user is very low, so I wouldn't bother; you can only really work with users your bot can see

crimson coral
supple ravineBOT
#

Here's the persistent example.

crimson coral
rose shard
#

It worked too yeahboi yeahboi

upbeat hill
crimson coral
storm burrow
crimson coral
#

update to 2.0.0rc1

storm burrow
#

Okay

#

Thanks, it works now..

warm tundra
#
    global lmao
    id=doc.guild.id
    lol=f"select sprefix from servers where sid={id}"
    mycursor.execute(lol)
    lmao=mycursor.fetchone()[0]```

so i want to call this function but it gives an error saying doc is missing and i can't provide a value for doc as it's the context nor can i remove it as it is required for variable id 

so how do i call the function???
storm burrow
#

cus_prefix(ctx)

frank moon
#

what does this do/mean?

frigid lark
#

like #general is a Text Channel

frank moon
frigid lark
#

no

#

you can use

channel: discord.TextChannel
frank moon
#

discord.TextChannel and discord.VoiceChannel

frigid lark
#

Im not sure if it fixed

frigid lark
frank moon
frank moon
#

Union[discord.TextChannel, discord.VoiceChannel]

warm tundra
storm burrow
warm tundra
storm burrow
#

Show your whole code if possible.

warm tundra
storm burrow
#

You need to call the cus_prefix(ctx) function inside the command.

warm tundra
storm burrow
#

That's up to you in which commands and where do you wanna use it.

#

But you can't pass ctx to it unless you call it inside the command.

warm tundra
warm tundra
#

error which occurs is

#

lmao is not defined

i added cus_prefix(doc) in evrery cmd and changed command_prefix to lmao

storm burrow
#

@warm tundra
Try like this:

def prefix(bot, ctx):
    #Some code here to check prefix

intents = discord.Intents.all()
bot = commands.Bot(command_prefix=prefix, intents=intents)```
finite cliff
#
Ignoring exception in on_connect
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 352, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/.local/lib/python3.9/site-packages/discord/bot.py", line 793, in on_connect
    await self.register_commands()
  File "/home/container/.local/lib/python3.9/site-packages/discord/bot.py", line 460, in register_commands
    await self.http.bulk_upsert_command_permissions(
  File "/home/container/.local/lib/python3.9/site-packages/discord/http.py", line 338, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 405 Method Not Allowed (error code: 0): 405: Method Not Allowed```
storm burrow
# warm tundra

You need to return the prefix as string and it should not return None

warm tundra
#

so str()???

storm burrow
storm burrow
warm tundra
#

k

finite cliff
storm burrow
finite cliff
storm burrow
#

Idk then that's what fixed for me when I was getting that error

warm tundra
#

cmd doesn't run and there's no error]

#

also

#

this is the value of str(cus_prefix)

#

<function cus_prefix at 0x0000026CA2CDD240>

storm burrow
#

show your function code which fetches and returns prefix

warm tundra
humble marsh
crimson coral
#

i don't think so

#

if im not mistaken most stuff on the devportal requires a bearer token and isn't exposed to being edited via the api

upbeat hill
#
2> url=None disabled=False label='Delete' emoji=<PartialEmoji animated=False name=':no_entry:' id=None> row=None>:
Traceback (most recent call last):
  File "C:\Users\philc\AppData\Roaming\Python\Python310\site-packages\discord\ui\view.py", line 367, in _scheduled_task
    await interaction.response.defer()
  File "C:\Users\philc\AppData\Roaming\Python\Python310\site-packages\discord\interactions.py", line 471, in defer
    await adapter.create_interaction_response(
  File "C:\Users\philc\AppData\Roaming\Python\Python310\site-packages\discord\webhook\async_.py", line 192, in request        
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```

how do i get rid of this error when using a button to delete a channel
inner iris
#

does it delete the channel or does it just throw the error.
And pls show us your code...

upbeat hill
#

it deletes it but throws the error

paper schooner
#

Unable to get repr for <class 'discord.message.Message'>
Why is this error? I enabled the "message intent" on the developer site, but can't get the message content

inner iris
# upbeat hill

actually I can't help you here. I'm not (yet) really familiar with buttons etc.

upbeat hill
upbeat hill
inner iris
upbeat hill
inner iris
#

what about a simple file where the current incrementor gets stored and read from?

upbeat hill
inner iris
#

well then learn python xD
https://www.w3schools.com/python/

vagrant mortar
#

Now that we have Permissions V2. How can I force a command to only work when they have X role?

inner iris
vagrant mortar
#

Regardless what a server owner might set the permissions to?

inner iris
#

@commands.has_role() decorator

vagrant mortar
#

basically what I'm asking

What are the new methods for is_owner and has_roles

crimson gale
#

^ which is a check, permissions v2 cant do this

inner iris
#

they still work

#

don't they?

crimson gale
#

they do

#

they raise errors so they work regardless

vagrant mortar
#

I beg to differ? ๐Ÿ˜›

crimson gale
#

from the commands extension

inner iris
#

discord.ext

vagrant mortar
#

.< lel my bad

#

Thanks, works! ๐Ÿ™‚

inner iris
#
    message_group = discord.SlashCommandGroup(
        "message",
        "Interactions the bot can perform on its own messages.",
        default_member_permissions=discord.Permissions(administrator=True),
    )

Is this how one would set permissions v2 checks?
If not, how else and if, why doesn't it work on my server? No error, just still shows up to users that don't have the permission.

surreal nimbus
#

I honestly don't know

#

it may be a tuple too

#

tias ig

inner iris
#

nope, didn't work

#

sadly there is nothing in the docs about this...

obsidian garnet
#

One message removed from a suspended account.

inner iris
obsidian garnet
languid ruin
#

Is it possible to list all available slash_commands with for X in X Flash

inner iris
inner iris
languid ruin
#

but nevermind, I found the solution

#
    for application_command in client.application_commands:
        print(application_command)```
![smileC](https://cdn.discordapp.com/emojis/816624116534345758.webp?size=128 "smileC")
inner iris
#

that does work?

#

Why is this not in the docs?

languid ruin
#

idk

languid ruin
wide cloak
#

is this possible to to?

@bot.event
async def on_error(error):
    if isinstance(error, mysql.connector.Error):
        print(f"MYSQL ERROR: {error}")
inner iris
slender lintel
#

How would I use @option to grab a user?

cold zephyr
#

disable_all_items() is not, well, disabling all items. Have I misunderstood?

class CancelButton(discord.ui.Button):
    def __init__(self):
        super().__init__(
            label="Cancel",
            style=discord.enums.ButtonStyle.red
        )

    async def callback(self, interaction: discord.Interaction):
        self.view.disable_all_items()
        await interaction.response.send_message("New trip entry cancelled.", ephemeral=True)
slender lintel
#

Isn't discord.File a class?

#

I can't use it as a type for option()

ornate spade
#

try discord.Attachment

#

a File is different

crude temple
#

Is it possible to lock a private channel? Like people can see it but can't send messages

cold zephyr
slender lintel
#

Hi, does someone know to reload slash command choices for a user without reloading the whole bot?

#

without a cog btw

#

like I want custom choices for each user and add new choice without reloading the whole bot

#

is it possible?

slate stirrup
#

Can I have the examples bots GitHub link pls

hollow moth
#

Is there any way I can make a message_command (ran from the context menu) silent? So it doesn't respond/ responds with an ephemeral message then deletes it

rose shard
#

How do i remove the button after clicking it once with discord-components (cuz my pc sux and i cannot move to discord.py 2.0)

ornate spade
#

this isn't the discord-components support server.

ornate spade
rose shard
#

alright

clever lava
#

how do i 24/7 host my bot with visual studio code?

#

im tired of replit

inner iris
#

look for a cheap bot hoster, you'll find many if you just use google...
Or do you mean free hosting?

clever lava
#

um

#

i use uptimerobot

#

its free

#

and to run it i use flask server

#

but if i turn my pc off for logic reasons the flask server file will not be running anymore

#

then 24/7 host in visual studio code is complicated

humble talon
#
  File "C:\Users\Me\Downloads\Python\Bot\commands.py", line 68, in send_announcement
    webhook.edit(name=ctx.author.display_name, avatar=ctx.author.avatar)
  File "C:\Users\Me\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\sync.py", line 850, in edit
    payload["avatar"] = utils._bytes_to_base64_data(avatar) if avatar is not None else None
  File "C:\Users\Me\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\utils.py", line 523, in _bytes_to_base64_data
    mime = _get_mime_type_for_image(data)
  File "C:\Users\Me\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\utils.py", line 509, in _get_mime_type_for_image
    if data.startswith(b"\x89\x50\x4E\x47\x0D\x0A\x1A\x0A"):
AttributeError: 'Asset' object has no attribute 'startswith'
#

What am I doing wrong? Want to set the webhook's avatar to the author's avatar?

#

do I need to do Asset.read()?

#

Ahah! That's what I needed to do

#

Case closed

analog elk
#
    @dategroup.command()
    @has_permissions(administrator=True)
    @option("year", description="RP Year")
    @option("month", description="RP Month (Default: Jan.)", default=1, required=False)
    @option("day", description="RP Day (Default: 1st of the month)", default=1, required=False)
    @option("sep", description="IRL days per in-RP year (Default: 2)", default=2, required=False)
    async def set(self, ctx: ApplicationContext, year: int, month: int, day: int, sep: float) -> None:
        """Sets the RP date."""
        
        rpdate = RPDate(year, month, day, sep)
        io.save_rpdate(rpdate, ctx.guild_id)

        await ctx.respond(f"Successfully set RP date to {rpdate}!")

    @dategroup.command()
    async def get(self, ctx: ApplicationContext) -> None:
        """Returns the current RP date."""

        await ctx.respond(f"The RP date is {io.load_rpdate(ctx.guild_id)}.")

Is this well written? I can't help but think there are way too many decorators for this to be written properly

zealous vapor
#

How do I get the user from ctx

idle linden
#

one of those

warm jungle
#

hey yall

#

how do i make it so a dropdown timeout sends a message

sudden path
#

on_timeout event

zealous vapor
#

How do I make something like this

#

where it says "Only you can see this"

gilded widget
#

use the ephemeral parameter

supple ravineBOT
#
|coro|

Responds to this interaction by sending a message.

Parameters
-----------
content: Optional[:class:`str`]
    The content of the message to send.
embeds: List[:class:`Embed`]
    A list of embeds to send with the content. Maximum of 10. This cannot
    be mixed with the ``embed`` parameter.
embed: :class:`Embed`
    The rich embed for the content to send. This cannot be mixed with
    ``embeds`` parameter.
tts: :class:`bool`
    Indicates if the message should be sent using text-to-speech.
view: :class:`discord.ui.View`
    The view to send with the message.
ephemeral: :class:`bool`
    Indicates if the message should only be visible to the user who started the interaction.
    If a view is sent with an ephemeral message and it has no timeout set then the timeout
    is set to 15 minutes.
allowed_mentions: :class:`AllowedMentions`
    Controls the mentions being processed in this message.
    See :meth:`.abc.Messageable.send` for more information.
delete_after: :class:`float`
    If provided, the number of seconds to wait in the background
    before deleting the message we just sent.
file: :class:`File`
    The file to upload.
files: :class:`List[File]`
    A list of files to upload. Must be a maximum of 10.

Raises
-------
HTTPException
    Sending the message failed.
TypeError
    You specified both ``embed`` and ``embeds``.
ValueError
    The length of ``embeds`` was invalid.
InteractionResponded
    This interaction has already been responded to before.```
#
Represents an Audit Log entry.

You retrieve these via :meth:`Guild.audit_logs`.

.. container:: operations

    .. describe:: x == y

        Checks if two entries are equal.

    .. describe:: x != y

        Checks if two entries are not equal.

    .. describe:: hash(x)

        Returns the entry's hash.

.. versionchanged:: 1.7
    Audit log entries are now comparable and hashable.

Attributes
-----------
action: :class:`AuditLogAction`
    The action that was done.
user: :class:`abc.User`
    The user who initiated this action. Usually a :class:`Member`\, unless gone
    then it's a :class:`User`.
id: :class:`int`
    The entry ID.
target: Any
    The target that got changed. The exact type of this depends on
    the action being done.
reason: Optional[:class:`str`]
    The reason this action was done.
extra: Any
    Extra information that this entry has that might be useful.
    For most actions, this is ``None``. However in some cases it
    contains extra information. See :class:`AuditLogAction` for
    which actions have this field filled out.```
zealous vapor
#

oh cool

slender lintel
#

How can I get my bot to reply to webhooks?
Like the webhook says "?help"
and the bot replys with all commands

alpine totem
#

my buttons timeout after a certain amount of time and returns interaction failed, how do I make it so it never times out?

supple ravineBOT
#

Here's the persistent example.

analog elk
#

Is it possible to get a bot to use a slash command by sending a message? or is the only way to get a bot to use a command through sending a message to use prefix commands?

south ermine
#

there's on_message but I don't recommend it

analog elk
#

i want to get carlbot to periodically use a slash command

south ermine
#

yeah you can't call a slash command from another bot

analog elk
#

Quite annoying innit

#

is that an intentional limitation from Discord or has it just not been implemented?

mint quiver
#

Quick question: does discord.Option(discord.SlashCommandOptionType.user) always return an instance of discord.Member?

EDIT: Yup, they are

mint quiver
finite cliff
#
Traceback (most recent call last):
  File "c:\Users\DELL\Desktop\flash\bot.py", line 13, in <module>
    bot.load_extension("cogs.ticket")
  File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\cog.py", line 787, in load_extension
    self._load_from_module_spec(spec, name)
  File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\cog.py", line 732, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.ticket' raised an error: AttributeError: 'Bot' object has no attribute 'add_command'```
#

can anyone help?

mint quiver
#

is your bot a discord.Client?

#

If you are using a discord.Client it will not work with regular commands, only application (slash) commands

#

Change your bot object to a discord.ext.commands.Bot

grave hollow
#

my bot does not respond

slow dome
#

in your dev portal and code

grave hollow
#

And just a simple send hello

#

and it won't

#

With slash it gave missing access

slow dome
#

?tag missing_access

hearty rainBOT
grave hollow
#

Bruh

#

He appeared

analog elk
#

how do I get a channel ID from a database saved to my PC into a loop to send it to that specific channel?

#

because i have a loop and i want it to send messages to a channel set by users in a guild and the users in the guild can choose

#

so for each guild it's a different channel ID and a different interval of sending the message

grave hollow
#

Idk

#

?tag method not allowed

hearty rainBOT
#

dynoError No tag method found.

grave hollow
#

?tag method Not Allowed

hearty rainBOT
#

dynoError No tag method found.

grave hollow
#

?tag Method Not Allowed

hearty rainBOT
#

dynoError No tag Method found.

grave hollow
#

?tag 405

hearty rainBOT
#

dynoError No tag 405 found.

grave hollow
#

Now gave method not allowed

#

bruh

mint quiver
#

Iterate over the entries

analog elk
#

That would work to send a message to each of the channels in the database all at the same time

#

but what about having a different interval for each guild?

mint quiver
#

Then store the interval in your database..?

#

use thread.sleep

#

You can sleep the task, it'll block

#

await asyncio.sleep

analog elk
#

where would i put that? in the @tasks.loop() function?

mint quiver
#

Yep.

#

If the intervals are regular, you can sort items with similar intervals together

#

then send out all the messages simultaneously too

analog elk
#

I am a bit shaky on how the looping itself works so i'll send you my implementation of that which will probably be incorrect

#
    @tasks.loop()
    async def advance_date(self):
        for guild_id in io.get_guilds():
            
            rpdate = io.load_rpdate(guild_id)

            if rpdate is not None and rpdate.channel is not None:
                channel = await self.bot.fetch_channel(rpdate.channel)
                await sleep(rpdate.advancement_freq)
                channel.send(f"The RP date is {rpdate}.")
#

I don't really understand how this would send it at different intervals for each guild

mint quiver
#

sort them together

#

you could use a direct access array

#

for each interval, just store all the servers that need said interval in a linkedlist

#

For example

#

Guild A,B interval: 60s
Guild C,D,E interval: 65s
Guild F interval: 70s

#

ok wait hold on

#

Ok yeah sorry my method won't work

#

You can construct the Loop object manually, then add them to the task queue

analog elk
mint quiver
#

Construct the loop object and add them to the task queue

analog elk
#

I do not know how to do that but i will research how to do it

supple ravineBOT
#

discord/ext/tasks/__init__.py line 763

def loop(```
mint quiver
#

All the loop decorator does is spit out a Loop class

agile tundra
agile tundra
#

Thx

rose shard
#

How can i know that who clicked the button

finite cliff
#

idk why my test bot is unable to respond to any command

sudden path
sudden path
finite cliff
sudden path
#

Do you have intents

finite cliff
#

yes

finite cliff
crimson gale
rose shard
obsidian garnet
#

One message removed from a suspended account.

tall fossil
#

hello, how can I create a loop that occures every day at midnight?

slow dome
#

 @tasks.loop(time=time(3, 0, tzinfo=timezone.utc))  # Task that runs every day at 3 AM UTC
    async def time_task(self):
        channel = self.get_channel(1234567)  # Your Channel ID goes here
        await channel.send("It's 3 AM!")

    @my_background_task.before_loop
    @time_task.before_loop
    async def before_my_task(self):
        await self.wait_until_ready()  # Wait until the bot logs in
#

that is taken from the examples on github

tall fossil
#

ty

lean hare
#

discord.errors.HTTPException: 405 Method Not Allowed (error code: 0): 405: Method Not Allowed

#

im getting this error but i have no clue why :3

supple ravineBOT
magic dock
#

Hello! Small question, Is it possible to know if a user is marked as Likely Spammer? Or does discord not release that information to bots?
Thanks in advance!

tall fossil
lean hare
#

oh its a bug?

magic dock
obsidian garnet
#

One message removed from a suspended account.

rose ruin
#

bridge commands don't seem to work

#

if I use ctx.respond it says ```py
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'respond'

#

if I use ctx.reply it says the same but for applications commands

sudden path
rose ruin
obsidian garnet
sudden path
#

Your channels returned None. What I just said.

rose ruin
sudden path
#

Make sure you have intents.

obsidian garnet
rose ruin
sudden path
#

Looks like it uses ctx.respond

rose ruin
#

isn't working with normal cmds

#

should I install the b7 version

sudden path
#

I'd open an issue

odd arch
#

how to access view in a button sub class

rose acorn
lean hare
#

okay so i cant figure out how my slash commands are not updating/registring as new ones?

odd arch
#

nvm i can use self.view to access the view

obsidian garnet
#

One message removed from a suspended account.

crimson coral
#

.timestamp()

rose acorn
#

oh

crimson coral
#

useable on any datetime object

rose acorn
#

ok im slow at typing

crimson coral
#

it'sfine

obsidian garnet
obsidian garnet
obsidian garnet
crimson coral
#

just convert to int i guess

obsidian garnet
#

One message removed from a suspended account.

#

One message removed from a suspended account.

crimson coral
#

yeah

#

the comma is to represent the decimal time/milliseconds (this is a point in some languages, a comma in others)

obsidian garnet
#

One message removed from a suspended account.

shell bobcat
#

Is it possible to deny users from interacting with buttons?

sudden path
#

Check user's ID'S

crimson coral
#

you can override the view's interaction_check method to apply a check to all items in the view

humble talon
crimson coral
#

are you subclassing?

shell bobcat
#

I was already thinking of adding a user id check, but I've over 80 buttons so couldn't be the most efficient way

crimson coral
#

or are you just doing view = discord.ui.View(...)

shell bobcat
crimson coral
#

define a interaction check function

async def some_name(interaction):
    ... # Return True if valid

then just set view.interaction_check = some_name

#

this is always called before any of the callbacks, if it returns false the button's callback won't run at all

obsidian garnet
shell bobcat
obsidian garnet
crimson coral
#

i think you want current_timestamp - 3600; then < max_time is more and > max_time is less

#

(also you don't need timegm, you can just do date = datetime.datetime.utcnow().timestamp())

obsidian garnet
crimson coral
#

oh wait my bad

#

your swap was correct

obsidian garnet
crimson coral
#

nono im pretty sure your change was correct

obsidian garnet
#

One message removed from a suspended account.

crimson coral
#

yes

obsidian garnet
#

One message removed from a suspended account.

crimson coral
#

all good

tall fossil
shell bobcat
#

how do I fix this?

crimson gale
shell bobcat
#

And how would I provide the Permission object?

crimson gale
#

docs exist dude

shell bobcat
#

Yea I know, I was looking at them for a while

#

But yea, sorry man

rose ruin
#

Still normal cmds aren't working in bridges while using ctx.respond and if I use ctx.reply or ctx.send it wont work for application commands

gentle crag
#

Is there a way to call something else from a dictionary if key = value? Using the page dict(0) method is fine if I already know the dictionary. But what if Iโ€™m looking in one with like 2000 results and I just want the โ€œnameโ€ where โ€œcolorโ€ = red

rose ruin
south ermine
slender lintel
#

Hey, how can I display what was clicked or added (in the select menu)?
Tried it with interaction.values, but it didn't work..

crimson coral
#

i feel like this had a pr before but i might be wrong

south ermine
#

yeah I remember this issue before

crimson coral
ornate fog
#

Maybe this is a dump question but can you ping roles i interaction responses ?
I have a hard time doing so

crimson coral
#

uhhh yeah it should work fine

ornate fog
#

hmmmmmm

crimson coral
#

what were you trying

rose stratus
#

i doing a script that scan a lot of servers and if found a match send a match but if doesnt just give me a error can i make so when doesnt find send a error message

south ermine
ornate fog
crimson coral
ornate fog
# crimson coral what were you trying
@slash_command(guild_ids=ConfigManager.get_debug_guild_when_debug())
    async def ping_me(self, ctx, p: Option(discord.Role)):
        await ctx.respond(p.mention)

It writes the mention just fine but i dont get the yellow background

crimson coral
#

does your bot have permissions to mention the role?

ornate fog
crimson coral
#

and you definitely have the role you entered

south ermine
#

webhook messages (which is what ctx.respond sends) are different

ornate fog
#

100% sure

crimson coral
#

oh that's interesting

#

apparently .respond can't mention roles

slender lintel
south ermine
#

also can't @ here