#Basic Pycord Help

1 messages · Page 17 of 1

cerulean lake
#

How to get commands like these? Like is there a template somewhere?

rugged lodgeBOT
#

Here's the context menus example.

loud kayak
#

o you beat me to it

cerulean lake
#

Thx

little cobalt
#

xd

young skiff
#

Why does Pycord use 'discord' as the module name? It's annoying to confuse it with other modules like discord.py, it should be 'py-cord' instead of 'discord', right?

steep cliff
#

It’ll be pycord in v3 if it ever gets released

little cobalt
plucky moss
#

Can I get an answer on why my slash commands aren't working?

hallow copper
plucky moss
hallow copper
#

meanie

plucky moss
#

Nah but fr why 😭

hallow copper
#

wut commands are the problem?

plucky moss
#

I did everything it said in the docs

plucky moss
#

Regular ones are working fine

hallow copper
#

its kinda hard to tell you why when you share no details or code

plucky moss
#

Ill send them wait

#

I'm getting a call

#
import discord 
from discord.ext import commands

class Fun(commands.Cog):
  def __init__(self, client):
    self.client = client
  
  @commands.command()
  async def ping(self, ctx):
    await ctx.send(f"Pong! {round(self.client.latency * 1000)}ms")

  @commands.slash_command()
  async def ballbeater(self,ctx):
    await ctx.respond("ballbeater")

  @commands.user_command(name='Test2')
  async def test2(self, ctx, user: discord.Member):
    await ctx.respond(f'{user.mention} is cool')

  @commands.Cog.listener()
  async def on_ready(self):
    print('Fun cog is ready')

def setup(client):
  client.add_cog(Fun(client))
    
#

This is my cog code

#

The slash commands and context menus don't work

#

The cogs do get loaded

#

And prefix cmds work

lapis pollen
#

is there no way to dm all members in a server w my bot?

atomic fern
#

you can, just iterate over all guild member

#


why commands.has_role won't work with bridge commands? is it only supported
prefixed commands? and how do i make it work with bridge

fleet cedar
#

Yep. Or use @bot.event in the main file

edgy glen
#

Why are application commands not working?

heavy sky
sly karmaBOT
# edgy glen Why are application commands not working?

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.

opal hamlet
#

does discord IP Ban bots or smth? bots running fine on my Linux server suddenly all stopped working and all of them just log: discord.client INFO logging in using static token

#

the bots start without issues on my pc so they aren't banned or anything

slender lantern
#

Is pycord compatible with aiohttp >= 3.9?

hollow plank
#

Discord does not allow you to edit a channel several times in a short period of time. Is it possible to filter this out if Discord is currently blocking it?

pseudo osprey
#

Any help?

hollow plank
shell radish
opal hamlet
#

Well it worked again after a while, probably a temp ban cuz of some ratelimit issue

#

Happens when your code is shit IG

hollow plank
shell radish
loud kayak
#

When a user selects an option in a select menu and the bot responds to the interaction, the option they selected is still on their view. How would I be able to have discord not show the option still selected and show no options selected?

shell radish
loud kayak
#

thanks that works

loud kayak
#

How many select menus can be on a message?

#

Is it 5?

little cobalt
#

5 Menus

#

25 buttons

loud kayak
#

Ok

crisp pollen
#

is there a reason for my bot randomly restarting with no errors? the .py file is still running, on_ready is just being called again

#

i'm able to dm 2 users 1 file each and then it just restarts

#

cooldown of 7.5s between dms

crisp pollen
#

every single time it dms 2 people

shell radish
#

without timestamps that doesn’t say anything

crisp pollen
#

sometimes it completes ("done", in the ss), sometimes it fails

#

task begins with "new update"

shell radish
#

without providing the code for the task, it’s practically impossible to diagnose the issue

#

there could be other factors that cause a “restart” so to speak

crisp pollen
#

yeah hold on im uploading the code

rugged lodgeBOT
crisp pollen
#

my giant for loop (going through a 100k+ length list of dictionaries) was timing out the bot as it was blocking for some reason

#

is there a reason async code run inside of a task would be blocking and cause the entire bot to freeze

#

im playing the game of "how many times can I fk around with my code and have it still not work" 😭

crisp pollen
#

solved my problem, just reduced the amount of data i was iterating through

grave scaffold
#

hello, on my journey of understanding pycord.
i was following the example:

channel = await guild.create_forum_channel('cool-channel')

but since guild.create_forum_channel() does not exist i tried using

@bot.slash_command(name="create_channel", description="")
async def create_channel(createchannelfunc):
    await guild.Guild.create_category(guild,'test')

but this does not work erroring with

AttributeError: module 'discord.guild' has no attribute '_create_channel'

could a poor soul be helped out to be shown the answer?

grave scaffold
#

i have looked and looked and have found no answer -_-

#

i even tried:

await bot.get_guild(guild.Guild.id).create_text_channel('test')

and i get this error instead:

AttributeError: module 'discord.guild' has no attribute 'create_text_channel'
obsidian blaze
#

What is createchannelfunc?

#

What are you trying to do? Create a channel?

#

It would be await ctx.guild.create_text_channel("cool-channel")

grave scaffold
#

oh so referance the slash command 🤦‍♂️

obsidian blaze
#

right

grave scaffold
#

sorry im stupid sometimes. its dumb bc pycharm doesnt auto fill any of that

little cobalt
#

;3

grave scaffold
#

i use that and it acts dumb sometimes.

#

doing autofills that make no sense and dont work at all in c++ so i hardly use it there

little cobalt
grave scaffold
#

oh really ill check that out!

little cobalt
grave scaffold
#

interesting

obsidian blaze
#

Need some suggestions

Needing to send a message from an interaction to say how many votes are remaining, but then that same interaction also needs to be able to edit the message for a new image. These are done at two seperate times and I am aware you can't edit the same interaction twice

lofty parcel
#

Just use interaction.edit_original_response

obsidian blaze
#

Oh, interesting. I was using interaction.response.edit_message so I guess that’s why. Thanks

lofty parcel
#

You use that if you're responding

#

If you need a second edit/response, you use what I said

plucky moss
#

Can someone show me an example on how to make a slash command in a cog, because I followed the docs and the GitHub guide and neither work?

shell radish
#

.idw

sly karmaBOT
#

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.

plucky moss
#

I tried everything I got in, in the docs and the GitHub guys but the command just dosent appear.

#

No errors

#

Prefix cmds work

shell radish
#

.slashnoshow

sly karmaBOT
#

Application Commands Not Showing Up?

  • Uninstall libraries that conflict with the discord namespace (e.g. discord.py).
  • Invite your bot with the application.commands scope.
  • Load cogs before bot.run() (e.g. not in on_ready).
  • Do not override on_connect.
  • Update to the newest version of py-cord (see ?tag install).
  • Turn off User Settings > Accessibility > Chat Input > Use legacy chat input.
  • Share your code and errors.
sinful juniper
heavy sky
autumn gust
#

semi-related to PyCord, but

#

what would be the most optimal way to like, export a list of User IDs into a list which my bot can sample and add to at any time

#

and won't lose it when it reboots

#

SQLite?

#

I want to make(upgrade lmao) a whitelist system, where I get a prompt whether to allow somebody in or deny them

#

and if I allow them, add their user ID to the whitelist

shell radish
autumn gust
#

what would you recommend?

#

SQLite seems... vaguely nice? but I've never really done anything with db

#

my dbs were always just plain txt files lmao

hazy turret
#

Does anyone know how I can send the whole thing if I use interaction.defer() beforehand?

await paginator.respond(interaction, ephemeral=True)```
hazy turret
# shell radish you can't

But you can simply:

await interaction.response.defer(ephemeral=True)

And then:

await paginator.respond(interaction, ephemeral=True)

Use without problems 🙂
Just tested it 🙂

#

The docs also state the following:

Paginator.respond() is used to send an interaction response (or followup) message with the paginator.```
shell radish
#

I misread the question 💀

pliant tusk
#

why is await reaction.users() so slow

#

i only want a list of user ids who reacted a certain reaction on a message

shell radish
#

ask discord lol

coral lake
#

Is there any way to access response headers with Pycord? I need to better understand individual rate limits.

If not, is there some other way to understand specific rate limits such as ephemeral interaction responses?

summer knot
#

can some help me with this error

Ignoring exception in on_connect
Traceback (most recent call last):
  File "/home/container/.venv/lib/python3.11/site-packages/discord/client.py", line 378, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/.venv/lib/python3.11/site-packages/discord/bot.py", line 1164, in on_connect
    await self.sync_commands()
  File "/home/container/.venv/lib/python3.11/site-packages/discord/bot.py", line 719, in sync_commands
    registered_commands = await self.register_commands(
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.venv/lib/python3.11/site-packages/discord/bot.py", line 588, in register_commands
    data = [cmd["command"].to_dict() for cmd in filtered_deleted]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.venv/lib/python3.11/site-packages/discord/bot.py", line 588, in <listcomp>
    data = [cmd["command"].to_dict() for cmd in filtered_deleted]
            ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.venv/lib/python3.11/site-packages/discord/commands/core.py", line 1164, in to_dict
    "options": [c.to_dict() for c in self.subcommands],
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.venv/lib/python3.11/site-packages/discord/commands/core.py", line 1164, in <listcomp>
    "options": [c.to_dict() for c in self.subcommands],
                ^^^^^^^^^
AttributeError: 'BridgeExtCommand' object has no attribute 'to_dict'```

this is the script:

group = bot.create_group("comandos-de-staff", "Comandos para el personal del servidor")

group.add_command(bot.get_command("warn"))
group.add_command(bot.get_command("unwarn"))
group.add_command(bot.get_command("warnings"))
group.add_command(bot.get_command("imagewarn"))
group.add_command(bot.get_command("mute"))
group.add_command(bot.get_command("unmute"))

bot.add_application_command(group)

little cobalt
summer knot
summer knot
#

from here:

https://guide.pycord.dev/extensions/bridge

https://stackoverflow.com/questions/74790979/pycord-how-to-make-subcommands-or-slashcommands-groups

https://guide.pycord.dev/extensions/commands/groups
summer knot
little cobalt
#

If you want to use a bridge group yea

summer knot
little cobalt
#

You mean with the build in help one?

summer knot
# little cobalt You mean with the build in help one?

if you look here:

Use `@ElBotDelYonny help [command]` for more info on a command.
You can also use `@ElBotDelYonny help [category]` for more info on a category.

__**Excepsiones**__
modo_molestar
__**​No Category**__
8ball avatar cancel_outro clear desilenciar desilenciar_all embed_creator fijar grafica help imagewarn info jumbo mute outro ping randomcolor randomuser rank record rps say server servericon silenciar silenciar_all stock stop_recording top translate unmute unwarn user-info warn warnings xp_remove

Here it shows the !help command of my bot but it only shows the cog commands in one category
What I want to know is how to put the commands that are in the category called: No Category in a category, which says that it is not in a category, this is because the commands are integrated into the main.py file

#

not in a cog file

little cobalt
#

yea, that is the build in help command for prefix commands and I dont know how to use it x3

summer knot
little cobalt
#

I usually create a full custome one at my bots

summer knot
little cobalt
summer knot
# little cobalt https://guide.pycord.dev/extensions/commands/help-command

:v

Ignoring exception in on_command_error
Traceback (most recent call last):
  File "C:\Users\Angel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 178, in wrapped        
    ret = await coro(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Angel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\help.py", line 858, in command_callback
    return await self.send_bot_help(mapping)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Angel\Downloads\yonny\main.py", line 44, in send_bot_help
    filtered = await self.filter_commands(commands, sort=True)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Angel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\help.py", line 604, in filter_commands
    for cmd in iterator:
  File "C:\Users\Angel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\help.py", line 584, in <lambda>       
    else filter(lambda c: not c.hidden, prefix_commands)
                              ^^^^^^^^
AttributeError: 'BridgeCommand' object has no attribute 'hidden'

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

Traceback (most recent call last):
  File "C:\Users\Angel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 378, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\Angel\Downloads\yonny\cogs\excepsiones.py", line 65, in on_command_error
    raise error
  File "C:\Users\Angel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 347, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Angel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 950, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\Angel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 187, in wrapped        
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'BridgeCommand' object has no attribute 'hidden'
#

I tried to investigate a solution but it seems that it is a problem in the library

#

this is what i found

This error is occurring because the filter_commands method in your send_bot_help function is trying to access the hidden attribute of a command object, but it appears that the ‘BridgeCommand’ object does not have this attribute.
#

The best part is that I used the example that the website you gave me gave me.

stray pasture
#

is it me or the search is not working anymore in doc ?

shell radish
#

you probably want master instead of stable

#

also bookmark bar (if you care)

stray pasture
#

oooh I see thank you !

summer knot
shell radish
summer knot
shell radish
summer knot
# shell radish you can probably override the `filter_commands` method with one that would work ...

it didn't work for me 5head

           class MyNewHelp(commands.MinimalHelpCommand):
    async def filter_commands(self, commands, *, sort=False, key=None):
        """Returns a list of commands that meet the conditions specified by the predicate and sorter."""

        if sort and key is None:
            key = lambda c: c.name

        iterator = commands if self.show_hidden else filter(lambda c: not c.hidden, commands)

        # Verifica si el comando es una instancia de 'BridgeCommand' y si tiene el atributo 'name'
        return sorted(filter(lambda c: isinstance(c, commands.BridgeCommand) and hasattr(c, 'name') and self.verify_checks(c), iterator), key=key)

    async def send_bot_help(self, mapping):
        destination = self.get_destination()
        for category, commands in commands_dict.items():
            filtered = await self.filter_commands(commands, sort=True)
            command_signatures = [self.get_command_signature(c) for c in filtered]
            emby = discord.Embed(description=f"{category}: {command_signatures}")
            await destination.send(embed=emby)

I get almost the same error

Ignoring exception in on_command_error
Traceback (most recent call last):
  File "C:\Users\Angel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 178, in wrapped
    ret = await coro(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Angel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\help.py", line 861, in command_callback
    return await self.send_bot_help(mapping)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Angel\Downloads\yonny\main.py", line 1870, in send_bot_help
    filtered = await self.filter_commands(commands, sort=True)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Angel\Downloads\yonny\main.py", line 1865, in filter_commands
    return sorted(filter(lambda c: isinstance(c, commands.BridgeCommand) and hasattr(c, 'name') and self.verify_checks(c), iterator), key=key)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Angel\Downloads\yonny\main.py", line 1862, in <lambda>
    iterator = commands if self.show_hidden else filter(lambda c: not c.hidden, commands)
                                                                      ^^^^^^^^
AttributeError: 'BridgeCommand' object has no attribute 'hidden'

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

Traceback (most recent call last):
  File "C:\Users\Angel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 378, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\Angel\Downloads\yonny\cogs\excepsiones.py", line 65, in on_command_error
    raise error
  File "C:\Users\Angel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 347, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Angel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 950, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\Angel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 187, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'BridgeCommand' object has no attribute 'hidden'
shell radish
#

you can probably override the filter_commands method with one that would work for bridge commands

summer knot
atomic fern
#

why persistent view still expired?

class Verify(discord.ui.View):
  def __init__(self, bot):
    self.bot = bot
    super().__init__(timeout=None)
    
  @discord.ui.button(custom_id="unranked_button", label="Unranked")
  async def callback_1(self, button, interaction):
    role = discord.utils.get(interaction.guild.roles, name="Unranked")
    await interaction.user.add_roles(role)
little cobalt
atomic fern
#

no

little cobalt
#

;3

plucky moss
#

.docs

sly karmaBOT
#
Nziie's Utilities
`.[doclink|dcl|docslink|docs] <section> <flags>`

Get a doc section easily
Flags

d - the directory, most likely to be data_classes for most things, index by default

Aliases

dcl, docslink, docs

plucky moss
#

.docslink

sly karmaBOT
#
Nziie's Utilities
`.[doclink|dcl|docslink|docs] <section> <flags>`

Get a doc section easily
Flags

d - the directory, most likely to be data_classes for most things, index by default

Aliases

dcl, docslink, docs

plucky moss
#

I'm fucking dumb 💀

#

Its working now guys

deft kestrel
#

MailTM - Tempmail API not working

lofty parcel
deft kestrel
lofty parcel
#

And the error is kinda self explanatory

atomic fern
#

why commands.has_role won't work with bridge commands? and how do i make it work with bridge

atomic fern
deft kestrel
little cobalt
#

lol

atomic fern
# lofty parcel How it doesnt?

idk, i tried it, the command can be used without the role, when i changed it to prefixed command, the role is required

lofty parcel
atomic fern
#

too much work xd

#

just only to check if user has a role

lofty parcel
topaz basin
#

Hi, does anyone know how to exclude users from a cooldown?
My cooldown looks like this

@commands.cooldown(1, 30, commands.BucketType.user)
lofty parcel
topaz basin
#

How can I do that?

lofty parcel
topaz basin
#

Thx mc

stray pasture
#

I am trying to get the oldest_first in the audit logs:

                async for entry in guild.audit_logs(limit=None, after=object_id,
                                                    oldest_first=True, action=discord.AuditLogAction.member_role_update):
                    print(f'{entry.created_at}')

But it is returning the most recent first ...

2023-12-28 19:49:21.731000+00:00
2023-12-28 19:49:18.526000+00:00
2023-12-28 19:49:14.620000+00:00
2023-12-28 19:49:11.040000+00:00
shell radish
stray pasture
shell radish
#

try seeing if this sae behavior happens on master. If so, please file a bug report on github

stray pasture
#

I see will try that !

#

yeah it still does it

#

so many bugs with audit logs !

stray pasture
#

In the mean time I just did:

entries = await guild.audit_logs(limit=None, after=object_id,
                                    oldest_first=True, action=discord.AuditLogAction.member_role_update).flatten()
entries.sort(key=lambda val: val.created_at)
shell radish
stray pasture
#

yeah but it is not a real fix, more a work around

hexed herald
#

hey, is there a given way through pycord to access the /gateway/bot endpoint?

shell radish
hexed herald
#

okay, just using the token and aiohttp?

lofty parcel
hexed herald
#

okay, thx

atomic fern
#

is it should be placed in on_ready?

little cobalt
fresh totem
#

How can I get a slash command user's profile pciture URL

#

ctx.author's pfp

#

I tried avatar_url, doesn't work

little cobalt
#

^ got answerd here #1190258685532966983

atomic fern
#

does persistent view uses api request to discord? if want to make selfrole system is it necessary to keep that message only in one channel? so if i want to change the selfrole location i need to delete the old message

#

just to prevent rate limiting

teal crag
#

#1190309845459533865

sage tendon
young cove
#

Any thoughts why an interaction_check isn't working on a modal?

class bioModal(discord.ui.Modal):
    def __init__(self, buttonInteraction, *args, **kwargs, ) -> None:
        super().__init__(*args, **kwargs)
        self.buttonInteraction = buttonInteraction
  
    async def interaction_check(self, interaction: discord.Interaction):
        print(interaction.user.id)
        print(self.buttonInteraction.user.id)
        if interaction.user.id == self.buttonInteraction.user.id:
            return True
        else:
            return False

    async def callback(self, interaction: discord.Interaction):
     await interaction.response.send_message(
            "view", view=MyView(),
            ephemeral=True)```

The print statements aren't running so I think it's being skipped over for some reason
lofty parcel
#

Don't know why you'd need one? Modals just show to the user that receives it

young cove
lofty parcel
#

Well, modals don't have interaction checks

sage tendon
#

which de facto replaced self roles in every bot

atomic fern
#

hmm, i use bots because I'm creating complex selfroles

sage tendon
#

like what

hybrid fossil
#

Hi there!
Since I've added a verification system to an API I've been getting this error, any ideas?

Ignoring exception in view <VMonthlyPass timeout=None children=7> for item <BVoteVerify style=<ButtonStyle.success: 3> url=None disabled=False label='Vérifier' emoji=<PartialEmoji animated=False name='2️⃣' id=None> row=1>:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/ui/view.py", line 421, in _scheduled_task
    await item.callback(interaction)
  File "/home/container/addons/EAVote/functions/buttons/buttonVoteVerify.py", line 111, in callback
    await interaction.response.send_message(embeds=embeds, ephemeral=True, delete_after=120)
  File "/home/container/.local/lib/python3.11/site-packages/discord/interactions.py", line 904, in send_message
    await self._locked_response(
  File "/home/container/.local/lib/python3.11/site-packages/discord/interactions.py", line 1198, in _locked_response
    await coro
  File "/home/container/.local/lib/python3.11/site-packages/discord/webhook/async_.py", line 220, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
#

It appears completely at random, so I don't really understand...

scarlet knot
#

How can I check if my bot is already connected to a vc or not
is there any way?

lofty parcel
scarlet knot
#

Hello I'm Getting an issue.. ctx.content always returning an empty string

little cobalt
#

What is ctx.content?

fresh totem
#

Documentation page for adding dropdown list to embed

sage tendon
#

what

lofty parcel
shell radish
lofty parcel
#

LMAO

#

YOU STOLE MY WORDS

sage tendon
#

fr

fresh totem
#

Thank you, yall are so helpful

sage tendon
#

use google?

#

We aren't living link dispensers dude

rugged lodgeBOT
#

Here's the dropdown example.

sage tendon
#

truly an impossible feat

shell radish
edgy nest
#

why the fucj

#

are you using bing

sage tendon
#

bing chat, thats why

fresh totem
#

imagine getting trolled for asking help in the one and only support server

sage tendon
#

Support is for actual issues not for "pls give me this publicly accessible website link"

edgy nest
sage tendon
shell radish
edgy nest
sage tendon
#

you know how hardcore google regionlocks stuff
even their new gemini model for bard is region locked

edgy nest
sage tendon
shell radish
#

@edgy nest @sage tendon #general

plucky moss
#

how to add description to parameters, like if I have a slash command:

#not an actual command just example
@client.slash_command()
async def test(ctx, answer: str):
       await ctx.respond(f'cool opinion about {answer}')

How can I add a description when we are inputting answer.

lofty parcel
#

.rtfm discord.Option

plucky moss
#

Works thanks

sinful juniper
#

hey, what is the best way to make a handler that checks whether the user is on a mongodb blacklist or not every time a slash command is executed. if so, the bot should only send that it is on a blacklist.

i had just tried this with the on_application_commmand, but i only get problems with my on_application_command_error event. what is the best way to do this?

hazy turret
#

Is it not possible to use Discord timestamps in an embed footer?

hazy turret
lapis dock
lapis dock
#

I dont think it matters but try it an see. Also if you do this you should make a cache so you are not constantly calling the DB if someone is "spamming" commands

sinful juniper
lapis dock
#

Yeah, I guess you are right, there is not a huge difference. What are you trying to avoid?

#

Or what is the issue with on_application_command_error

sinful juniper
lapis dock
#

Do you still have this old handler avalible for me to help debug?

#

I will be back in ~20 to help you fix your error handling. As that is the best way other than just putting a function at that start of every command.

short rivet
#

to make commands work with prefix as well as when bot is mentioned we use the when_mentioned_or function when creating the bot object but if i just have to make some commands which have the mentioned at property what should i do according to the best practice

sinful juniper
lapis dock
short rivet
sinful juniper
# lapis dock Do you still have this old handler avalible for me to help debug?
import discord
from discord.ext import commands
import json
from mongodb import db


# json config laden für die verschiedenb parameter in den embeds
def load_config():
    with open("config.json", "r", encoding="utf-8") as f:
        config = json.load(f)
        color = int(config["color"], 16)
        footer_text = config["footer-text"]
        return color, footer_text


class ErrorHandler(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.db = db
        self.collection = self.db['bans']

    @commands.Cog.listener()
    async def on_application_command_error(self, ctx, error):
        # Embeds
        color, footer_text = load_config()
        avatar = self.bot.user.display_avatar.url

        embed = discord.Embed(
            description=f"Unfortunately, the following error occurred when executing the (slash) command: {error}",
            color=color
        )
        embed.set_footer(text=footer_text, icon_url=avatar)

        if isinstance(error, commands.CheckFailure):
            # Check if the interaction is still valid before responding
            if ctx.interaction:
                await ctx.respond(embed=embed, ephemeral=True)
            return

        # Check if the interaction is still valid before responding
        if ctx.interaction:
            await ctx.respond(embed=embed, ephemeral=True)
        raise error
    
    @commands.Cog.listener()
    async def on_application_command(self, ctx):
        user_id = ctx.author.id

        if self.collection.find_one({"user_id": user_id}):
            await ctx.respond("you are banned", ephemeral=True)
            return False
        return True




def setup(bot):
    bot.add_cog(ErrorHandler(bot))

unfortunately i didn't find the code from before, but i have now created a new one. the user id, with which i execute the command, is on the blacklist, but still no error or other grade appears, the blacklisted user can execute the command just like that.

tepid coyote
#
channel = self.bot.get_channel(result[3])
        if channel is None:
            channel = await self.bot.fetch_channel(result[3])

this returns a: NotFound: 404 Not Found (error code: 10003): Unknown Channel

i coppied the code into a notmal prefixed command and coppied the id from the db and it works fine

lapis dock
lapis dock
#

with what kind of option?

#

Make sure the value is an int and not a string

tepid coyote
sinful juniper
tepid coyote
# lapis dock But it does not work in a slash comand?
    async def get_channel(self, channel_id: int):
        channel = self.bot.get_channel(channel_id)
        if channel is None:
            channel = await self.bot.fetch_channel(channel_id)
            print('fetch')
            print(channel)
        if channel is not None:
            print('get')
            print(channel)

coppied the channelID from the db and it returns get then the channel name
in the same cog file aswell
the perfixed command for testing btw

lapis dock
lapis dock
tepid coyote
# lapis dock Can you show the slash command that it is not working for
@medbay.command(name="return", description="Returns a user from the medbay")
    @discord.option(name="member", description="The member to return from the medbay", input_type=discord.Member,
                    required=False)
    async def _return(self, ctx: discord.ApplicationContext, member: discord.Member = None):
        if member is None:
            member = ctx.author
        db, cursor = await connect_to_db()
        await cursor.execute(
            f"SELECT UserID, endDate, Status, channelID FROM medbay WHERE UserID = {member.id} AND (Status = {1} OR Status = {3})")
        result = await cursor.fetchone()
        if result is None:
            await ctx.respond(f"No active medbay ticket open for member: {member.display_name}")
            await cursor.close()
            await db.close()
            return
        print(result[3])
        # channel = await self.get_channel(result[3])
        channel = self.bot.get_channel(result[3])
        if channel is None:
            channel = await self.bot.fetch_channel(result[3])
#
if result[2] == 1:
            await cursor.execute(f"UPDATE medbay SET Status = {2} WHERE UserID = {member.id} AND Status = {1}")
            await db.commit()
            await cursor.close()
            await db.close()
            await ctx.respond(f"Returned {member.display_name} from medbay")
        elif result[2] == 3:
            end_date = datetime.datetime.strptime(result[1], "%d-%m-%Y")
            days_late = (datetime.datetime.today() - end_date).days
            new_end_date = datetime.datetime.today().strftime("%d-%m-%Y")
            print(new_end_date)
            await cursor.execute(
                f"UPDATE medbay SET endDate = {new_end_date}, Status = {4} WHERE UserID = {member.id} AND Status = {3}")
            await db.commit()
            await cursor.close()
            await db.close()
            await ctx.respond(f"Returned {member.display_name} from medbay. {days_late} days late")

        await channel.delete()
lapis dock
#

can you add print(type(result[3]))

sinful juniper
# lapis dock You would have to create your own error or just choose one that already exists. ...

something like that?

import discord
from discord.ext import commands
import json
from mongodb import db

class UserBanned(commands.CommandError):
    pass

# json config laden für die verschiedenen parameter in den embeds
def load_config():
    with open("config.json", "r", encoding="utf-8") as f:
        config = json.load(f)
        color = int(config["color"], 16)
        footer_text = config["footer-text"]
        return color, footer_text

class ErrorHandler(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.db = db
        self.collection = self.db['bans']

    @commands.Cog.listener()
    async def on_application_command_error(self, ctx, error):
        # Embeds
        color, footer_text = load_config()
        avatar = self.bot.user.display_avatar.url

        embed = discord.Embed(
            description=f"Unfortunately, the following error occurred when executing the (slash) command: {error}",
            color=color
        )
        embed.set_footer(text=footer_text, icon_url=avatar)

        
        if ctx.interaction:
            await ctx.respond(embed=embed, ephemeral=True)
        
        raise error

    @commands.Cog.listener()
    async def on_application_command(self, ctx):
        user_id = ctx.author.id
        print(f"User ID: {user_id}")

        if self.collection.find_one({"user_id": user_id}):
            print(f"User {user_id} is banned.")
            raise UserBanned()

        return True

def setup(bot):
    bot.add_cog(ErrorHandler(bot))
tepid coyote
lapis dock
sinful juniper
#
import discord
from discord.ext import commands
import json
from mongodb import db

class UserBanned(commands.CommandError):
    pass

# json config laden für die verschiedenen parameter in den embeds
def load_config():
    with open("config.json", "r", encoding="utf-8") as f:
        config = json.load(f)
        color = int(config["color"], 16)
        footer_text = config["footer-text"]
        return color, footer_text

class ErrorHandler(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.db = db
        self.collection = self.db['bans']

    @commands.Cog.listener()
    async def on_application_command_error(self, ctx, error):
        # Embeds
        color, footer_text = load_config()
        avatar = self.bot.user.display_avatar.url

        embed = discord.Embed(
            description=f"Unfortunately, the following error occurred when executing the (slash) command: {error}",
            color=color
        )
        embed.set_footer(text=footer_text, icon_url=avatar)

        if ctx.interaction:
            await ctx.respond(embed=embed, ephemeral=True)

        if isinstance(error, UserBanned):
            return 

        raise error

    @commands.Cog.listener()
    async def on_application_command(self, ctx):
        user_id = ctx.author.id
        print(f"User ID: {user_id}")

        if self.collection.find_one({"user_id": user_id}):
            print(f"User {user_id} is banned.")
            raise UserBanned()

def setup(bot):
    bot.add_cog(ErrorHandler(bot))
lapis dock
# tepid coyote <class 'int'>

Sorry I dont know why this is. The docs say that your error only occurs when the channel ID is not valid. Something must be going wrong with the results from your database.

#

what pacakge are you using to access the DB?

tepid coyote
sinful juniper
lapis dock
#

try changing @commands.Cog.listener() to @bot.event()

sinful juniper
tepid coyote
#

thanks for the help :)

lapis dock
hexed herald
#

hey, is there a way to get the raw member as json format? like the raw response from discord is?

hexed herald
#

but I then do 2 requests for 1 user, my idea is to send the raw data to a dashboard, but I could also build my own jsons using only the data I need in the dashboard

sinful juniper
# lapis dock I hope that works for you if not try to make custom check, simple example you ca...

idk, this also doesn't work.

class Blacklisted(CheckFailure):
    pass

class UserBanned(commands.CommandError):
    pass  

@bot.event
async def on_application_command(ctx):
    user_id = ctx.author.id
    print(f"User ID: {user_id}")

    
    if db['bans'].find_one({"user_id": user_id}):
        print(f"User {user_id} is banned.")
        raise UserBanned()

@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, Blacklisted):
        return await ctx.send("du kannst nichts mehr benutzen.")
    elif isinstance(error, UserBanned):
        
        return await ctx.send("You are banned from using this command.")
    else:
       
        await bot.handle_error(ctx, error)
    
sage tendon
#

nice mix of languages

sinful juniper
sinful juniper
shell radish
#

did you read the footnote regarding the event?

sinful juniper
shell radish
sinful juniper
# shell radish you need to put this at the bottom of your event where things that should be tri...

you mean this?

class Blacklisted(CheckFailure):
    pass

class UserBanned(commands.CommandError):
    pass  

@bot.event
async def on_interaction(interaction):
    user_id = interaction.user.id
    print(f"User ID: {user_id}")

    if db['bans'].find_one({"user_id": user_id}):
        print(f"User {user_id} is banned.")
        raise UserBanned()

    await bot.process_application_commands(interaction)


@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, Blacklisted):
        return await ctx.send("du kannst nichts mehr benutzen.")
    elif isinstance(error, UserBanned):
        
        return await ctx.send("You are banned from using this command.")
    else:
       
        await bot.handle_error(ctx, error)
shell radish
#

ig so

sinful juniper
# shell radish ig so

puhh, idk, the commands work again, but a blacklisted user can still execute the commands...

no idea

shell radish
#

does the if statement work

sinful juniper
shell radish
#

if db['bans'].find_one({"user_id": user_id}):

sinful juniper
#

I can't get a print there either

shell radish
#

idk how your DB is organized

shell radish
#

the user id is an int, but you saved it as a string

#

so you should convert it a string then search for it

sinful juniper
# shell radish the user id is an int, but you saved it as a string
class Blacklisted(CheckFailure):
    pass

class UserBanned(commands.CommandError):
    pass

@bot.event
async def on_interaction(interaction):
    user_id = str(interaction.user.id)
    print(f"User ID: {user_id}")

    if db['bans'].find_one({"user_id": user_id}):
        print(f"User {user_id} is banned.")
        raise UserBanned()

    await bot.process_application_commands(interaction)


@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, Blacklisted):
        return await ctx.send("du kannst nichts mehr benutzen.")
    elif isinstance(error, UserBanned):
        
        return await ctx.send("You are banned from using this command.")
    else:
       
        await bot.handle_error(ctx, error)

Now the prints are going through, but I still get this little error:

User ID: 1038849770380345457
User 1038849770380345457 is banned.
Ignoring exception in on_interaction
Traceback (most recent call last):
  File "C:\Users\Max\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 378, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\Max\PycharmProjects\Vysion\main.py", line 67, in on_interaction
    raise UserBanned()
UserBanned
#

This is how it would work now.

short rivet
#

is there a way to add alises like this one ["np add"] ... basically which have a space between them

#

?

#

would i have to make a command group ?

lapis dock
sinful juniper
lapis dock
#

If i understand what you mean yes

teal crag
#

is there like a command mention

like example if they click on this <#command> it runs the command?

shell radish
#

.slashmention

sly karmaBOT
#

</full name:ID>

rugged lodgeBOT
teal crag
#

thanks

shell radish
short rivet
#

without making a group is it not possible to make a command like "np add"

#

without using the on message event ofcurse

lapis dock
tepid coyote
#

is there an upper limit to guild.fetch_members?

lapis dock
#

There should not be.

tepid coyote
#

im adding members to a db. matches the display name to a regex and if theres a match it adds the member to the db but there are some members missing that should be added

tepid coyote
#

but its still missing some

lapis dock
#

Are you sure it is not an issue with your regex?

#

Also make sure you are using the right name not that there is user name, display name, nickname, etc

tepid coyote
tepid coyote
#
pattern = r"^([A-Z0-9]{2,4}) ([A-Z][a-z]+) ([A-Z]{1,2}-(?:[0-9]+|(?:\d-\d+\/\d+)))$"
        async for member in ctx.guild.fetch_members(limit=12000):
            print(counter, member.display_name)
            if re.match(pattern, member.display_name):
                name_info = member.display_name.split(" ")
                RANK = name_info[0]
                NAME = name_info[1]
                DESG = name_info[2]
                try:
                    await cursor.execute(
                        f"INSERT INTO Members (ID, Rank, Name, Designation) VALUES ({member.id}, '{RANK}', '{NAME}', '{DESG}')"
                    )
                    counter += 1
                except IntegrityError:
                    pass

the main part of the command

shell radish
#

?tag sqli

limber wagonBOT
#

SQL Injection is a technique used by attackers to interfere with and alter queries that an application makes to its database via input data. A vulnerability to this exploit can lead to attackers being able to read sensitive data, modify existing data (Insert/Update/Delete), perform administrative operations on your database and in some cases even issue commands directly to the operating system of the server.

More information on SQL Injection
w3schools, owasp.org

To avoid SQL Injection vulnerability, you should never directly merge or concatenate data into an SQL query through string operations (f-strings, + operator, string interpolation with %, etc.). Always use the parameterized queries included with the library you are using.

Examples of parameterized queries for popular libraries
psycopg2, asyncpg, sqlite3, mysql

shell radish
#

side-note

sour flint
#

is there a way to reload the code of the bot like push changes without restarting the bot/server, without using a cog or do i need to use cogs

stray pasture
#

what exactly this take in consideration and what it does not. For exemple I found that it take in considerations the admin roles

plucky palm
short obsidian
#

discord.ActivityType.custom isn't working? when i try like watching it works fine but custom just don't

sour flint
#

hmmm thx

short rivet
#

for the get_prefix function in which i get the prefix from a database made in aiosqlite should i just make a single conn and reuse it since it will be triggered on every message

#

or i should create conn easch time ?

short rivet
#

if i have seperate error handeler for a command using @commandname.error
the command gives the error to it but it also raises it on the on_command_error cant we prevent this since for some commands we need specific error handelers

#

would i have to specifically chekc on the on_command_error that if the command has its on_error already or not

async def on_command_error(self, ctx: Context, error: CommandError) -> None:
        if ctx.command.on_error:
            return```
steep cliff
autumn gust
#

how do you get the amount of pins in a channel?

#

I essentially want a simple if statement

#
if pinamount == 50:
  print("can't pin")
else
  pin()
#

does this work?

pinlist = channel.pins()
pincount = pinlist.count()
glad garnet
autumn gust
#

oh, with justm messages, message author etc. can you get a channel?

lost ocean
#

hey wsg!

#

i recently reset my pc

#

and im unable to install pyc again

#

the installation fails at 'aiohttp build wheel'

#
  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for aiohttp
Failed to build aiohttp
ERROR: Could not build wheels for aiohttp, which is required to install pyproject.toml-based projects
#
Building wheels for collected packages: aiohttp
  Building wheel for aiohttp (pyproject.toml) ... error
  error: subprocess-exited-with-error

  × Building wheel for aiohttp (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [110 lines of output]```
plucky palm
lost ocean
#

i installed py again yesterday

plucky palm
#

some libraries didn't yet update to 3.12

lost ocean
#

3.11?

autumn gust
#

yeah 3.11 works fine

plucky palm
#

yeah

autumn gust
#

3.11.7

#

works fine

lost ocean
#

alright, tysm!

plucky palm
#

np

sinful juniper
reef spire
#

How can i create/edit/delete channels using the bot?

lapis dock
#

and to edit you need to have a channel object and just run edit

plucky palm
# sinful juniper

try updating to new ver (uninstall pycord and install py-cord-dev; see #library-updates)

sinful juniper
plucky palm
sinful juniper
#

oh, sorry. I meant him

lapis dock
#

Due to some issue with uploading a new version to pypi we made a temporary version called py-cord-dev it is just as stable as 2.4. In the future we will switch back to using py-cord

plucky palm
#

^

#

though some bugs might've been fixed already

#

stable obv doesn't mean no bugs at all

sinful juniper
#

okay, then I'll try

short obsidian
#

nah i'm using the stable version

#

that must be a bug

sinful juniper
short obsidian
#

2.4.1

short obsidian
#

yeah

sinful juniper
#

yes

deft kestrel
#

how i can get the ping down?

sage tendon
#

get better internet lol

deft kestrel
#

there is not other option?

sage tendon
#

well, where is your bot hosted

deft kestrel
#

wdym?

shell radish
sage tendon
#

yea, i was gonna get to that lol

shell radish
#

getting better internet does help, but the difference generally isn't large

sage tendon
deft kestrel
sage tendon
#

lol

deft kestrel
#

i am using the free one of course

sage tendon
#

There are about 30 ways i could tell you that can host your bot for free

#

But how high is the bot's ping anyway

shell radish
deft kestrel
sage tendon
#

thats not really much for a bot

deft kestrel
#

good

shell radish
#

anything below 300 is fine

lapis dock
#

?Tag install

limber wagonBOT
#

1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
python -m pip uninstall discord.py discord -y

2a. Install py-cord
python -m pip install py-cord

2b. Update py-cord
python pip install -U py-cord

Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.

Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord

sinful juniper
sage tendon
#

status is not a user attribute

rugged lodgeBOT
shell radish
#

also legally, the people you are taking the status from should consent to have their data being collected

#

this isn’t a problem until bot verification, but something to note

grizzled loom
#

make sure to make a check, so it uses fetch when get returns None.

#

alright

autumn gust
#

hey, any idea why my message command isn't appearing, nor does the ping command?

@bot.slash_command(name="ping", description="Check if the bot is alive.")
async def ping(ctx):
    ctx.respond(f"🏓 Pong! at `{bot.latency()}ms`")
@bot.message_command(name="Unpin")
async def unpin(ctx, message=discord.Message):
    link = message.jump_url
    caller = ctx.author
    caller = caller.global_name
    victim = message.author
    victim = victim.global_name
    channel = message.channel
    if message.pinned:
        await ctx.respond(f"{caller} Unpinned message {link} by {victim}.")
        await message.clear_reaction("📌")
        await message.unpin()
    else:
        await ctx.respond(f"{caller} Can't unpin this message, as that message isn't pinned!", ephemeral=True)
short obsidian
#

just wait a bit

autumn gust
#

discord api bad, got it

short obsidian
#

yep

lapis dock
#

.tag slashnoshow

sly karmaBOT
#

Application Commands Not Showing Up?

  • Uninstall libraries that conflict with the discord namespace (e.g. discord.py).
  • Invite your bot with the application.commands scope.
  • Load cogs before bot.run() (e.g. not in on_ready).
  • Do not override on_connect.
  • Update to the newest version of py-cord (see ?tag install).
  • Turn off User Settings > Accessibility > Chat Input > Use legacy chat input.
  • Share your code and errors.
atomic fern
#

how to add description to an slash's option in slashcommandgroup? i don't find it in docs

red mist
# atomic fern how to add description to an slash's option in slashcommandgroup? i don't find i...

I take it you wish to add a description to a group?

You can add a description to a group when creating them
https://docs.pycord.dev/en/stable/api/clients.html#discord.Bot.create_group

#

bot.create_group("name", "description")

atomic fern
#

i mean add description to option

#

async def example(ctx, arg)
add a description into "arg" argument

#

in slash

red mist
#

oh

#

wait are you using the @option decorator or not?

atomic fern
#

thnk u

atomic fern
#

maybe i should try that

sinful juniper
red mist
sinful juniper
lapis dock
#

Master should be stable as of now

mighty otter
#

Hey! I have some questions! Can anyone tell me how to make a command be able to run before the same command's first usage if finished? (My wordings bad so lemme explain)

Let's say i have a command that takes some time, and i used the command >long_command. before it returns me a result, i want to use >long_command again, but when i do, the code waits for the first one to return a result first, and then starts the second one. I want to make it more efficient by running both of them immediately once the command is recieved, so instead of waiting 2 long commands, i save some time buy running them in parallel. Any way i can do that? Thank you!

lapis dock
mighty otter
#
@bridge.bridge_command(
    name="imagine",
    description="Make pictures with OpenAI's image generation AI: Dall-E!",
    help="Create gorgeous pieces of art using OpenAI's famous Dall-E!",
    aliases=["dall","img","dalle","image"],
)
async def _bing_img(self, ctx: Context, *, prompt: str):
        
    await ctx.defer() 

    windows = os.name in ('nt', 'dos')  
            
    if windows: service = Service('C:\chromedriver-win64\chromedriver.exe')
    options = Options()
    #options.add_argument('--headless=new')

    if windows: options.add_argument("--user-data-dir=C:\\Users\\Administrator\\Desktop")
    else: options.add_argument("--user-data-dir=/home/ubuntu/botpp/chromeprofiles/")

    options.add_argument("--profile-directory=Profile 4")

    if windows: driver = webdriver.Chrome(service=service, options=options)
    else: driver = webdriver.Chrome(options=options)
    self.driver = driver

    prompt = ''.join(c for c in unicodedata.normalize('NFC', prompt) if c <= '\uFFFF')
    self.prompt = prompt

    try:
        driver.get('https://www.bing.com/images/create/')

        search_box = driver.find_element(By.NAME, 'q')
        search_box.send_keys(prompt)
        search_box.send_keys(Keys.RETURN)

        try:
            wait_for_error = WebDriverWait(driver, 2, ignored_exceptions=self.ignored_exceptions)
            error_text = wait_for_error.until(EC.presence_of_element_located((By.XPATH, '//*[@id="girer"]/div/div[1]'))).text
            error_msg = self.find_error(error_text)

            if error_msg != None:
                await ctx.send(error_msg)
            
        except:
            wait_for_gen = WebDriverWait(driver, 60, ignored_exceptions=self.ignored_exceptions)

            image = wait_for_gen.until(EC.presence_of_element_located((By.XPATH, '//img[contains(@src, "w=270&h=270")]')))
            images = driver.find_elements(By.TAG_NAME, 'img')
            image_links = []
#

            for image in images:
                src = image.get_attribute('src')
                if src and 'w=270&h=270' in src:
                    src = src.replace('w=270&h=270&c=6&r=0&o=5&', '')
                    image_links.append(src)

            image_links = list(set(image_links)) # Remove duplicates by converting the list to a set and then back to a list...
            driver.close()
            print(image_links)

            async with aiohttp.ClientSession() as session:
            files = []
            for i in range(len(image_links)):
                async with session.get(image_links[i]) as resp:
                    img = resp.read()
                    async with io.BytesIO(img) as file:
                        files.append(discord.File(file, "imagine_prax.png"))
            await ctx.send(f"*Your prompt:* `{prompt}`", files=files)            

    except Exception as e:
        print(e)
        await ctx.send("There was an error while generating your image!")
#

I'm using selenium, that's probably blocking it...

#

I don't know where, or how to fix it though...

deft kestrel
#

how i can make the bot send a message every time somebody is getting on live in YouTube?

lapis dock
mighty otter
#

How could I implement that to pycord?

short obsidian
#

take this as an example

#

i'm using that as a helper

mighty otter
#

so you suggest i use concurrent.futures.ThreadPoolExecutor?

short obsidian
#

worked for me

mighty otter
#

I mean i did try but didnt rlly succeed, i will retry looking at this code

#

also

#

does the other def has to be just def or can it be async def

#

i mean the one being run by the executor

short obsidian
deft kestrel
#
guild = self.bot.get_guild(guild_id) 
        premium_roles = discord.utils.get(guild.roles, id=premium_role)
        await interaction.user.add_roles(premium_roles)

user object has no attribute add_roles
Actions take place inside discord.ui.select

sage tendon
#

well, you cant add roles to a user

#

you need a member

wise parcel
#

Hi, so i have a cog with commands in it. When i start the bot it says the cog has been started but i cant use any of the commands in it

#

it says command not found

deft kestrel
wise parcel
#
import platform
import psutil
import datetime
import aiohttp
from discord.ext import commands

class basic(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.command(aliases=["botinfo", "bot-info", "binfo", "bi", "boti"])
    async def botinfó(self, ctx):
        pythonVersion = platform.python_version()
        dpyVersion = discord.__version__
        serverCount = len(self.client.guilds)
        memberCount = len(set(self.client.get_all_members()))
        channelCount = len(set(self.client.get_all_channels()))
        embed = discord.Embed(title=f"Bot információ", description="A Retron bot információi", color=0x10b9e3, timestamp=datetime.datetime.utcnow())
        embed.add_field(name="Bot neve", value="Retron", inline=True)
        embed.add_field(name="Készült", value="2021.03.31.", inline=True)
        embed.add_field(name="Programozási könytár", value="Pycord")
        embed.add_field(name="Szerverek", value=f"{serverCount}")
        embed.add_field(name="Csatornák", value=f"{channelCount}")
        embed.add_field(name="Felhasználók", value=f"{memberCount}")
        embed.add_field(name="Python verzió", value=f"{pythonVersion}")
        embed.add_field(name="Parancsok száma", value=f"{len(self.client.commands)}")
        embed.add_field(name="Pycord verzió", value=f"{dpyVersion}")
        embed.add_field(name="CPU magok száma", value=f"{psutil.cpu_count()} db")
        embed.add_field(name="Memória mérete", value=f"0,5 GB")
        embed.add_field(name="CPU kihasználtság", value=f"{psutil.cpu_percent()}%")
        embed.add_field(name="Memória kihasználtság", value=f"{psutil.virtual_memory().percent}%")
        await ctx.reply(embed=embed, mention_author=False)

def setup(client):
    client.add_cog(basic(client))```
shell radish
#

how are you loading your cog

wise parcel
#
        if filename.endswith('.py'):

            client.load_extension(f"cogs.{filename[:-3]}")
            print(f"[COGS] ~> {filename} elindítva\n ")
print("[INFO] ~> Parancs cooldownok betöltése...")
if os.path.exists("cooldown.pkl"): 
        with open("cooldown.pkl", 'rb') as f:
            d = pickle.load(f)
            for cmd in list(client.commands):
                if cmd.name in d:
                    cmd._buckets = d[cmd.name]
print("[INFO] ~> Parancs cooldownok betöltve!")

shell radish
#

how do you run your bot

wise parcel
#

what do you mean by that?

shell radish
#

what do method do you call to run your bot

wise parcel
#

you mean how i start the main.py? or what

#

sorry

shell radish
#

if I asked you which line of code would start the entire bot, what would that be?

wise parcel
#

client.run("mytoken")

shell radish
wise parcel
#
import sqlite3
import os
import pickle
from discord.ext import commands

intents = discord.Intents.all()
a = []
x = 1
x = x +1
players = {}

client = commands.Bot(command_prefix=_get_prefix, case_insensitive=True, intents=intents)

for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):

            client.load_extension(f"cogs.{filename[:-3]}")
            print(f"[COGS] ~> {filename} elindítva\n ")
print("[INFO] ~> Parancs cooldownok betöltése...")
if os.path.exists("cooldown.pkl"): 
        with open("cooldown.pkl", 'rb') as f:
            d = pickle.load(f)
            for cmd in list(client.commands):
                if cmd.name in d:
                    cmd._buckets = d[cmd.name]
print("[INFO] ~> Parancs cooldownok betöltve!")

@client.event
async def on_ready():
    for x in client.commands:
        a.append(x)

    print("gg")


client.run("mytoken")```
shell radish
#

i don't see client defined anywhere

wise parcel
#

there it is

shell radish
#

you say that the cog is being loaded?

wise parcel
#

yeah

#

when i start it said basic.py has been started

shell radish
#

you say when you run botinfo you get the CommandNotFound error?

wise parcel
#

yep

shell radish
#
    @commands.command(aliases=["botinfo", "bot-info", "binfo", "bi", "boti"])
    async def botinfó(self, ctx):

I think you can't have an alias being the same as the original command name

#

try removing "botinfo" from aliases?

wise parcel
#

its not the same. botinfó and botinfo is different

#

but okay i will try

#

still nothing

sage tendon
#

why the hell does your command name have an ó

shell radish
#

not an

wise parcel
#

because in hungary we spell it like that

sage tendon
#

i think it was common practice to not use any special characters in code ever

wise parcel
#

it worked

sage tendon
#

my bet is that it's that

sage tendon
shell radish
sage tendon
#

No, in general

#

ideally, code should be written in english anyway :)

shell radish
#

i beg to differ

#

but wrong channel for this

sage tendon
wise parcel
#

no the command worked before today

#

like it was working yesterday

shell radish
wise parcel
#

any idea whats the problem?

shell radish
#

do all your commands not work?

#

and a bunch of things in your main.py that you've shown are not defined

wise parcel
wise parcel
#

but they are just random commands

shell radish
#

does moving to a different cog work

wise parcel
#

what should i do?

wise parcel
#

hmm

wise parcel
# shell radish does moving to a different cog work

hmm sorry i just found it. i got this error when i start it RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited client.load_extension(f"cogs.{filename[:-3]}") RuntimeWarning: Enable tracemalloc to get the object allocation traceback

lofty parcel
deft kestrel
#

member = await guild.get_user(int(user_id))
object has no attribute get_user
Also I tried fetch_user / fetch_member but error was same no attribute fetch_member

wise parcel
lofty parcel
#

Read the docs.

deft kestrel
lofty parcel
deft kestrel
#
guild = self.bot.get_guild(1185946025479909447)
            member = await guild.get_member(int(user_id))
            role = guild.get_role(premium_role)
            if premium_roles:
                await member.remove_roles(premium_roles)```
lofty parcel
deft kestrel
lofty parcel
#

That means the bot isn't in that guild or the guild isn't cached or the guild ID is invalid

vital bramble
#

Is it possible to get the bot object from anywhere in my program?
Like a decorator that gets the bot object from the global scope or something and does something with it?

#

Ofc I mean the wrapper getting the bot object (so at runtime), not the decorator.

lofty parcel
#

Otherwise you'd just be in your main file where your bot object is there

deft kestrel
deft kestrel
#

Since every time it starts, it enters a channel in the voice on the server

lofty parcel
deft kestrel
# lofty parcel What's stopping you from using ctx.guild?
import discord
from discord.ext import commands, tasks
import sqlite3
from datetime import datetime
from main import *

class PremiumCheck(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.check_expiration.start()

    @tasks.loop(seconds=1)
    async def check_expiration(self):
        conn = sqlite3.connect('database.db')
        cursor = conn.cursor()
        current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

        cursor.execute('SELECT user_id FROM premium_user WHERE end_time <= ?', (current_time,))
        expired_users = cursor.fetchall()

        for user_id_tuple in expired_users:
            user_id = user_id_tuple[0]
            guild = self.bot.get_guild(guild_id)
            role = guild.get_role(premium_role)
            member = guild.get_member(int(user_id))
            if premium_roles:
                await member.remove_roles(role)
            cursor.execute('DELETE FROM premium_user WHERE user_id = ?', (user_id,))

        conn.commit()
        conn.close()

    def cog_unload(self):
        self.check_expiration.cancel()

def setup(bot):
    bot.add_cog(PremiumCheck(bot))
shell radish
#

is bot.guilds populated or empty

vital bramble
#

That way I can actually get the bot instance even from a utils function

#

Although that might actually not be good practice... Well, whatever xD

sage tendon
#

what do you even need that for

vital bramble
sage tendon
#

wtf

vital bramble
#

Basically I wanted to access the bot in a decorator wrapper for a method in a Modal

#

But didn't want to just pass the bot to the Modal xD

#

don't ask me why

#

Oh I know why: I like to overcomplicate things before I can actually make them simpler

vital bramble
#

Do modals that have timed out not get deleted from the modal store automatically?
I can successfully submit a modal that has already timed out... Is that right?

#

Even when I do modal.stop() it can still be submitted successfully

#

pycord v2.4.1

hazy turret
deft kestrel
#

how to get rid off this error?

little cobalt
lofty parcel
#

bro joined the wrong support server

deft kestrel
deft kestrel
deft kestrel
red mist
little cobalt
red mist
red mist
#

my man, this is a support server, not a code writing server >-<

little cobalt
#

You should create full new project and rewrite your bot with py-cord

little cobalt
deft kestrel
red mist
#

._.

#

no.

#

come back here when you have got actual questions, we will not be writing code for you, this is a support server not a code generating server. dito.

lapis dock
little cobalt
#

interaction.user

#

not author

#

but you should get a error for it?

lofty parcel
#

Or read the docs

vital bramble
#

intellisense...

deft kestrel
#

AttributeError: module 'discord' has no attribute 'Bot'

After py-cord-dev got deleted idk how to fix this

deft kestrel
little cobalt
#

take a look at here -> #app-commands message

#

Can you show the pip list if its still the same error

deft kestrel
#

i think that was the prboelm

#

let me relaunch

#

shit yeah

#

alr thank u

cursive zealot
#

Hey guys, I was wondering if there's an easy way to stop the bot ?
I made a command to stop it, but it doesn't work properly: the bot itself closes its connection to the Discord API but the process doesn't stop, does someone have an idea to make it stop the process also ?
Here's my code from my bot class (which is a subclass of discord.Bot)

async def stop(self):
  """Stops the bot"""
  await self.close()
  exit(0)

And here's the error message when I force the process to end with a control-C:

^CException ignored in: <module 'threading' from '/home/mathis/.pyenv/versions/3.11.7/lib/python3.11/threading.py'>
Traceback (most recent call last):
  File "/home/mathis/.pyenv/versions/3.11.7/lib/python3.11/threading.py", line 1590, in _shutdown
    lock.acquire()
KeyboardInterrupt: 

Thanks 😄

vital bramble
#

Where and how are you running the bot?

#

usually you can just stop the bot in the console by using ctrl + c

cursive zealot
cursive zealot
vital bramble
cursive zealot
#

And I don't want to connect to the server every time I want to stop the bot properly

vital bramble
#

oh ok

#

gimme a moment

#

try

await self.close()
self.loop.stop()
cursive zealot
#

and same error

#

seems like it gets stuck waiting for a lock

vital bramble
#

try to implement this:

def _cleanup_loop(loop: asyncio.AbstractEventLoop) -> None:
    try:
        _cancel_tasks(loop)
        loop.run_until_complete(loop.shutdown_asyncgens())
    finally:
        _log.info("Closing the event loop.")
        loop.close()
def _cancel_tasks(loop: asyncio.AbstractEventLoop) -> None:
    tasks = {t for t in asyncio.all_tasks(loop=loop) if not t.done()}

    if not tasks:
        return

    _log.info("Cleaning up after %d tasks.", len(tasks))
    for task in tasks:
        task.cancel()

    loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True))
    _log.info("All tasks finished cancelling.")

    for task in tasks:
        if task.cancelled():
            continue
        if task.exception() is not None:
            loop.call_exception_handler(
                {
                    "message": "Unhandled exception during Client.run shutdown.",
                    "exception": task.exception(),
                    "task": task,
                }
            )
#

after or before the loop.stop()

#

That's basically what the bot does on ctrl+c

cursive zealot
#

what is the _cancel_tasks ?

cursive zealot
vital bramble
#

oh, yeah. sorry xD

little cobalt
#
await bot.close()

should be right

vital bramble
cursive zealot
#

It stops the connection but not the process

#

even with an exit just after

#

I feel like the problem "comes" from asyncio, as the error message is always on the lock.acquire

vital bramble
#

yeah some coroutines are locked

vital bramble
#

But as already said, take a look at bot.run(), that's where all that is implemented

little cobalt
#

close is killing the process for me

cursive zealot
vital bramble
#

I just tried it

#
@argobot.slash_command(...)
async def stop(ctx):
    await argobot.close()
cursive zealot
#

Here's my bot class:

class ArgoBot(discord.Bot):
    def __init__(self, description=None, *args, **kwargs):
        super().__init__(description, *args, **kwargs)

        self.load_extension('cogs.diver_info')
        self.load_extension('cogs.admin')
    
    async def stop(self):
        """Stops the bot"""
        await self.close()
        print("hello")
        exit(0)
cursive zealot
vital bramble
#

try removing the exit(0)

cursive zealot
vital bramble
cursive zealot
#

I'll try wait

#

Ok i think i found the problem

#
@argobot.event
async def on_ready():
  await database.init_db()
  await argobot.stop()
  print('Launching bot')

If i put await argobot.stop() before the db init it stops

#

and if I put it after it doesn't

vital bramble
#

Oh, you're using a db

#

yeah, you need to stop that too

cursive zealot
#

yeah aiosqlite so that's probably why

vital bramble
#

yeah

#

that won't get stopped by bot.close() so it locks the loop

#

just overwrite the bot.close() method like this:

class MyBot(discord.Bot):
    async def close(self):
        await database.stop() #or whatever it is
        await super().close()
#

then you can use bot.close() and the database will be closed too

cursive zealot
#

yes that was the problem, it works now thanks 😄

spark ibex
#

when using buttons, how do i edit original message to change the embed

#

Using edit original it gives me 404 error

lofty parcel
#

interaction.response.edit_message

spark ibex
#

ok ill try that

deft kestrel
#

how do i send messages to a specific channel

#

with channel id

little cobalt
deft kestrel
lofty parcel
#

.rtfm get_channel

lofty parcel
#

.rtfm Channel.send

little cobalt
#

I was close to mention google but that also works ;3

deft kestrel
young skiff
#

view=MyView(timeout=30)) these are 30 seconds? or ms, or minutes? idk

lofty parcel
young skiff
deft kestrel
#

how i can make the bot send a message every time somebody is getting on live in YouTube?

lofty parcel
short obsidian
#

@lofty parcel before bot run then?

lofty parcel
short obsidian
#

thanks

loud kayak
#

How do I set a cooldown for a command with a specific amount of time (determined in the command's function) using commands.cooldown?

velvet cradle
#

own question:

in file /discord/ext/commands/converter.py
there is
CONVERTER_MAPPING, which is used to determine, which converter is used for which type.
is there any better way to override a specific converter than putting it in there when my bot starts?
I want my threads to be resolved, even if the bot needs to call the api for this (archived threads)

loud kayak
#

"use some cooldown"

#

Doesn't help.

velvet cradle
loud kayak
#

I'll just wait for a helper or someone reputable.

velvet cradle
#

https://docs.pycord.dev/en/stable/ext/commands/api.html#discord.ext.commands.cooldown just use this decorator.
if you want to be able to "change the waiting time", you might need to create your own decorator (just look at the source) which enables you to pass the cooldown object yourself, instead of the type of bucket.
store this cooldown object somewhere and you can manipulate it

#

a few weeks ago, I created my own cooldown object to limit the clicks on a button by user which clicked it
it is possible, but I just do not know, how much you know about these things

lofty parcel
loud kayak
#

Application cooldown if you will.

stray pasture
#

is there a way to use a Role from one guild in another guild with a bot ?

lofty parcel
stray pasture
lofty parcel
#

Roles are per guild.

#

They have a unique ID for the guild

stray pasture
#

that is what I though, but I read online that bot have a nitro like permissions for roles

#

(they can use role from other guild to another)

#

like if you have nitro

#

but not sure if true

lofty parcel
#

Bots don't have nitro

#

Nitro doesn't even do that

#

Bots can't randomly give a role from X guild in a Y guild.

stray pasture
#

no I dont mean give a role, just use it in text

lofty parcel
#

Uh? As in?

stray pasture
#

like: Hi ! You won 2 rooDuck

#

and be the same emote in the 2 server

lofty parcel
#

You can't mention a role that's from another guild.

#

It won't parse.

#

You could just use the name.

stray pasture
#

I see, so the role should exist in both server right in order for it to work ?

lofty parcel
#

No?

#

I'm literally not understand what you want to do.

#

WHY do you need a role from another server

#

HOW do you want to use such role

stray pasture
#

the user would run the command, after that the bot will respond: You have won x {emote}

#

I want to use the same emote in both server

lofty parcel
#

Emote or role

#

You literally mixing stuff now

stray pasture
#

I mean emote

lofty parcel
#

Girl

#

Emote or role

#

Are you dumb, I'm for real askingn

stray pasture
#

emote

lofty parcel
#

Why do you say emote when you're asking about a role

#

AND NOW YOU SAY EMOTE

#

We wasted 10 minutes arguing about some imaginary role when it was just an emote.

stray pasture
#

there is emote in the last 3 message, I just use the wrong world at the start

#

not everyone speek english as native language

lofty parcel
#

English is not my native language

#

Role and emote are not even a remotely close word.

#

Now that we agreed you want an EMOTE.

stray pasture
#

I just use the wrong word, why are you getting so worked up

lofty parcel
#

You just upload it to some private server of yours and just copy it.

lofty parcel
stray pasture
#

well mistake happen, I did not meant to use the wrong word on purpose and I am sorry for that.

little cobalt
deft kestrel
#

how i can move a specific text channel into a specific category?

lofty parcel
#

Read the docs.

sage tendon
#

man the rude role does fit

deft kestrel
#

thats true

#

but what parameter i need to use? category?

lofty parcel
#

The docs tell you.

sage tendon
#

yea

deft kestrel
sage tendon
#

both

deft kestrel
#

very specific

sage tendon
#

if you dont want it sorted i think you only need the category and maybe sync_permissions param depending on what you need

deft kestrel
#

thanks

little cobalt
#

Should I use discord.Cog or commands.Cog for a bridge bot?

shell radish
#

discord.Cog if you only have application commands

little cobalt
#

So I have to use commands.Cog for both, I see ;3

vapid tangle
#

@errant trout hi, sorry if I'm bothering you, you've once once mentioned about "ctx.me.activity", where can I read more about this method?

little cobalt
#

.rtfm activity

errant trout
rugged lodgeBOT
young skiff
#
class MyView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=10)

    async def on_timeout(self):
        self.disable_all_items()

    # Buttons below...

The buttons stop working after 10 seconds but their animation does not change to disabled, what i'm doing wrong?

little cobalt
young skiff
#

nope

little cobalt
#

;3

young skiff
#

how?

little cobalt
#

Its at the example for buttons

young skiff
#

yeah but there is no interaction i cant use await interaction.response.edit_message()

little cobalt
young skiff
#

uhm i see

#

thanks

tidal estuary
#

Anyone know off-hand if you're able to get the reddit username of a user who has connected reddit to their account and joined your server? Last I checked this was not the case but was hoping it'd changed

deft kestrel
#

so i am trying to put the bot up and it keeps saying it is not finding a module discord

#

can anyone quick help me?

deft kestrel
vital bramble
meager token
#

httpx.LocalProtocolError: Illegal header value then bots discord key

class accept(discord.ui.View): # Create a class called MyView that subclasses discord.ui.View
  @discord.ui.button(label="Post", style=discord.ButtonStyle.success) # Create a button with the label "😎 Click me!" with color Blurple
  @discord.ui.button(label="Delete", style=discord.ButtonStyle.danger) # Create a button with the label "😎 Click me!" with color Blurple
  async def button_callback(self, button:discord.Button, interaction:discord.Interaction):
    if button.label == "Post":
      #todo
      await interaction.respond(content="Posted", ephemeral = True)
    if button.label == "Delete":
      await interaction.respond(content="Ignored", ephemeral = True)```
#

oh wait fuck I did it wrong

vital bramble
#

I don't think you can actually use two command decorators on one function can you?
Also the class name is triggering me xD

meager token
#

accept.

vital bramble
#

It just defies common practice xD

meager token
#

most understandable function names when its only you working on the project

meager token
# vital bramble I don't think you can actually use two command decorators on one function can yo...
class accept_vw(discord.ui.View): # Create a class called MyView that subclasses discord.ui.View
  @discord.ui.button(label="Post", style=discord.ButtonStyle.success) # Create a button with the label "😎 Click me!" with color Blurple
  async def bcp(self, button:discord.Button, interaction:discord.Interaction):
    if button.label == "Post":
      await interaction.respond(content="Posted", ephemeral = True)
  @discord.ui.button(label="Delete", style=discord.ButtonStyle.danger) # Create a button with the label "😎 Click me!" with color Blurple
  async def bcd(self, button:discord.Button, interaction:discord.Interaction):
    await interaction.respond(content="Deleted", ephemeral = True)```
#

it still not working 😭

#

same error

vital bramble
#

can you send the exact error pls

meager token
#

httpx.LocalProtocolError: Illegal header value b'eyJhbGciOiJIUzI1NiIsInR5cC..bot key

lofty parcel
#

The whole traceback

#

And preferably the file too.

meager token
vital bramble
#

but seems like you got something wrong with the bot key...

#

there is a \n at the end

#

also now regen you bot key

meager token
#

oh shit yeah I made a new key its like a fourth of the size

#

well now it says improper token

meager token
#

where tf is it getting the key to my database

vital bramble
#

is it an environment variable?

meager token
#

no I just made a file and .readlines()

vital bramble
#

can you just show us your code please? How you start the bot and add the token etc...

lofty parcel
vital bramble
lofty parcel
#

Use a doenv if you want to do it properly

vital bramble
#

Yeah. Like in the guide

meager token
#

💀

#

so uhm I fixed it it didnt have anything to do with pycord

#

I jsut assumed it did

vital bramble
meager token
#

also dotenv wont install because AttributeError: module 'importlib._bootstrap' has no attribute 'SourceFileLoader' this is with --use-pep517

#

idk wth I did to make it do that

vital bramble
#

me neither...

deft bronze
#

How can i get the ID's of the people who reactioned to a msg?

#

should be smt like msg.reactions[0].users()

vital bramble
#

yes

vital bramble
#

or users = await reaction.users().flatten()

deft bronze
#

await msg.reactions[0].users().next() shows them but only using next

#

its strange xd

tepid coyote
#

can options in slash commands be dropped depending on a previous option?
e.g
/add <x> <y> <z>
if y is 0 dont ask for an input for z

deft bronze
#

you can just ignore z

#

@vital bramble sorry i just read correctly your answer

#

thank you, it worked

vital bramble
# deft bronze returns none

yeah, it's actually users() at the end.
also you can just use users = await reaction.users().flatten() to get a list of users or just go read the docs yourself

fiery stratus
#

Hey, I'm trying to make a global error handler whenever one of my checks fails for a command. Even though I've set up a dedicated check for this exception, its still going through. Why is that? It works for some commands but doesn't work for others.

pseudo pebble
#

I am trying to work on coding challenges, and was trying to find how to replace values. Ex. I want to change all e's someone puts in with f.

fiery stratus
pseudo pebble
#

Ok so the string is being modified with .replace?

fiery stratus
#

no strings in python are immutable

#
def replace_e_with_f(string: str) -> str:
  return string.replace('e', 'f')

string: str = "hello"
replace_e_with_f(string)
print(hello)```
will print `>>> hello`
pseudo pebble
#

Thank you for the explanation.

loud kayak
#

How do I set a cooldown for a command with a specific amount of time (determined in the command's function) using commands.cooldown? I have an apply command and the application settings has a cooldown time, and I want to apply that cooldown when the command is done.

little cobalt
#

But it should be possible to do

loud kayak
#

A command object only has the reset_cooldown, is_on_cooldown, and get_cooldown_retry_after methods.

little cobalt
#

mhm

#

I know that you can create a cooldown without the decorator

loud kayak
little cobalt
#
cd_mapping = commands.CooldownMapping.from_cooldown(1, 60, commands.BucketType.user)

bucket = cd_mapping.get_bucket(ctx.message)
retry_after = bucket.update_rate_limit()
if retry_after:
  await ctx.send("Error")
else:
  await ctx.send("Text")
#

That also works with buttons and menus

loud kayak
little cobalt
#

No, I found that at searching for a cooldown for the on_message event

loud kayak
#

Oh I see, thanks

loud kayak
little cobalt
#

Can you set the cd_mapping = commands.CooldownMapping.from_cooldown(1, 60, commands.BucketType.user) outside of the command?

loud kayak
umbral gazelle
#

how to unmute bot in voice?

robust ginkgo
#

Since you can't defer before sending a modal, is there any other similar alternatives?

spark ibex
#

how do i add a callback to this?

#

need to do it this way since i cant predefine all options

#

tried this but it annoyed and i cant figure out how to give it what it wants

#

and if i run it anyways... Application Command raised an exception: AttributeError: 'method' object has no attribute '__discord_ui_model_type__'

fleet cedar
#

For example

class MyView(discord.ui.View):
  def __init__(self, select_options):
    super().__init__(…)
    self.my_select.options = select_options

  @discord.ui.select()
  async def my_select():
    …
#

Notice the callback name and the method I am calling in the init

shrewd spade
#

how to use cooldown on user id but admins don't get affected?

plucky moss
#

Do you guys know how some bots have certain commands that are visible only to mods like Arcanes xp set level?

#

How can I replicate that?

deft kestrel
deft kestrel
vital bramble
vital bramble
#

bro don't just randomly ping me for a problem please. It's for replying to me, not for getting help.

#

there is a typo in the second line...
also what errors did you get?
also have you tried google?

#

google says that?

#

bro idk ask chatgpt or whatever but if you want to get help here, describe what you're trying to do, what the problem is, what errors you get and what you have already tried to solve the problem.
a.k.a. everything in #help-rules ...

lofty parcel
#

Just use ctx.edit

#

What?

#

I said ctx.edit

#

I never said var.ctx.edit

deft kestrel
green kernel
#

Is it possible to have a view with multiple reusable buttons? Think I've had an issue in the past where Discord would say I already sent a response or something and error out.

lofty parcel
#

You can use the view as many times as you want as long it doesnt timeout or your don't disable the buttons.

green kernel
lofty parcel
#

No...

#

You have to respond

green kernel
#

Hmm. Maybe I should explain what I'm trying to do better to give you an idea of what I'm working with.

#

I've got this blackjack game (vs the bot only) that uses emojis right now. You can hit any of the two reaction emojis to change the state of the game until you win or lose (or draw).

#

Issue with this is that reactions are painfully fucking slow compared to buttons from what I've noticed.

#

But the thing is, these reactions can be pressed over and over again (the bot removes the user's reaction after they click on an emoji).

#

Is it possible to have a system like this with buttons or do I have to figure something else out?

lofty parcel
#

Yes. That's what I told you.

#

You can click buttons whatever many times you want as long as the view doesn't timeout or your disable the buttons.

green kernel
#

Ah, see my concern with no response is that the user will get some kind of response timeout error, won't they? Because it'll just infinitely wait for a response.

#

And a deferred response still seems to count as a response? So sending multiples of those isn't really an option is it? Or can I send the deferred response once and let the user keep clicking after?

lofty parcel
#

You can just defer it (which will send an interaction failed message after like 15 minutes) or edit the message passing no new things

lofty parcel
#

Every click is a new interaction

green kernel
#

Gotcha, thanks.

stoic patio
#

so my bot is in a big server with 2fa moderation enabled

#

how do i make it work even without 2fa

edgy nest
stoic patio
#

oh

#

i see

#

thx

deft kestrel
#

I know that this question is not on the topic of the server, but hosting support simply does not answer me, so I solved it here.

What to do if requirements.txt I add py-cord But the result is an error no module discord

little cobalt
deft kestrel
#

That's all there is

#

I found something when I tried to install hosting py-cord These are the errors

glad garnet
deft kestrel
spark ibex
#

How do I add / remove items from a view? Like I want to be able to add buttons if the user selects a certain option from a selector, and remove the buttons and add anothrr delector if they change the option

rugged lodgeBOT
spark ibex
#

Ok thanks

quiet siren
#

Quick question, I currently have a View with 2 Dropdown menu and a confirm button, right now when someone select an option on the dropdown menu it the response go though fine, but how do i make it so that the user's side don't show "This interaction failed"? Do I ping the interaction or something?

little cobalt
#

The "Interaction failed" is from discord and not py-cord

quiet siren
#

yea i know but like, do i make pycord side send out a ping or something so it doesnt' show that?

#

Or will it always happen?

little cobalt
#

it will always happen

quiet siren
#

right.. i should probably just send a small message or something so it doesn't confuse users then

little cobalt
#

unless you set a timeout or edit the view so they cannot press the button again

#

you can "lock" the views so they cannot press it anymore

karmic solar
#

guys, how to make a similar feature for commands?

#

for example, I have a /account command that I would like to add to this list

rugged lodgeBOT
#

Here's the context menus example.

karmic solar
#

thx

tepid coyote
#

is there a reason why auto complete and options stop working, was setting up a slash command with auto complete and it was working fine, added a few more options and it stopped syncing with the new options and the autocompete wont load

reef lake
#

whats causing this exception
await interaction.followup("Your LFG channel has been deleted.")
TypeError: 'Webhook' object is not callable

little cobalt
tepid coyote
little cobalt
#

it doesnt have a limit

#

it only shows 25 at autocomplete

#

the options have a limit of 25

tepid coyote
#

but either way its between 4 and 14

#

options

reef lake
#

new question, how do i get discord to update my slash commands, i added a new one but its not appearing nor usable

little cobalt
reef lake
#

no

shell radish
#

.slashnoshow

sly karmaBOT
#

Application Commands Not Showing Up?

  • Uninstall libraries that conflict with the discord namespace (e.g. discord.py).
  • Invite your bot with the application.commands scope.
  • Load cogs before bot.run() (e.g. not in on_ready).
  • Do not override on_connect.
  • Update to the newest version of py-cord (see ?tag install).
  • Turn off User Settings > Accessibility > Chat Input > Use legacy chat input.
  • Share your code and errors.
fierce fable
#

how to i set my embed's colour to a custom hex value?

little cobalt
#

;3

fierce fable
# little cobalt color=

ive already tried that, but i get Expected discord.Colour, int, or Embed.Empty but received str instead.

fierce fable
#

@little cobalt ??

little cobalt
#

usually 0x992d22 should work?

fierce fable
#

oh, thanks :3

smoky trench
#

hi hi i have a quick question, i have a command using autocomplete a function for choices.

the choices come from a database which is a dictionary that contains the name of the option, is there a way to let that name be the choices the user sees AND keep the dictionary in scope for the actual command function?